wcstack 3.4.0 → 3.5.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/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={seen:!1},o={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},s=o,r=Symbol.for("wcstack.binder"),i=Symbol.for("wcstack.binder.pending"),a=Symbol.for("wcstack.binder.taken");const l=".",c="*",u=128,d=128,h="#",f="|",p="prevent",m="stop",g="ro",y="init",b="sync",w="else",v="...",_="on",$="eventToken",x="state",S="command",I="class",P="attr",k="style",N={};for(let t=0;t<u;t++)N[`$${t+1}`]=t;const A=Object.freeze(N),E="$connectedCallback",C="$disconnectedCallback",M="$renderedCallback",T="$errorCallback",O="$stateReadyCallback",L="$bindables",R="$commands",j="$commandTokens",W="$command",D="$eventTokens",z="$on",B="$stream",F="$watch",H="$scan",q="$recursion",U="**",V="$listKeys",G="$streamStatus",K="$streamError",J="data-wc-definition",Q=/\{\{\s*(.+?)\s*\}\}/g,X=new Set(["SCRIPT","STYLE"]);function Y(t){if(!s.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&&X.has(t.parentElement.tagName)||Z(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),Y(e.content)}else Y(t.content)}function Z(t){const e=t.data;if(Q.lastIndex=0,!Q.test(e))return;Q.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Q.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 tt(t){throw new Error(`[@wcstack/state] ${t}`)}const et=new Map;let nt=0;function ot(t){let e=et.get(t);if(void 0!==e)return e;-1!==t.indexOf(U)&&tt(`[wcs/recursion-unsupported] "${t}" uses "${U}", 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.`);const n=function(t){let e=1;for(let n=0;n<t.length;n++)t[n]===l&&e++;return e}(t);return n>512&&tt(`[wcs/binding-syntax] "${t}" has ${n} path segments — the limit is 512. Every prefix of a path is interned, so the cost grows with the square of the depth.`),e=Object.freeze(new st(t)),et.set(t,e),e}class st{id=++nt;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:ot(e),n=t.split("."),o=[],s=[],r=[],i={},a=[],l=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===c&&(r.push(h),i[h]=p,a.push(e(h)),l.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=l,this.wildcardParentPathSet=new Set(l),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 rt(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 it(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=rt(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const at=" Validate statically: npx @wcstack/lint <file>.",lt=new Set(["if","elseif","else","for"]);function ct(t,e){return`${JSON.stringify(t)}${JSON.stringify(e)}`}function ut(t){if(0===t.length)return"";let e="";for(let n=0;n<t.length;n++){const o=t[n];n>0&&(e+="|"),e+=`${o.filterName}(${ct(o.args,o.literals??o.args)})`}return e}const dt=new Map([["not",()=>t=>!t]]),ht=new Map([["not",[0,0]]]),ft={input:new Map,output:new Map},pt={input:new Map,output:new Map},mt={input:new Map,output:new Map},gt=new Map;function yt(t,e,n,o){const s=ft[t],r=pt[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)}const i=o??{},a=mt[t];for(const[t,n]of[...a])Object.prototype.hasOwnProperty.call(e,n)&&i[t]!==n&&a.delete(t);for(const t of Object.keys(i))a.set(t,i[t]);gt.clear()}function bt(t,e,n,o=e){const s=mt[n].get(t)??t,r=`${s}${ct(e,o)}:${n}`,i=gt.get(r);if(void 0!==i)return i;const a=ft[n].get(s)??dt.get(s);if(void 0===a){const e=0===ft[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";tt(`[wcs/filter-unknown] filter not found: ${t}.${it(t,function(t){return[...new Set([...dt.keys(),...ft[t].keys()])]}(n))}${e}${at}`)}const l=pt[n].get(s)??ht.get(s);void 0!==l&&(e.length<l[0]||e.length>l[1])&&tt(e.length<l[0]?`[wcs/filter-arity] filter "${t}" requires at least ${l[0]} argument(s) (${e.length} given).${at}`:`[wcs/filter-arity] filter "${t}" accepts at most ${l[1]} argument(s) (${e.length} given).${at}`);const c=a(e,o);return gt.set(r,c),c}function wt(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 vt=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function _t(t,e){return e?t:"true"===t||"false"!==t&&("null"===t?null:vt.test(t)?Number(t):t)}function $t(t){const e=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const t=wt(o,i,a);e.push(t),n.push(_t(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&&tt(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${t})". Close the quote.${at}`);const c=wt(o,i,a);return(c||r)&&(e.push(c),n.push(_t(c,r))),{args:e,literals:n}}const xt=t=>t.trim(),St=t=>"'"===t||'"'===t;function It(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(St(s))n=s;else if(s===e)return o}return-1}function Pt(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):St(i)?o=i:i===e&&(n.push(t.slice(s,r)),s=r+1)}return n.push(t.slice(s)),n}function kt(t,e,n){const o=n??t.join("|");return t.map(t=>{const n=It(t,"(");let s=function(t){let e=null,n=-1;for(let o=0;o<t.length;o++){const s=t[o];null!==e?s===e&&(e=null):St(s)?e=s:")"===s&&(n=o)}return n}(t);if(-1===s&&(s=t.lastIndexOf(")")),-1!==n&&-1===s&&tt(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${t}".${at}`),-1!==s&&-1===n&&tt(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${t}".${at}`),-1!==s&&s<n&&tt(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${t}".${at}`),-1!==s&&t.slice(s+1).trim().length>0){const e=t.slice(s+1).trim();tt(`[wcs/binding-syntax] "${t}": unexpected "${e}" after the filter's closing ")" — separate filters with "|" (write "${t.slice(0,s+1)}|${e}").${at}`)}const r=(-1===n?t:t.substring(0,n)).trim();if(0===r.length&&tt(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${at}`),r.includes(h)){const[t,n]=r.split(h);tt("input"===e?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${h}${n}" comes before the input filters, not inside one — write "<property>${h}${n}|${t}".${at}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${h}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${t}" here.${at}`)}return-1===n?{filterName:r,args:[],literals:[]}:{filterName:r,...$t(t.substring(n+1,s))}})}const Nt=new Map;function At(t){const e=It(t,f);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Nt.has(s)?r=Nt.get(s):(o=Pt(s,f).map(xt),r=kt(o,"input",t),Nt.set(s,r))):n=t.trim();const i=n.split(h).map(xt);i.length>2&&tt(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${h}" — write "${i[0]}${h}${i.slice(1).join(",")}".${at}`);const[a,c]=i,u=a.split(l).map(xt);return u.length>1&&""===u[0]||0!==a.length&&!u.some(t=>0===t.length)||tt(`[wcs/binding-syntax] "${t}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${at}`),{propName:a,propSegments:u,propModifiers:c?c.split(",").map(xt):[],inFilters:r}}const Et=new Map;function Ct(t){const e=It(t,f);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Et.has(s)?r=Et.get(s):(o=Pt(s,f).map(xt),r=kt(o,"output",t),Et.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&tt(`"${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.`);const i=n,a=i.startsWith(l),c=a?i.slice(1):i;return(c.length>0&&c.split(l).some(t=>0===t.length)||!a&&0===c.length)&&tt(`[wcs/binding-syntax] "${t}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).${at}`),{statePathName:i,statePathInfo:ot(i),outFilters:r}}const Mt=new Set([w,"if","elseif","for",v]),Tt=new Set([I,P,k,S,$,x]);function Ot(t){const[...e]=function(t){return Pt(t,";")}(t).map(xt).filter(t=>t.length>0),n=e.map(t=>{const e=It(t,":");-1===e&&tt(`[wcs/binding-syntax] Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.${at}`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim(),s=n.split(h)[0].split(f)[0].trim();if(s!==n&&Mt.has(s)&&tt(`[wcs/binding-syntax] "${t}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${at}`),n===w){o.length>0&&tt(`[wcs/binding-syntax] "${t}": "else" takes no value — write "else:".${at}`);const e=ot("#else");return{propName:w,propSegments:[w],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===v){0===o.length&&tt(`[wcs/binding-syntax] Invalid spread binding "${t}": spread target path is required.${at}`);const e=Ct(o);return e.outFilters.length>0&&tt(`[wcs/binding-syntax] Invalid spread binding "${t}": filters are not allowed on spread targets.${at}`),{propName:v,propSegments:[v],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ct(o),bindingType:n};if("radio"===s||"checkbox"===s){const t=Ct(o);return{...At(n),...t,bindingType:s}}{const t=Ct(o),e=At(n);if(""===e.propSegments[0]&&e.propSegments.length>1){const o=e.propSegments.slice(1);return(o.includes("")||Tt.has(o[0]))&&tt(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Tt].join(", ")}).${at}`),{...e,propName:o.join(l),propSegments:o,...t,bindingType:"prop"}}return e.propSegments[0]===$||e.propSegments[0].startsWith(_)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>lt.has(t.bindingType))&&tt(`[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">).${at}`),n}const Lt=new WeakMap,Rt=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),jt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Wt(t){const e=Lt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),o=jt.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return Rt.has(r)?(Lt.set(t,o[2]),o[2]):null}function Dt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ct(t),bindingType:"text"}}const zt=new WeakMap,Bt=new WeakSet;let Ft=0;async function Ht(t){const e=function(t){let e,n=zt.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++Ft,promise:o,resolve:e},zt.set(t,n),Bt.has(t)&&n.resolve(),n}(t);await e.promise}function qt(t){const e=zt.get(t);void 0===e?Bt.add(t):e.resolve()}const Ut=new WeakMap;function Vt(t){const e=Ut.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{Ut.set(t,n)}}function Gt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Kt(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Gt(e);if(void 0!==n)return Gt(n)}return Gt(globalThis.customElements)}function Jt(t,e){t.upgrade?.(e)}function Qt(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=te(s.properties,Xt);if(null===r)return null;const i=void 0===s.inputs?new Map:te(s.inputs,Yt);if(null===i)return null;const a=void 0===s.commands?new Map:te(s.commands,Zt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Xt(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 Yt(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 Zt(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 te(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 ee(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:ot(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ne(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function oe(t,e,n={}){const o=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&&tt("Spread binding requires an element node.");const e=t,s=Vt(e);null===s&&tt(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Kt(e);if(null===a&&tt(`CustomElementRegistry is unavailable for <${s}>.`),void 0===a.get(s)){o||tt(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Jt(a,e);const l=Qt(e);null===l&&tt(`Spread binding "${n.statePathName}" requires <${s}> 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=ee(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=ee(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=ne(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=ne(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(s.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 se(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 re(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:bt(s.filterName,s.args,e,r)})}return n}function ie(t){return{...t,inFilters:re(t.inFilters,"input"),outFilters:re(t.outFilters,"output")}}const ae=new WeakMap;function le(t){return ae.get(t)||null}function ce(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(s.bindAttributeName)}function ue(t){const e=[],n=t.querySelectorAll(`${s.tagNames.state}[bind-component]`);for(const o of n){if(!ce(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function de(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 he(t){const e=[],n=ue(t),o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Wt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;o.nextNode();){const t=o.currentNode;n.length>0&&de(t,n)||e.push(t)}return e}const fe=new WeakSet;function pe(t,e,n,o){const s=oe(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Vt(t):null;return null===n&&tt("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}fe.add(t);const r=function(t,e){const n=[];for(const o of e){const e=re(o.inFilters,"input"),s=re(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){ae.set(t,e)}(t,r),qt(t),{bindings:r,deferred:null}}function me(t,e){return ge(he(t),e)}function ge(t,e){const n=[],o=[];for(const s of t){if(fe.has(s))continue;const t=pe(s,Tl(s),{allowDeferred:!0},e);null===t.deferred?n.push(...t.bindings):o.push(t.deferred)}return[t,n,o]}function ye(t){fe.add(t)}function be(t){const{node:e,parseResults:n,transform:o}=t;return function(t){fe.delete(t)}(e),pe(e,n,{allowDeferred:!1},o).bindings}const we=new WeakMap;let ve=null;function _e(t){let e=t;for(;e;){const t=we.get(e);if(t)return t;let n=e.parentNode;null===n&&null!==ve&&e instanceof ShadowRoot&&(n=ve(e)),e=n}return null}function $e(t,e){null!==e?we.set(t,e):we.delete(t)}let xe=null,Se=0;function Ie(){return`u${(Se++).toString(36)}`}let Pe=0,ke=0;const Ne=Symbol("wcs.listIndex.noValue");class Ae{uuid=Ie();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;cacheStamp=0;ref;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ne,this._index=e,this._version=Pe,this._chainGeneration=ke}get index(){return this._index}set index(t){this._index=t,this._version=++Pe,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}set homeParentListIndex(t){this._homeParentListIndex=t}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=Pe),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===ke||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=ke),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++Pe,ke++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function Ee(t,e,n=t){return new Ae(t,e,n)}function Ce(t,e){t.reparent(e)}function Me(t){return t.homeParentListIndex}function Te(t,e){t.homeParentListIndex=e}function Oe(t){return t?.cacheStamp}function Le(t,e){const n=t,o=n.value,s=o!==Ne&&!Object.is(o,e);return o!==e&&(Re.get(o)?.delete(n.ref),function(t,e){if("object"!=typeof t||null===t||null===e.parentListIndex)return;let n=Re.get(t);void 0===n?(n=new Set,Re.set(t,n)):n.size>=(je.get(n)??8)&&(We(n,e,!0),je.set(n,2*n.size+8)),n.add(e.ref??=new WeakRef(e))}(e,n)),n.value=e,s}const Re=new WeakMap,je=new WeakMap;function We(t,e,n=!1){const o=[];return t?.forEach(s=>{const r=s.deref();void 0===r||n&&ze(r)?t.delete(s):r!==e&&o.push(r)}),o}const De=new WeakSet;function ze(t){for(let e=t;null!==e;e=e.parentListIndex)if(De.has(e))return!0;return!1}function Be(t){return t.value}function Fe(t,e){const n=t.value;return n!==Ne&&n===e.value}let He=0;const qe=new WeakSet;function Ue(t){qe.add(t)}function Ve(t){return qe.has(t)}const Ge=new WeakMap;function Ke(t){return De.has(t)}const Je=new WeakMap,Qe=new WeakMap,Xe=new WeakMap;function Ye(t,e){return!0===Je.get(e)?.has(t)}function Ze(t,e){return Ye(t,e)||ze(e)}const tn=new WeakMap;function en(t){tn.delete(t)}function nn(t,e,n){const o=Object(Be(e)),s=Be(n);for(const e in s)if(s[e]===t&&o[e]!==t)return!1;return!0}function on(t,e){return!Ze(t,e)&&tn.get(e)!==He}const sn=new WeakMap,rn=new WeakMap,an=new WeakSet;function ln(t){const e=Ge.get(t);return void 0===e?null:e}function cn(t,e){const n=Ge.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o&&!Ve(t)){const s=null!==e&&o.parentListIndex!==e&&tn.get(e)!==He,r=function(t,e,n){const o=Me(e),s=e.parentListIndex;return null!==o&&o!==s&&!Ze(t,o)&&nn(t,o,s)?o:function(t,e,n,o){return null!==e&&null!==o&&o!==n&&!!De.has(e)&&!(!on(t,o)||o.position!==e.position)&&!Ye(t,e)&&Fe(o,e)}(t,o,s,n)||function(t,e,n){return e!==n&&null!==e&&null!==n&&e.position===n.position&&Ze(t,e)&&on(t,n)}(t,s,n)?n:null}(t,o,e);if(null!==r&&an.has(t)){an.delete(t);const e=[...t];Ue(e),Ge.set(e,n),mn(t,e);const o=n.map((e,n)=>{const o=Ee(r,n);return Le(o,t[n]),o});return Ge.set(t,o),o}if(null!==r)for(const t of n)Ce(t,r);else if(s){!function(t,e){let n=sn.get(t);void 0===n?(n=new Set,sn.set(t,n)):n.size>=(rn.get(t)??8)&&(n.forEach(e=>{Ze(t,e)&&n.delete(e)}),rn.set(t,2*n.size+8));for(const t of e)n.add(t)}(t,[o.parentListIndex,e]);const s=o.parentListIndex;if(null!==s&&s.position===e.position&&!nn(t,s,e)&&nn(t,e,s))for(const t of n)Ce(t,e)}}return n}const un=new WeakSet;function dn(t){un.delete(t)}function hn(t,e,n=!1){null!==e?(n?un.add(e):dn(e),Ge.set(t,e)):Ge.delete(t)}const fn=new WeakMap;function pn(t){let e=fn.get(t);return void 0===e&&(e={value:t},fn.set(t,e)),e}function mn(t,e){const n=fn.get(t);void 0!==n&&(n.value=e,fn.delete(t))}const gn=new WeakMap,yn=new WeakMap,bn=new Set,wn=new WeakMap,vn=new WeakMap;function _n(t){const e=t.absolutePathInfo.stateElement;let n=yn.get(e);return void 0===n&&(n=new WeakMap,yn.set(e,n)),n}function $n(t){return gn.get(t)??[]}function xn(t,e){const n=gn.get(t);gn.set(t,e),vn.delete(t);const o=_n(t);n!==e&&void 0!==n&&o.get(n).delete(t);const s=o.get(e);void 0===s?o.set(e,new Set([t])):s.has(t)||(s.size>=(wn.get(s)??8)&&(s.forEach(t=>{Sn(t.listIndex)&&s.delete(t)}),wn.set(s,Math.max(8,2*s.size))),s.add(t))}function Sn(t){for(let e=t;null!==e;e=e.parentListIndex)if(Ke(e))return!0;return!1}function In(t,e){const n=_n(t).get(e);return void 0===n?bn:(n.forEach(t=>{Sn(t.listIndex)&&n.delete(t)}),n)}function Pn(t,e){return!vn.has(t)&&(vn.set(t,e),!0)}function kn(t){return gn.has(t)}const Nn=new WeakMap;let An=null,En=0;function Cn(t){return Nn.get(t)??[]}function Mn(t,e){null===An?Nn.set(t,e):An.set(t,e)}function Tn(){En++,null===An&&(An=new Map)}function On(){if(0!==En&&(En--,!(En>0||null===An))){for(const[t,e]of An)Nn.set(t,e);An=null}}function Ln(t){return(An?.has(t)??!1)||Nn.has(t)}const Rn=Symbol("$$setLoopContext"),jn=Symbol("$$getByAddress"),Wn=Symbol("$$hasByAddress"),Dn=Symbol("$$connectedCallback"),zn=Symbol("$$disconnectedCallback"),Bn=Symbol("$$updatedCallback"),Fn=Symbol("$$errorCallback"),Hn=new WeakMap,qn=new WeakMap;class Un{absolutePathInfo;listIndex;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}}function Vn(t,e){if(null===e){let e=qn.get(t);return void 0!==e||(e=new Un(t,null),qn.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 Un(t,e),n.set(t,o)),o}}const Gn=new WeakMap;function Kn(t,e){let n=Gn.get(t);void 0===n&&(n=new Map,Gn.set(t,n));let o=n.get(e);return void 0===o&&(o=Object.freeze(new Jn(t,e)),n.set(e,o)),o}class Jn{pathInfo;stateElement;constructor(t,e){this.pathInfo=e,this.stateElement=t}}function Qn(t,e){return Vn(Kn(t,e.pathInfo),e.listIndex)}function Xn(t,e,n){return Vn(Kn(t,e),n)}const Yn=new WeakMap;function Zn(t,e){null===e?Yn.delete(t):Yn.set(t,e)}function to(t){return Yn.get(t)||null}const eo=new Map;function no(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=eo.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,eo.set(s,r)),r}function oo(t,e,n){return e<0||e>=n?null:t.at(e-n)}function so(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const ro=new WeakMap;function io(t){const e=_e(t.node);if(null===e)return null;let n=ro.get(e);if(void 0===n)n=new WeakMap,ro.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=no(e.pathInfo,t.statePathInfo);return n>0&&(o=oo(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const ao=new WeakMap;function lo(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=to(n);null===e?tt(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function co(t,e){let n=null;if(n=ao.get(t)||null,null!==n)return n;const o=lo(t,e),s=io(t),r=Il(o);return null===r&&tt("No state tree found on this root for binding."),n=Xn(r,t.statePathInfo,s),ao.set(t,n),n}function uo(t){ao.delete(t)}const ho=new WeakMap;function fo(t,e){const n=ho.get(t);void 0===n?ho.set(t,e):n instanceof Set?n.add(e):n!==e&&ho.set(t,new Set([n,e])),null!==xe&&xe({type:"state:binding-added",absoluteAddress:t,binding:e})}function po(t,e){const n=ho.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&ho.delete(t),null!==xe&&xe({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const mo=new WeakMap;function go(t){const e=ho.get(t);return void 0!==e?e:null!==t.listIndex?mo.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const yo=new WeakMap,bo=new WeakMap;class wo{pathInfo;listIndex;_parentAddress;_rowAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e,this._rowAddress=null!==e&&t.lastSegment===c}get parentAddress(){const t=this._parentAddress;if(void 0!==t&&(!this._rowAddress||t.listIndex===this.listIndex.parentListIndex))return t;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let n=null;n=this.pathInfo.segments[this.pathInfo.segments.length-1]===c?this.listIndex?.parentListIndex??null:this.listIndex;const o=_o(e,n);return void 0!==t&&!vo(o,this.listIndex)&&vo(t,this.listIndex)?t:this._parentAddress=o}}function vo(t,e){const n=t.pathInfo;let o=Be(t.listIndex);for(const t of n.segments.slice(n.wildcardPositions[n.wildcardCount-1]+1))o=Object(o)[t];return ln(o)?.[e.index]===e}function _o(t,e){if(null===e){let e=bo.get(t);return void 0!==e||(e=new wo(t,null),bo.set(t,e)),e}{let n=yo.get(e);void 0===n&&(n=new WeakMap,yo.set(e,n));let o=n.get(t);return void 0!==o||(o=new wo(t,e),n.set(t,o)),o}}const $o=new WeakMap;function xo(t){let e=null;if(e=$o.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=io(t);null===n&&tt(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=_o(t.statePathInfo,n)}else e=_o(t.statePathInfo,null);return $o.set(t,e),e}function So(t){$o.delete(t)}function Io(){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 Po=new Map,ko=Io();function No(t,e){const n=ut(t.inFilters);return`${t.statePathName}::${e}::${n}`}function Ao(t){let e="input";for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}function Eo(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function Co(t,e){console.error(`[wcstack/state] ${e} rejected.`,t)}function Mo(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Eo(t)&&Promise.resolve(t).catch(t=>Co(t,e))}class To{_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)try{e.push(n(...t))}catch(t){e.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,t)}return e}}class Oo extends To{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==xe&&xe({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const Lo=new WeakMap;function Ro(t,e){let n=Lo.get(t);void 0===n&&(n=new Map,Lo.set(t,n));let o=n.get(e);return void 0===o&&(o=new Oo(e,t),n.set(e,o)),o}const jo=new WeakMap;class Wo extends To{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==xe&&xe({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function Do(t){return t instanceof Wo}const zo=new Map,Bo=Io();function Fo(t){const e=t.propModifiers.filter(t=>t===p||t===m).sort().join(",");return`${t.statePathName}::${e}`}function Ho(t){return"event"===t.bindingType&&t.propName.startsWith(_)}function qo(t){if(!Ho(t))return!1;const e=Fo(t);let n=zo.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(p)&&o.preventDefault(),e.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Il(r);null===i&&tt("No state tree found on this root for event handler.");const a=_e(s),l=t.startsWith(W+".");i.createStateAsync("writable",async e=>{const c=e[Rn](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?so(a.listIndex,c):[];if(l){const s=e[jn](_o(n,null));return Do(s)||tt(`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&&tt(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});Mo(c,`"${t}"`)}).catch(e=>Co(e,`"${t}"`))})(t.statePathName,t.propModifiers,t.statePathInfo),zo.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Bo.add(e,t),!0}function Uo(t){if(!Ho(t))return!1;const e=Fo(t),n=zo.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);return t.node.removeEventListener(o,n),0!==Bo.countOf(e)&&(Bo.remove(e,t)&&zo.delete(e),!0)}const Vo=new Map,Go=Io();function Ko(t,e){const n=ut(t.inFilters);return`${t.statePathName}::${e}::${n}`}function Jo(t){let e="input";for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}const Qo=new Set(["radio","checkbox"]),Xo=new Set(["value","valueAsNumber","valueAsDate"]);function Yo(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(Qo.has(t)&&"checked"===e)return!0;if(Xo.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Vt(n);if(null!==s){const t=Kt(n)?.get(s);void 0===t&&tt(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Qt(n);if(o?.knownProperties.has(e))return!0}return!1}let Zo=1,ts=1,es=1;const ns=new WeakMap;function os(t,e,n){let o=ns.get(t);void 0===o&&(o=new Map,ns.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=Zo++,o.set(s,r)),r}function ss(t,e){return"to-element"===e?2*t:2*t+1}const rs=new Set;function is(t){return{transactionId:ts++,originBindingId:t,visitedEdges:rs,hop:0}}function as(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 ls=null;function cs(){return ls}function us(t,e){const n=ls;ls=t;try{return e()}finally{ls=n}}const ds=[];let hs=0;function fs(t,e,n,o,s=!1){hs=s?2:1;try{t.createState("writable",t=>{t[Rn](e,()=>{t[n]=o})})}finally{hs=0}}const ps=new Map,ms=Io(),gs=new WeakMap,ys=t=>t.detail,bs=new WeakMap,ws=new WeakMap;let vs=0;const _s=new WeakMap;function $s(t){const e=Vt(t.node);if(null!==e){const n=Kt(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&tt(`CustomElementRegistry is unavailable for <${e}>.`))}if(Yo(t.node,t.propName)&&-1===t.propModifiers.indexOf(g)){const e=function(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Vt(t.node);if(null!==n){const o=Kt(t.node)?.get(n);void 0===o&&tt(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Qt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}(t),n=function(t){if(null!==Vt(t.node)){const e=Qt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??ys}return null}(t),o=function(t){if(null===Vt(t.node))return!1;const e=Qt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}(t),r=function(t,e,n,o){const s=ut(t.inFilters);return`${t.propName}::${t.statePathName}::${e}::${s}::${function(t){if(null===t)return"n";let e=ws.get(t);return void 0===e&&ws.set(t,e=++vs),`g${e}`}(n)}::${o?"o":"s"}`}(t,e,n,o);_s.set(t,{key:r,eventName:e});let i=ps.get(r);void 0===i&&(i=((t,e,n,o,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==o)l=o(i),o!==ys||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=bs.get(t);void 0===r&&(r=new Set,bs.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=gs.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(s.enablePropagationContext){const n=os(a,t,e),o=function(t,e){for(let n=ds.length-1;n>=0;n--){const o=ds[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==o&&Object.is(o.writtenValue,l))return s.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:o.transactionId,coveredBySameValueGuard:s.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==xe&&xe({type:"propagation:suppressed",reason:"confirmation",transactionId:o.transactionId,edgeId:ss(n,"to-state"),node:a,member:t}));const r=ss(n,"to-state"),i=cs();if(null!==i&&i.visitedEdges.has(r))return void(null!==xe&&xe({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=as(i??is(n),r)}const h=Il(a.getRootNode());null===h&&tt("No state tree found on this root for two-way binding.");const f=_e(a),p=()=>fs(h,f,e,c,r);null!==d?us(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,o),ps.set(r,i)),t.node.addEventListener(e,i),ms.add(r,t)}}const xs=new WeakSet;function Ss(t){xs.add(t)}function Is(t){return!!xs.has(t)&&(xs.delete(t),!0)}const Ps=new WeakMap;function ks(t,e){const n=Ps.get(t);return!(void 0===n||n<e||(n===e?Ps.delete(t):Ps.set(t,n-e),0))}const Ns=new WeakSet;function As(t){Ns.add(t)}function Es(t){return!!Ns.has(t)&&(Ns.delete(t),!0)}let Cs=0;function Ms(){Cs--}function Ts(){return Cs>0}class Os{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 Ls=new WeakMap;function Rs(t){let e=Ls.get(t);return void 0===e&&(e=new Os(t),Ls.set(t,e)),e}const js=new Set([I,P,k,S]);function Ws(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!==y&&s!==b&&tt(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&tt(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Ds(t){return t.propModifiers.some(t=>t.includes("="))}const zs=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Bs=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Fs(t,e){return"state"===t&&"call"===e?zs:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Hs(t){if(!s.enableDirectionalInitialSync)return Ds(t)&&tt("init=/sync= modifiers require enableDirectionalInitialSync."),zs;const e=null===(n=Ws(t,y))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:tt(`Invalid init modifier value "${n}".`);var n;const o=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":tt(`Invalid sync modifier value "${t}".`)}(Ws(t,b));if("event"===t.bindingType)return null!==e&&"none"!==e&&tt("Event bindings only allow init=none."),"call"===o?Bs:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(js.has(t.propSegments[0]))return Fs("state",o);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&tt(`Binding type "${t.bindingType}" does not support init=${e}.`),Fs(e??"state",o);const r=Qt(t.node);if(null===r)return Fs(e??"state",o);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||tt(`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)||tt(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==o||i||tt(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:o,observable:i,outputOnly:i&&!a}}function qs(t){let e=t.getRootNode();return e instanceof DocumentFragment&&!(e instanceof ShadowRoot)&&(e=to(e)),null===e?null:Il(e)}let Us=0,Vs=null,Gs=0;const Ks=["active","disposed","failed"],Js=new WeakMap,Qs=new WeakMap,Xs=new WeakMap,Ys=new WeakMap,Zs=new WeakMap,tr=new WeakMap;function er(t,e){const n=tr.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):tr.set(t,new Set([n,e]))):tr.set(t,e)}function nr(t){return tr.has(t)}function or(t,e){const n=tr.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function sr(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))sr(n,e)}function rr(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class ir{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||!ks(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)Is(t)||sr(t,t=>{or(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)Es(t)&&!Ts()||sr(t,t=>{or(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&dl(o)}}const ar=new WeakMap;function lr(t){let e=ar.get(t);return void 0===e&&(e=new ir(t),ar.set(t,e)),e}function cr(t){const e=ut(t.inFilters),n=ut(t.outFilters);return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function ur(t,e,n){const o=Il(lo(t,n));null===o&&tt("No state tree found on this root for binding.");const s=Kn(o,t.statePathInfo);return function(t,e,n){let o=mo.get(t);void 0===o&&(o=new WeakMap,mo.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!==xe&&xe({type:"state:binding-added",absoluteAddress:Vn(t,e),binding:n})}(s,e,t),s}function dr(t,e){const n=co(t,e);return fo(n,t),n}function hr(t,e,n,o){null!==e?po(e,t):function(t,e,n){const o=mo.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!==xe&&xe({type:"state:binding-removed",absoluteAddress:Vn(t,e),binding:n}))}(n,o,t),So(t),uo(t)}function fr(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class pr{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;disposedAt=0;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=Xs.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(rr(e)&&lr(e),null===this.rowPlan)for(const n of t){const t=Xs.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(!s.enableDirectionalInitialSync)return Ds(t)&&Hs(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=Xs.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){let o=Qs.get(e);return void 0===o&&Qs.set(e,o=[]),{id:o[n]??(o[n]=++Us),info:t,generation:e.generation,phase:Ks[e.phases[n]],teardowns:null}}const o=Xs.get(t);return o?.session===this?o:null}addTeardown(t,e){const n=Xs.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(fr(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=this.deferredByNode.get(t)??new Set,r=()=>s.delete(a)&&this.deferred.delete(a),i=()=>{const s=Kt(t);null===s&&tt(`CustomElementRegistry is unavailable for <${e}>.`),a.cancel=Rs(s).wait(e,()=>{if(r())try{Jt(s,t),n()}catch(t){o(t)}},t=>{r()&&o(t)})},a={node:t,born:++Gs,cancel:null,arm:()=>{if(null===a.cancel&&this.deferred.has(a))try{i()}catch(t){r(),o(t)}}},l=t.getRootNode();if(null!==Vs||11===l.nodeType&&!rr(l)){if(null===Vs){const t=Vs=[];queueMicrotask(()=>{Vs=null;for(let e=0;e<t.length;e++)t[e].arm()})}Vs.push(a)}else i();return rr(l)&&lr(l),er(t,this),this.deferredByNode.set(t,s.add(a)),this.deferred.add(a),()=>{r(),a.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=Xs.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.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&&(po(n,t.bindings[e]),t.addresses[e]=null),t.phases[e]=1}}dispose(){this.disposedAt=Gs;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.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(){this.disposedAt=Gs;for(const t of this.rows)this.destroyRowRecord(t);this.rows.clear();for(const t of this.records)null!==t.address&&(po(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?co(n):null;if(hr(n,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null,this.registerAddress(e),null!==o){const t=co(n);t!==o&&kn(o)&&xn(t,$n(o)),t!==o&&Ln(o)&&Mn(t,Cn(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return rr(e)?e:null}(t);null!==e&&lr(e)}handleMutations(t,e,n){for(const n of e)sr(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)sr(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&dl(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);this.deferredByNode.get(t)?.forEach(t=>{t.cancel?.(),t.cancel=null,this.deferred.delete(t)})}handleAddedNode(t,e){this.deferredByNode.get(t)?.forEach(t=>{t.born<=this.disposedAt||(this.deferred.add(t),t.arm())});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=Xs.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||n.pendingDefinitions>0&&n.generation>this.disposedAt)&&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=Zs.get(e);void 0===t&&(t=cr(e),Zs.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;er(n,this);const o=this.knownMapFor(n);let s=Zs.get(t);void 0===s&&(s=cr(t),Zs.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:++Us,session:this,generation:++Gs,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(er(r,this),this.addKnownRowBinding(r,o,t),Js.set(o,s),n[t].isEvent){let n=!1;try{n=qo(o)}catch(e){throw s.phases[t]=2,e}n&&(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=++Gs,r=!0,this.rows.add(o)),o.phases[t]=0,o.flags[t]=0,s[t].isEvent){let n=!1;try{n=qo(e[t])}catch(e){throw o.phases[t]=2,this.runRowSlotTeardowns(o,t),e}n&&(o.flags[t]|=2)}this.registerRowSlot(o,t,n)}}rowOf(t){const e=Js.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=io(o);null!==s?(t.patternPathInfos[e]=ur(o,s,n),t.patternListIndexes[e]=s):t.addresses[e]=dr(o,n)}unregisterRowSlot(t,e){const n=t.addresses[e],o=t.patternPathInfos[e];null===n&&null===o||(hr(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{Uo(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:++Us,info:t,generation:++Gs,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};Xs.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;qo(e)?t.eventAttached=!0:e.propSegments[0]!==$?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const o=Jo(t),s=Ko(t,o);let r=Vo.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=Il(o.getRootNode());null===r&&tt("No state tree found on this root for two-way binding.");const i=_e(o);r.createState("writable",t=>{t[Rn](i,()=>{t[e]=s})})},Vo.set(s,r)),t.node.addEventListener(o,r),Go.add(s,t),!0}var e,n;return!1}(e)&&fr(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const e=Jo(t),n=Ko(t,e),o=Vo.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Go.countOf(n)&&(Go.remove(n,t)&&Vo.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const o=Ao(t),s=No(t,o);let r=Po.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=Il(o.getRootNode());null===i&&tt("No state tree found on this root for two-way binding.");const a=_e(o);i.createState("writable",t=>{t[Rn](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]:[]})})},Po.set(s,r)),t.node.addEventListener(o,r),ko.add(s,t),!0}var e,n;return!1}(e)&&fr(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const e=Ao(t),n=No(t,e),o=Po.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==ko.countOf(n)&&(ko.remove(n,t)&&Po.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(s.enableDirectionalInitialSync&&Yo(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const n=function(t,e,n){let o=gs.get(t);void 0===o&&(o=new Map,gs.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&&gs.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});fr(t,n)}$s(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==$)return!1;const e=t.node,n=Vt(e),o=Kt(e);if(null!==n&&void 0===o?.get(n))return null===o&&tt(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(jo.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||tt('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Vt(t)?null:Qt(t)}(e);null===r&&tt(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&tt(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${it(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,c=t.propModifiers,u=t=>{c.includes(p)&&t.preventDefault(),c.includes(m)&&t.stopPropagation();const n=Il(e.getRootNode());null===n&&tt("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||tt(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${it(l,n.eventTokenNames)}${at}`);const o=_e(e);n.createStateAsync("writable",async e=>{Mo(e[Rn](o,()=>{const s=null!==o?so(o.listIndex,o.pathInfo.wildcardCount):[];return Ro(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,u),jo.set(t,{eventName:a,handler:u}),!0})(e)&&fr(t,()=>function(t){if(t.propSegments[0]!==$)return!1;const e=jo.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),jo.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Vt(t.info.node);if(null===n)return void e();const o=Kt(t.info.node);if(null===o&&tt(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation;fr(t,this.deferUntilDefined(t.info.node,n,()=>{this.isAlive(t,s)&&(e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t)))},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))}))}settleInitialRecord(t){if(s.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Hs(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=qs(t.replaceNode);null===e&&tt("No state tree found on this root for binding.");const n=xo(t);let o=!1;return e.createState("readonly",t=>{o=t[Wn](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 Cs++;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,Ms()),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=qs(t.node);null===o&&tt("No state tree found on this root for initial binding sync."),fs(o,_e(t.node),t.statePathName,n)}(t.info,r))}settleConnectedSnapshot(t){if(s.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=io(n);if(null!==o?(t.patternPathInfo=ur(n,o,e),t.patternListIndex=o):t.address=dr(n,e),!t.options.registerPathInfo)return;const s=Il(n.replaceNode.getRootNode());null===s&&tt("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&&Xs.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,Ms());const e=t.info;if(null!==t.address||null!==t.patternListIndex)try{hr(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=_s.get(t);if(void 0===e)return;_s.delete(t);const n=ps.get(e.key);void 0!==n&&(t.node.removeEventListener(e.eventName,n),ms.remove(e.key,t)&&ps.delete(e.key))}(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{Uo(e)}catch{}}}}function mr(t){let e=Ys.get(t);return void 0===e&&(e=new pr(t),Ys.set(t,e)),e}function gr(t){return Xs.get(t)?.session??Js.get(t)?.session??null}let yr=null;function br(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const wr=Object.freeze([]),vr=new WeakMap,_r=new WeakMap;function $r(t){return _r.get(t)??[]}function xr(t,e){_r.set(t,e)}const Sr=new WeakMap;function Ir(t){return Sr.get(t)??[]}function Pr(t,e){Sr.set(t,e)}function kr(t,e){const n=Ir(t);for(const t of n)$e(t,e)}const Nr=new WeakMap;function Ar(t){return Nr.get(t)??[]}function Er(t,e){Nr.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});const Cr=new WeakMap,Mr=new WeakSet;function Tr(t,e){if(null===e)Cr.delete(t);else{Cr.set(t,e);const{stateElement:n,pathInfo:o}=t.absolutePathInfo;if(o.wildcardCount>0){for(let t=o.parentPathInfo;null!==t&&t.wildcardCount===o.wildcardCount&&!Mr.has(t);t=t.parentPathInfo)Mr.add(t);n.setPathInfo(o.lastWildcardPath,"prop","internal")}}}function Or(t){const e=Cr.get(t);e&&(e.dirty=!0),null!==t.listIndex&&Mr.has(t.absolutePathInfo.pathInfo)&&t.listIndex.cacheStamp++}const Lr=Symbol.for("wcstack.transition-runner");function Rr(t){const e=globalThis[Lr];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 jr(t,e,n){const o=Rr(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const Wr=[],Dr=[];let zr=-1,Br=0,Fr=!1;function Hr(t){Dr.includes(t)||Dr.push(t)}function qr(t,e=0){const n=Wr.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Wr.push(o):Wr.splice(n,0,o)}function Ur(t){queueMicrotask(()=>{throw t})}const Vr=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){for(let e=0;e<Dr.length;e++)Dr[e](t);zr>Br&&(Br=zr),zr<0&&(Fr=!0);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(){Tn(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],He++,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=[]){let o=Fr?0:Br;Br=0,Fr=!1;const s=new Map,r=new Set;for(let e=0;e<t.length;e++){const n=t[e],o=s.get(n.absoluteAddress);null!==xe&&null!=o&&null!==n.context&&o.transactionId!==n.context.transactionId&&xe({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:o.transactionId,winnerTransactionId:n.context.transactionId}),s.set(n.absoluteAddress,n.context),r.add(n.absoluteAddress)}for(let t=0;t<n.length;t++){const e=n[t];s.has(e)||s.set(e,null)}const i=[],a=new Map;s.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!==xe&&xe({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop}));const n=go(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(i.push(e),null!==t&&a.set(e,t));else!1!==n.replaceNode.isConnected&&(i.push(n),null!==t&&a.set(n,t))});try{const t=()=>{zr=o+1;try{a.size>0?dl(i,a):dl(i)}finally{zr=-1}};if(o>100&&i.length>0){if(101===o++){const t=[...new Set(Array.from(r,t=>t.absolutePathInfo.pathInfo.path))];console.error("[@wcstack/state] render chain depth limit exceeded; bindings for this batch were not applied.",{maxDepth:100,paths:t}),null!==xe&&xe({type:"state:render-chain-limit",maxDepth:100,paths:t})}}else if(e()||0===i.length)t();else{const e=jr("state",t);void 0!==e&&e.catch(Ur)}}finally{On(),zr=o,function(t){for(const e of Wr.slice())e.listener(t)}(r),zr=-1}}};function Gr(){return Vr}const Kr=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,Xr=new WeakMap;let Yr=!1;const Zr=new WeakMap;function ti(t){const e=t.absolutePathInfo.stateElement;let n=Zr.get(e);void 0===n&&Zr.set(e,n=new Set),n.add(t)}function ei(t){const e=Zr.get(t);return void 0===e?null:(Zr.delete(t),e)}const ni=new WeakMap,oi=new WeakMap,si=new WeakMap,ri=new WeakMap,ii=new WeakMap,ai=[];function li(t,e){const n=ci(t);if(n.recorded.has(e))return;n.recorded.add(e);const o=ot(e).cumulativePaths;if(o.length<2)return;let s=ii.get(t);void 0===s&&ii.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 ci(t){let e=Kr.get(t);return void 0===e&&Kr.set(t,e={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),e}function ui(t,e,n){let o=t.get(e);void 0===o&&t.set(e,o=new Set),o.add(n)}function di(t,e,n){const o=t.get(e);o.delete(n),0===o.size&&t.delete(e)}function hi(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=Jr.get(o);if(void 0===r&&Jr.set(o,r=new Map),r.has(e)){const t=r.get(e);return Object.is(t,n)||(di(s,t,o),r.set(e,n),ui(s,n,o)),!1}return r.set(e,n),ui(s,n,o),!0}function fi(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):(o.push(n),!1)}function pi(t,e,n,o,s,r){t.lastValue.set(e,n),s&&(null!==o.listIndex&&fi(Qr,o.listIndex,r)&&function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){let n=si.get(e);void 0===n&&si.set(e,n=new Set),n.add(t)}}(o.listIndex),null!==r.levelListIndex&&fi(Xr,r.levelListIndex,r))}function mi(t,e,n,o,s){Yr=!0;const r=ci(t);li(t,e),pi(r,e,s,o,hi(r,e,n,o),{stateElement:t,path:e,absAddress:o,levelListIndex:null})}function gi(t,e){ci(t).tracked.add(e)}function yi(t,e){return!0===Kr.get(t)?.byPath.has(e)||!0===ni.get(t)?.has(e)}function bi(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(Qn(t.stateElement,_o(e,o)))}function wi(t,e){if(!Yr||t===e)return;const n=oi.get(t);if(void 0===n)return;oi.delete(t);const o=oi.get(e);oi.set(e,void 0===o?n:o.concat(n)),dn(e);for(const o of n){o.indexes=e;const n=ci(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&&!Ke(t))for(const e of o.getters){const n=Qn(o.stateElement,_o(e,t));Or(n),Gr().enqueueAbsoluteAddress(n,null),ti(n)}}}function vi(t,e){if(void 0!==t)for(const n of t)e.push(n)}function _i(t,e,n,o,s){const r=Kr.get(t),i=r?.byPath.get(e),a=ni.get(t)?.get(e);if(void 0===r||void 0===i&&void 0===a)return ai;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&&vi(i.get(o),u),h&&vi(i.get(c),u),d&&vi(i.get(s),u)),void 0!==a)for(const t of a)n&&bi(t,o,u),h&&bi(t,c,u),d&&bi(t,s,u);return u}function $i(t,e){return!0===ii.get(t)?.has(e)}function xi(t,e){let n=t;for(const t of e){if("object"!=typeof n||null===n)return;n=n[t]}return n}function Si(t,e,n,o,s=!0){const r=ot(e).segments.length,i=[];for(const a of ii.get(t).get(e)){const e=ot(a).segments.slice(r);if(e.includes(c)){Ii(t,a,i);continue}const l=s?xi(n,e):void 0;for(const n of _i(t,a,s,l,xi(o,e)))i.push(n)}return i}function Ii(t,e,n){const o=Kr.get(t).byPath.get(e);if(void 0!==o)for(const t of o.values())vi(t,n);const s=ni.get(t)?.get(e);if(void 0!==s)for(const t of s)for(let e=0;e<t.indexes.length;e++)bi(t,e,n)}function Pi(t){const e=Xr.get(t.levelListIndex),n=e.indexOf(t);e.splice(n,1)}function ki(t){const e=Qr.get(t);if(void 0!==e){Qr.delete(t),function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){const n=si.get(e);void 0!==n&&(n.delete(t),0===n.size&&si.delete(e))}}(t);for(const t of e){const{stateElement:e,path:n,absAddress:o}=t,s=Jr.get(o),r=s.get(n);s.delete(n),di(Kr.get(e).byPath.get(n),r,o),null!==t.levelListIndex&&Pi(t)}}}function Ni(t){const e=ri.get(t);if(void 0!==e){ri.delete(t);for(const t of e){const e=ni.get(t.stateElement),n=e.get(t.path);n.delete(t),0===n.size&&e.delete(t.path);const o=oi.get(t.indexes);o.splice(o.indexOf(t),1),0===o.length&&oi.delete(t.indexes)}}}function Ai(t){if(!Yr)return;ki(t),Ni(t);const e=si.get(t);if(void 0!==e){si.delete(t);for(const t of e)ki(t),Ni(t),si.delete(t)}}function Ei(t,e,n){if(!Yr)return;const o=Xr.get(t);if(void 0!==o)for(const{stateElement:t,path:s,absAddress:r}of o){const o=Kr.get(t),i=o.byPath.get(s);di(i,e,r),ui(i,n,r),Jr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,e)||Object.is(a,n))&&(Or(r),Gr().enqueueAbsoluteAddress(r,null),ti(r))}}const Ci=new WeakMap,Mi=Object.freeze([]),Ti=new Set,Oi=new WeakMap,Li=new WeakMap;function Ri(t,e){Li.set(t,new WeakRef(Object(e)))}function ji(t){return Li.get(t)?.deref()}function Wi(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}function Di(t){!function(t){for(const e of t)De.add(e)}(t);for(const e of t)Ai(e)}function zi(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:Mi,s=Array.isArray(n)&&n.length>0?n:Mi,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:Mi,o=Array.isArray(e)&&e.length>0?e:Mi;let s=Ci.get(n);return s&&s.get(o)||null}(o,s);if(r&&r.newIndexes===cn(s,t))return r;const i=cn(o,t)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Ti,deleteIndexSet:new Set(i),addIndexSet:Ti};let e=cn(s,t);if(null===e&&null!==t&&function(t,e){const n=sn.get(t);for(const o of n??[])if(Ze(t,o))n.delete(o);else if(o!==e)return!0;return!1}(o,t)&&Ri(s,o),0===o.length||null===e&&ji(s)===o){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=Ee(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:Ti,deleteIndexSet:new Set(i),addIndexSet:new Set(e)}}if(Wi(o,s)&&(e??i)===i)return o!==s&&Bi(o,i,t),a={oldIndexes:i,newIndexes:i,changeIndexSet:Ti,deleteIndexSet:Ti,addIndexSet:Ti};if(null!==e)return Fi(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,l=new Set;let c=!1;for(let o=0;o<s.length;o++){const a=s[o],u=n.get(a),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=Ee(t,o);e.push(n),l.add(n)}else{const t=i[d];c=!0,d!==o&&r.add(t),e.push(t)}}return c&&Bi(o,e,t),a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(function(t,e,n){let o=Ci.get(t);o||(o=new WeakMap,Ci.set(t,o)),o.set(e,n)}(o,s,a),dn(i),hn(s,a.newIndexes))}}(t,e,n);return function(t,e){const n=t.newIndexes;let o;for(let t=0;t<n.length;t++){if(n[t].index!==t){const e=n[t].index;n[t].index=t,Ei(n[t],e,t)}Le(n[t],e[t])&&(o??=[]).push(n[t])}const s=Oi.get(e);s?.[0]===He&&(o=o?s[1].concat(o):s[1]),o&&Oi.set(e,[He,o]),t.valueChangeIndexes=o}(o,Array.isArray(n)&&n.length>0?n:Mi),function(t){for(const e of t)De.delete(e)}(o.newIndexes),ji(n)!==e&&(Di(o.deleteIndexSet),wi(o.oldIndexes,o.newIndexes)),o}function Bi(t,e,n){var o;if(o=t,an.add(o),null!==n)for(const t of e)Te(t,n)}function Fi(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}}const Hi=new WeakMap;function qi(t){return Hi.get(t)??null}function Ui(t,e){Hi.set(t,e)}const Vi=new WeakMap,Gi=new WeakMap;function Ki(t,e){for(let n=0;n<t.length;n++)if(e.has(t[n]))return!0;return!1}function Ji(t,e,n){kr(t,e);const o=$r(t),s=qi(t);if(null!==s&&(s.activate(o,n.rootNode),null!==e&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(t){return Vi.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=Gi.get(t);void 0===o&&Gi.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,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let t=0;t<e.length;t++){const u=e[t];if(!n.shouldApplyState(u))continue;const d=r[t];if(null===d||Ki(d.prefixes,i)){cl(u,s);continue}if(s.appliedBindingSet.has(u))continue;c||(l=s.state[jn](o),c=!0);const h=d.tail;let f=l,p=!1;for(let t=0;t<h.length;t++){if(null==f){f=void 0;break}if(a&&!(h[t]in Object(f))){p=!0;break}f=f[h[t]]}p?cl(u,s):(s.appliedBindingSet.add(u),ll(u,s,f))}}(r,o,s,e,n)}for(const t of o)null===s&&fo(co(t),t),(null===s||s.shouldApplyState(t))&&cl(t,n);t.spreads&&hl(t.spreads,e,s,o,Ar(t))}function Qi(t){if(!t.mounted)return;const e=$r(t),n=qi(t);for(let t=0;t<e.length;t++){const o=e[t];null!==n?n.disposeBinding(o):po(co(o),o)}!function(t){const e=Ir(t);for(let t=0;t<e.length;t++)$e(e[t],null)}(t)}const Xi=new WeakMap,Yi=Object.freeze(new Set);function Zi(t,e){const n=Xi.get(t);n?n.add(e):Xi.set(t,new Set([e]))}function ta(t){const e=Xi.get(t);return void 0!==e?e:Yi}function ea(t,e){const n=Xi.get(t);n&&(n.delete(e),0===n.size&&Xi.delete(t))}const na=new Set(["if","elseif","else","for"]);class oa{_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];As(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){As(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=qi(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRow($r(this));const e=this._childNodeArray;for(let t=0;t<e.length;t++){const n=e[t];null!==n.parentNode&&(Ss(n),n.parentNode.removeChild(n))}const n=$r(this);for(let t=0;t<n.length;t++){const e=n[t];na.has(e.bindingType)&&ta(e.node).forEach(t=>{t.tryDestroy()||t.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const t=qi(this);null!==t&&(t.isRowSession?t.disposeBindings($r(this)):t.dispose())}this._teardownBindings()}_teardownBindings(){const t=$r(this);for(let e=0;e<t.length;e++){const n=t[e];na.has(n.bindingType)&&ta(n.node).forEach(t=>{t.unmount()}),So(n),uo(n)}}unmount(){{const t=qi(this);null!==t&&(t.isRowSession?t.disposeBindings($r(this)):t.dispose())}for(const t of this._childNodeArray)null!==t.parentNode&&(Ss(t),t.parentNode.removeChild(t));const t=$r(this);for(let e=0;e<t.length;e++){const n=t[e];na.has(n.bindingType)&&ta(n.node).forEach(t=>{t.unmount()}),So(n),uo(n)}this._mounted=!1}}function sa(t){return 1<<Math.min(t,31)}function ra(t){let e=t.indexBits;if(void 0===e){e=0;for(const n of t.nodeInfos)for(const t of n.parseBindTextResults)t.statePathName in A&&(e|=sa(A[t.statePathName])),"string"==typeof t.uuid&&(e|=ra(Ml(t.uuid)));t.indexBits=e}return e}function ia(t){return ra(Ml(t.uuid))}function aa(t,e){return t.statePathName in A||na.has(t.bindingType)&&0!==(ia(t)&e)}function la(t,e){const n=document.createDocumentFragment(),o=new oa(n,e);return o._childNodeArray=t,o._firstNode=t.length>0?t[0]:null,o._lastNode=t.length>0?t[t.length-1]:null,o._mounted=!0,o}function ca(t){void 0!==t.uuid&&null!==t.uuid||tt("BindingInfo.uuid is null.");const n=Ml(t.uuid);n||tt(`Fragment with UUID "${t.uuid}" not found.`);const o=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${s.commentForPrefix}|${s.commentIfPrefix}|${s.commentElseIfPrefix}|${s.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!==s.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=s.enableDirectionalInitialSync,n=[],o=t.nodeInfos;for(let e=0;e<o.length;e++){const s=o[e],r=se(t.fragment,s.nodePath);if(null===r)return null;for(const t of s.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!==Vt(r))return null;if("prop"===o&&Yo(r,t.propName))return null;const i=ie(t);let a;try{a=Hs({...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 A,policy:a,authority:a.authority})}}return 0===n.length?null:{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=se(o,s[t].nodePath);null===e&&tt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),ye(e),qt(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=pl.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new pr,pl.set(n,o)),o.initializeRow(t,e),o}(n,a,t.node),u=new oa(o);return Ui(u,c),xr(u,a),function(t,e){Vi.set(t,e)}(u,n),Er(u,l),Pr(u,r),Zi(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o,s]=function(t,e){const n=[],o=[],s=[];for(const r of e){const e=se(t,r.nodePath);if(null===e&&tt(`Node not found by path [${r.nodePath.join(", ")}] in fragment.`),fe.has(e))continue;const i=pe(e,r.parseBindTextResults,{allowDeferred:!0});null!==i.deferred&&(s.push(i.deferred),fe.add(e)),o.push(...i.bindings),n.push(e)}return[n,o,s]}(t,e),r=new pr;return{nodes:n,bindingInfos:r.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:r,spreads:s}}(i,n.nodeInfos);o&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new oa(i,o);a.spreads.length>0&&(l.spreads=a.spreads),Ui(l,a.bindingSession),xr(l,a.bindingInfos);const c="for"===t.bindingType?(u=t.statePathInfo.wildcardCount+1,2**Math.min(u,32)-1):-1;var u;const d=[];for(const t of a.bindingInfos)aa(t,c)&&d.push(t);return Er(l,d),Pr(l,a.nodes),Zi(t.node,l),l}const ua=new WeakSet,da=Symbol.for("wcstack.state.view-transition-naming");function ha(){const t=Rr("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function fa(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||ua.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[da]??={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.`)):(ua.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 pa=new WeakMap,ma=new WeakMap,ga=new WeakMap,ya=new WeakMap,ba=new WeakMap,wa=new WeakMap;function va(t,e,n,o){let s=wa.get(t);void 0===s&&(s=[document.createComment(""),document.createComment("")],wa.set(t,s));const[r,i]=s;r.data=`@@wcs-for-start:${o}`,i.data=`@@wcs-for-end:${o}`,t.mounted||(r.remove(),i.remove());const a=null===n?null:n.nextSibling;if(null===r.parentNode)e.insertBefore(r,a),e.insertBefore(i,a),t.mountAfter(r);else if(a!==r){let t=r;for(;t!==i;){const n=t.nextSibling;e.insertBefore(t,a),t=n}e.insertBefore(i,a)}return i}function _a(t,e,n){!function(t,e,n){let o=ma.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,ma.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function $a(t,e){pa.set(t,e)}function xa(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 Sa(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 Ia=new Set(["if","elseif","else","for"]);function Pa(t,e){for(const n of $r(t))if(e.appliedBindingSet.delete(n),Ia.has(n.bindingType))for(const t of ta(n.node))Pa(t,e)}function ka(t,e,n){for(const o of Ar(t))if(Ia.has(o.bindingType)){if(o.statePathName in A&&cl(o,e),0!==(ia(o)&n))for(const t of ta(o.node))t.mounted&&ka(t,e,n)}else cl(o,e)}function Na(t){for(const e of $r(t)){if(!Ia.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of ta(e.node))Na(n),t&&n.mounted&&(Qi(n),n.unmount(),ea(e.node,n),ba.delete(e.node),ma.delete(e.node))}}function Aa(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function Ea(t,o,r){const i=Boolean(r);let a;const l=ta(t.node);a=0===l.size?ca(t):l.values().next().value;const c=e(),u=t.uuid??"",d=t.bindingType;if(i||(s.debug&&console.log(`unmount if content : ${Aa(t)}`),c&&a.mounted&&(n.seen=!0),Qi(a),a.unmount()),i){s.debug&&console.log(`mount if content : ${Aa(t)}`);const e=_e(t.node);if(kr(a,e),c){if(!a.mounted){const e=document.createComment(`@@wcs-${d}-start:${u}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),a.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${u}:${t.statePathName}`),o=a.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}}else a.mountAfter(t.node);Ji(a,e,o);const n=ha();null!==n&&fa(a,"branch",n)}}const Ca=new WeakMap;function Ma(t){return Ca.get(t)??[]}const Ta=new Set;function Oa(){Ta.clear()}const La=Symbol.for("wcstack.trustedTypes.policy");function Ra(){const t=globalThis[La];return null===t||"object"!=typeof t?null:t}let ja,Wa=!1;const Da={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")}};function za(t,n,o){if(1===t.propSegments.length){const e=t.propSegments[0];"textContent"===e||"innerText"===e?o=null==o?"":String(o):void 0===o&&"innerHTML"===e&&(o="")}if(void 0===o)return void(s.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!==o){null!==yr&&null!==u&&"object"==typeof u&&null!==o&&"object"==typeof o&&null!==Vt(r)&&yr.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=Ra(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(o):o,t=!0}catch(t){e&&function(t,e){if(Wa)return;if(!function(){if(void 0!==ja)return ja;if(!("trustedTypes"in globalThis))return ja=!1,ja;try{document.createElement("div").innerHTML="<i></i>",ja=!1}catch{ja=!0}return ja}())return;Wa=!0;const n="function"==typeof Ra()?.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),s.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:o,error:t})}if(t){const t=function(t,e){const n=Vt(t);if(null===n)return null;const o=Kt(t)?.get(n);if(void 0===o)return null;const s=Qt(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,o)}catch(e){s.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:o,error:e})}}};if(s.enablePropagationContext&&Yo(r,c)){const e=os(r,c,t.statePathName),s=ss(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??cs()??is(e);if(a.visitedEdges.has(s))null!==xe&&xe({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:s,node:r,member:c});else{const t=as(a,s);us(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:es++,writtenValue:n};ds.push({receipt:i,node:t});try{return r()}finally{ds.pop()}}(r,c,o,e,t.transactionId,i))}}else i()}if(e()){const t=Da[c];t?t(r,o):(function(t,e,n){let o=Ca.get(t);o||(o=[],Ca.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,o),a=r,Ta.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!==o){if(Object.isFrozen(u))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:o}));null!==yr&&2===i.length&&"object"==typeof u&&null!==u&&null!==Vt(r)&&(d in u?yr.rememberOverwrittenValue(r,c,d,u[d]):yr.recordInjectedKey(r,c,d));try{u[d]=o}catch(t){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:o,error:t})}}}const Ba=new WeakSet;function Fa(t,e,n){}function Ha(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)}}const qa=new WeakMap;function Ua(t,e,n,o){const s=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),r=e.length>0?e+l:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(l)&&!qa.has(Ha(o,t)?.get)&&s.push(e)}return s}const Va={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Ga={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Ka(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}.${at}`}function Ja(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 Qa(t,e){return`$setAll("${t}") ${e}`}function Xa(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.${at}`}const Ya=new WeakSet;function Za(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const tl=Object.freeze({[I]:function(t,e,n){const o=t.node,s=t.propSegments[1];null!=n?("boolean"!=typeof n&&tt(`Invalid value for class application: expected boolean, got ${typeof n}. Write "|truthy" if you mean to coerce.`),o.classList.toggle(s,n)):o.classList.toggle(s,!1)},[P]:function(t,e,n){const o=t.node,s=t.propSegments[1];if(null==n)return void(o.hasAttribute(s)&&o.removeAttribute(s));const r=String(n);o.getAttribute(s)!==r&&o.setAttribute(s,r)},[k]: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){Do(n)||tt("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=vr.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||tt('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Vt(t);if(null===e)return null;const n=Kt(t)?.get(e);return void 0===n&&tt(`Custom element <${e}> is not defined for command binding.`),Qt(t)}(r);null===a&&tt(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||tt(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${it(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),vr.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 vr.delete(t);const o=n[i];return"function"!=typeof o&&tt(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),vr.set(t,{token:o,unsubscribe:c,elementRef:l})}}),el={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Ba.has(t.replaceNode)){Ba.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,o,s){const r=t.statePathInfo,i=io(t),a=co(t),l=$n(a),u=ba.get(t.node);let d,h;const f=void 0!==u&&function(t,e){const n=vn.get(t);return void 0!==n&&(n===e||ln(e)===ln(n))}(a,s),p=f||void 0===u||u.value===l?null:zi(i,l,s);f?(d=u.value,h=Fi(ln(d),ln(s))):null!==p&&p.newIndexes.every(t=>t.parentListIndex===i||Ke(t.parentListIndex)||!Ye(s,t.parentListIndex))?(d=u.value,h=Fi(ln(d)??[],p.newIndexes)):(d=l.length>0&&!ma.has(t.node)?[]:l,h=zi(i,d,s));const m=Array.isArray(s)?s:[];o.newListValueByAbsAddress.set(a,m),ba.set(t.node,pn(m));let g=ma.get(t.node);const y=void 0!==g?function(t,e,n){if(!Ve(e))return null;let o=null;for(let e=0;e<n.newIndexes.length;e++){const s=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(s)&&n.deleteIndexSet.has(r)?t.get(r):void 0;void 0!==i&&(o??={byAddedIndex:new Map,reused:new Set},o.byAddedIndex.set(s,i),o.reused.add(i))}return o}(g,d,h):null,b=Array.isArray(d)&&d.length===h.deleteIndexSet.size&&h.deleteIndexSet.size>0;if(b&&null===y&&null!==t.node.parentNode){let e=ya.get(t.node);if(void 0===e){const n=pa.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(xa(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(xa(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n.parentNode===t.node.parentNode?n:t.node),ya.set(t.node,e)}if(e){const e=t.node.parentNode;!function(t,e){Ps.set(t,(Ps.get(t)??0)+e)}(e,e.childNodes.length),e.textContent="",e.appendChild(t.node)}}let w=b?1e3-function(t){return ga.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;const v=e();if(void 0!==g){const e=g;h.deleteIndexSet.forEach(o=>{const s=e.get(o);void 0!==s&&(v&&(wa.get(s)?.forEach(t=>t.remove()),n.seen=!0),null!==y&&y.reused.has(s)?(Qi(s),Na(s),s.unmountInPlace()):w<=0&&s.tryDestroy()?ea(t.node,s):(Qi(s),s.unmount(),function(t,e){let n=ga.get(t.node);void 0===n&&(n=[],ga.set(t.node,n)),n.length<1e3?n.push(e):ea(t.node,e)}(t,s),w-=1),b||e.delete(o))}),b&&(ma.delete(t.node),g=void 0)}let _=t.node;const $=ot(r.path+"."+c),x=o.stateElement.loopContextStack,S=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}(h);let I=null;h.newIndexes.length==h.addIndexSet.size&&h.newIndexes.length>0&&_.isConnected&&null===y&&(I=document.createDocumentFragment(),Zn(I,o.rootNode));const P=v?`${t.uuid}:${r.path}:`:"",k=ha(),N=ga.get(t.node);for(const e of h.newIndexes){let n;if(h.addIndexSet.has(e)){const s=_o($,e);if(x.createLoopContext(s,s=>{n=y?.byAddedIndex.get(e)??(void 0!==N?N.pop():void 0),void 0===n?n=ca(t):(Pa(n,o),kr(n,s)),v?_=null!==I?va(n,I,null,P+e.index):va(n,_.parentNode,_,P+e.index):null!==I?n.appendTo(I):_.nextSibling!==n.firstNode&&n.mountAfter(_),Ji(n,s,o),null!==k&&fa(n,"row",k)}),void 0===n&&tt(`Content not found for ListIndex: ${e.index} at path "${r.path}"`),null!==y&&y.reused.has(n)){const t=o.stateElement.addressHooks;if(t){const e=t.rowReused;for(let t=0;t<e.length;t++)e[t](o.stateElement,n)}}}else{n=void 0!==g?g.get(e)??null:null,h.changeIndexSet.has(e)&&ka(n,o,sa(r.wildcardCount)),null===n&&tt(`Content not found for ListIndex: ${e.index} at path "${r.path}"`);const t=!n.mounted;if(v?_=va(n,_.parentNode,_,P+e.index):null!==S&&S.has(e)&&Sa(_,n.firstNode)||_.nextSibling===n.firstNode||n.mountAfter(_),t){const t=n,s=_o($,e);x.createLoopContext(s,e=>{Ji(t,e,o)})}}v||(_=n.lastNode||_),void 0===g&&(g=new WeakMap,ma.set(t.node,g)),g.set(e,n)}pa.set(t.node,_),null!==I&&(t.node.parentNode.insertBefore(I,t.node.nextSibling),Zn(I,null))},if:Ea,else:Ea,elseif:Ea,radio:function(t,e,n){const o=t.node,s=br(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=br(o.value,t.inFilters),r=Array.isArray(n)?n:wr;o.checked=r.includes(s)}},nl=new WeakMap,ol=new WeakMap,sl=new WeakMap;function rl(){}function il(t){const e=yr;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return Fa;if(e.isDeclared(n,o))return rl}return za}function al(t,e){ll(t,e,function(t,e){const n=xo(e);if(n.pathInfo.path in A){const t=_e(e.node);return null===t&&tt(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&tt("ListIndex not found for loopContext:");const n=A[e];void 0===n&&tt(`Invalid index name: ${e}`);const o=oo(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&tt(Xa(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[jn](n)}(e.state,t))}function ll(t,e,n){const o=br(n,t.outFilters);if(!0===ol.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=nl.get(t);if(void 0===s){if(nl.has(t))return s=il(t),s===Fa&&nl.set(t,s),void s(t,e,o);if(s=el[t.bindingType],void 0===s){const e=t.propSegments[0];s=tl[e],nl.set(t,s),void 0===s&&(Vt(t.replaceNode)?(s=il(t),s===Fa&&nl.set(t,s)):(s=za,nl.set(t,s)))}if(s===za&&"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 ol.set(t,!0)}s(t,e,o)}else s(t,e,o)}function cl(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=co(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=gr(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==sl.get(t)){const e=Vt(t.replaceNode);if(e&&(void 0===Kt(t.replaceNode)?.get(e)||function(t){return"waiting-definition"===Xs.get(t)?.phase}(t)))return void function(t,e){if(Ya.has(t))return;Ya.add(t);const n=()=>{Ya.delete(t);const e=gr(t);(null===e||e.shouldApplyState(t))&&dl([t])},o=n=>{Ya.delete(t),Za(e,n)},s=gr(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Ya.delete(t),r()})||(Ya.delete(t),r()))}const r=Kt(t.replaceNode);if(null===r)return Ya.delete(t),void Za(e,new Error("CustomElementRegistry is unavailable."));Rs(r).wait(e,()=>{t.replaceNode.isConnected?n():Ya.delete(t)},o)}(t,e);sl.set(t,!0)}if(!0===e.sameRootVerified)return void al(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=to(o),null===o&&tt("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Il(o);null===n&&tt("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};al(t,r)})}else al(t,e)}function ul(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!==xe&&xe({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function dl(t,e,n){let o=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;o<t.length;){let n=t[o];if(!1===n.replaceNode.isConnected){s.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),o++;continue}let u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=to(u),null===u&&tt("Root node for fragment not found for binding."));const d=Il(u);null===d&&tt("No state tree found on this root for binding."),d.createState("readonly",s=>{const h={rootNode:u,stateElement:d,state:s,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{cl(n,h)}catch(t){ul(n,t,d,c)}o++;const e=t[o];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{za(t,{propagationContextByBinding:e},n)}catch(e){ul(t,e,o??null,c)}for(const[t,e]of i.entries())xn(t,e),Mn(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[Bn](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[Fn](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 hl(t,e,n,o,s){for(const r of t)r.cancel?.(),r.cancel=n.deferUntilDefined(r.node,r.tagName,()=>{const i=be(r);o&&(t.splice(t.indexOf(r),1),o.push(...i),s.push(...i.filter(t=>t.statePathName in A))),0!==i.length&&($e(r.node,e),dl(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1})))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,t)})}function fl(t,e,n){const[o,s,r]=me(t,n),i=mr(t);for(const t of o)$e(t,e);dl(i.initialize(s)),hl(r,e,i)}const pl=new WeakMap;async function ml(t){const e=t.querySelectorAll(s.tagNames.state),n=[],o=Kt(t);null===o&&tt(`CustomElementRegistry is unavailable for <${s.tagNames.state}>.`),await o.whenDefined(s.tagNames.state);for(const t of e){if(ce(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function gl(t){if(t===document)await ml(document),Y(document),Xl(document,document),fl(document.body,null);else{const e=t;e.host.hasAttribute(s.bindAttributeName)&&await Ht(e.host),await ml(e),Y(e),Xl(e,e),fl(e,null)}}const yl={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function bl(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${yl[t]??t}" before the state is defined.`}let wl=null;function vl(t){return null===wl&&tt(bl("ssr",t)),wl}const _l=new WeakMap,$l=new WeakMap,xl=new Set,Sl=[];function Il(t){return _l.get(t)??null}function Pl(t){return $l.get(t)??Promise.resolve()}const kl=new WeakSet;function Nl(t){kl.add(t)}function Al(t,n){const o=_l.get(t);if(null===n){if(void 0===o)return;_l.delete(t),xl.delete(o),null!==xe&&xe({type:"state:element-unregistered",rootNode:t,element:o}),s.debug&&console.debug("State element unregistered")}else{if(o===n)return;if(void 0===o){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 vl('the "enable-ssr" attribute').hydrate(t)||await gl(t),Nl(t),oc(),e()}catch(t){n(t)}})});$l.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await gl(t),Nl(t),oc(),e()}catch(t){n(t)}})});$l.set(t,e)}}void 0!==o&&tt('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="...">.'),_l.set(t,n),xl.add(n);for(let e=0;e<Sl.length;e++)Sl[e](t,n);null!==xe&&xe({type:"state:element-registered",rootNode:t,element:n}),s.debug&&console.debug("State element registered",n)}}const El=new Map;function Cl(t,e,n){if(null===n)El.delete(t);else{El.set(t,n);const o=Il(e);null===o&&tt("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 Ml(t){return El.get(t)||null}function Tl(t){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=Ot(e.getAttribute(s.bindAttributeName)||"");if(e.localName===s.tagNames.state){if(e.hasAttribute("mount"))return n.filter(t=>t.propSegments[0]!==x);const t=n.find(t=>t.propSegments[0]===x);if(void 0!==t){const e=`on a volume element — a <${s.tagNames.state}> with a "mount" attribute`;tt(1===t.propSegments.length?`[wcs/mount-path-invalid] "${t.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${x}.<key>: <path>") ${e}.`:`[wcs/mount-path-invalid] "${t.propName}: ${t.statePathName}" is a volume injection declaration, and it can only be written ${e}. Add mount="<path>", or bind an element property instead.`)}}return n}if(t.nodeType===Node.COMMENT_NODE){const e=Wt(t);null===e&&tt("Comment node binding text not found.");const n=Ml(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Dt(e),s=null):s=e,[{...o,uuid:s}]}return[]}let Ol;function Ll(){return Ol??={filterName:"not",args:[]}}const Rl=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function jl(t,e){const n=e+l+c,o=It(t,"|");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+l+s.slice(1)}return r.length>0?s+r:s}function Wl(t,e){const n=Rl.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+jl(s,e)+r}function Dl(t,e){const n=Pt(t,";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=It(n,":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=jl(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function zl(t,e){return Dl(t,e)}function Bl(t,e){const n=s.bindAttributeName,o=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const t=o.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=Wl(n.data,e);continue}const s=t;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const t=Dl(r,e);t!==r&&s.setAttribute(n,t)}}}function Fl(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}const Hl=new WeakMap;function ql(t){return Hl.get(t)??null}function Ul(t){const e=[],n=he(t);for(const t of n){const n=Tl(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");Hl.set(e,t.data),t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:Fl(o),parseBindTextResults:n})}return e}function Vl(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const Gl=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),Kl=Ll();function Jl(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Kl],bindingType:t}}function Ql(t,e,n,o,s,r=!0){Vl(e),"string"==typeof o&&Bl(e,o),Xl(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ul(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 Xl(t,e,n,o){const r=s.commentElsePrefix,i=ue(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(s.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(s.bindAttributeName)||"";"string"==typeof n&&(i=zl(i,n));let a=Ot(i)[0];const u=Gl.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=Ie();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&tt("'else' binding found without preceding 'if' or 'elseif' binding."),a=Jl("else",l.parseBindTextResult),p=Ql(t,h,a,m,o,!1),Cl(f,t,p);const n=c.at(-1),s=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:Fl(s),parseBindTextResults:Tl(s)})):e.replaceWith(s)}else if("elseif"===d){null===l&&tt("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ql(t,h,a,m,o),Cl(f,t,p);const n=document.createComment(`@@${u}:${f}`),s=Ie(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Jl("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Fl(n),parseBindTextResults:Tl(n)}),Cl(s,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${s}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:Fl(g),parseBindTextResults:Tl(g)})):e.replaceWith(g)}else{p=Ql(t,h,a,m,o),Cl(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 Yl=()=>`[${s.bindAttributeName}]`;function Zl(t){if(nr(t))return!0;if(!tc(t))return!1;if(t.hasAttribute(s.bindAttributeName))return!1;const e=t.querySelector(Yl());return null!==e&&nr(e)}function tc(t){return 1===t.nodeType}function ec(t){if(Zl(t))return;Y(t),Xl(t.getRootNode(),t);const e=t.hasAttribute(s.bindAttributeName),n=t.parentNode,o=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);fl(e&&o?n:t,null)}const nc=[];function oc(){const t=nc.splice(0,nc.length);for(const e of t)ec(e);!function(){const t=function(){const t=globalThis[r];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[i];return void 0===e&&(e=[],t[i]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[a];return void 0===e&&(e=new WeakSet,t[a]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const sc={protocol:"wcs-binder",version:1,bind:function(t){var e;tc(t)&&!Zl(t)&&(e=t.getRootNode(),kl.has(e)?ec(t):nc.push(t))}},rc="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let ic=0;async function ac(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++ic}\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 ${rc}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${rc}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function lc(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){tt(`Failed to load script file: ${t}`)}}class cc{_loopContextStack=Array(d).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&tt("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=d&&tt("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&&tt("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&&tt("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&&tt(`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 uc={$updatedCallback:M,$streams:B},dc=new WeakSet;function hc(t,e){let n=t;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,e);)n=Object.getPrototypeOf(n);return n}function fc(t){if((null===t||"object"!=typeof t&&"function"!=typeof t)&&tt(`The state must be an object, got ${null===t?"null":typeof t}. Check the source of the state element (json / src / the inline <script>).`),!dc.has(t)){for(const e of Object.keys(uc)){if(!(e in t))continue;const n=uc[e];n in t&&tt(`[wcs/declaration-alias] The state declares both "${e}" and "${n}". "${e}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${at}`),Object.isExtensible(t)||tt(`[wcs/declaration-alias] The state is not extensible, so the old name "${e}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${at}`);const o=hc(t,e),s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,n,{...s,configurable:!0}),o===t&&delete t[e]}dc.add(t)}}const pc=new WeakMap;function mc(t,e){let n=pc.get(t);void 0===n&&(n=new Map,pc.set(t,n));let o=n.get(e);return void 0===o&&(o=new Wo(e,t),n.set(e,o)),o}const gc=new WeakMap;function yc(t){const e=gc.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 mc(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:mc(t,n)}},set(){tt("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){tt("$command namespace is read-only; deleting from it is not allowed.")}});return gc.set(t,n),n}const bc=Symbol("wcs.notHandled"),wc=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],vc=new Map;function _c(t,e){vc.set(t,e)}const $c=new Map;let xc=[],Sc=[];function Ic(t,e){$c.set(t,e),xc=Array.from($c.values()).sort((t,e)=>t.order-e.order),Sc=xc.slice().reverse()}function Pc(t){return $c.has(t)}function kc(t,e){for(let n=0;n<xc.length;n++)xc[n].activate?.(t,e)}const Nc=new Map;class Ac{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=ot(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 Ec(t){let e;return Nc.get(t)??(Nc.set(t,e=new Ac(t)),e)}function Cc(t){"readonly"===t.mutability&&tt("This state is readonly.")}function Mc(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:oo(n.listIndex,o,n.pathInfo.wildcardCount)}function Tc(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=no(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?oo(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?oo(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}function Oc(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Lc(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!==bc)return a}}return bc}function Rc(t,e,n,o,s){if(e.pathInfo.segments[0]===W)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}(yc(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){if(null===e.parentAddress){const r=Lc(s,e,null,n,o);if(r!==bc)return r;tt(function(t,e,n){return`[${Va.binding}] Path "${t}" does not exist on the state tree.${it(t,Ua(e,"",n,e))}${at}`}(e.pathInfo.path,t,s.getterPaths))}const r=Dc(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!==c&&!(i in Object(r))){const t=Lc(s,e,Object(r),n,o);if(t!==bc)return t}if(i===c){const t=e.listIndex?.index??tt(Xa(`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()}}const jc=new WeakSet;function Wc(t){return jc.has(t)}function Dc(t,e,n,o){Tc(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!==bc)return i}}return Oc(s,e)?function(t,e,n,o,s){const r=Qn(s,e),i=function(t){return Cr.get(t)??null}(r),a=s.stateGeneration,l=e.pathInfo.lastSegment===c?void 0:Oe(e.listIndex);if(null!==i&&!1===i.dirty&&i.generation===a&&i.rowStamp===l)return i.value;const u=Rc(t,e,n,o,s);"function"!=typeof u&&Tr(r,{value:u,dirty:!1,generation:a,rowStamp:l});const d=i?.value;return Array.isArray(u)&&u!==d&&s.getterPaths.has(e.pathInfo.path)&&function(t,e,n,o,s,r){const{path:i,wildcardCount:a}=e.pathInfo;r.beginUntrack();try{for(const[l,c]of r.stateElement.dynamicDependency){const u=ot(l);if(!c.includes(i)||u.wildcardCount>a)continue;const d=Dc(t,_o(u,oo(e.listIndex,u.wildcardCount-1,a)),s,r);d===n?jc.add(e.pathInfo):d===o&&Ri(n,o)}}finally{r.endUntrack()}}(t,e,u,d,n,o),u}(t,e,n,o,s):Rc(t,e,n,o,s)}function zc(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=_o(h,r),p=Qn(n.stateElement,f),m=Cn(p),g=Dc(t,f,e,n),y=zi(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]??tt(`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())Mn(t,Array.isArray(e)?e:[]);return l}function Bc(t,e,n){const o=cn(n,e.listIndex);if(null!==o)return o;const s=Qn(t.stateElement,e),r=zi(e.listIndex,Cn(s),n);return Mn(s,Array.isArray(n)?n:[]),r.newIndexes}function Fc(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=_o(a,r),c=Bc(n,l,Dc(t,l,e,n)),u=s[i];r=c[u]??tt(`ListIndex not found at index ${u} of ${a.path}`)}return r}function Hc(t,e,n,o){"object"==typeof t&&null!==t||tt(`${V} 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&&tt(`${V} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function qc(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&tt(`${V} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Uc(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];Hc(a,n,o,i);const l=qc(a,e,n,o,i);r.has(l)&&tt(`${V} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Vc(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 Gc(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const r=Dc(t,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=e.pathInfo.lastSegment;if(i===c){const t=e.listIndex?.index;return"number"==typeof t&&t in r}return i in r}const Kc=new WeakMap;function Jc(t){return Kc.get(t)??null}function Qc(t,e){null===e?Kc.delete(t):(dn(e.listIndexes),Kc.set(t,e))}function Xc(t,e,n){const o=_o(ot(t.wildcardParentPaths[e]),n),r=Qn(t.stateElement,o),i=Cn(r),a=t.stateProxy[jn](o),l=zi(o.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 s.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)Xc(t,e+1,n)}function Yc(t,e,n,o){n?t.result.has(e)||t.quiet.add(e):t.quiet.delete(e),t.result.add(e),o.push(e)}const Zc=[];function tu(t,e,n){return"full"!==t.listExpansion&&t.listPathSet.has(e)?t.stateElement.crossRowListPaths?.has(e)?{fullRows:n.newIndexes,movedRows:null}:0===n.addIndexSet.size&&0===n.changeIndexSet.size?0===n.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:Zc,movedRows:null}:{fullRows:n.newIndexes,movedRows:null}:{fullRows:Zc,movedRows:null}:{fullRows:n.addIndexSet,movedRows:n.changeIndexSet}:{fullRows:n.newIndexes,movedRows:null}}const eu=[];function nu(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return eu;let s=null;const r=e+l;for(const t of o){if(t!==e&&!t.startsWith(r))continue;const o=ot(t);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??eu}function ou(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),t.quiet.has(a)?Or(Qn(t.stateElement,a)):n(a),i.length=0,su(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}function su(t,e,n){const o=e.pathInfo.path,s=t.quiet.has(e),r=t.staticMap.get(o);if(r)for(const i of r){const r=ot(i);if(r.lastSegment===c){const a=t.stateProxy[jn](e),l=Array.isArray(a)?a:[],c=Qn(t.stateElement,e),u=Cn(c),d=t.listPathSet.has(o);if(!d&&"diff"===t.listExpansion&&(t.keyedMergePath===o||ln(l)?.length!==l.length&&!Wi(u,l)))continue;const h=zi(e.listIndex,u,l);t.observedListValueByAbsAddress.set(c,l);const f=tu(t,o,h);for(const e of f.fullRows)Yc(t,_o(r,e),s||!d,n);for(const e of h.valueChangeIndexes??Zc)Yc(t,_o(r,e),s||!d,n);if(null!==f.movedRows){const e=nu(t,i,r);if(null===e)for(const e of f.movedRows)Yc(t,_o(r,e),s,n);else if(e.length>0)for(const o of f.movedRows)for(const r of e)Yc(t,_o(r,o),s,n)}}else Yc(t,_o(r,e.listIndex),s,n)}const i=t.dynamicMap.get(o);if(i)for(const o of i){const r=ot(o),i=[];if(r.wildcardCount>0){const n=no(e.pathInfo,r);if(r.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&tt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=oo(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const s={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:r.wildcardPaths,wildcardParentPaths:r.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Xc(s,n,o),i.push(...s.targetListIndexes)}else{null===e.listIndex&&tt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=oo(e.listIndex,n-1,e.pathInfo.wildcardCount);i.push(t)}}else i.push(null);for(const e of i)Yc(t,_o(r,e),s,n)}}function ru(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&&tt(`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,quiet:new Set};ou(d,e,a),function(t,e){for(let n=0;n<1e3;n++){const n=ei(t.stateElement);if(null===n)return;n.forEach(n=>{ou(t,_o(n.absolutePathInfo.pathInfo,n.listIndex),e)})}}(d,a);for(const[t,e]of d.observedListValueByAbsAddress)Mn(t,e);return Array.from(d.result)}function iu(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 au(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 lu(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 cu(t,e,n,o,s,r){const i=yi(t,e),a=$i(t,e);if(!i&&!a)return null;const l=[],c=du(l);return i&&_i(t,e,n,o,s).forEach(c),a&&Si(t,e,n?o:r(),s).forEach(c),l}function uu(){return s.enablePropagationContext?cs()??null:null}function du(t){const e=Gr(),n=uu();return o=>{Or(o),e.enqueueAbsoluteAddress(o,n),t.push(o)}}function hu(t,e,n){if(null===t||0===t.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=Gr(),a=uu();for(let n=0;n<t.length;n++){const l=t[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const u=_o(l.pathInfo,t[n].listIndex);ru(o,u,s,r,o.listPaths,e,"new",t=>{if(t===u)return;const e=Qn(o,t);Or(e),i.enqueueAbsoluteAddress(e,a)},{listExpansion:"diff"})}}function fu(t,e,n,o,r,i,a="diff"){const u=s.enablePropagationContext?cs()??is(-1):null,d=Gr(),h=o.stateElement;d.enqueueAbsoluteAddress(e,u),i&&Or(e);const f=e=>ru(h,e,h.staticDependency,h.dynamicDependency,h.listPaths,n,"new",e=>{if(e===t)return;const n=Qn(h,e);Or(n),d.enqueueAbsoluteAddress(n,u)},{listExpansion:a,keyedMergePath:r});if(f(t),t.pathInfo.lastSegment!==c&&null!==t.listIndex&&null!==t.listIndex.parentListIndex){const e=t.listIndex,o=t.pathInfo.wildcardParentPathInfos[e.position],s=_o(o,e.parentListIndex),r=()=>n[jn](s),i=t=>{Or(t),d.enqueueRenderOnlyAddress(t)};for(const n of function(t,e){const n=(o=t,We(Re.get(o.value),o));var o;if(0===n.length)return n;const s=new Set(Ge.get(e()));return n.filter(e=>e.position===t.position&&!s.has(e)&&!ze(e))}(e,r))i(Qn(h,_o(t.pathInfo,n)));const a=t.pathInfo.path.slice(t.pathInfo.wildcardPaths[e.position].length);for(const t of In(Qn(h,s),r())){const n=t.absolutePathInfo.pathInfo;n!==o&&n.wildcardCount===o.wildcardCount&&i(Xn(h,ot(n.path+l+c+a),e))}}const{path:p,lastSegment:m,wildcardCount:g,wildcardParentPaths:y,wildcardParentPathInfos:b}=t.pathInfo,w=t.listIndex;for(let t=0;w&&t<g;t++){const e=oo(w,t-1,g);for(const o of h.dynamicDependency.get(y[t])??[]){const s=ot(o);if(h.listPaths.has(o)&&s.wildcardCount===t&&Wc(s)&&n[jn](_o(s,e))===n[jn](_o(b[t],e))){const e=_o(ot(o+p.slice(y[t].length)),w);f(e),m===c&&d.enqueueRenderOnlyAddress(Qn(h,e.parentAddress))}}}}function pu(t,e,n,o,s){s&&(t.getterPaths.has(e)?Or(n):Tr(n,{value:o,dirty:!1,generation:t.stateGeneration,rowStamp:n.absolutePathInfo.pathInfo.lastSegment===c?void 0:Oe(n.listIndex)}))}function mu(t,e,n,o,s,r,i,a,l=!0){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const i=Dc(t,n,s,r),a=e.pathInfo.segments[e.pathInfo.segments.length-1];if(a===c){const t=e.listIndex?.index??tt(Xa(`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{l&&fu(e,n,s,r,i,a)}}function gu(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=Dc(t,e,o,s),a=function(t,e,n,o){const s=Uc(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Uc(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!==a)return function(t,e,n,o,s,r){const i=e.pathInfo.path,a=e.listIndex;null===ln(o)&&zi(a,null,o);const u=zi(a,o,n.list),d=yu(t,e,n.list,s,r,i),h=ot(i+l+c);for(const e of n.matched){const n=Vc(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const i of n)void 0!==o?gu(t,_o(ot(h.path+l+i.field),o),i.value,s,r):e.oldRow[i.field]=i.value}return d}(t,e,a,r,o,s)}}return yu(t,e,n,o,s,null)}function yu(t,e,n,o,r,i){const a=r.stateElement,u=e.pathInfo.path,d=a.addressHooks;if(d){const t=d.write;for(let s=0;s<t.length;s++){const i=t[s](a,e,n,o,r);if(i!==bc)return i}}const h=function(){const t=hs;return hs=0,t}(),f=h>1;if(!(u in t)&&null!==e.parentAddress&&!a.elementPaths.has(u)){const l=Dc(t,e.parentAddress,o,r);if("object"==typeof l&&null!==l){const t=e.pathInfo.lastSegment,h=t===c?e.listIndex?.index:t;let p,m=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==h&&h in l,e=void 0!==h?l[h]:void 0;if(t&&Object.is(e,n))return!0;p=e,m=!0}t===c&&(e=function(t,e,n,o,s){const r=e.listIndex,i=ln(n);if(i?.[o]!==r||n[o]===s)return e;const a=Ee(r.parentListIndex,o,Me(r));if(function(t){return fn.has(t)}(n)){const t=Jc(n)??{value:n.slice(),listIndexes:i};hn(t.value,t.listIndexes),mn(n,t.value)}const l=function(t){return un.has(t)}(i)?i:i.slice();l[o]=a,hn(n,l,!0),wi(i,l),Di([r]);const c=_o(e.pathInfo,a);return lu(t,Qn(t,c),Qn(t,e)),c}(a,e,l,h,n));const g=cu(a,u,m,p,n,()=>l[h]),y=Oc(a,e),b=Qn(a,e);null!==xe&&xe({type:"state:write",absoluteAddress:b,value:n,oldValue:p,hasOldValue:m}),iu(a,u,b,p,m);let w=!1;try{if(void 0===h&&tt(Xa(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),d&&0!==d.writeMissing.length&&t!==c&&!(h in l)){const t=d.writeMissing;for(let s=0;s<t.length;s++){w=!0;const i=t[s](a,e,l,h,n,o,r);if(i!==bc)return i;w=!1}}if(t!==c&&null!==e.listIndex){const o=l[h];o!==n&&(function(t,e,n,o){if(!Ge.has(t))return!1;let s=!1;for(const e in n)s||=e!==o&&n[e]===t;if(!s){let n=Je.get(e);void 0===n&&(n=new WeakSet,Je.set(e,n)),n.add(t)}const r=Ge.get(t),i=Xe.get(t);if(r[0]?.parentListIndex===e&&(!s||i?.[0]!==e||i[1]!==He))for(const n of sn.get(t)??[])if(n!==e&&n.position===e.position&&on(t,n)&&Object(Be(n))[o]===t){r.forEach(t=>Ce(t,n)),Qe.set(t,[e,He]);break}return s}(o,e.listIndex,l,t)&&Array.isArray(n)&&Ri(n,o),function(t,e){Je.get(e)?.delete(t);const n=Ge.get(t);if(void 0!==n){Xe.set(t,[e,He]);const o=Qe.get(t);o?.[0]===e&&o[1]===He&&n.forEach(t=>Ce(t,e))}}(n,e.listIndex))}return Reflect.set(l,h,n)}finally{fu(e,b,o,r,i,y),hu(g,o,r),w?Or(b):pu(a,u,b,n,y),au(a,e.pathInfo,{value:n})}}}let p,m=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=Dc(t,e,o,r);if(Gc(t,e,o,r)&&Object.is(s,n))return!0;p=s,m=!0}const g=cu(a,u,m,p,n,()=>Dc(t,e,o,r)),y=a.elementPaths.has(e.pathInfo.path),b=Oc(a,e),w=Qn(a,e);null!==xe&&xe({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:m}),iu(a,u,w,p,m);try{return y?function(t,e,n,o,s,r,i,a,u){const d=e.parentAddress??tt(`address.parentAddress is undefined path: ${e.pathInfo.path}`),h=Dc(t,d,s,r)??[],f=Jc(h);if(u)return f&&(f.value[e.listIndex.index]=o),Le(e.listIndex,o),mu(t,e,n,o,s,r,i,a);const p=e.listIndex,m=f??{value:[...h],listIndexes:ln(h)??[],written:new Map};try{return mu(t,e,n,o,s,r,i,a,!1)}finally{const t=function(t,e,n){const{value:o,listIndexes:s}=t,r=new Map;s.forEach((t,n)=>{if(e[n]!==o[n]){const e=r.get(o[n]);e?e.push(t):r.set(o[n],[t])}});let i,a=0;const l=[];for(let t=0;t<s.length;t++){const n=e[t]===o[t]?s[t]:r.get(e[t])?.shift();if(!n&&(a++?(i??=new Set(o)).has(e[t]):o.includes(e[t])))return null;l.push(n)}return l.map((t,e)=>t??Ee(n,e))}(m,h,d.listIndex);if(null===t)Qc(h,m),Le(p,o),m.written.set(p,He),function(t){tn.set(t,He)}(p),fu(e,n,s,r,i,a);else{Qc(h,null);const e=[p.index];en(p),m.written.forEach((t,n)=>{en(n),Le(n,m.value[n.index]),t===He&&e.push(n.index)}),m.written.delete(p),t.forEach((t,e)=>{t.index=e}),hn(h,t),wi(m.listIndexes,t),function(t,e,n,o,s,r,i){const a=r.stateElement,u=Gr(),d=Qn(a,t);hn(e.value,e.listIndexes),Ue(e.value),mn(n,e.value),$n(d)===n&&xn(d,e.value),u.enqueueRenderOnlyAddress(d);for(const t of In(d,n))Pn(t,n)&&u.enqueueRenderOnlyAddress(t);const h=new Map;e.listIndexes.forEach((t,e)=>h.set(t,e));const f=ot(t.pathInfo.path+l+c);for(let t=0;t<o.length;t++){const n=o[t],i=h.get(n);if(i===t)continue;const l=_o(f,n),c=Qn(a,l);if(void 0===i){const n=Xn(a,f,e.listIndexes[t]);lu(a,c,n),fu(l,c,s,r,null,Oc(a,l),"full");continue}ru(a,l,a.staticDependency,a.dynamicDependency,a.listPaths,s,"new",t=>{const e=Qn(a,t);Or(e),u.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}for(const t of i){const n=o[t];if(h.has(n)&&e.written.get(n)!==He){const o=_o(f,n),i=Qn(a,o);lu(a,i,Xn(a,f,e.listIndexes[t])),fu(o,i,s,r,null,Oc(a,o))}}}(d,m,h,t,s,r,e)}}}(t,e,w,n,o,r,i,b,h):mu(t,e,w,n,o,r,i,b)}finally{hu(g,o,r),y||pu(a,u,w,n,b),au(a,e.pathInfo,{value:n})}}function bu(t,e,n,o){return(e,s,...r)=>{Array.isArray(s)||tt(`$resolve("${e}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&tt(`$resolve("${e}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=ot(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&&tt(Ka("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=_o(i,Fc(t,n,o,i,s));if(0===r.length)return Dc(t,a,n,o);Cc(o),gu(t,a,r[0],n,o)}}function wu(t,e,n,o){const s=bu(t,0,n,o);return(e,r)=>{const i=ot(e);if(void 0===r||Array.isArray(r)||tt(`$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&&tt(Ka("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Mc(o,i.wildcardPaths[t]);if(e){r=so(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&&tt(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=zc(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 vu(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Mc(o,s.wildcardPaths.at(-1)??tt(`lastWildcardPath is null: ${e.pathInfo.path}`))??tt(`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]??tt(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=_o(i,s),l=Bc(o,a,Dc(t,a,n,o)),c=e.wildcardIndexes[r]??tt(`wildcardIndex is null: ${e.pathInfo.path}`);s=l[c]??tt(`ListIndex not found at index ${c} of ${i.path}`)}return s}case"partial":tt(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function _u(t,e,n,o){return(e,s,r,i)=>{Cc(o);const a=ot(e);Array.isArray(s)||tt(Qa(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&tt(Ka("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,u="function"==typeof r;l&&u&&tt(Qa(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&tt(Qa(e,"requires an array as the value when { spread: true } is set."));const d=zc(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&tt(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,d.length,r.length));const h=[];for(let e=0;e<d.length;e++){const s=Fc(t,n,o,a,d[e]);h.push(_o(a,s))}const f=a.lastSegment===c;let p=0;for(let e=0;e<h.length;e++){const s=f?_o(a,Fc(t,n,o,a,d[e])):h[e];let i;i=u?r(Dc(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(gu(t,s,i,n,o),p++)}return p}}function $u(t,e){if("all"===Ec(e).wildcardType)return!0;const n=t.getterPaths;if(0===n.size)return!1;for(const t of ot(e).cumulativePaths)if(n.has(t))return!0;return!1}const xu=/^\$\d+$/,Su=`${G}${l}`,Iu=`${K}${l}`,Pu=new WeakMap;function ku(t,e,n,o){const s=A[e];if(void 0===s&&"string"==typeof e&&36===e.charCodeAt(0)&&xu.test(e)&&tt(`[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&&tt(`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&&tt(`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=oo(r,i,a.wildcardCount);return c?.index??tt(`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!==bc)return i}}if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>wu(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>_u(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=Ec(e),i=vu(t,r,n,o),a=_o(r.pathInfo,i),l=Qn(s,a),c=Gr();c.enqueueAbsoluteAddress(l),function(t,e,n,o,s){const r=yi(t,e),i=$i(t,e);if(!r&&!i)return;const a=n(),l=[],c=du(l);r&&_i(t,e,!1,void 0,a).forEach(c),i&&Si(t,e,void 0,a,!1).forEach(c),hu(l,o,s)}(s,r.pathInfo.path,()=>Dc(t,a,n,o),n,o),ru(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Qn(s,t);Or(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)=>bu(t,0,n,o)(e,s,...r);case"$dependOn":case"$trackDependency":return t=>function(t,e,n,o){return t=>{-1!==t.indexOf(U)&&tt(`[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&&tt(`No active state reference to track dependency for path "${t}".`);const n=o.lastAddressStack?.pathInfo??tt("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($u(o.stateElement,t))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&gi(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)&&mi(o.stateElement,t,e,Qn(o.stateElement,s),r),Object.is(r,e)};case"$eqPath":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=$u(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?gi(o.stateElement,t):mi(o.stateElement,t,i,Qn(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||tt(`$eqIndex("${t}") needs a list row scope.`);const r=oo(s.listIndex,e-1,s.pathInfo.wildcardCount);if(null===r&&tt(`$eqIndex("${t}", ${e}): no list index at that level.`),$u(o.stateElement,t))return o.stateElement.getterPaths.has(s.pathInfo.path)&&(gi(o.stateElement,t),o.stateElement.addIndexDependentGetterPath?.(s.pathInfo.path)),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?ln(l):null;null!==e?function(t,e,n,o,s){Yr=!0,ci(t).lastValue.set(e,s),li(t,e);let r=ni.get(t);void 0===r&&ni.set(t,r=new Map);let i=r.get(e);void 0===i&&r.set(e,i=new Set);let a,l=oi.get(o);if(void 0===l?(oi.set(o,l=[]),dn(o)):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);const n=o[0]?.parentListIndex??null;if(null!==n){let t=ri.get(n);void 0===t&&ri.set(n,t=new Set),t.add(a)}}a.getters.add(n)}(o.stateElement,t,s.pathInfo,e,a):function(t,e,n,o,s){Yr=!0;const r=ci(t);li(t,e),pi(r,e,s,o,hi(r,e,n.index,o),{stateElement:t,path:e,absAddress:o,levelListIndex:n})}(o.stateElement,t,r,Qn(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 W:return yc(o.stateElement)}if(!e.startsWith(Su)&&!e.startsWith(Iu))return}const r=Ec(e),i=vu(t,r,n,o),a=_o(r.pathInfo,i);return Dc(t,a,n,o)}if("symbol"==typeof e){const s=function(t){let e=Pu.get(t);return void 0===e&&(e=new Map,Pu.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case Rn:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&tt("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 jn:i=e=>Dc(t,e,n,o);break;case Wn:i=e=>Gc(t,e,n,o);break;case Dn:i=()=>async function(t,e,n){const o=Reflect.get(t,E);"function"==typeof o&&await o.call(n)}(t,0,n);break;case zn:i=()=>function(t,e,n){const o=Reflect.get(t,C);"function"==typeof o&&o.call(n)}(t,0,n);break;case Bn:i=e=>function(t,e,n,o){const s=Reflect.get(t,M);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=so(n.listIndex,e.wildcardCount),o=i[s];void 0===o?i[s]=[t]:o.push(t)}}(t.size>0||0===e.length)&&(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 Fn: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}}class Nu{_stateElement;_addressStack=Array(d).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Il(t);null===n&&tt("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&&tt("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=d&&(this._hasRepeatedAddress()&&tt(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),tt(`[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&&tt(`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 ku(t,e,n,this)}set(t,e,n,o){return Cc(this),function(t,e,n,o,s){if("string"==typeof e){const r=Ec(e),i=vu(t,r,o,s);return gu(t,_o(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)}deleteProperty(t,e){return Cc(this),Reflect.deleteProperty(t,e)}defineProperty(t,e,n){return Cc(this),Reflect.defineProperty(t,e,n)}}const Au=Promise.resolve(),Eu=new Map;let Cu=[];function Mu(t,e){Eu.set(t,e),Cu=Array.from(Eu.values()).sort((t,e)=>t.order-e.order)}function Tu(t,e){return tt(bl(t,e))}const Ou="undefined"==typeof HTMLElement?class{}:HTMLElement;function Lu(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 Ru=null;const ju=new Set(["for","if","elseif","else"]);const Wu=[[F,"watch"],[H,"scan"],[B,"streams"],[q,"recursion"]];class Du extends Ou{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return Pl(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 cc}();_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&&tt(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){fc(t),function(t){for(let e=0;e<Wu.length;e++){const[n,o]=Wu[e];n in t&&!Pc(o)&&tt(bl(o,`"${n}"`))}}(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<xc.length;o++)xc[o].validateEarly?.(t,e,n)}(this,t,n);const o=function(t){const e=new Set,n=t[j];if(void 0===n)return e;Array.isArray(n)||tt(`${j} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||tt(`${j} entries must be non-empty strings.`),t===W&&tt(`${j} entry "${t}" conflicts with the reserved namespace name "${W}".`),e.has(t)&&tt(`${j} entry "${t}" is duplicated.`),e.add(t);return e}(t),s=function(t){const e=new Set,n=t[D];if(void 0===n)return e;Array.isArray(n)||tt(`${D} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||tt(`${D} entries must be non-empty strings.`),e.has(t)&&tt(`${D} entry "${t}" is duplicated.`),e.add(t);return e}(t),r=function(t){const e=t[V];if(void 0===e)return null;"object"==typeof e&&null!==e||tt(`${V} 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&&tt(`${V} entry path must be a non-empty string.`);const e=t.split(l);e.some(t=>0===t.length)&&tt(`${V} entry "${t}" must not contain empty path segments.`),e[e.length-1]===c&&tt(`${V} entry "${t}" must be the list path itself, not the element path (drop the trailing "${l}${c}").`),-1!==t.indexOf(U)&&tt(`[wcs/recursion-unsupported] ${V} entry "${t}" uses "${U}", which ${V} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${l}${c}${l}children").`),"function"!=typeof o?("string"!=typeof o&&tt(`${V} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&tt(`${V} entry "${t}" key field name must be a non-empty string.`),(o.includes(l)||o.includes(c))&&tt(`${V} entry "${t}" key field name "${o}" must be a flat property name ("${l}" / "${c}" are not allowed).`),o in Object.prototype&&tt(`${V} 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<xc.length;o++)xc[o].validate?.(t,e,n)}(this,t,n),function(t,e,n){for(let o=0;o<xc.length;o++)xc[o].preCommit?.(t,e,n)}(this,t,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=t,void 0!==e&&Ru?.reset(this),this._hasUpdatedCallback=M in t,this._hasErrorCallback=T in t,Lo.delete(this),function(t,e,n){for(let o=0;o<xc.length;o++)xc[o].applyEarly?.(t,e,n)}(this,t,n),function(t,e,n){const o=e[z];if(void 0!==o){"object"==typeof o&&null!==o||tt(`${z} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||tt(`${z} entry "${e}" is not declared in $eventTokens.${it(e,n)}`),"function"!=typeof s&&tt(`${z} entry "${e}" must be a function.`),Ro(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=Lu(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<xc.length;o++)xc[o].apply?.(t,e,n)}(this,t,n),this._listKeys=r,this._rebuildPathInfo(),function(t,e,n){for(let o=0;o<xc.length;o++)xc[o].register?.(t,e,n)}(this,t,n),kc(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 <${s.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?vl('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){tt("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 ac(t,s.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.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||tt(`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 lc(t);tt(`Unsupported src file type: ${t}`)}}catch(t){tt(`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&&(Al(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),tt(t)}_failInitializeLoudly(t,e=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${s.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),e&&null!==this._rootNode&&null===Il(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),$l.set(t,n)}(this._rootNode,t),function(t,e,n){for(let o=0;o<Cu.length;o++)Cu[o].initializeFailed?.(t,e,n)}(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{E in t&&await t[Dn]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{C in t&&t[zn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(t){for(let e=0;e<Cu.length;e++)if(!0===Cu[e].reconnecting?.(t))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Il(this._rootNode)===this||Al(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<Cu.length;e++){const n=Cu[e].connecting?.(t);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{Tu("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}const n=this.parentNode;if(n instanceof ShadowRoot&&n.host.hasAttribute(J))try{Tu("dcc",`a <${s.tagNames.state}> inside a [${J}] host`)}catch(t){this._failInitializeLoudly(t)}let o=!1;try{const t=function(t){for(let e=0;e<Cu.length;e++){const n=Cu[e].preparing?.(t);if(null!=n)return n}return null}(this);null===t&&this.hasAttribute("bind-component")&&Tu("scopes",'the "bind-component" attribute'),o=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(o)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 vl('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}kc(this,t),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!function(t){for(let e=0;e<Cu.length;e++)if(!0===Cu[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<Cu.length;n++)Cu[n].initializeFailureCleared?.(t,e)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Al(this.rootNode,null),gc.delete(this),function(t){for(let e=0;e<Sc.length;e++)Sc[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=>(fc(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",F)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&tt(`$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 Ha(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&&tt("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=vc.get(t);return void 0===n&&tt(bl(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<wc.length;n++){const o=wc[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",L)}_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){if(!this._addDependency(this._dynamicDependency,t,e))return!1;const n=ot(t);for(let t=n.parentPathInfo;null!==t&&t.wildcardCount>0&&t.wildcardCount===n.wildcardCount;t=t.parentPathInfo)this._addDependency(this._dynamicDependency,t.path,e);return!0}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+"."+c)),!this._pathSet.has(t)){const e=ot(t);this._pathSet.add(t);const o=function(t,e){const n=Ec(e);return"all"===n.wildcardType&&1===n.wildcardIndexes.length&&isNaN(+n.segments[0])&&!e.includes("#")&&Object.isExtensible(t)&&!(e in t)}(this.__state,t);if(Ru?.check(this,this.__state,t,n,o),o&&function(t,e){const{segments:n,cumulativePaths:o}=ot(e),s=n.length-1,r=(t,r,i)=>{let a,l=!1;for(let c=0;c<=s;c++){const u=n[c];if(l||=!(isNaN(+u)||Array.isArray(a)&&+u in a),r&&c===s)return l?a[u]=i:t[e]=i;a=l?a?.[u]:t[o[c]]}return a},i=function(){return r(this)};qa.set(i,Ec(e).pathInfo.path),t.defineTreeAccessor(e,{get:i,set(t){r(this,!0,t)},configurable:!0})}(this,t),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=ot(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 Nu(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&&tt(`<${s.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<Cu.length;e++)Cu[e].replacingState?.(t)}(this),(this._hasGraftedVolumes||this._hasMounts)&&tt("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(Lu(n)))t.startsWith("$")||t.includes(c)||"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=ot(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=Qn(t,e);if(i.has(n))return;i.add(n);const o=go(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(_o(n,e.listIndex))}};Tn();try{if(t.createState("readonly",e=>{for(const o of n){const n=_o(ot(o),null);a(n);try{ru(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)ju.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=()=>{dl(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=jr("state",s);void 0!==i&&i.catch(Ur)}finally{On()}}(this,t,this._pathRegistrations.keys())}}const zu=[],Bu=[];function Fu(){const t=[];let e=0;for(let n=0;n<Bu.length;n++){const o=Bu[n].deref();void 0!==o&&(t.push(o),Bu[e++]=Bu[n])}return Bu.length=e,t}function Hu(t,e){const n=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;n&&((i=n).tagNames&&Object.assign(o.tagNames,i.tagNames),"string"==typeof i.bindAttributeName&&(o.bindAttributeName=i.bindAttributeName),"string"==typeof i.commentTextPrefix&&(o.commentTextPrefix=i.commentTextPrefix),"string"==typeof i.commentForPrefix&&(o.commentForPrefix=i.commentForPrefix),"string"==typeof i.commentIfPrefix&&(o.commentIfPrefix=i.commentIfPrefix),"string"==typeof i.commentElseIfPrefix&&(o.commentElseIfPrefix=i.commentElseIfPrefix),"string"==typeof i.commentElsePrefix&&(o.commentElsePrefix=i.commentElsePrefix),"string"==typeof i.locale&&(o.locale=i.locale),"boolean"==typeof i.debug&&(o.debug=i.debug),"boolean"==typeof i.enableMustache&&(o.enableMustache=i.enableMustache),"boolean"==typeof i.enableDirectionalInitialSync&&(o.enableDirectionalInitialSync=i.enableDirectionalInitialSync),"boolean"==typeof i.enablePropagationContext&&(o.enablePropagationContext=i.enablePropagationContext),"boolean"==typeof i.enableContractAnalyzer&&(o.enableContractAnalyzer=i.enableContractAnalyzer),"boolean"==typeof i.sameValueGuard&&(o.sameValueGuard=i.sameValueGuard)),function(t=customElements){Fu().includes(t)||Bu.push(new WeakRef(t));for(let e=0;e<zu.length;e++)zu[e](t);t.get(s.tagNames.state)||t.define(s.tagNames.state,Du)}(e),function(){const t=globalThis;void 0===t[r]&&(t[r]=sc)}()}let qu=null;function Uu(t){return qu??tt(bl("watch",`"$watch" in <wcs-state mount="${t}">`))}let Vu=null;const Gu=Object.freeze([]),Ku="3.4.0",Ju=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Qu(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 Xu="__WCSTACK_DEVTOOLS_HOOK__";const Yu=t=>{null!==xe&&xe({type:"state:update-batch",addresses:t})};function Zu(t){const e=null!==xe;!function(t){xe=t}(t);const n=null!==t;n&&!e?qr(Yu,0):!n&&e&&function(t){const e=Wr.findIndex(e=>e.listener===t);-1!==e&&Wr.splice(e,1)}(Yu)}function td(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 ed(t){return Il(t)??tt("devtools: no state tree on this root")}let nd=null;function od(){if(e())return;if(null!==nd)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Ku,getStateElements(){const t=[];for(const e of xl)t.push(td(e));return t},overlays(t){return e=ed(t),null===Vu?Gu:Vu(e);var e},keyedSubscriptions:t=>function(t){const e=function(t){const e=Kr.get(t);return void 0===e?null:{byPath:e.byPath,lastValue:e.lastValue,tracked:e.tracked,watchers:ni.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}(ed(t)),keys(t){const e=ed(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 ed(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){ed(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,o=new Set,r=t=>{const o=function(t){const e=`${ut(t.inFilters)}\0${ut(t.outFilters)}`;return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(o.has(t))return;o.add(t);const e=Ml(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Qu(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(s.bindAttributeName);if(null===n||0===n.length)continue;try{const t=oe(e,Ot(n));for(const o of t)r(Qu(e,o,"attribute",n))}catch{}continue}const e=Ju.exec(t.data.trim());if(null===e)continue;const n=e[1]||s.commentTextPrefix,o=e[2],a=Ml(o);if(null===a){if(n===s.commentTextPrefix)try{r(Qu(t,Dt(o),"comment",o))}catch{}}else r(Qu(t,a.parseBindTextResult,"comment",o)),i(o)}return e}(t),_setSink:Zu};nd=t,function(){const t=globalThis,e=t[Xu];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[Xu]=n,n}().register(t)}const sd={name:"devtools",install(){od()}},rd=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),id=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])}),ad=new WeakMap,ld=new WeakMap,cd=new WeakSet,ud=new WeakMap;function dd(t,e,n,o){console.warn(`[@wcstack/state] [${Va[n]}] ${Ga[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${it(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${at}`),null!==xe&&xe({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const hd={check:function(t,e,n,o,s){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const r=t.addressHooks;if(r){const e=r.suppressPathDiagnostic;for(let o=0;o<e.length;o++)if(e[o](t,n))return}const i=ot(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=ad.get(t);return void 0===n&&(n=new Set,ad.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const a=function(t,e,n,o){if(void 0!==Ha(t,e))return id;const s=ot(e).segments;let r=t,i="";for(let e=0;e<s.length;e++){const a=o&&Array.isArray(r)&&+s[e]>=0?c:s[e],u=i;i=0===e?a:i+l+a;const d=e>0&&Ha(t,i),h=d&&qa.get(d.get);if(d&&(!h||Ha(t,h)))return e<s.length-1?rd:id;if(Object(r)!==r)return rd;if(a===c){if(!Array.isArray(r)||0===r.length)return rd;r=r[0];continue}const f=Ha(r,a);if(void 0===f)return{existence:"missing",missingSegment:a,candidates:Ua(r,u,n,t)};if("function"==typeof f.get)return e===s.length-1?id:rd;r=f.value}return id}(e,n,t.getterPaths,s);"missing"===a.existence&&(function(t,e){return!0===ud.get(t)?.has(e)}(t,n)||("binding"!==o?dd(0,n,o,a):function(t,e,n){let o=ld.get(t);void 0===o&&(o=new Map,ld.set(t,o)),o.set(e,n),cd.has(t)||(cd.add(t),setTimeout(()=>function(t){cd.delete(t);const e=ld.get(t);if(void 0!==e){ld.delete(t);for(const[t,n]of e)dd(0,t,"binding",n)}}(t),0))}(t,n,a)))},reset:function(t){ad.delete(t),ld.delete(t)},markExported:function(t,e){let n=ud.get(t);void 0===n&&(n=new Set,ud.set(t,n)),n.add(e),ld.get(t)?.delete(e)}};let fd=!1;const pd={name:"diagnostics",install(){fd||(fd=!0,Ru=hd)}};function md(t){tt(`filter ${t} requires at least one option`)}function gd(t){tt(`filter ${t} requires a number as option`)}function yd(t){tt(`filter ${t} requires a number value`)}function bd(t){tt(`filter ${t} requires a date value`)}const wd={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function vd(t){return!(!t||isNaN(Number(t)))}function _d(t,e){return vd(t)||gd(e),Number(t)}function $d(t,e,n){return _d(t?.[e]??md(n),n)}const xd=t=>e=>{const n=t(e);return t=>null==t?t:n(t)},Sd={eq:(t,e)=>{const n=t?.[0]??md("eq"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t===o:(vd(n)||gd("eq"),t===Number(n)):"string"==typeof t?t===n:t===o},ne:(t,e)=>{const n=t?.[0]??md("ne"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t!==o:(vd(n)||gd("ne"),t!==Number(n)):"string"==typeof t?t!==n:t!==o},not:t=>t=>!t,lt:t=>{const e=$d(t,0,"lt");return t=>("number"!=typeof t&&yd("lt"),t<e)},le:t=>{const e=$d(t,0,"le");return t=>("number"!=typeof t&&yd("le"),t<=e)},gt:t=>{const e=$d(t,0,"gt");return t=>("number"!=typeof t&&yd("gt"),t>e)},ge:t=>{const e=$d(t,0,"ge");return t=>("number"!=typeof t&&yd("ge"),t>=e)},add:t=>{const e=$d(t,0,"add");return t=>("number"!=typeof t&&yd("add"),t+e)},sub:t=>{const e=$d(t,0,"sub");return t=>("number"!=typeof t&&yd("sub"),t-e)},mul:t=>{const e=$d(t,0,"mul");return t=>("number"!=typeof t&&yd("mul"),t*e)},div:t=>{const e=$d(t,0,"div");return t=>("number"!=typeof t&&yd("div"),t/e)},mod:t=>{const e=$d(t,0,"mod");return t=>("number"!=typeof t&&yd("mod"),t%e)},abs:t=>t=>("number"!=typeof t&&yd("abs"),Math.abs(t)),clamp:t=>{const e=$d(t,0,"clamp"),n=$d(t,1,"clamp");return t=>("number"!=typeof t&&yd("clamp"),Math.min(Math.max(t,e),n))},toFixed:t=>{const e=_d(t?.[0]??"0","toFixed");return t=>("number"!=typeof t&&yd("toFixed"),t.toFixed(e))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&yd("locale"),t.toLocaleString(e??s.locale))},upper:xd(t=>t=>String(t).toUpperCase()),lower:xd(t=>t=>String(t).toLowerCase()),capitalize:xd(t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)}),trim:xd(t=>t=>String(t).trim()),slice:xd(t=>{const e=[$d(t,0,"slice")],n=t?.[1];return void 0!==n&&e.push(_d(n,"slice")),t=>String(t).slice(...e)}),substr:xd(t=>{const e=$d(t,0,"substr"),n=$d(t,1,"substr");return t=>String(t).substr(e,n)}),padStart:xd(t=>{const e=$d(t,0,"padStart"),n=t?.[1]??"0";return t=>String(t).padStart(e,n)}),padEnd:xd(t=>{const e=$d(t,0,"padEnd"),n=t?.[1]??" ";return t=>String(t).padEnd(e,n)}),repeat:xd(t=>{const e=$d(t,0,"repeat");return t=>String(t).repeat(e)}),reverse:xd(t=>t=>String(t).split("").reverse().join("")),truncate:xd(t=>{const e=$d(t,0,"truncate"),n=t?.[1]??"…";return t=>{const o=String(t);return o.length<=e?o:o.slice(0,e)+n}}),join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||tt("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=Math.pow(10,_d(t?.[0]??"0","round"));return t=>("number"!=typeof t&&yd("round"),Math.round(t*e)/e)},floor:t=>{const e=Math.pow(10,_d(t?.[0]??"0","floor"));return t=>("number"!=typeof t&&yd("floor"),Math.floor(t*e)/e)},ceil:t=>{const e=Math.pow(10,_d(t?.[0]??"0","ceil"));return t=>("number"!=typeof t&&yd("ceil"),Math.ceil(t*e)/e)},percent:t=>{const e=_d(t?.[0]??"0","percent");return t=>("number"!=typeof t&&yd("percent"),`${(100*t).toFixed(e)}%`)},unit:xd(t=>{const e=t?.[0]??md("unit");return t=>String(t)+e}),date:t=>{const e=t?.[0];return t=>(t instanceof Date||bd("date"),t.toLocaleDateString(e??s.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||bd("time"),t.toLocaleTimeString(e??s.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||bd("datetime"),t.toLocaleString(e??s.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||bd("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||bd("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]??md("defaults"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t||o},coalesce:(t,e)=>{const n=t?.[0]??md("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},Id={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:[2,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,1],time:[0,1],datetime:[0,1],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]},Pd=Sd,kd=Sd;let Nd=!1;const Ad={name:"formats",install(){Nd||(Nd=!0,yt("input",kd,Id,wd),yt("output",Pd,Id,wd))}};function Ed(t){return-1!==t.indexOf(U)}function Cd(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+l;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(Ed(o))return null;const s=o.slice(1).split(l);return s[0]===c||s.some(t=>0===t.length)?null:o}function Md(t){return 0===t.length?t:l+Ld(t.slice(1))}function Td(t,e,n){const o=l+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 Od(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(l,o-1))if(Td(t,e,n.slice(0,o)))return!0;return!1}function Ld(t){const e=t.split(l);for(let t=0;t<e.length;t++)e[t]===c||Number.isNaN(Number(e[t]))||(e[t]=c);return e.join(l)}function Rd(t,e){const n=t.repeat.split(l),o=l+t.repeat;let s=e;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===l+t.repeatList+l+"length")return!0;for(let t=1;t<n.length;t++)if(s===l+n.slice(0,t).join(l))return!0;return!1}function jd(t,e,n){n<0&&tt(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=l+t.repeat;const s=o+e;let r=0;for(const t of s.split(l))t===c&&r++;return r>u&&tt(`[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 Wd(t,e){return jd(t,"",e)}function Dd(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=l+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 zd(t,e,n){const o=t.recursionRegistry,s=Cd(o.spec,n);null===s&&tt(Ja(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=l+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&&tt(`[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 Bd(t,e,n,o,s){const r=o.spec,i=[],a=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(_o(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 l=_o(o,s),c=Qn(n.stateElement,l),d=Dc(t,l,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)&&tt(`[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)&&tt(`[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=zi(s,Cn(c),d);return a.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:a}=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:ot(n),childListPathInfo:ot(r+l+u)};return c[t]=i,i})(t),y=a;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(_o(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,ot(d),null);for(const[t,e]of a)Mn(t,e);return i}const Fd={write(t,e){if(!0!==t.hasRecursion)return bc;const n=t.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);return null!==n&&tt(`[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.`),bc},get(t,e,n,o){if(!0!==t.stateElement.hasRecursion)return bc;if("$getAll"===e)return(e,s)=>{if(Ed(e)){if(void 0!==s)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=Cd(r.spec,o);null===i&&tt(Ja(o,r.spec.recursiveAnchor)),Array.isArray(s)||tt(`[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&&tt(`[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=Bd(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Dc(t,a[o],e,n));return l}(o,n,t,e,s);e=zd(t.stateElement,t,e)}return wu(o,0,n,t)(e,s)};if("$setAll"===e)return(e,s,r,i)=>Ed(e)?function(t,e,n,o,s,r,i){Cc(n);const a=n.stateElement.recursionRegistry,l=Cd(a.spec,o);null===l&&tt(Ja(o,a.spec.recursiveAnchor));const c=Md(l);Array.isArray(s)||tt(Qa(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&tt(`[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&&tt(Qa(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&tt(Qa(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){Rd(t,n)&&tt(`[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&&tt(`[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=Bd(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(gu(t,d[o],r,e,n),h++);return h}(o,n,t,e,s,r,i):_u(o,0,n,t)(e,s,r,i);if(36!==e.charCodeAt(0)&&Ed(e)){const s=Ec(zd(t.stateElement,t,e)),r=vu(o,s,n,t);return Dc(o,_o(s.pathInfo,r),n,t)}return bc}};let Hd=!1;function qd(t,e){"string"==typeof e&&0!==e.length||tt(`[wcs/recursion-declaration-invalid] ${q} ${t} must be a non-empty string.`);const n=e.split(l);n.some(t=>0===t.length)&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain empty path segments.`),n.length<2&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must name a list element: a property path ending with "${l}${c}" (for example "nodes${l}${c}").`),n[n.length-1]!==c&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must end with "${l}${c}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===c&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must have exactly one "${c}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===U&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain "${U}" — the declaration is what gives "${U}" its meaning.`),isNaN(Number(n[o]))||tt(`[wcs/recursion-declaration-invalid] ${q} ${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 Ud=new WeakSet;function Vd(t){return"function"==typeof t.get&&Ud.has(t.get)}const Gd="[wcs/recursion-declaration-invalid]";class Kd{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=Lu(e);for(const[e,o]of Object.entries(n)){if(!Ed(e))continue;"function"==typeof o.set&&tt(`${Gd} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&tt(`${Gd} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Cd(t,e);null===n&&tt(Ja(e,t.recursiveAnchor)),0===n.length&&tt(`${Gd} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${l}total"), not the node.`),Rd(t,Md(n))&&tt(`${Gd} "${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}${l}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(Ed(e)||Vd(n))continue;const t=this._matchExpansion(e);null!==t&&tt(`${Gd} "${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++)Td(this.spec,t[e].suffix,t[n].suffix)&&tt(`${Gd} "${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(Od(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=Ld(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(l);null===s&&t>this.spec.anchor.length;t=n.lastIndexOf(l,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!==Dd(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=Dd(this.spec,t.suffix,e);null!==n&&(null!==o&&tt(`"${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||Vd(s)||tt(`"${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,Ud.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(Wd(t,o)+l+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&&Vd(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))}}}}(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=jd(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 Jd="recursionSpec",Qd="recursionRegistry",Xd={order:5,validateEarly(t,e,n){const o=function(t){const e=t[q];if(void 0===e)return null;"object"==typeof e&&null!==e||tt(`[wcs/recursion-declaration-invalid] ${q} 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&&tt(`[wcs/recursion-declaration-invalid] ${q} must declare exactly one anchor; it is empty.`),n.length>1&&tt(`[wcs/recursion-declaration-invalid] ${q} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];qd("anchor",o),"string"!=typeof s&&tt(`[wcs/recursion-declaration-invalid] ${q} entry "${o}" must map to the repeating sub-path as a string (for example "children${l}${c}").`),qd("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(l)),i=s.slice(0,s.lastIndexOf(l)),a=r+l+U;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(e);n.set(Jd,o),n.set(Qd,null===o?null:new Kd(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(Qd)??null;t.setRecursionRegistry?.(s),null!==s&&t.attachAddressHooks?.("recursion",q)},apply(t,e,n){const o=n.get(Jd)??null;null!==o&&t.addListPath(o.anchorList)}};let Yd=!1;const Zd={name:"recursion",install(){Yd||(Yd=!0,Hd||(Hd=!0,_c("recursion",Fd)),Ic("recursion",Xd))}},th={written:function(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1&&-1===e.path.indexOf("#")?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 eh=!1;function nh(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 oh(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 sh(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 rh(t){return t.startsWith("$")}function ih(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 ah(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||tt(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||tt(`${e} entries must be non-empty strings.`),t.startsWith("$")&&tt(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&tt(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function lh(t,e,n){const o=t.tagName.toLowerCase();o.includes("-")||tt(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const r=Kt(t);null!==r&&"function"==typeof r.define||tt(`DCC: CustomElementRegistry is unavailable for "${o}".`),r.get(o)&&tt(`DCC: "${o}" 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){fc(t);const e=ah(t,L)??[],n=ah(t,R)??[],o=Lu(t),s=function(t){const e=t[B];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}tt(`${L} entry "${t}" is not declared on the state.${it(t,ih(o,"value"))}`)}"function"==typeof e.value&&tt(`${L} entry "${t}" is a method. Declare it in ${R} instead.`)}for(const t of n){const e=o[t];void 0===e&&tt(`${R} entry "${t}" is not declared on the state.${it(t,ih(o,"method"))}`),"function"!=typeof e.value&&tt(`${R} entry "${t}" is not a method. Declare it in ${L} 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}}(o,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(o,c):{},p=s.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(J))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=Kt(this._shadow);return null!==t&&Jt(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?(eh||(eh=!0,_c("dcc",th)),e.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${L} but its template has no <${s.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=Lu(n);for(const[t,e]of Object.entries(g)){if(rh(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=sh(t,o)}else n.get=nh(t),n.set=oh(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:nh(t),set:oh(t)});r.define(o,m)}const ch={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(J)?async function(t,e,n){const o=t;try{o.hasAttribute("bind-component")&&tt(`"bind-component" cannot be used inside a [${J}] 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 lc(e);tt(`DCC: Unsupported src type: ${e}`)}const n=t.querySelector('script[type="module"]');if(n)return await ac(n,e.tagName.toLowerCase());tt(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}catch(t){tt(`DCC: Failed to load state: ${t}`)}}(o,e);lh(e,n,s),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}(t,e.host,e):null}};let uh=!1;function dh(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 hh(t,e){for(const n of t)if(dh(e,n.innerSegments))return n;return null}function fh(t,e){const n=e.slice(t.innerSegments.length);return 0===n.length?t.outerPathInfo.path:t.outerPathInfo.path+l+n.join(l)}const ph=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function mh(t,e,n){const o=ph.get(t);return void 0===o?null:(...t)=>{const s=t.slice();for(let t=0;t<o.length;t++){const n=o[t];"string"==typeof s[n]&&(s[n]=e(s[n]))}return n(s)}}const gh=new WeakMap;function yh(t,e,n){let o=gh.get(t);void 0===o&&(o=new Map,gh.set(t,o));null!=o.get(e)&&tt(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function bh(t,e){if(null===t)return!1;const n=gh.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+l)||t.startsWith(e+l))return!0;return!1}const wh=new WeakMap,vh=[];function _h(t,e,n,o){if(e.length>0){const s=n.split(l),r=hh(e,s);if(null!==r)return o&&r.readonly&&tt(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${x}.${r.innerSegments.join(l)}#${g}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${g} from the injection.`),fh(r,s)}return t+l+n}function $h(t,e,n){let o=-1,s=null;for(const t of e){const e=t.outerPathInfo.path;e.length<=o||(n===e?(o=e.length,s=t.innerSegments.join(l)):n.startsWith(e+l)&&(o=e.length,s=t.innerSegments.join(l)+n.slice(e.length)))}if(t.length>o){if(n===t)return"";if(n.startsWith(t+l))return n.slice(t.length+1)}return s}function xh(t,e,n=vh){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](_h(t,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>e.$setAll(_h(t,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>e.$resolve(_h(t,n,o,s.length>1),...s);const o=mh(s,e=>_h(t,n,e,!1),t=>e[s](...t));return null!==o?o:e[s]}return e[_h(t,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(e[s]=r,!0):(e[_h(t,n,s,!0)]=r,!0)),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Sh=new WeakMap,Ih=[],Ph=new WeakMap,kh=new WeakSet;function Nh(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 Ah=null,Eh=0;const Ch=["$watch",B,"$scan","$listKeys",M,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Mh=new Set;function Th(t,e,n){const o=t.stateObject[e];if("function"==typeof o)try{const s=o.call(n());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 Oh(t){const e=t.indexOf(l);return-1===e?t:t.slice(0,e)}function Lh(t,e){const n=hh(t.entries,e);return null===n?null:fh(n,e)}function Rh(t,e){return t.markerBasePath+l+e}function jh(t,e,n,o){let s=t.accessorBySuffixByMarkerParent.get(e);void 0===s&&(s=new Map,t.accessorBySuffixByMarkerParent.set(e,s));const r=e+l+n;s.set(n,{accessorName:o,indexShift:ot(r).wildcardCount-ot(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(r),t.addedGetterPaths.add(r))}function Wh(t,e){return!t.injectedKeys.has(e)&&(!t.getterKeys.has(e)&&"function"==typeof t.stateObject[e]||!t.mappedKeys.has(e)&&Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function Dh(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(l)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${Oh(e)}: path") or declare the key on the component state.`}const zh=/^\$(\d+)$/;function Bh(t,e){if(!t.hasReadonlyEntries)return null;const n=e[0];if("$"===n||"#"===n)return null;if(t.getterKeys.has(e)||t.setterKeys.has(e))return null;const o=Oh(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||Wh(t,o))return null;const s=function(t,e){return hh(t.entries,e)}(t,e.split(l));return null!==s&&s.readonly?s:null}function Fh(t,e){const n=Bh(t,e);if(null!==n){const o=0===n.innerSegments.length?"":l+n.innerSegments.join(l);tt(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${g}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${g} from the mount.`)}return Hh(t,e)}function Hh(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(l);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===c){o=t;break}if(-1===o)return jh(t,t.markerBasePath,e,e),Rh(t,e);if(Wh(t,n[0]))return jh(t,t.markerBasePath,e,e),Rh(t,e);const s=n.slice(0,o+1),r=n.slice(o+1),i=Lh(t,s);null===i&&tt(Dh(t,e)),0===r.length&&tt(`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 a=i+l+t.marker;return jh(t,a,r.join(l),e),a+l+r.join(l)}(t,e);const o=Oh(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return Rh(t,e);if(Wh(t,o))return Rh(t,e);const s=Lh(t,e.split(l));if(null!==s)return s;tt(Dh(t,e))}const qh=new Set(["prop","radio","checkbox"]);function Uh(t,e,n,o,s){if(void 0===o)return;const r=ot(n).wildcardCount-ot(e).wildcardCount;return 0===r?o:(s.length<r&&tt(`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])}function Vh(t,e,n){if(-1!==t.indexOf(c))return e;const o=e.split(l);let s=0;for(let t=0;t<o.length&&s<n.length;t++)o[t]===c&&(o[t]=String(n[s++]));return o.join(l)}const Gh=new WeakMap,Kh=new WeakMap,Jh=new WeakMap,Qh=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)}),Xh=new WeakMap;function Yh(t){return Xh.get(t)??null}let Zh=!1;function tf(t){return Gh.get(t)??null}function ef(t){return nf(t).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join(l),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]}))}function nf(t){const e=Jh.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 of(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=Jh.get(t);if(void 0===o)return null;const s=e.indexOf(l,n),r=-1===s?e.slice(n):e.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const sf=new WeakMap,rf=new Set;function af(t,e,n,o){let s=sf.get(t);if(void 0===s){if(!o)return null;s=new Map,sf.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 lf(t,e){if(!t.component.isConnected)return!1;const n=_e(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 cf(t,e,n,o){const s=af(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&&lf(n,e)?n:null}(r,o);if(null!==t)return{record:t,entry:r.entry}}let i=null,a=null;for(const t of s.holders){const r=t.ref.deref();void 0!==r?lf(r,o)&&(null!==a&&tt(`[wcs/mount-export-ambiguous] "${e}${l}${n}" is exported by two mounted components on the same instance: <${a.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,a=r):s.holders.delete(t)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function uf(t){const e=t.parentStateElement,n=_e(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[Rn](n,()=>{t.$postUpdate(o.exportedPath)})})}const df=new WeakMap,hf=new WeakMap,ff=new WeakMap,pf=new WeakMap;function mf(t,e){hf.set(t,e);const n=[];for(let t=e?.listIndex.parentListIndex??null;null!==t;t=t.parentListIndex)n.push(t);pf.set(t,n)}function gf(t){return _e(t.component)??hf.get(t)??null}function yf(t){return gf(t)?.listIndex??null}function bf(t){tt(`The host row of <${t.component.tagName.toLowerCase()}> was removed.`)}function wf(t){for(;null!==t;t=t.parentListIndex)if(Ke(t))return!0;return!1}function vf(t,e){return!t.component.isConnected&&(wf(e)||!0===pf.get(t)?.some(t=>Ke(t)))}class _f{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(t,e,n,o,s,r,i,a=!1){this.record=t,this.markerParentPath=e,this.listIndex=n,this.hostRow=o,this.isBase=s,this.receiver=r,this.handler=i,this.authorFacing=a}authorThis(t,e){return this.authorFacing?e:new Proxy(t,new _f(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return _o(ot(this.markerParentPath+l+t),this.listIndex)}hostIndexes(){const t=this.listIndex??yf(this.record),e=this.hostRow??t;return(null===this.listIndex?e!==t||vf(this.record,e):wf(e))&&bf(this.record),e?.indexes??[]}resolveTreePath(t,e){return-1===e.indexOf(c)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==Ec(e).wildcardType&&!vf(this.record,this.listIndex)?e:Vh(t,e,this.hostIndexes())}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(this.resolveTreePath(t,Hh(this.record,t)))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.hostIndexes(),o=this.receiver,s=this.handler,r=this.listIndex;if("$resolve"===e)return(e,s,...r)=>{const i=r.length>0?Fh(t,e):Hh(t,e),a=Uh(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const i=e;return(e,a,...l)=>{const c="$setAll"===i?Fh(t,e):Hh(t,e),u=Uh(0,e,c,void 0===a&&"$getAll"===i&&null===r&&null===Mc(s,ot(c).wildcardPaths[0])?[]:a,n);return o[i](c,u,...l)}}const t=this.record,n=this.receiver,o=mh(e,e=>this.resolveTreePath(e,Hh(t,e)),t=>n[e](...t));return null!==o?o: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 Tc(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(this.authorThis(t,n))}return this.receiver[this.resolveTreePath(e,Hh(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)||tt(`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,this.authorThis(t,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(t,e)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress(_o(ot(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+l+e]=n}finally{this.handler.popAddress()}return!0}return t[e]=n,!0}return this.receiver[this.resolveTreePath(e,Fh(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 Hh(this.record,e),!0}catch{return!1}}}function $f(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=df.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},df.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 _f(t,s,e.listIndex,e.listIndex??yf(t),r,n,o))}function xf(t){if(null===yf(t))return t.component[t.stateProp];let e=ff.get(t);if(void 0===e){const n={row:null};ff.set(t,e=[Sf(t,n),n])}return e[0]}function Sf(t,e){const n=()=>{const n=gf(t);return void 0!==e&&ff.get(t)?.[0]!==i&&n.listIndex!==e.row&&bf(t),n},o=()=>{const e=n();return vf(t,e?.listIndex??null)&&bf(t),e?.listIndex.indexes??[]},s=(e,n)=>-1===n.indexOf(c)?n:"partial"===Ec(n).wildcardType?Vh(e,n,o()):-1===n.indexOf("#")&&vf(t,yf(t))?bf(t):n,r=(e,o)=>{let s;const r=n();return t.parentStateElement.createState(e,t=>{s=t[Rn](r,()=>o(t))}),s},i=new Proxy({},{get(e,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(t,e,n,o,s){return"$postUpdate"===e?e=>n("readonly",n=>n.$postUpdate(s(e,Hh(t,e)))):(s,r,...i)=>{const a="$setAll"===e||"$resolve"===e&&i.length>0,l=a?Fh(t,s):Hh(t,s),c=Uh(0,s,l,"$resolve"===e?r??[]:r,o());return n(a?"writable":"readonly",t=>t[e](l,c,...i))}}(t,n,r,o,s);const i=mh(n,e=>s(e,Hh(t,e)),t=>r("readonly",e=>e[n](...t)));if(null!==i)return i;const a=e=>e["$"===n[0]?n:s(n,Hh(t,n))],l=r("readonly",a);return"$"===n[0]||t.getterKeys.has(n)||"function"!=typeof t.stateObject[n]?l:function(...t){return r("writable",e=>a(e).apply(this,t))}},set:(e,n,o)=>("string"==typeof n&&r("writable",e=>{e["$"===n[0]?n:s(n,Fh(t,n))]=o}),!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 Hh(t,n),!0}catch{return!1}}});return i}function If(t,e){const n=tf(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&tt(`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&&mr(e).dispose(),function(t,e){Zh||(Zh=!0,ve=t=>Gh.has(t)?t.host:null),Gh.set(t,e),Xh.set(e,t);let n=Jh.get(e.parentStateElement);void 0===n&&(n=new Map,Jh.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=Kh.get(e.component);void 0===o&&(o=new Map,Kh.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&Qh.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=_l.get(t);if(void 0!==n){if(n===e)return;tt("A state tree is already registered on this root.")}_l.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const s=zh.exec(e.statePathName);if(null!==s){const r=function(t,e){return void 0===e?t.delta:ot(Hh(t,e)).wildcardCount-ot(e).wildcardCount}(t,n);o=0===r?e.statePathName:`$${Number(s[1])+r}`}else if(o=Hh(t,e.statePathName),"for"===e.bindingType){const n=ot(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+l+c,n)}const r=e.propModifiers,i=null===s&&Array.isArray(r)&&qh.has(e.bindingType??"")&&!r.includes(g)&&null!==Bh(t,e.statePathName);return o!==e.statePathName||i?{...e,statePathName:o,statePathInfo:ot(o),...i?{propModifiers:[...r,g]}:{}}:e}(t,e,n);Y(e);const o=_e(t.component);mf(t,o),Xl(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),fl(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=Hh(t,n)}catch{continue}const o=e.indexOf(l+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)+l+r,a=ot(i);if(a.wildcardCount!==t.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:e,exportedPath:i};t.exports.set(i,c),af(t.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,i),Ru?.markExported(t.parentStateElement,i)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=_e(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(rf.has(s))continue;const r=ot(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[Rn](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(rf.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),uf(t),o=e,s=Promise.resolve(),$l.set(o,s),s.then(()=>Nl(o),()=>{})}function Pf(t,e){dl(kf(t,e).rebindAddresses()),uf(t)}function kf(t,e){const n=mr(e),o=_e(t.component);return mf(t,o),n.forEachActiveBindingNode(t=>$e(t,o)),n}function Nf(t){for(let e=t.parentNode;null!==e;e=e.parentNode){const t=tf(e);if(null!==t)return Nf(t.component),void kf(t,e)}}function Af(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 Ef={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const s=of(t,e.pathInfo.path);if(null!==s)return $f(s,e,n,o)}return bc},readMissing(t,e,n,o,s){if(null===n){if(bh(t.rootNode??null,e.pathInfo.path))return;return bc}if(!0===t.hasMounts){const n=cf(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s){const r=$f(t,_o(ot(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(n.record,n.entry,e.listIndex,o,s)}return bc},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=wh.get(t);if(void 0===n||0===n.size)return null;const o=e+l;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&tt(`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 bc},writeMissing(t,e,n,o,s,r,i){if(!0===t.hasMounts){const n=cf(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s,r){const i=$f(t,_o(ot(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(n.record,n.entry,e.listIndex,s,r,i)}return bc},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=of(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(l,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=Gh.get(n);if(void 0!==t)return t;n=n.parentNode}return Gh.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 Sh.get(t)??Ih}(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=$h(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=so(n.listIndex,a);(r[i]??=[]).push(t)}}if(o.size>0)try{s.callback.call(xh(s.mountPath,n,s.injections),Array.from(o),r)}catch(t){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>bh(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(function(t){const e=Jh.get(t);return void 0!==e&&e.size>0}(e))for(const n of nf(e)){if(!Af(n.component,t))continue;const e=Yh(n);null!==e&&Pf(n,e)}}(e,t)}};let Cf=!1;const Mf=new WeakMap;function Tf(t){let e=Mf.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Mf.set(t,e)),e}function Of(t,e){null!==e.slotRootNode&&(function(t,e,n){const o=gh.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function Lf(t,e,n){if(e.slotRootNode===n)return!0;const o=e.mountPath;try{yh(n,o,t)}catch{return console.error(`[@wcstack/state] <${s.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return Il(n)?.markHasVolume?.(),e.slotRootNode=n,!0}const Rf={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=Tf(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{yh(n,e.mountPath,t),Il(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,Au}return async function(t,e){const n=t,o=t.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(t){0===t.length&&tt('"mount" requires a non-empty tree path.');const e=ot(t);for(const n of e.segments)0===n.length&&tt(`"mount" path "${t}" has an empty segment.`),n===c&&tt(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&tt(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),i=function(t,e){const n=[],o=new Set;let r;try{r=Ot(t)}catch(t){tt(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${e}"> has an invalid ${s.bindAttributeName}: ${t instanceof Error?t.message:String(t)}`)}for(const t of r){if(t.propSegments[0]!==x)continue;const r=t.propSegments.slice(1),i=t.statePathInfo,a=n=>tt(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${e}"> "${t.propName}: ${t.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==c&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${x}.<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)."),(t.inFilters.length>0||t.outFilters.length>0)&&a("an injection takes no filters."),t.propModifiers.some(t=>t!==g)&&a(`an injection accepts only #${g}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:t.propModifiers.includes(g)})}return n.sort((t,e)=>e.innerSegments.length-t.innerSegments.length),n}(n.getAttribute(s.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&tt('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${s.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),yh(o,r,t),Il(o)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=o}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===Il(o)&&function(t,e){const n=()=>{if(null!==Il(t))return;const n=t.querySelectorAll(s.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${s.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${s.tagNames.state}> to this root node (an empty <${s.tagNames.state}></${s.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=t.ownerDocument??t;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&Of(t,e),t.settleInitialization()};let l;try{await Promise.resolve(),l=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&&Lf(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?(lp(),function(t,e){if(kh.has(t))return void Nh(e);let n=Ph.get(t);void 0===n&&(n=[],Ph.set(t,n)),n.push(e)}(t,a)):ip(e,a)}(u,Il(u),r,l,a,()=>Lf(t,e,u),i):a(null)}(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=Tf(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&Il(n)===e.graftInfo.rootStateElement&&sp(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==Mf.get(t)?.initializing)return;const e=t.getAttribute("mount");tt(`Cannot replace the state of <${s.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){kh.add(t);const e=Ph.get(t);if(void 0!==e){Ph.delete(t);for(const t of e)Nh(t)}}(e)},initializeFailureCleared(t,e){!function(t){kh.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=Tf(t);return null!==e.graftInfo&&sp(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,Of(t,e)),t.clearConnectedRootNode(),!0}};let jf=!1;const Wf=new WeakMap;function Df(t,e){let n=Wf.get(t);n||(n=new Set,Wf.set(t,n)),n.add(e)}const zf=new WeakMap,Bf=new WeakMap,Ff=new WeakMap,Hf=new WeakMap,qf={isComplete:function(t,e){return!0===Wf.get(t)?.has(e)},isDeclared:function(t,e){return!0===zf.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=Bf.get(t);o||(o=new Map,Bf.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=Ff.get(t);o||(o=new Map,Ff.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=Hf.get(t);s||(s=new Map,Hf.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}};const Uf=new WeakMap;class Vf{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=Uf.get(t);return n?n.get(e)??null:null}(t,e)??tt("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 Gf=t=>()=>t;function Kf(t,e,n,o){!function(t,e,n){let o=Uf.get(t);o||(o=new Map,Uf.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 Vf(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:Gf(s),enumerable:!0,configurable:!0}),Df(e,n),Jf(e,n)}function Jf(t,e){if(O in t){const n=t[O];"function"==typeof n?n.call(t,e).catch(t=>{tt(`Error in ${O}: ${t instanceof Error?t.message:String(t)}`)}):tt(`${O} is not a function.`)}}const Qf=new Set;function Xf(t,e){Qf.has(t)||(Qf.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Yf(t){const e=t.rootEntry,n=_e(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Rn](n,()=>{o=t[e.outerPathInfo.path]})}),o}const Zf=new WeakMap;function tp(t,e){t.landInitialization(),tt(e)}async function ep(t,e){const n=t;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,c=a?Vt(a):null;null!==a&&null!==c||tt(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(s.bindAttributeName)||tp(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&&tt(`"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=zf.get(t);n||(n=new Set,zf.set(t,n)),n.add(e)}(a,d);const h=Kt(a);null===h&&tt(`CustomElementRegistry is unavailable for <${c}>.`),await h.whenDefined(c.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await Ht(a),d in a||tt(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||tt(`Component property "${d}" is not an object for state binding.`);const p=function(t,e){const n=Bf.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,d);if(void 0!==p&&function(t,e){if(!t.hasAttribute(s.bindAttributeName))return!1;const n=le(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,d)&&(a[d]=p,f=p),e.boundComponent=a,e.boundComponentStateProp=d,t.setBoundComponent(a,d),i instanceof ShadowRoot||(le(a)??[]).some(t=>t.propSegments[0]===d)||tp(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").`),a.hasAttribute(s.bindAttributeName)){const s=(le(a)??[]).filter(t=>t.propSegments[0]===d);if(s.length>0){const u=Il(a.getRootNode())??tp(t,`No state tree found on this root for mount host <${c}>.`);let h=(o=a,r=d,Kh.get(o)?.get(r)??null);const p=null!==h;if(null===h&&(function(t,e,n){const o=Hf.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;Hf.get(t).delete(e)}}(a,d,f),h=function(t,e,n,o,s,r=new Set){0===n.length&&tt(`Cannot build a mount record without host bindings for "${e}".`),fc(s);const i=[],a=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(l);a.has(n)&&tt("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(g)};i.push(o),0===e.length&&(c=o)}i.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++Eh,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Lu(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)1===t.innerSegments.length&&p.add(t.innerSegments[0]);const m={};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)||(m[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+l+d,stateObject:s,getterKeys:h,setterKeys:f,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(t=>t.readonly),privateSnapshot:m,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(a,d,s,u,f,function(t,e){return Ff.get(t)?.get(e)}(a,d)),function(t){!function(t){const e=t.component.tagName.toLowerCase(),n=t.stateProp;let o=null;for(const s of t.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=Lu(t.stateObject);const i=o[r];let a;if(t.getterKeys.has(r)||t.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)a="an accessor";else if("function"==typeof i?.value)a="a method";else{if(t.mappedKeys.has(r)||t.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(t.stateObject,r))continue;a="an own data key"}const c=s.innerSegments.join(l);Xf(`${e}|${n}|${c}|entry`,`<${e}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${c}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(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=Yf(t),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const e=t.rootEntry.outerPathInfo.path;Xf(`${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{If(h,i instanceof ShadowRoot?i:a)}catch(e){throw t.landInitialization(),e}if(!p){const t=Sf(h);Object.defineProperty(a,d,{get:()=>t,enumerable:!0,configurable:!0}),Df(a,d)}return Jf(a,d),function(t){const e=Ch.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(U)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Mh.has(n)||(Mh.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 Th(h,"$connectedCallback",()=>xf(h))}}Kf(t,e.boundComponent,e.boundComponentStateProp,f)}var o,r}const np={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=Zf.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Zf.set(t,e)),e}(t);return ep(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=Zf.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&Pf(n,o)}),t.isConnected&&(Nf(n.component),kf(n,o)),Th(n,"$connectedCallback",()=>xf(n)),!0},disconnecting(t){const e=Zf.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord;return Th(n,"$disconnectedCallback",()=>xf(n)),function(t){const e=ff.get(t);void 0!==e&&(e[1].row=yf(t),ff.delete(t))}(n),uf(e.mountRecord),t.clearConnectedRootNode(),!0}};let op=!1;function sp(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(xh(t.mountPath,o,t.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function rp(t,e,n,o=[]){fc(n),function(t,e,n,o){const s=0===o.length?null:Lu(n);for(const t of o){const n=t.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||tt(`[wcs/mount-path-invalid] Volume "${e}" declares "${n}" as an accessor or a method and also injects it ("${x}.${n}: ${t.outerPathInfo.path}"). Rename one of them.`)}const r=n[F];if(void 0!==r){"object"==typeof r&&null!==r||tt(`${F} must be an object mapping state paths to handler functions.`);const t=Uu(e);for(const[e,n]of Object.entries(r))"function"!=typeof n&&tt(`${F} entry "${e}" must be a function.`),t.assertValidPath(e)}const i=n[V];if(void 0!==i){"object"==typeof i&&null!==i||tt(`${V} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(i)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&tt(`${V} entry "${n}" must map a list path to a field name or a key function.`);const r=_h(e,o,n,!1);t.listKeys?.has(r)&&tt(`${V} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[B]&&tt(`Volume "${e}" declares ${B}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&tt(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[q]&&tt(`Volume "${e}" declares ${q}, 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(Lu(n)))-1!==t.indexOf(U)&&tt(`Volume "${e}" declares "${t}", which uses "${U}". 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(Lu(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=ot(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;tt(`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+l+o];n=""===n?o:n+l+o,s||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(a)return;tt(`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=wh.get(t);void 0===n&&(n=new Set,wh.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,s]of r){const r=e+l+n,i=s.get,a=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(xh(e,this,o))}),"function"==typeof a&&(c.set=function(t){a.call(xh(e,this,o),t)}),t.defineTreeAccessor(r,c)}!function(t,e,n,o){const s=n[F];if(void 0!==s){const n=Uu(e),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=_h(e,o,n,!1),c=function(t,n,...s){l.call(xh(e,this,o),t,n,...s)};r.push({path:s,pathInfo:ot(s),handler:c,order:1e6+a++}),i.add(s),t.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(t,r),t.addVolumeWatchPaths?.(i),n.start(t))}const r=n[V];if(void 0!==r){const n=new Map;for(const[t,s]of Object.entries(r))n.set(_h(e,o,t,!1),s);t.mergeVolumeListKeys?.(n)}const i=n[M];"function"==typeof i&&(function(t,e){let n=Sh.get(t);void 0===n&&(n=[],Sh.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(xh(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 ip(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=rp(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 ap=!1;function lp(){var t;ap||(ap=!0,Cf||(Cf=!0,_c("scopes",Ef),Vu=ef),jf||(jf=!0,Mu("scopes",Rf)),op||(op=!0,Mu("bindComponent",np),yr=qf),Ah=ip,t=cp,Sl.includes(t)||Sl.push(t))}function cp(t,e){(function(t){const e=gh.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){kh.delete(t);const n=Ph.get(t);if(void 0===n||0===n.length||null===Ah)return;Ph.delete(t);const o=Ah;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const up={name:"scopes",install(){lp(),uh||(uh=!0,Mu("dcc",ch))}},dp=/^@@wcs-(?:for|if|elseif|else):[^-]/,hp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,fp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,pp=/^@@wcs-text-start:(.+)$/;function mp(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function gp(t,e){const n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const t=n.currentNode;e(t.data)&&o.push(t)}return o}const yp=t=>dp.test(t),bp=t=>hp.test(t),wp=t=>hp.test(t)||fp.test(t);function vp(t){if("else"===t.bindingType)return"else:";let e=`${t.bindingType}: ${t.statePathName}`;for(const n of t.outFilters){const t=n.literals??n.args;e+=`|${n.filterName}`,n.args.length>0&&(e+=`(${n.args.map((e,n)=>"string"==typeof t[n]?`'${e.split("'").join("'\"'\"'")}'`:e).join(",")})`)}return e}function _p(t){const e=t.fragment.cloneNode(!0);for(const n of t.nodeInfos){const o=ql(se(t.fragment,n.nodePath));if(null===o)continue;const s=se(e,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return e}class $p extends Ou{_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=Ku.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=s.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,o){const r=o??t.ownerDocument;n.seen&&function(t){const e=new Map;for(const n of gp(t,bp)){if(null===n.parentNode)continue;const[,t,o]=hp.exec(n.data),s=o.split(":")[0],r=n.previousSibling?.data,i=`@@wcs-${t}-end:${o}`;if(r!==`@@wcs-${t}:${s}`&&e.get(r)!==s)for(let t=n;null!==t;){const e=t.nextSibling;t.remove(),t=t.data===i?null:e}else"for"===t&&e.set(i,s)}}(r);const i=document.createElement("script");i.setAttribute("type","application/json"),i.textContent=mp(JSON.stringify(e)),t.appendChild(i);for(const[e,n]of function(t){const e=new Map,n=[t];for(;n.length>0;)for(const t of gp(n.shift(),yp)){const o=t.data,s=o.slice(o.indexOf(":")+1);if(e.has(s))continue;const r=Ml(s);null!==r&&(e.set(s,r),n.push(r.fragment))}return e}(r)){const o=document.createElement("template");o.setAttribute("id",e),o.setAttribute(s.bindAttributeName,vp(n.parseBindTextResult)),o.content.appendChild(_p(n)),t.appendChild(o)}const a=t.ownerDocument,l=Array.from(Ta);if(l.length>0){const e={};for(let t=0;t<l.length;t++){const n=l[t];if(!n.isConnected||n.ownerDocument!==a)continue;const o=Ma(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const t of o)r[t.propName]=t.value;e[s]=r}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=mp(JSON.stringify(e)),t.appendChild(n)}}Oa()}static removeBlockBoundaryComments(t){for(const e of gp(t,wp))e.remove()}static removeStructuralComments(t){for(const e of gp(t,yp))e.remove()}static restoreTextBindings(t){for(const e of gp(t,t=>pp.test(t))){const t=pp.exec(e.data)[1],n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;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(s.tagNames.ssr),o=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&o.set(e,t)}}for(const t of gp(e,bp)){const e=hp.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()}$p.restoreTextBindings(e);const r=t=>{for(const e of gp(t,yp)){const t=o.get(e.data.split(":")[1]);if(t){const n=document.createElement("template"),o=t.getAttribute(s.bindAttributeName);o&&n.setAttribute(s.bindAttributeName,o);const i=document.importNode(t.content,!0);if(i.childNodes.length>0)n.content.appendChild(i);else for(const e of Array.from(t.childNodes))n.content.appendChild(document.importNode(e,!0));r(n.content),e.parentNode.replaceChild(n,e)}}};r(e);const i=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of i)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const xp={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=s.tagNames.state,n=s.tagNames.ssr,o=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of o){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Ku),$p.buildContent(o,$p.extractStateData(t),t.getRootNode()),t.parentNode?.insertBefore(o,t)}Oa()},reset:function(){El.clear(),Oa(),n.seen=!1}},Sp=new Set(["for","if","elseif","else"]);function Ip(t){const[,e,n]=hp.exec(t),[o,...s]=n.split(":");return"for"===e?{type:e,uuid:o,path:s[0],index:parseInt(s[1],10),nodes:[]}:{type:e,uuid:o,path:s.join(":"),index:null,nodes:[]}}function Pp(t){const e=[];for(const n of t)if(n.nodeType===Node.ELEMENT_NODE){const t=n;t.hasAttribute(s.bindAttributeName)&&e.push(t),Array.from(t.children).some(t=>t.localName===s.tagNames.state&&ce(t))||e.push(...he(t))}else null!==Wt(n)&&e.push(n);return e}function kp(t){const[e,n,o]=ge(t),s=new pr;return{bindingInfos:s.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:e,bindingSession:s,deferredSpreads:o}}const Np=/^\s*@@\s*(?:wcs-text)?\s*:/;function Ap(t,e){for(const n of e)"event"===n.bindingType||Sp.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&Np.test(n.node.data))&&t.push(n)}function Ep(t,e){const n=[];for(let o=0;o<t.nodes.length;o++){const s=e.get(t.nodes[o]);s?o+=s.nodes.length+1:n.push(t.nodes[o])}return n}function Cp(t,e,n,o,s,r){e.length>0&&(t.spreads=e);for(const t of e)ye(t.node);hl(e,n,o,s,r)}function Mp(t,e){const n=Ml(e),o=Il(t.getRootNode());let s=null;if(n&&o){const{statePathName:t,outFilters:e}=n.parseBindTextResult;o.createState("readonly",n=>{const o=br(n[t],re(e,"output"));Array.isArray(o)&&(s=o)})}return s}function Tp(t,e){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[t]}:${e}`}function Op(t,e,n){const o=Tp(e,n);return gp(t,t=>t===o)[0]??null}function Lp(t,e){const n=t,o=e.templates,r=new Map;for(const[t,e]of o)for(const n of gp(e.content,yp))r.set(n.data.slice(n.data.indexOf(":")+1),t);const i=new Set(ue(t));if(i.size>0)for(const t of gp(n,yp)){const e=t.data.slice(t.data.indexOf(":")+1);let n=t.parentNode;for(;null!==n&&!i.has(n);)n=n.parentNode;null===n||r.has(e)||r.set(e,n)}const a=new Map,l=[];for(const[t,e]of o){let n=Ot(e.getAttribute(s.bindAttributeName)||"")[0];const o=n.bindingType,i=r.get(t),c=a.get(i);"else"===o&&c&&(n={...c,outFilters:[...c.outFilters,Ll()],bindingType:"else"}),"if"===o||"elseif"===o?a.set(i,n):"else"===o&&a.set(i,null),l.push([t,e,n])}for(const[t,e,o]of l.reverse()){const s=document.importNode(e.content,!0),r="for"===o.bindingType?o.statePathName:void 0;Vl(s),"string"==typeof r&&Bl(s,r),Xl(n,s,r),Cl(t,n,{fragment:s,parseBindTextResult:o,nodeInfos:Ul(s)})}}const Rp={hydrate:async function(t){await ml(t);const e=t.querySelectorAll(s.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="${Ku}". Falling back to full render.`),$p.cleanupDom(t),!1}const n=function(t){const e=[];for(const n of gp(t,wp)){if(!bp(n.data)){e.pop();continue}const t=Ip(n.data),o=e.at(-1);if("for"===t.type&&o&&o.uuid!==t.uuid)return[t,o];e.push(t)}return null}(document.body);if(null!==n){const[e,o]=n;return console.warn(`[@wcstack/state] SSR: "for: ${e.path}" in "${o.type}: ${o.path}" (known limitation). Falling back to full render.`),$p.cleanupDom(t),!1}for(const n of e)Lp(t,n);$p.restoreTextBindings(document.body);const o=function(t){const e=[];for(const n of gp(t,bp)){const t=Ip(n.data);t.start=n;const o=n.data.replace("-start:","-end:");let s=n.nextSibling;for(;s&&(s.nodeType!==Node.COMMENT_NODE||s.data!==o);)t.nodes.push(s),s=s.nextSibling;e.push(t)}return e}(document.body),r=new Map,i=function(t,e,n=new Map){const o=new Map,s=[],r=new Map(e.map(t=>[t.start,t])),i=new Set;for(let t=e.length-1;t>=0;t--){const n=Pp(e[t].nodes).filter(t=>!i.has(t));for(const t of n)i.add(t);e[t].subscribers=n}for(const i of e){const e=Ep(i,r);if(0===e.length)continue;const a=e.some(t=>yp(t.data));if(a){const t=document.createComment(`wcs-row-end:${i.uuid}`);i.nodes[i.nodes.length-1].after(t),e.push(t)}const{bindingInfos:l,subscriberNodes:u,bindingSession:d,deferredSpreads:h}=kp(i.subscribers);for(const t of l)if(t.node!==t.replaceNode){const n=e.indexOf(t.node);n>=0&&(e[n]=t.replaceNode)}const f=la(e,a);Ui(f,d),xr(f,l),Pr(f,u);const p=l.filter(t=>aa(t,-1));if(Er(f,p),"for"===i.type&&null!==i.index){const e=Op(t,"for",i.uuid);if(e){let t=n.get(i.uuid);if(!t){const s=Mp(e,i.uuid)??i.path;t=o.get(s),t||o.set(s,t=[]),n.set(i.uuid,t)}const r=t[i.index]??=Ee(null,i.index);_a(e,r,f),$a(e,f.lastNode),Zi(e,f);const a=_o(ot(i.path+"."+c),r);kr(f,a),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ap(s,l),Cp(f,h,a,d,l,p)}}else{const e=i.start.previousSibling,n=e?.data===Tp(i.type,i.uuid)?e:Op(t,i.type,i.uuid);if(n){Zi(n,f);const t=_e(n);kr(f,t),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ap(s,l),Cp(f,h,t,d,l,p)}}}return s}(document.body,o,r);$p.removeBlockBoundaryComments(document.body);const a=[];for(const t of e)t.parentNode&&(a.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());const[,l,u]=me(document.body),d=[],h=[],f=mr(document.body),p=f.initialize(l);hl(u,null,f);for(const t of p)if("event"!==t.bindingType)if(Sp.has(t.bindingType))h.push(t);else{if(t.statePathName.includes(c))continue;d.push(t)}for(const t of h)if("for"===t.bindingType){const e=co(t),n=Il(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=br(n[t.statePathName],t.outFilters);if(Array.isArray(o)){const n=r.get(t.uuid);n&&hn(o,n),xn(e,o),s=t.node,i=o,ba.set(s,pn(i)),Mn(e,o)}var s,i})}dl([...d,...i]);for(const{el:t,parent:e,next:n}of a)e.insertBefore(t,n);const m=new Map;for(const e of t.querySelectorAll("[data-wcs-ssr-id]"))m.set(e.getAttribute("data-wcs-ssr-id"),e);for(const e of t.querySelectorAll(s.tagNames.ssr))for(const[t,n]of Object.entries(e.hydrateProps)){const e=m.get(t);if(e)for(const[t,o]of Object.entries(n))yr?.isDeclared(e,t)||(e[t]=o)}for(const e of t.querySelectorAll("[data-wcs-ssr-id]"))e.removeAttribute("data-wcs-ssr-id");return!0},loadState(t){const e=t.parentNode;if(!e)return null;const n=$p.find(e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(t){await Pl(t.rootNode);const e=$p.extractStateData(t),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",Ku),$p.buildContent(n,e,t.rootNode),t.parentNode?.insertBefore(n,t)}};let jp=!1;const Wp={name:"ssr",install(){jp||(jp=!0,wl=Rp,function(t){if(!zu.includes(t)){zu.push(t);for(const e of Fu())t(e)}}(t=>{t.get(s.tagNames.ssr)||t.define(s.tagNames.ssr,$p)}),function(){const e=globalThis;void 0===e[t]&&(e[t]=xp)}())}},Dp=new WeakMap,zp=new Set,Bp=new Set;function Fp(t){return t.byFromPath.size>0||t.byResetPath.size>0}function Hp(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function qp(t){return Dp.get(t)}function Up(t){Vp(t),Dp.delete(t)}function Vp(t){zp.delete(t),Bp.delete(t)}const Gp=new WeakSet;let Kp=0;function Jp(t){return qp(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function Qp(t){if(0===Bp.size)return;if(e=t.absolutePathInfo.stateElement,!Bp.has(e))return;var e;const n=Jp(t);if(void 0!==n)for(const t of n)Xp(t)}function Xp(t){Gp.has(t)||(Gp.add(t),Kp++)}function Yp(t){return!!Gp.delete(t)&&(Kp--,!0)}const Zp=/^(?:0|[1-9]\d*)$/;function tm(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function em(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&&Zp.test(e)&&tm(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&tm(t,e))?null:"object"}function nm(t,e){const n=em(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]=nm(o[t],e);return r}function om(t){return nm(t,new Map)}function sm(t,e,n){if(Object.is(t,e))return!0;const o=em(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(em(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(!sm(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&sm(s[t],r[t],n))}function rm(t,e){return sm(t,e,new Map)}const im=new WeakMap;function am(t,e){if("function"!=typeof e)return;const n=im.get(e);void 0===n?im.set(e,new Set([t])):n.add(t)}function lm(t,e){return"function"==typeof e&&!0===im.get(e)?.has(t)}const cm={"read-source":t=>`${H} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-rows":t=>`${H} could not read the rows of "from" for "${t}". Nothing was folded or written.`,"read-output":t=>`${H} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${H} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${H} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${H} could not write the output "${t}".`},um={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function dm(t,e,n){null!==xe&&xe({type:"state:watch-error",phase:e,path:`${H}.${t}`,error:n})}function hm(t,e,n){console.error(`[@wcstack/state] ${cm[n](t)}`,e),dm(t,um[n],e)}function fm(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function pm(t,e){e.then(void 0,()=>{}),hm(t,new TypeError(`${H} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const mm=new WeakSet,gm="[wcs/scan-declaration-invalid]",ym=Object.freeze([]);function bm(t){return`${H} entry "${t}"`}function wm(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function vm(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${c}${c}`)?`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.${at}`}function _m(t,e,n){0===n.length&&tt(`${gm} ${t} "${e}" must be a non-empty state path.${at}`),n.startsWith("$")&&tt(`${gm} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${at}`),n.includes("@")&&tt(`${gm} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${at}`),n in Object.prototype&&tt(`${gm} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${at}`);const o=ot(n);for(const s of o.segments)0===s.length&&tt(`${gm} ${t} ${e} "${n}" has an empty path segment.${at}`);return o.wildcardCount>u&&tt(`${gm} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function $m(t,e,n,o){const s=bm(t);0===t.length&&tt(`${gm} ${H} entry name must be a non-empty string.${at}`),(t.includes(l)||t.includes(c))&&tt(`${gm} ${s} must be a flat property name ("${l}" and "${c}" are not allowed). The output is a property the runtime owns.${at}`),t.startsWith("$")&&tt(`${gm} ${s} must not start with "$" (reserved namespace).${at}`),t in Object.prototype&&tt(`${gm} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${at}`),e.has(t)&&tt(`${gm} ${s} conflicts with a getter declared on the state.${at}`),n.has(t)&&tt(`${gm} ${s} conflicts with a setter declared on the state.${at}`),o.has(t)&&tt(`${gm} ${s} conflicts with the ${B} entry of the same name — each output has exactly one owner.${at}`)}function xm(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!lm(t,o)&&tt(`${gm} ${bm(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${at}`)}function Sm(t,e,n,o,s,r){const i=bm(t),a=void 0!==e.from,c=void 0!==e.on;if(a===c&&tt(`${gm} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${at}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||tt(`${gm} ${i} "on" must be a non-empty event-token name.${at}`),n.has(t)||tt(`${gm} ${i} on "${t}" is not declared in ${D}.${it(t,n)}${at}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&tt(`${gm} ${i} "from" must be a state path string.${at}`);const d=_m(i,"from",u),h=wm(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&tt(vm(i,"from",u,h));const f=wm(d,s);return null!==f&&tt(function(t,e,n){return`${gm} ${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.${at}`}(i,u,f)),(u===t||u.startsWith(t+l))&&tt(`${gm} ${i} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${at}`),{kind:"path",path:u,pathInfo:d}}function Im(t,e,n,o){if(void 0===e)return ym;const s=bm(t);Array.isArray(e)||tt(`${gm} ${s} "resetOn" must be an array of state paths.${at}`);const r=[];for(const t of e){"string"!=typeof t&&tt(`${gm} ${s} "resetOn" must contain only state path strings.${at}`);const e=_m(s,"resetOn",t);e.wildcardCount>0&&tt(`${gm} ${s} resetOn "${t}" must not contain "${c}" — a reset returns the whole output to "initial".${at}`);const i=wm(e,o);null!==i&&tt(vm(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&tt(`${gm} ${s} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${at}`),"path"===n.kind&&t.startsWith(n.path+l)&&tt(`${gm} ${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.${at}`),r.push(t)}return r}function Pm(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 Gp.has(t)}(t),l=a&&!rm(n,t.initial)?om(t.initial):n,c=e(l,o,...s);if(fm(c))return void pm(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,am(t.name,c)),a&&Yp(t)}catch(e){hm(t.name,e,i)}}}const km="scanEntries",Nm={order:8,validate(t,e,n){const o=function(t,e,n=null){const o=t[H];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&tt(`${gm} ${H} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${at}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(Lu(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){fc(t);const e=t[B];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)){$m(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&tt(`${gm} ${bm(t)} must be an object ({ from | on, initial, fold, resetOn? }).${at}`);const o=d;xm(t,a,o);const h=Sm(t,o,e,s,i,n);"initial"in o||tt(`${gm} ${bm(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${at}`),"function"!=typeof o.fold&&tt(`${gm} ${bm(t)} fold must be a function.${at}`);const f=Im(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=ot(t).segments[0];e.has(n)&&tt(`${gm} ${bm(o.name)} resetOn "${t}" reads the ${H} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${at}`)}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&&tt(`${gm} ${H} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${at}`),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(km,o)},applyEarly(t,e,n){const o=n.get(km)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=om(n.initial);t[n.name]=e,am(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&Ro(t,n.source.tokenName).subscribe(Pm(n))}(t,o))},register(t,e,n){const o=n.get(km)??null,s=function(t){const e=new Map,n=qp(t);if(void 0!==n)for(const t of n.entries)Yp(t)&&e.set(t.name,t.resetOn);return Up(t),e}(t);t.setScanPaths?.(null===o?null:function(t,e,n){const o=function(t,e){Up(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&Hp(n,t.source.path,t);for(const e of t.resetOn)Hp(o,e,t),"event"===t.source.kind&&Hp(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return Dp.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)&&Gr().hasQueuedPath(t,n))&&Xp(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 Am=!1;const Em=Object.freeze([]),Cm=Object.freeze([]);function Mm(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Em,i=t.dynamicDependency.get(n)??Em,a=e.byFromPath.get(n)??Cm;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const Tm=Symbol("wcs-stream-last-notified-uncertain"),Om=new WeakMap;function Lm(t,e){const n=Om.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Rm(t,e){const n=Om.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Tm,error:Object.is(o.error,null)?null:Tm})}const jm=new Set;function Wm(t){jm.delete(t)}const Dm=new WeakMap;function zm(t){return Dm.get(t)??new Map}function Bm(t){Wm(t);const e=Dm.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Rm(t,n.name)}const Fm=(t,e)=>e,Hm=new Set;const qm=new WeakMap,Um=new WeakMap;function Vm(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=zm(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&zm(t).has(n),ownKeys:()=>Array.from(zm(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=zm(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){tt(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){tt(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Gm(t){const e=qm.get(t);if(void 0!==e)return e;const n=Vm(t,G,t=>t.status);return qm.set(t,n),n}function Km(t){const e=Um.get(t);if(void 0!==e)return e;const n=Vm(t,K,t=>t.error);return Um.set(t,n),n}function Jm(t){qm.delete(t),Um.delete(t)}let Qm=null;function Xm(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 Ym={read(t,e){!function(t,e){null!==Qm&&Qm.add(Qn(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===G?Xm(Gm(t),e.pathInfo.segments):n===K?Xm(Km(t),e.pathInfo.segments):bc},get:(t,e)=>e===G?Gm(t.stateElement):e===K?Km(t.stateElement):bc};let Zm=0,tg=null,eg=0;const ng=new WeakMap;function og(t){Zm=t+1}function sg(){Zm=0}function rg(t){if(Zm>0){const e=tg??=new Map;Zm>(e.get(t)??0)&&e.set(t,Zm),eg=Math.max(eg,Zm)}}function ig(t,e){return ng.get(t)?.get(e)??0}function ag(t){pg();const e=zm(t);if(0!==e.size){!function(t){jm.add(t)}(t);for(const n of e.values())lg(t,n)}}function lg(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=Qm,s=new Set;let r;Qm=s;try{t.createState("readonly",t=>{r=n(t)})}finally{Qm=o}r instanceof Promise&&tt(`${B} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${G}${l}${e.name}`,a=`${K}${l}${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!==a||tt(`${B} 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&&tt(`${B} 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=qp(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=Mm(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&tt(`[wcs/scan-feedback-loop] ${B} entry "${e.name}" args read "${n}", which is derived from the ${H} 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}),am(e.name,e.definition.initial),cg(t,e,"active",null);const s=e.definition,r={fold(n){t.createState("writable",t=>{const o=s.fold(t[e.name],n);t[e.name]=o,am(e.name,o)})},done(){cg(t,e,"done",null)},fail(o){cg(t,e,"error",o),n.abort()}};!async function(t,e,n,o){let s=null;const r=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",r,{once:!0});try{const i=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] ${B}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();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",r)}}(s.source,o,n.signal,r)}function cg(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return Om.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=Om.get(t);void 0===s&&(s=new Map,Om.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${G}${l}${e.name}`),i&&t.$postUpdate(`${K}${l}${e.name}`)}))}function ug(t){const e=jm;if(0===e.size)return;const n=[];for(const o of e)for(const e of zm(o).values()){let s=-1;for(const n of e.depAddresses)t.has(n)&&(s=Math.max(s,ig(t,n)));s>=0&&s<=32&&n.push({stateElement:o,entry:e,depth:s})}try{for(const{stateElement:t,entry:o,depth:s}of n)if(e.has(t)&&zm(t).get(o.name)===o){og(s);try{lg(t,o)}catch(n){o.controller?.abort(),e.has(t)&&zm(t).get(o.name)===o&&cg(t,o,"error",n)}}}finally{sg()}}let dg=!1;const hg=new WeakMap,fg={order:20,apply(t,e){var n;Jm(t),Bm(n=t),Wm(n),Dm.delete(n),function(t,e){fc(e);const n=e[B];if(void 0===n)return void Lm(t,Hm);"object"==typeof n&&null!==n||tt(`${B} must be an object mapping stream names to stream definitions.`);const o=new Map,s=Lu(e);for(const[r,i]of Object.entries(n)){0===r.length&&tt(`${B} entry name must be a non-empty string.`),r.includes(l)&&tt(`${B} entry "${r}" must be a flat property name ("${l}" is not allowed).`),r.includes(c)&&tt(`${B} entry "${r}" must be a flat property name ("${c}" is not allowed).`),r.startsWith("$")&&tt(`${B} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&tt(`${B} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(r)&&tt(`${B} entry "${r}" conflicts with a getter declared on the state.`),t.setterPaths.has(r)&&tt(`${B} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||tt(`${B} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||lm(r,a)||tt(`${B} entry "${r}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&tt(`${B} entry "${r}" source must be a function.`);const u=void 0!==n.fold;u&&"function"!=typeof n.fold&&tt(`${B} entry "${r}" fold must be a function.`),u&&!("initial"in n)&&tt(`${B} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&tt(`${B} entry "${r}" args must be a function.`);const d={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??Fm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in e||(e[r]=d.definition.initial,am(r,d.definition.initial)),o.set(r,d)}!function(t,e){Dm.set(t,e)}(t,o),Lm(t,new Set(o.keys()))}(t,e),void 0!==e[B]&&t.attachAddressHooks?.("streams",B)},activate(t,n){if(!e()&&null!=t.connectedRootNode){if(null===n){if(!0!==t.initialized)return;return ag(t),void hg.set(t,t.connectGeneration??0)}n===t.connectGeneration&&hg.get(t)!==n&&ag(t)}},deactivate(t){Bm(t),Jm(t)}};function pg(){dg||(dg=!0,_c("streams",Ym),Ic("streams",fg),qr(ug,20))}const mg=new WeakMap;function gg(t,e,n){let o=mg.get(t);void 0===o&&(o=new Map,mg.set(t,o)),o.set(e,n)}const yg=new Map;function bg(t,e){yg.has(t)||yg.set(t,e)}function wg(t){return yg.get(t)}const vg=new WeakMap,_g=new WeakMap,$g=new Set,xg=new Map;function Sg(t){return vg.get(t)??xg}function Ig(t,e){let n=_g.get(t);void 0===n&&(n=new Map,_g.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)}}const Pg=new Map;function kg(t){return _g.get(t)??Pg}function Ng(t){0===t.length&&tt(`[wcs/watch-declaration-invalid] ${F} entry name must be a non-empty state path.`),t.startsWith("$")&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not start with "$" (reserved namespace).${at}`),t.includes("@")&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${at}`),t in Object.prototype&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=ot(t);for(const n of e.segments)0===n.length&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" has an empty path segment.${at}`);return e.wildcardCount>u&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const Ag={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||bg(n,o)},swapped(t,e,n){var o;o=n,yg.has(o)&&bg(e,wg(n))}};function Eg(t){for(let e=t;null!==e;e=e.parentListIndex)if(Ke(e))return!0;return!1}function Cg(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[jn](_o(e.wildcardParentPathInfos[i],r)),l=ln(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=oo(o,i,e.wildcardCount);if(l!==c&&!Fe(l,c)){if(Ke(c))return"gone";s="replaced"}r=l}return s}function Mg(t,e,n){const o=new Map;for(const s of n){const n=Cg(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 Tg=Object.freeze([]);function Og(t,e,n,o){let s=t.get(n);return void 0===s&&(s={stateElement:e,entry:n,rows:[],reset:!1,depth:o},t.set(n,s)),s.depth=Math.max(s.depth,o),s}function Lg(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 Rg(t,e){return e.has(t.stateElement)&&!0===qp(t.stateElement)?.entries.has(t.entry)}function jg(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Wg(n,t))||Yp(e)}function Wg(t,e){return Gr().hasQueuedPath(t,e)}function Dg(t,e){!function(t,e,n){if(0!==Kp)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=Jp(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||Yp(e)}}(t,e,Wg)}function zg(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function Bg(t,e,n){if(!Rg(t,n))return jg(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(mm.has(t))return;mm.add(t);const o=`[wcs/scan-source-computed] ${H} 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}`),dm(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=zm(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];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?t.rows:Mg(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(Lg)){let n;try{n=zg(e,r,t)}catch(t){hm(s.name,t,"read-source");continue}const o=a(l,n,wg(t.absAddress),...t.indexes);if(fm(o))return void pm(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){hm(s.name,t,i.failure)}return i.plan}function Fg(t,e){const{group:n}=t;if(!Rg(n,e))return void jg(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Yp(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!rm(o,s.initial):!Object.is(o,t.next)){const o=n.reset?om(s.initial):t.next;e[s.name]=o,am(s.name,o)}})}catch(t){hm(s.name,t,"write")}}function Hg(t){Yg(),(0!==Sg(t).size||0!==kg(t).size||function(t){const e=Dp.get(t);return void 0!==e&&Fp(e)}(t))&&(function(t){$g.add(t),function(t){const e=Dp.get(t);void 0!==e&&(Fp(e)&&zp.add(t),function(t){return t.eventResetByPath.size>0}(e)&&Bp.add(t))}(t)}(t),function(t){const e=[];for(const n of Sg(t).values())qg(t,n)&&e.push(n);for(const n of kg(t).values())for(const o of n)qg(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{gg(t,Xn(t,o.pathInfo,null),n[o.path])}catch(e){Vg(t,o.path,"prime",e)}})}(t))}function qg(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Ug={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Vg(t,e,n,o){console.error(`[@wcstack/state] $watch ${Ug[n]} "${e}" threw.`,o),null!==xe&&xe({type:"state:watch-error",phase:n,path:e,error:o})}function Gg(t){const e=$g,n=function(t){const e=eg;return e>0&&(ng.set(t,tg),tg=null,eg=0),e}(t);try{if(n>32){Dg(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!==xe&&xe({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}if(0===e.size)return void Dg(t,e);!function(t,e){if(0!==t.length)try{for(const n of t)og(n.group.depth),Fg(n,e)}finally{sg()}}(function(t,e){if(Dg(t,e),0===zp.size)return Tg;const n=new Map;for(const o of t){const s=o.absolutePathInfo.stateElement;if(!e.has(s))continue;const r=qp(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=ig(t,o),l=r.byFromPath.get(i.path);if(void 0!==l){let t=[];if(i.wildcardCount>0){if(null===o.listIndex)continue;t=so(o.listIndex,i.wildcardCount)}for(const e of l)Og(n,s,e,a).rows.push({absAddress:o,indexes:t})}const c=r.byResetPath.get(i.path);if(void 0!==c)for(const t of c)Og(n,s,t,a).reset=!0}if(0===n.size)return Tg;const o=Array.from(n.values()).sort((t,e)=>t.entry.order-e.entry.order),s=[];try{for(const n of o){og(n.depth);const o=Bg(n,t,e);null!==o&&s.push(o)}}finally{sg()}return s}(t,e),e),function(t,e){const n=[],o=new Set;for(const s of t){const t=s.absolutePathInfo.stateElement;if(!e.has(t))continue;const r=s.absolutePathInfo.pathInfo.path;o.add(r);const i=Sg(t).get(r),a=kg(t).get(r);if(void 0===i&&void 0===a)continue;const l=void 0===i?[]:[i];void 0!==a&&l.push(...a);for(const e of l){let o=[];if(e.pathInfo.wildcardCount>0){if(null===s.listIndex)continue;o=so(s.listIndex,e.pathInfo.wildcardCount)}n.push({stateElement:t,entry:e,absAddress:s,indexes:o})}}if(0===n.length)return;n.sort(Jg);const s=function(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(0===s.entry.pathInfo.wildcardCount)continue;const r=t[o-1];(Eg(s.absAddress.listIndex)||r?.entry===s.entry&&Kg(r.indexes,s.indexes)||s.entry.pathInfo.wildcardParentPaths.some(t=>e.has(t)))&&(n??=new Set).add(s.entry)}if(null===n)return t;const o=new Set;for(const e of n){const n=t.filter(t=>t.entry===e),s=n[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(Mg(t,e.pathInfo,n));for(const t of n)s.has(t)||o.add(t)})}catch(t){Vg(0,e.path,"evaluate",t);for(const t of n)o.add(t)}}return t.filter(t=>!o.has(t))}(n,o);try{for(const n of s){if(!e.has(n.stateElement))continue;const o=Sg(n.stateElement).get(n.entry.path)===n.entry,s=!0===kg(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(og(ig(t,n.absAddress)),Qg(n))}}finally{sg()}}(t,e)}finally{yg.clear()}}function Kg(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Jg(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 Qg(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=qg(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 Vg(0,n.path,"evaluate",t)}const a=r?function(t,e){return mg.get(t)?.get(e)}(e,o):wg(o);r&&gg(e,o,i),null!==xe&&xe({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){Vg(0,n.path,"handler",t)}}let Xg=!1;function Yg(){Xg||(Xg=!0,_c("watch",Ag),Ic("watch",Zg),qr(Gg,10),Hr(rg),qu={assertValidPath:Ng,addEntries:Ig,start:Hg})}const Zg={order:10,register(t,e){var n;n=t,$g.delete(n),Vp(n),vg.delete(n),function(t){mg.delete(t)}(t);const o=function(t,e){const n=e[F];if(void 0===n)return null;"object"==typeof n&&null!==n||tt(`[wcs/watch-declaration-invalid] ${F} must be an object mapping state paths to handler functions.${at}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must be a function.${at}`);const n=Ng(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){vg.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?F:H)},activate(t,n){e()||null==t.connectedRootNode||(null===n?!0===t.initialized:n===t.connectGeneration)&&Hg(t)},deactivate(t){var e;e=t,$g.delete(e),Vp(e)}},ty=[Ad,{name:"temporal",install(){Yg(),Am||(Am=!0,Ic("scan",Nm),Hr(Qp)),pg()}},Zd,up,Wp,sd,pd];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(ty),void Hu(void 0,void 0));const ey={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"},ny=!1,oy=[".html"];function sy(){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 ry(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let iy=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const ay={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 ly(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function cy(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 uy={static:2,param:1,"catch-all":0};let dy=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&&ry(`${ey.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&ry(`${ey.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+=uy[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(ay).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||ry(`${ey.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:ly(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new iy("Navigation cancelled by guard.",o);if(!o)throw new iy("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new iy("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},hy=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=sy();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new dy(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||ry(`${ey.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):ry(`${ey.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&&ry(`${ey.route} with fallback attribute must be a direct child of ${ey.router}.`),t.fallbackRoute&&ry(`${ey.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 fy=Symbol.for("wcstack.trustedTypes.policy"),py=Symbol.for("wcstack.trustedTypes.internal"),my="wcstack";function gy(){const t=globalThis[fy];return null===t||"object"!=typeof t?null:t}let yy=!1;function by(t){const e=function(){const t=globalThis,e=t[py];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(my,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof gy()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${my}". Allow it in the CSP (\`trusted-types ${my};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[py]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=gy(),s=o?.createHTML;return"function"==typeof s?(yy||(yy=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${my}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${my};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const wy=new Map;let vy=class extends HTMLElement{_uuid=sy();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||ry(`${ey.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return wy.set(t,n),n}catch(e){ry(`${ey.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(`${ey.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)wy.has(t)?n.innerHTML=by(wy.get(t)||""):n.innerHTML=by(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=by(t):console.warn(`${ey.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")&&ny}get name(){return this.getAttribute("name")||""}},_y=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||ry(`${ey.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")&&ny}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const $y=new Set(["props","states","attr",""]);function xy(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 Sy(t,e){t.hasAttribute("data-bind")||ry(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";$y.has(n)||ry(`${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&&xy(t,e,o)}).catch(()=>{ry(`Failed to define custom element: ${s}`)}):xy(t,e,o)}let Iy=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||ry(`${ey.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(`${ey.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=>{Sy(e,t)}),e.hasAttribute("data-bind")&&Sy(e,t))}};function Py(){return document.createElement(ey.layoutOutlet)}const ky="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Ny(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){ry(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 ${ky}`:`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 ${ky}`}(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 Ay(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 Ey(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===ey.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),Ay(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===ey.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Ny(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===ey.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=Py();o.layout=n,i=o,a=e}}const c=await Ey(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function Cy(t){const e=new Map;return await Ey(t,t.template.content,[],e)}function My(t){return!1!==t.checkVisibility?.()}function Ty(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=ay[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)Ty(s,e,n,o)}function Oy(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)Ty(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 Ly=null,Ry=null;function jy(){const t=oy;return 0===t.length?null:(Ly===t&&Ry||(Ly=t,Ry=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Ry)}function Wy(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=jy();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Dy(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function zy(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=jy();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function By(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function Fy(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=>{Sy(e,t.typedParams)}),n.hasAttribute("data-bind")&&Sy(n,t.typedParams),n.querySelectorAll(ey.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===ey.layoutOutlet&&n.assignParams(t.typedParams)}}function Hy(t,e){Fy(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 qy=Symbol.for("wcstack.transition-runner");const Uy=Symbol.for("wcstack.binder");function Vy(){const t=globalThis[Uy];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const Gy=Symbol.for("wcstack.binder.pending"),Ky=Symbol.for("wcstack.binder.taken");function Jy(){const t=globalThis;let e=t[Ky];return void 0===e&&(e=new WeakSet,t[Ky]=e),e}function Qy(t){const e=Vy();return null===e?(function(){const t=globalThis;let e=t[Gy];return void 0===e&&(e=[],t[Gy]=e),e}().push(t),!1):(Jy().add(t),e.bind(t),!0)}const Xy=new WeakSet,Yy="data-wcs";function Zy(t,e,n){!Xy.has(t)&&function(t){return t.hasAttribute(Yy)||null!==t.querySelector(`[${Yy}]`)}(t)&&(Xy.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==Vy()||(o=t,Jy().has(o))||console.warn(`[@wcstack/router] ${e} contains ${Yy} 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 tb(t){for(const e of t.childNodeArray)1===e.nodeType&&(Qy(e)||Zy(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 eb(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 iy)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 nb(t,e,n,o,s=""){const r=Dy(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=Oy(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:ry(`${ey.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 eb(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||By(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=Hy(o,e),n.length>0&&!s.has(o)&&tb(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[qy];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(My(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(My(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 ob(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function sb(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 rb(t){return"?"===t?"":t}function ib(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 ab(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const lb="data-wcs-ssr",cb="data-wcs-ssr-link",ub="@@wcs-route-ph:",db="@@wcs-route-start:",hb="@@wcs-route-end:",fb=Object.freeze({});class pb 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=fb;_typedParams=fb;_searchParams=fb;_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 Wy(t)}_normalizeBasename(t){return zy(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(ey.outlet))return t;const e=document.createElement(ey.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||ry(`${ey.router} has no outlet.`),this._outlet}get template(){return this._template||ry(`${ey.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=ly(t.search),s=t.data??null,r=this._data!==s,i=!cy(this._params,e),a=this._routeName!==t.routeName,l=!cy(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(`${ey.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(`${ey.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=sb(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+rb(n.search)+n.hash,r=ob();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(Dy(t,this._basename));await nb(this,this.outlet,t,this._path,rb(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(Dy(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await nb(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${ey.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 nb(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=ab();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||ry(`${ey.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||ry(`${ey.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await Cy(this),r=!t&&this._outlet.hasAttribute(lb);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&&ry(`${ey.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(lb);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await nb(this,this.outlet,i,this._path,window.location.search||""),(r||null!==Vy())&&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(ey.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(ub)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(db)){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(hb)){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=Dy(t,this._basename);let d=Oy(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(db)){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()===ey.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(lb);for(const t of d.routes)Fy(t,d);return this.outlet.lastRoutes=d.routes,!await eb(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=Dy(t,this._basename),n=Oy(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&ry(`${ey.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await nb(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${ub}${t.absolutePath}`}),this.outlet.setAttribute(lb,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${db}${t.absolutePath}`),s=document.createComment(`${hb}${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&&Qy(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(!ib(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),ab()){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=ob();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&&(ob()?.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 mb=["title","rel","target","download","hreflang","lang","dir"];class gb extends HTMLElement{static get observedAttributes(){return["to",...mb]}_childNodeArray=[];_uuid=sy();_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(ey.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(ey.router);if(n)return this._router=n;ry(`${ey.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 Wy(t)}_joinInternalPath(t,e){const n=zy(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}=sb(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+rb(o)+s}else try{t.href=new URL(e).toString()}catch{ry(`[${ey.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){ab()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(cb)?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(cb),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-")||mb.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,ab())return this._updateActiveState(),void n.setAttribute(cb,"");ob()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!ob()?.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(){ob()?.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(mb.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}=sb(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 yb=[],bb=new Map;let wb=!1;const vb=new WeakMap;class _b 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(),wb||(this._captureInitialHead(),wb=!0),yb.push(this),this._reapplyHead()}disconnectedCallback(){const t=yb.indexOf(this);-1!==t&&yb.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||ry("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=vb.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return vb.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);bb.has(t)||bb.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of yb)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of bb.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=yb.length-1;e>=0;e--){const o=yb[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&bb.has(n)&&(t=bb.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),Qy(t)||Zy(t,`<${t.tagName.toLowerCase()}> inside <${ey.head}>`,`<${ey.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(ey.layout)||t.define(ey.layout,vy),t.get(ey.layoutOutlet)||t.define(ey.layoutOutlet,Iy),t.get(ey.outlet)||t.define(ey.outlet,_y),t.get(ey.route)||t.define(ey.route,hy),t.get(ey.router)||t.define(ey.router,pb),t.get(ey.link)||t.define(ey.link,gb),t.get(ey.head)||t.define(ey.head,_b)}(void 0);const $b="data-fetchtarget",xb={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Sb=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 Ib(t,e){return e.every(e=>"available"===t.availability.get(e))}const Pb=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let kb=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 Sb("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 Ib(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}}(Pb,{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(!Ib(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)}}},Nb=!1;function Ab(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${$b}]`);if(!n)return;const o=n.getAttribute($b);if(!o)return;const s=customElements.get(xb.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function Eb(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 Cb=Symbol.for("wcstack.trustedTypes.policy");function Mb(){const t=globalThis[Cb];return null===t||"object"!=typeof t?null:t}let Tb,Ob=!1;let Lb=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...kb.wcBindable,properties:[...kb.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 kb(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(xb.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(xb.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=Mb(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Tb)return Tb;if(!("trustedTypes"in globalThis))return Tb=!1,Tb;try{document.createElement("div").innerHTML="<i></i>",Tb=!1}catch{Tb=!0}return Tb}())return void function(){if(Ob)return;Ob=!0;const t="function"==typeof Mb()?.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(!Eb(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Nb||(Nb=!0,document.addEventListener("click",Ab)),!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 Rb extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class jb extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Wb=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 Lb&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(xb.fetch)||t.define(xb.fetch,Lb),t.get(xb.fetchHeader)||t.define(xb.fetchHeader,Rb),t.get(xb.fetchBody)||t.define(xb.fetchBody,jb),t.get(xb.infiniteScroll)||t.define(xb.infiniteScroll,Wb)}(void 0);const Db="data-storagetarget",zb={storage:"wcs-storage"},Bb="wcs-storage:value-changed",Fb="wcs-storage:loading-changed",Hb="wcs-storage:error",qb="wcs-storage:error-info-changed",Ub="wcs-storage:trigger-changed";let Vb=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Bb,semantics:"state",getter:t=>t.detail},{name:"loading",event:Fb,semantics:"state"},{name:"error",event:Hb,semantics:"state"},{name:"errorInfo",event:qb,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(Fb,{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(Hb,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(qb,{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(Bb,{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)}},Gb=!1;function Kb(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Db}]`);if(!n)return;const o=n.getAttribute(Db);if(!o)return;const s=customElements.get(zb.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function Jb(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 Qb=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Vb.wcBindable,properties:[...Vb.wcBindable.properties,{name:"trigger",event:Ub,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 Vb(this),this._internals=this._initInternals(),this._wireStates({[Fb]:t=>({loading:!0===t}),[Hb]: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(Ub,{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(!Jb(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Gb||(Gb=!0,document.addEventListener("click",Kb)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(zb.storage)||t.define(zb.storage,Qb)}(void 0);const Xb="*",Yb="vanilla",Zb={scanImportmap:!0,loaders:{[Yb]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[Xb]:Yb},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function tw(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 ew(t,e,n){let o;if(null===e||e===Xb||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===Xb)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[Xb],"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 nw=new Set,ow=new Map;let sw=new WeakMap;function rw(t){if(t===globalThis.customElements)return ow;let e=sw.get(t);return void 0===e&&(e=new Map,sw.set(t,e)),e}const iw=new Map;async function aw(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 iw)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){nw.has(e)||(console.error(`Failed to eager load component '${e}':`,t),nw.add(e))}}function lw(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 cw(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&&iw.set(t,e)});const uw=new WeakSet,dw=new WeakSet;async function hw(t,e,n){t.shadowRoot&&(uw.has(t)||await async function(t,e,n){uw.add(t),await gw(t.shadowRoot,e,n)}(t,e,n))}async function fw(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=rw(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=ew("",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),nw.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function pw(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=cw(t);void 0===o.get(s.name)?(dw.has(t)||(dw.add(t),o.whenDefined(s.name).then(async()=>{await hw(t,e,n)})),a.has(s.name)||nw.has(s.name)||(a.add(s.name),i.push(s))):await hw(t,e,n)}let l=0;for(const t of i)await fw(t,e,n,o),l++;return l}async function mw(t,e,n,o){for(;await pw(t,e,n,o)>0;);}async function gw(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 lw(e)}return lw(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await mw(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 mw(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class yw extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),yw._instance)throw new Error(`${Zb.tagNames.autoloader} can only be instantiated once.`);yw._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=tw(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=ew(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(aw(s,o,r))}await Promise.all(n)}(n,Zb.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 gw(document,Zb,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,yw._instance===this&&(yw._instance=null)}}!function(t=customElements){t.get(Zb.tagNames.autoloader)||t.define(Zb.tagNames.autoloader,yw)}(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={seen:!1},o={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},s=o,r=Symbol.for("wcstack.binder"),i=Symbol.for("wcstack.binder.pending"),a=Symbol.for("wcstack.binder.taken");const l=".",c="*",u=128,d=128,h="#",f="|",p="prevent",m="stop",g="ro",y="init",b="sync",w="else",v="...",_="on",$="eventToken",x="state",S="command",I="class",P="attr",k="style",N={};for(let t=0;t<u;t++)N[`$${t+1}`]=t;const A=Object.freeze(N),E="$connectedCallback",C="$disconnectedCallback",M="$renderedCallback",T="$errorCallback",O="$stateReadyCallback",L="$bindables",R="$commands",j="$commandTokens",W="$command",D="$eventTokens",z="$on",B="$stream",F="$watch",H="$scan",q="$recursion",U="**",V="$listKeys",G="$streamStatus",K="$streamError",J="data-wc-definition",Q=/\{\{\s*(.+?)\s*\}\}/g,X=new Set(["SCRIPT","STYLE"]);function Y(t){if(!s.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&&X.has(t.parentElement.tagName)||Z(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),Y(e.content)}else Y(t.content)}function Z(t){const e=t.data;if(Q.lastIndex=0,!Q.test(e))return;Q.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Q.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 tt(t){throw new Error(`[@wcstack/state] ${t}`)}const et=new Map;let nt=0;function ot(t){let e=et.get(t);if(void 0!==e)return e;-1!==t.indexOf(U)&&tt(`[wcs/recursion-unsupported] "${t}" uses "${U}", 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.`);const n=function(t){let e=1;for(let n=0;n<t.length;n++)t[n]===l&&e++;return e}(t);return n>512&&tt(`[wcs/binding-syntax] "${t}" has ${n} path segments — the limit is 512. Every prefix of a path is interned, so the cost grows with the square of the depth.`),e=Object.freeze(new st(t)),et.set(t,e),e}class st{id=++nt;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:ot(e),n=t.split("."),o=[],s=[],r=[],i={},a=[],l=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===c&&(r.push(h),i[h]=p,a.push(e(h)),l.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=l,this.wildcardParentPathSet=new Set(l),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 rt(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 it(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=rt(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const at=" Validate statically: npx @wcstack/lint <file>.",lt=new Set(["if","elseif","else","for"]);function ct(t,e){return`${JSON.stringify(t)}${JSON.stringify(e)}`}function ut(t){if(0===t.length)return"";let e="";for(let n=0;n<t.length;n++){const o=t[n];n>0&&(e+="|"),e+=`${o.filterName}(${ct(o.args,o.literals??o.args)})`}return e}let dt=null;const ht=new Map([["not",()=>t=>!t]]),ft=new Map([["not",[0,0]]]),pt={input:new Map,output:new Map},mt={input:new Map,output:new Map},gt={input:new Map,output:new Map},yt=new Map;function bt(t,e,n,o){const s=pt[t],r=mt[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)}const i=o??{},a=gt[t];for(const[t,n]of[...a])Object.prototype.hasOwnProperty.call(e,n)&&i[t]!==n&&a.delete(t);for(const t of Object.keys(i))a.set(t,i[t]);yt.clear()}function wt(t,e,n,o=e){const s=gt[n].get(t);void 0!==s&&dt?.renamed(t,s);const r=s??t,i=`${r}${ct(e,o)}:${n}`,a=yt.get(i);if(void 0!==a)return a;const l=pt[n].get(r)??ht.get(r);if(void 0===l){const e=0===pt[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";tt(`[wcs/filter-unknown] filter not found: ${t}.${it(t,function(t){return[...new Set([...ht.keys(),...pt[t].keys()])]}(n))}${e}${at}`)}const c=mt[n].get(r)??ft.get(r);void 0!==c&&(e.length<c[0]||e.length>c[1])&&tt(e.length<c[0]?`[wcs/filter-arity] filter "${t}" requires at least ${c[0]} argument(s) (${e.length} given).${at}`:`[wcs/filter-arity] filter "${t}" accepts at most ${c[1]} argument(s) (${e.length} given).${at}`);const u=l(e,o);return yt.set(i,u),u}function vt(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 _t=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function $t(t,e){return e?t:"true"===t||"false"!==t&&("null"===t?null:_t.test(t)?Number(t):t)}function xt(t){const e=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const t=vt(o,i,a);e.push(t),n.push($t(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&&tt(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${t})". Close the quote.${at}`);const c=vt(o,i,a);return(c||r)&&(e.push(c),n.push($t(c,r))),{args:e,literals:n}}const St=t=>t.trim(),It=t=>"'"===t||'"'===t;function Pt(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(It(s))n=s;else if(s===e)return o}return-1}function kt(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):It(i)?o=i:i===e&&(n.push(t.slice(s,r)),s=r+1)}return n.push(t.slice(s)),n}function Nt(t,e,n){const o=n??t.join("|");return t.map(t=>{const n=Pt(t,"(");let s=function(t){let e=null,n=-1;for(let o=0;o<t.length;o++){const s=t[o];null!==e?s===e&&(e=null):It(s)?e=s:")"===s&&(n=o)}return n}(t);if(-1===s&&(s=t.lastIndexOf(")")),-1!==n&&-1===s&&tt(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${t}".${at}`),-1!==s&&-1===n&&tt(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${t}".${at}`),-1!==s&&s<n&&tt(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${t}".${at}`),-1!==s&&t.slice(s+1).trim().length>0){const e=t.slice(s+1).trim();tt(`[wcs/binding-syntax] "${t}": unexpected "${e}" after the filter's closing ")" — separate filters with "|" (write "${t.slice(0,s+1)}|${e}").${at}`)}const r=(-1===n?t:t.substring(0,n)).trim();if(0===r.length&&tt(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${at}`),r.includes(h)){const[t,n]=r.split(h);tt("input"===e?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${h}${n}" comes before the input filters, not inside one — write "<property>${h}${n}|${t}".${at}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${h}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${t}" here.${at}`)}return-1===n?{filterName:r,args:[],literals:[]}:{filterName:r,...xt(t.substring(n+1,s))}})}const At=new Map;function Et(t){const e=Pt(t,f);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),At.has(s)?r=At.get(s):(o=kt(s,f).map(St),r=Nt(o,"input",t),At.set(s,r))):n=t.trim();const i=n.split(h).map(St);i.length>2&&tt(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${h}" — write "${i[0]}${h}${i.slice(1).join(",")}".${at}`);const[a,c]=i,u=a.split(l).map(St);return u.length>1&&""===u[0]||0!==a.length&&!u.some(t=>0===t.length)||tt(`[wcs/binding-syntax] "${t}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${at}`),{propName:a,propSegments:u,propModifiers:c?c.split(",").map(St):[],inFilters:r}}const Ct=new Map;function Mt(t){const e=Pt(t,f);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Ct.has(s)?r=Ct.get(s):(o=kt(s,f).map(St),r=Nt(o,"output",t),Ct.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&tt(`"${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.`);const i=n,a=i.startsWith(l),c=a?i.slice(1):i;return(c.length>0&&c.split(l).some(t=>0===t.length)||!a&&0===c.length)&&tt(`[wcs/binding-syntax] "${t}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).${at}`),{statePathName:i,statePathInfo:ot(i),outFilters:r}}const Tt=new Set([w,"if","elseif","for",v]),Ot=new Set([I,P,k,S,$,x]);function Lt(t){const[...e]=function(t){return kt(t,";")}(t).map(St).filter(t=>t.length>0),n=e.map(t=>{const e=Pt(t,":");-1===e&&tt(`[wcs/binding-syntax] Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.${at}`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim(),s=n.split(h)[0].split(f)[0].trim();if(s!==n&&Tt.has(s)&&tt(`[wcs/binding-syntax] "${t}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${at}`),n===w){o.length>0&&tt(`[wcs/binding-syntax] "${t}": "else" takes no value — write "else:".${at}`);const e=ot("#else");return{propName:w,propSegments:[w],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===v){0===o.length&&tt(`[wcs/binding-syntax] Invalid spread binding "${t}": spread target path is required.${at}`);const e=Mt(o);return e.outFilters.length>0&&tt(`[wcs/binding-syntax] Invalid spread binding "${t}": filters are not allowed on spread targets.${at}`),{propName:v,propSegments:[v],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Mt(o),bindingType:n};if("radio"===s||"checkbox"===s){const t=Mt(o);return{...Et(n),...t,bindingType:s}}{const t=Mt(o),e=Et(n);if(""===e.propSegments[0]&&e.propSegments.length>1){const o=e.propSegments.slice(1);return(o.includes("")||Ot.has(o[0]))&&tt(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Ot].join(", ")}).${at}`),{...e,propName:o.join(l),propSegments:o,...t,bindingType:"prop"}}return e.propSegments[0]===$||e.propSegments[0].startsWith(_)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>lt.has(t.bindingType))&&tt(`[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">).${at}`),n}const Rt=new WeakMap,jt=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),Wt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Dt(t){const e=Rt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),o=Wt.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return jt.has(r)?(Rt.set(t,o[2]),o[2]):null}function zt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Mt(t),bindingType:"text"}}const Bt=new WeakMap,Ft=new WeakSet;let Ht=0;async function qt(t){const e=function(t){let e,n=Bt.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++Ht,promise:o,resolve:e},Bt.set(t,n),Ft.has(t)&&n.resolve(),n}(t);await e.promise}function Ut(t){const e=Bt.get(t);void 0===e?Ft.add(t):e.resolve()}const Vt=new WeakMap;function Gt(t){const e=Vt.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{Vt.set(t,n)}}function Kt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Jt(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Kt(e);if(void 0!==n)return Kt(n)}return Kt(globalThis.customElements)}function Qt(t,e){t.upgrade?.(e)}function Xt(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=ee(s.properties,Yt);if(null===r)return null;const i=void 0===s.inputs?new Map:ee(s.inputs,Zt);if(null===i)return null;const a=void 0===s.commands?new Map:ee(s.commands,te);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Yt(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 Zt(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 te(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 ee(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 ne(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:ot(n),inFilters:[],outFilters:[],bindingType:"prop"}}function oe(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function se(t,e,n={}){const o=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&&tt("Spread binding requires an element node.");const e=t,s=Gt(e);null===s&&tt(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Jt(e);if(null===a&&tt(`CustomElementRegistry is unavailable for <${s}>.`),void 0===a.get(s)){o||tt(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Qt(a,e);const l=Xt(e);null===l&&tt(`Spread binding "${n.statePathName}" requires <${s}> 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=ne(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=ne(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=oe(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=oe(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(s.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 re(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 ie(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:wt(s.filterName,s.args,e,r)})}return n}function ae(t){return{...t,inFilters:ie(t.inFilters,"input"),outFilters:ie(t.outFilters,"output")}}const le=new WeakMap;function ce(t){return le.get(t)||null}function ue(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(s.bindAttributeName)}function de(t){const e=[],n=t.querySelectorAll(`${s.tagNames.state}[bind-component]`);for(const o of n){if(!ue(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function he(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 fe(t){const e=[],n=de(t),o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Dt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;o.nextNode();){const t=o.currentNode;n.length>0&&he(t,n)||e.push(t)}return e}const pe=new WeakSet;function me(t,e,n,o){const s=se(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Gt(t):null;return null===n&&tt("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}pe.add(t);const r=function(t,e){const n=[];for(const o of e){const e=ie(o.inFilters,"input"),s=ie(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){le.set(t,e)}(t,r),Ut(t),{bindings:r,deferred:null}}function ge(t,e){return ye(fe(t),e)}function ye(t,e){const n=[],o=[];for(const s of t){if(pe.has(s))continue;const t=me(s,Ol(s),{allowDeferred:!0},e);null===t.deferred?n.push(...t.bindings):o.push(t.deferred)}return[t,n,o]}function be(t){pe.add(t)}function we(t){const{node:e,parseResults:n,transform:o}=t;return function(t){pe.delete(t)}(e),me(e,n,{allowDeferred:!1},o).bindings}const ve=new WeakMap;let _e=null;function $e(t){let e=t;for(;e;){const t=ve.get(e);if(t)return t;let n=e.parentNode;null===n&&null!==_e&&e instanceof ShadowRoot&&(n=_e(e)),e=n}return null}function xe(t,e){null!==e?ve.set(t,e):ve.delete(t)}let Se=null,Ie=0;function Pe(){return`u${(Ie++).toString(36)}`}let ke=0,Ne=0;const Ae=Symbol("wcs.listIndex.noValue");class Ee{uuid=Pe();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;cacheStamp=0;ref;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ae,this._index=e,this._version=ke,this._chainGeneration=Ne}get index(){return this._index}set index(t){this._index=t,this._version=++ke,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}set homeParentListIndex(t){this._homeParentListIndex=t}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=ke),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Ne||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Ne),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++ke,Ne++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function Ce(t,e,n=t){return new Ee(t,e,n)}function Me(t,e){t.reparent(e)}function Te(t){return t.homeParentListIndex}function Oe(t,e){t.homeParentListIndex=e}function Le(t){return t?.cacheStamp}function Re(t,e){const n=t,o=n.value,s=o!==Ae&&!Object.is(o,e);return o!==e&&(je.get(o)?.delete(n.ref),function(t,e){if("object"!=typeof t||null===t||null===e.parentListIndex)return;let n=je.get(t);void 0===n?(n=new Set,je.set(t,n)):n.size>=(We.get(n)??8)&&(De(n,e,!0),We.set(n,2*n.size+8)),n.add(e.ref??=new WeakRef(e))}(e,n)),n.value=e,s}const je=new WeakMap,We=new WeakMap;function De(t,e,n=!1){const o=[];return t?.forEach(s=>{const r=s.deref();void 0===r||n&&Be(r)?t.delete(s):r!==e&&o.push(r)}),o}const ze=new WeakSet;function Be(t){for(let e=t;null!==e;e=e.parentListIndex)if(ze.has(e))return!0;return!1}function Fe(t){return t.value}function He(t,e){const n=t.value;return n!==Ae&&n===e.value}let qe=0;const Ue=new WeakSet;function Ve(t){Ue.add(t)}function Ge(t){return Ue.has(t)}const Ke=new WeakMap;function Je(t){return ze.has(t)}const Qe=new WeakMap,Xe=new WeakMap,Ye=new WeakMap;function Ze(t,e){return!0===Qe.get(e)?.has(t)}function tn(t,e){return Ze(t,e)||Be(e)}const en=new WeakMap;function nn(t){en.delete(t)}function on(t,e,n){const o=Object(Fe(e)),s=Fe(n);for(const e in s)if(s[e]===t&&o[e]!==t)return!1;return!0}function sn(t,e){return!tn(t,e)&&en.get(e)!==qe}const rn=new WeakMap,an=new WeakMap,ln=new WeakSet;function cn(t){const e=Ke.get(t);return void 0===e?null:e}function un(t,e){const n=Ke.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o&&!Ge(t)){const s=null!==e&&o.parentListIndex!==e&&en.get(e)!==qe,r=function(t,e,n){const o=Te(e),s=e.parentListIndex;return null!==o&&o!==s&&!tn(t,o)&&on(t,o,s)?o:function(t,e,n,o){return null!==e&&null!==o&&o!==n&&!!ze.has(e)&&!(!sn(t,o)||o.position!==e.position)&&!Ze(t,e)&&He(o,e)}(t,o,s,n)||function(t,e,n){return e!==n&&null!==e&&null!==n&&e.position===n.position&&tn(t,e)&&sn(t,n)}(t,s,n)?n:null}(t,o,e);if(null!==r&&ln.has(t)){ln.delete(t);const e=[...t];Ve(e),Ke.set(e,n),gn(t,e);const o=n.map((e,n)=>{const o=Ce(r,n);return Re(o,t[n]),o});return Ke.set(t,o),o}if(null!==r)for(const t of n)Me(t,r);else if(s){!function(t,e){let n=rn.get(t);void 0===n?(n=new Set,rn.set(t,n)):n.size>=(an.get(t)??8)&&(n.forEach(e=>{tn(t,e)&&n.delete(e)}),an.set(t,2*n.size+8));for(const t of e)n.add(t)}(t,[o.parentListIndex,e]);const s=o.parentListIndex;if(null!==s&&s.position===e.position&&!on(t,s,e)&&on(t,e,s))for(const t of n)Me(t,e)}}return n}const dn=new WeakSet;function hn(t){dn.delete(t)}function fn(t,e,n=!1){null!==e?(n?dn.add(e):hn(e),Ke.set(t,e)):Ke.delete(t)}const pn=new WeakMap;function mn(t){let e=pn.get(t);return void 0===e&&(e={value:t},pn.set(t,e)),e}function gn(t,e){const n=pn.get(t);void 0!==n&&(n.value=e,pn.delete(t))}const yn=new WeakMap,bn=new WeakMap,wn=new Set,vn=new WeakMap,_n=new WeakMap;function $n(t){const e=t.absolutePathInfo.stateElement;let n=bn.get(e);return void 0===n&&(n=new WeakMap,bn.set(e,n)),n}function xn(t){return yn.get(t)??[]}function Sn(t,e){const n=yn.get(t);yn.set(t,e),_n.delete(t);const o=$n(t);n!==e&&void 0!==n&&o.get(n).delete(t);const s=o.get(e);void 0===s?o.set(e,new Set([t])):s.has(t)||(s.size>=(vn.get(s)??8)&&(s.forEach(t=>{In(t.listIndex)&&s.delete(t)}),vn.set(s,Math.max(8,2*s.size))),s.add(t))}function In(t){for(let e=t;null!==e;e=e.parentListIndex)if(Je(e))return!0;return!1}function Pn(t,e){const n=$n(t).get(e);return void 0===n?wn:(n.forEach(t=>{In(t.listIndex)&&n.delete(t)}),n)}function kn(t,e){return!_n.has(t)&&(_n.set(t,e),!0)}function Nn(t){return yn.has(t)}const An=new WeakMap;let En=null,Cn=0;function Mn(t){return An.get(t)??[]}function Tn(t,e){null===En?An.set(t,e):En.set(t,e)}function On(){Cn++,null===En&&(En=new Map)}function Ln(){if(0!==Cn&&(Cn--,!(Cn>0||null===En))){for(const[t,e]of En)An.set(t,e);En=null}}function Rn(t){return(En?.has(t)??!1)||An.has(t)}const jn=Symbol("$$setLoopContext"),Wn=Symbol("$$getByAddress"),Dn=Symbol("$$hasByAddress"),zn=Symbol("$$connectedCallback"),Bn=Symbol("$$disconnectedCallback"),Fn=Symbol("$$updatedCallback"),Hn=Symbol("$$errorCallback"),qn=new WeakMap,Un=new WeakMap;class Vn{absolutePathInfo;listIndex;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}}function Gn(t,e){if(null===e){let e=Un.get(t);return void 0!==e||(e=new Vn(t,null),Un.set(t,e)),e}{let n=qn.get(e);void 0===n&&(n=new WeakMap,qn.set(e,n));let o=n.get(t);return void 0!==o||(o=new Vn(t,e),n.set(t,o)),o}}const Kn=new WeakMap;function Jn(t,e){let n=Kn.get(t);void 0===n&&(n=new Map,Kn.set(t,n));let o=n.get(e);return void 0===o&&(o=Object.freeze(new Qn(t,e)),n.set(e,o)),o}class Qn{pathInfo;stateElement;constructor(t,e){this.pathInfo=e,this.stateElement=t}}function Xn(t,e){return Gn(Jn(t,e.pathInfo),e.listIndex)}function Yn(t,e,n){return Gn(Jn(t,e),n)}const Zn=new WeakMap;function to(t,e){null===e?Zn.delete(t):Zn.set(t,e)}function eo(t){return Zn.get(t)||null}const no=new Map;function oo(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=no.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,no.set(s,r)),r}function so(t,e,n){return e<0||e>=n?null:t.at(e-n)}function ro(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const io=new WeakMap;function ao(t){const e=$e(t.node);if(null===e)return null;let n=io.get(e);if(void 0===n)n=new WeakMap,io.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=oo(e.pathInfo,t.statePathInfo);return n>0&&(o=so(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const lo=new WeakMap;function co(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=eo(n);null===e?tt(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function uo(t,e){let n=null;if(n=lo.get(t)||null,null!==n)return n;const o=co(t,e),s=ao(t),r=Pl(o);return null===r&&tt("No state tree found on this root for binding."),n=Yn(r,t.statePathInfo,s),lo.set(t,n),n}function ho(t){lo.delete(t)}const fo=new WeakMap;function po(t,e){const n=fo.get(t);void 0===n?fo.set(t,e):n instanceof Set?n.add(e):n!==e&&fo.set(t,new Set([n,e])),null!==Se&&Se({type:"state:binding-added",absoluteAddress:t,binding:e})}function mo(t,e){const n=fo.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&fo.delete(t),null!==Se&&Se({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const go=new WeakMap;function yo(t){const e=fo.get(t);return void 0!==e?e:null!==t.listIndex?go.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const bo=new WeakMap,wo=new WeakMap;class vo{pathInfo;listIndex;_parentAddress;_rowAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e,this._rowAddress=null!==e&&t.lastSegment===c}get parentAddress(){const t=this._parentAddress;if(void 0!==t&&(!this._rowAddress||t.listIndex===this.listIndex.parentListIndex))return t;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let n=null;n=this.pathInfo.segments[this.pathInfo.segments.length-1]===c?this.listIndex?.parentListIndex??null:this.listIndex;const o=$o(e,n);return void 0!==t&&!_o(o,this.listIndex)&&_o(t,this.listIndex)?t:this._parentAddress=o}}function _o(t,e){const n=t.pathInfo;let o=Fe(t.listIndex);for(const t of n.segments.slice(n.wildcardPositions[n.wildcardCount-1]+1))o=Object(o)[t];return cn(o)?.[e.index]===e}function $o(t,e){if(null===e){let e=wo.get(t);return void 0!==e||(e=new vo(t,null),wo.set(t,e)),e}{let n=bo.get(e);void 0===n&&(n=new WeakMap,bo.set(e,n));let o=n.get(t);return void 0!==o||(o=new vo(t,e),n.set(t,o)),o}}const xo=new WeakMap;function So(t){let e=null;if(e=xo.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=ao(t);null===n&&tt(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=$o(t.statePathInfo,n)}else e=$o(t.statePathInfo,null);return xo.set(t,e),e}function Io(t){xo.delete(t)}function Po(){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 ko=new Map,No=Po();function Ao(t,e){const n=ut(t.inFilters);return`${t.statePathName}::${e}::${n}`}function Eo(t){let e="input";for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}function Co(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function Mo(t,e){console.error(`[wcstack/state] ${e} rejected.`,t)}function To(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Co(t)&&Promise.resolve(t).catch(t=>Mo(t,e))}class Oo{_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)try{e.push(n(...t))}catch(t){e.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,t)}return e}}class Lo extends Oo{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==Se&&Se({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const Ro=new WeakMap;function jo(t,e){let n=Ro.get(t);void 0===n&&(n=new Map,Ro.set(t,n));let o=n.get(e);return void 0===o&&(o=new Lo(e,t),n.set(e,o)),o}const Wo=new WeakMap;class Do extends Oo{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==Se&&Se({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function zo(t){return t instanceof Do}const Bo=new Map,Fo=Po();function Ho(t){const e=t.propModifiers.filter(t=>t===p||t===m).sort().join(",");return`${t.statePathName}::${e}`}function qo(t){return"event"===t.bindingType&&t.propName.startsWith(_)}function Uo(t){if(!qo(t))return!1;const e=Ho(t);let n=Bo.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(p)&&o.preventDefault(),e.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Pl(r);null===i&&tt("No state tree found on this root for event handler.");const a=$e(s),l=t.startsWith(W+".");i.createStateAsync("writable",async e=>{const c=e[jn](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?ro(a.listIndex,c):[];if(l){const s=e[Wn]($o(n,null));return zo(s)||tt(`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&&tt(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});To(c,`"${t}"`)}).catch(e=>Mo(e,`"${t}"`))})(t.statePathName,t.propModifiers,t.statePathInfo),Bo.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Fo.add(e,t),!0}function Vo(t){if(!qo(t))return!1;const e=Ho(t),n=Bo.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);return t.node.removeEventListener(o,n),0!==Fo.countOf(e)&&(Fo.remove(e,t)&&Bo.delete(e),!0)}const Go=new Map,Ko=Po();function Jo(t,e){const n=ut(t.inFilters);return`${t.statePathName}::${e}::${n}`}function Qo(t){let e="input";for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}const Xo=new Set(["radio","checkbox"]),Yo=new Set(["value","valueAsNumber","valueAsDate"]);function Zo(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(Xo.has(t)&&"checked"===e)return!0;if(Yo.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Gt(n);if(null!==s){const t=Jt(n)?.get(s);void 0===t&&tt(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Xt(n);if(o?.knownProperties.has(e))return!0}return!1}let ts=1,es=1,ns=1;const os=new WeakMap;function ss(t,e,n){let o=os.get(t);void 0===o&&(o=new Map,os.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=ts++,o.set(s,r)),r}function rs(t,e){return"to-element"===e?2*t:2*t+1}const is=new Set;function as(t){return{transactionId:es++,originBindingId:t,visitedEdges:is,hop:0}}function ls(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 cs=null;function us(){return cs}function ds(t,e){const n=cs;cs=t;try{return e()}finally{cs=n}}const hs=[];let fs=0;function ps(t,e,n,o,s=!1){fs=s?2:1;try{t.createState("writable",t=>{t[jn](e,()=>{t[n]=o})})}finally{fs=0}}const ms=new Map,gs=Po(),ys=new WeakMap,bs=t=>t.detail,ws=new WeakMap,vs=new WeakMap;let _s=0;const $s=new WeakMap;function xs(t){const e=Gt(t.node);if(null!==e){const n=Jt(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&tt(`CustomElementRegistry is unavailable for <${e}>.`))}if(Zo(t.node,t.propName)&&-1===t.propModifiers.indexOf(g)){const e=function(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Gt(t.node);if(null!==n){const o=Jt(t.node)?.get(n);void 0===o&&tt(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Xt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}(t),n=function(t){if(null!==Gt(t.node)){const e=Xt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??bs}return null}(t),o=function(t){if(null===Gt(t.node))return!1;const e=Xt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}(t),r=function(t,e,n,o){const s=ut(t.inFilters);return`${t.propName}::${t.statePathName}::${e}::${s}::${function(t){if(null===t)return"n";let e=vs.get(t);return void 0===e&&vs.set(t,e=++_s),`g${e}`}(n)}::${o?"o":"s"}`}(t,e,n,o);$s.set(t,{key:r,eventName:e});let i=ms.get(r);void 0===i&&(i=((t,e,n,o,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==o)l=o(i),o!==bs||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=ws.get(t);void 0===r&&(r=new Set,ws.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=ys.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(s.enablePropagationContext){const n=ss(a,t,e),o=function(t,e){for(let n=hs.length-1;n>=0;n--){const o=hs[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==o&&Object.is(o.writtenValue,l))return s.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:o.transactionId,coveredBySameValueGuard:s.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==Se&&Se({type:"propagation:suppressed",reason:"confirmation",transactionId:o.transactionId,edgeId:rs(n,"to-state"),node:a,member:t}));const r=rs(n,"to-state"),i=us();if(null!==i&&i.visitedEdges.has(r))return void(null!==Se&&Se({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=ls(i??as(n),r)}const h=Pl(a.getRootNode());null===h&&tt("No state tree found on this root for two-way binding.");const f=$e(a),p=()=>ps(h,f,e,c,r);null!==d?ds(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,o),ms.set(r,i)),t.node.addEventListener(e,i),gs.add(r,t)}}const Ss=new WeakSet;function Is(t){Ss.add(t)}function Ps(t){return!!Ss.has(t)&&(Ss.delete(t),!0)}const ks=new WeakMap;function Ns(t,e){const n=ks.get(t);return!(void 0===n||n<e||(n===e?ks.delete(t):ks.set(t,n-e),0))}const As=new WeakSet;function Es(t){As.add(t)}function Cs(t){return!!As.has(t)&&(As.delete(t),!0)}let Ms=0;function Ts(){Ms--}function Os(){return Ms>0}class Ls{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 Rs=new WeakMap;function js(t){let e=Rs.get(t);return void 0===e&&(e=new Ls(t),Rs.set(t,e)),e}const Ws=new Set([I,P,k,S]);function Ds(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!==y&&s!==b&&tt(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&tt(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function zs(t){return t.propModifiers.some(t=>t.includes("="))}const Bs=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Fs=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Hs(t,e){return"state"===t&&"call"===e?Bs:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function qs(t){if(!s.enableDirectionalInitialSync)return zs(t)&&tt("init=/sync= modifiers require enableDirectionalInitialSync."),Bs;const e=null===(n=Ds(t,y))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:tt(`Invalid init modifier value "${n}".`);var n;const o=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":tt(`Invalid sync modifier value "${t}".`)}(Ds(t,b));if("event"===t.bindingType)return null!==e&&"none"!==e&&tt("Event bindings only allow init=none."),"call"===o?Fs:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(Ws.has(t.propSegments[0]))return Hs("state",o);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&tt(`Binding type "${t.bindingType}" does not support init=${e}.`),Hs(e??"state",o);const r=Xt(t.node);if(null===r)return Hs(e??"state",o);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||tt(`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)||tt(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==o||i||tt(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:o,observable:i,outputOnly:i&&!a}}function Us(t){let e=t.getRootNode();return e instanceof DocumentFragment&&!(e instanceof ShadowRoot)&&(e=eo(e)),null===e?null:Pl(e)}let Vs=0,Gs=null,Ks=0;const Js=["active","disposed","failed"],Qs=new WeakMap,Xs=new WeakMap,Ys=new WeakMap,Zs=new WeakMap,tr=new WeakMap,er=new WeakMap;function nr(t,e){const n=er.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):er.set(t,new Set([n,e]))):er.set(t,e)}function or(t){return er.has(t)}function sr(t,e){const n=er.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function rr(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))rr(n,e)}function ir(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class ar{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||!Ns(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)Ps(t)||rr(t,t=>{sr(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)Cs(t)&&!Os()||rr(t,t=>{sr(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&hl(o)}}const lr=new WeakMap;function cr(t){let e=lr.get(t);return void 0===e&&(e=new ar(t),lr.set(t,e)),e}function ur(t){const e=ut(t.inFilters),n=ut(t.outFilters);return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function dr(t,e,n){const o=Pl(co(t,n));null===o&&tt("No state tree found on this root for binding.");const s=Jn(o,t.statePathInfo);return function(t,e,n){let o=go.get(t);void 0===o&&(o=new WeakMap,go.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!==Se&&Se({type:"state:binding-added",absoluteAddress:Gn(t,e),binding:n})}(s,e,t),s}function hr(t,e){const n=uo(t,e);return po(n,t),n}function fr(t,e,n,o){null!==e?mo(e,t):function(t,e,n){const o=go.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!==Se&&Se({type:"state:binding-removed",absoluteAddress:Gn(t,e),binding:n}))}(n,o,t),Io(t),ho(t)}function pr(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class mr{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;disposedAt=0;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=Ys.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(ir(e)&&cr(e),null===this.rowPlan)for(const n of t){const t=Ys.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(!s.enableDirectionalInitialSync)return zs(t)&&qs(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=Ys.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){let o=Xs.get(e);return void 0===o&&Xs.set(e,o=[]),{id:o[n]??(o[n]=++Vs),info:t,generation:e.generation,phase:Js[e.phases[n]],teardowns:null}}const o=Ys.get(t);return o?.session===this?o:null}addTeardown(t,e){const n=Ys.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(pr(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=this.deferredByNode.get(t)??new Set,r=()=>s.delete(a)&&this.deferred.delete(a),i=()=>{const s=Jt(t);null===s&&tt(`CustomElementRegistry is unavailable for <${e}>.`),a.cancel=js(s).wait(e,()=>{if(r())try{Qt(s,t),n()}catch(t){o(t)}},t=>{r()&&o(t)})},a={node:t,born:++Ks,cancel:null,arm:()=>{if(null===a.cancel&&this.deferred.has(a))try{i()}catch(t){r(),o(t)}}},l=t.getRootNode();if(null!==Gs||11===l.nodeType&&!ir(l)){if(null===Gs){const t=Gs=[];queueMicrotask(()=>{Gs=null;for(let e=0;e<t.length;e++)t[e].arm()})}Gs.push(a)}else i();return ir(l)&&cr(l),nr(t,this),this.deferredByNode.set(t,s.add(a)),this.deferred.add(a),()=>{r(),a.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=Ys.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.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&&(mo(n,t.bindings[e]),t.addresses[e]=null),t.phases[e]=1}}dispose(){this.disposedAt=Ks;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.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(){this.disposedAt=Ks;for(const t of this.rows)this.destroyRowRecord(t);this.rows.clear();for(const t of this.records)null!==t.address&&(mo(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?uo(n):null;if(fr(n,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null,this.registerAddress(e),null!==o){const t=uo(n);t!==o&&Nn(o)&&Sn(t,xn(o)),t!==o&&Rn(o)&&Tn(t,Mn(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return ir(e)?e:null}(t);null!==e&&cr(e)}handleMutations(t,e,n){for(const n of e)rr(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)rr(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&hl(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);this.deferredByNode.get(t)?.forEach(t=>{t.cancel?.(),t.cancel=null,this.deferred.delete(t)})}handleAddedNode(t,e){this.deferredByNode.get(t)?.forEach(t=>{t.born<=this.disposedAt||(this.deferred.add(t),t.arm())});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=Ys.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||n.pendingDefinitions>0&&n.generation>this.disposedAt)&&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=tr.get(e);void 0===t&&(t=ur(e),tr.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;nr(n,this);const o=this.knownMapFor(n);let s=tr.get(t);void 0===s&&(s=ur(t),tr.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:++Vs,session:this,generation:++Ks,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(nr(r,this),this.addKnownRowBinding(r,o,t),Qs.set(o,s),n[t].isEvent){let n=!1;try{n=Uo(o)}catch(e){throw s.phases[t]=2,e}n&&(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=++Ks,r=!0,this.rows.add(o)),o.phases[t]=0,o.flags[t]=0,s[t].isEvent){let n=!1;try{n=Uo(e[t])}catch(e){throw o.phases[t]=2,this.runRowSlotTeardowns(o,t),e}n&&(o.flags[t]|=2)}this.registerRowSlot(o,t,n)}}rowOf(t){const e=Qs.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=ao(o);null!==s?(t.patternPathInfos[e]=dr(o,s,n),t.patternListIndexes[e]=s):t.addresses[e]=hr(o,n)}unregisterRowSlot(t,e){const n=t.addresses[e],o=t.patternPathInfos[e];null===n&&null===o||(fr(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{Vo(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:++Vs,info:t,generation:++Ks,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};Ys.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;Uo(e)?t.eventAttached=!0:e.propSegments[0]!==$?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const o=Qo(t),s=Jo(t,o);let r=Go.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=Pl(o.getRootNode());null===r&&tt("No state tree found on this root for two-way binding.");const i=$e(o);r.createState("writable",t=>{t[jn](i,()=>{t[e]=s})})},Go.set(s,r)),t.node.addEventListener(o,r),Ko.add(s,t),!0}var e,n;return!1}(e)&&pr(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const e=Qo(t),n=Jo(t,e),o=Go.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Ko.countOf(n)&&(Ko.remove(n,t)&&Go.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const o=Eo(t),s=Ao(t,o);let r=ko.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=Pl(o.getRootNode());null===i&&tt("No state tree found on this root for two-way binding.");const a=$e(o);i.createState("writable",t=>{t[jn](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]:[]})})},ko.set(s,r)),t.node.addEventListener(o,r),No.add(s,t),!0}var e,n;return!1}(e)&&pr(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const e=Eo(t),n=Ao(t,e),o=ko.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==No.countOf(n)&&(No.remove(n,t)&&ko.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(s.enableDirectionalInitialSync&&Zo(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const n=function(t,e,n){let o=ys.get(t);void 0===o&&(o=new Map,ys.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&&ys.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});pr(t,n)}xs(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==$)return!1;const e=t.node,n=Gt(e),o=Jt(e);if(null!==n&&void 0===o?.get(n))return null===o&&tt(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Wo.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||tt('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Gt(t)?null:Xt(t)}(e);null===r&&tt(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&tt(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${it(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,c=t.propModifiers,u=t=>{c.includes(p)&&t.preventDefault(),c.includes(m)&&t.stopPropagation();const n=Pl(e.getRootNode());null===n&&tt("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||tt(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${it(l,n.eventTokenNames)}${at}`);const o=$e(e);n.createStateAsync("writable",async e=>{To(e[jn](o,()=>{const s=null!==o?ro(o.listIndex,o.pathInfo.wildcardCount):[];return jo(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,u),Wo.set(t,{eventName:a,handler:u}),!0})(e)&&pr(t,()=>function(t){if(t.propSegments[0]!==$)return!1;const e=Wo.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),Wo.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Gt(t.info.node);if(null===n)return void e();const o=Jt(t.info.node);if(null===o&&tt(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation;pr(t,this.deferUntilDefined(t.info.node,n,()=>{this.isAlive(t,s)&&(e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t)))},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))}))}settleInitialRecord(t){if(s.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=qs(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=Us(t.replaceNode);null===e&&tt("No state tree found on this root for binding.");const n=So(t);let o=!1;return e.createState("readonly",t=>{o=t[Dn](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 Ms++;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,Ts()),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=Us(t.node);null===o&&tt("No state tree found on this root for initial binding sync."),ps(o,$e(t.node),t.statePathName,n)}(t.info,r))}settleConnectedSnapshot(t){if(s.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=ao(n);if(null!==o?(t.patternPathInfo=dr(n,o,e),t.patternListIndex=o):t.address=hr(n,e),!t.options.registerPathInfo)return;const s=Pl(n.replaceNode.getRootNode());null===s&&tt("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&&Ys.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,Ts());const e=t.info;if(null!==t.address||null!==t.patternListIndex)try{fr(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=$s.get(t);if(void 0===e)return;$s.delete(t);const n=ms.get(e.key);void 0!==n&&(t.node.removeEventListener(e.eventName,n),gs.remove(e.key,t)&&ms.delete(e.key))}(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{Vo(e)}catch{}}}}function gr(t){let e=Zs.get(t);return void 0===e&&(e=new mr(t),Zs.set(t,e)),e}function yr(t){return Ys.get(t)?.session??Qs.get(t)?.session??null}let br=null;function wr(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const vr=Object.freeze([]),_r=new WeakMap,$r=new WeakMap;function xr(t){return $r.get(t)??[]}function Sr(t,e){$r.set(t,e)}const Ir=new WeakMap;function Pr(t){return Ir.get(t)??[]}function kr(t,e){Ir.set(t,e)}function Nr(t,e){const n=Pr(t);for(const t of n)xe(t,e)}const Ar=new WeakMap;function Er(t){return Ar.get(t)??[]}function Cr(t,e){Ar.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});const Mr=new WeakMap,Tr=new WeakSet;function Or(t,e){if(null===e)Mr.delete(t);else{Mr.set(t,e);const{stateElement:n,pathInfo:o}=t.absolutePathInfo;if(o.wildcardCount>0){for(let t=o.parentPathInfo;null!==t&&t.wildcardCount===o.wildcardCount&&!Tr.has(t);t=t.parentPathInfo)Tr.add(t);n.setPathInfo(o.lastWildcardPath,"prop","internal")}}}function Lr(t){const e=Mr.get(t);e&&(e.dirty=!0),null!==t.listIndex&&Tr.has(t.absolutePathInfo.pathInfo)&&t.listIndex.cacheStamp++}const Rr=Symbol.for("wcstack.transition-runner");function jr(t){const e=globalThis[Rr];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 Wr(t,e,n){const o=jr(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const Dr=[],zr=[];let Br=-1,Fr=0,Hr=!1;function qr(t){zr.includes(t)||zr.push(t)}function Ur(t,e=0){const n=Dr.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Dr.push(o):Dr.splice(n,0,o)}function Vr(t){queueMicrotask(()=>{throw t})}const Gr=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){for(let e=0;e<zr.length;e++)zr[e](t);Br>Fr&&(Fr=Br),Br<0&&(Hr=!0);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(){On(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],qe++,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=[]){let o=Hr?0:Fr;Fr=0,Hr=!1;const s=new Map,r=new Set;for(let e=0;e<t.length;e++){const n=t[e],o=s.get(n.absoluteAddress);null!==Se&&null!=o&&null!==n.context&&o.transactionId!==n.context.transactionId&&Se({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:o.transactionId,winnerTransactionId:n.context.transactionId}),s.set(n.absoluteAddress,n.context),r.add(n.absoluteAddress)}for(let t=0;t<n.length;t++){const e=n[t];s.has(e)||s.set(e,null)}const i=[],a=new Map;s.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!==Se&&Se({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop}));const n=yo(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(i.push(e),null!==t&&a.set(e,t));else!1!==n.replaceNode.isConnected&&(i.push(n),null!==t&&a.set(n,t))});try{const t=()=>{Br=o+1;try{a.size>0?hl(i,a):hl(i)}finally{Br=-1}};if(o>100&&i.length>0){if(101===o++){const t=[...new Set(Array.from(r,t=>t.absolutePathInfo.pathInfo.path))];console.error("[@wcstack/state] render chain depth limit exceeded; bindings for this batch were not applied.",{maxDepth:100,paths:t}),null!==Se&&Se({type:"state:render-chain-limit",maxDepth:100,paths:t})}}else if(e()||0===i.length)t();else{const e=Wr("state",t);void 0!==e&&e.catch(Vr)}}finally{Ln(),Br=o,function(t){for(const e of Dr.slice())e.listener(t)}(r),Br=-1}}};function Kr(){return Gr}const Jr=new WeakMap,Qr=new WeakMap,Xr=new WeakMap,Yr=new WeakMap;let Zr=!1;const ti=new WeakMap;function ei(t){const e=t.absolutePathInfo.stateElement;let n=ti.get(e);void 0===n&&ti.set(e,n=new Set),n.add(t)}function ni(t){const e=ti.get(t);return void 0===e?null:(ti.delete(t),e)}const oi=new WeakMap,si=new WeakMap,ri=new WeakMap,ii=new WeakMap,ai=new WeakMap,li=[];function ci(t,e){const n=ui(t);if(n.recorded.has(e))return;n.recorded.add(e);const o=ot(e).cumulativePaths;if(o.length<2)return;let s=ai.get(t);void 0===s&&ai.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 ui(t){let e=Jr.get(t);return void 0===e&&Jr.set(t,e={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),e}function di(t,e,n){let o=t.get(e);void 0===o&&t.set(e,o=new Set),o.add(n)}function hi(t,e,n){const o=t.get(e);o.delete(n),0===o.size&&t.delete(e)}function fi(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=Qr.get(o);if(void 0===r&&Qr.set(o,r=new Map),r.has(e)){const t=r.get(e);return Object.is(t,n)||(hi(s,t,o),r.set(e,n),di(s,n,o)),!1}return r.set(e,n),di(s,n,o),!0}function pi(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):(o.push(n),!1)}function mi(t,e,n,o,s,r){t.lastValue.set(e,n),s&&(null!==o.listIndex&&pi(Xr,o.listIndex,r)&&function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){let n=ri.get(e);void 0===n&&ri.set(e,n=new Set),n.add(t)}}(o.listIndex),null!==r.levelListIndex&&pi(Yr,r.levelListIndex,r))}function gi(t,e,n,o,s){Zr=!0;const r=ui(t);ci(t,e),mi(r,e,s,o,fi(r,e,n,o),{stateElement:t,path:e,absAddress:o,levelListIndex:null})}function yi(t,e){ui(t).tracked.add(e)}function bi(t,e){return!0===Jr.get(t)?.byPath.has(e)||!0===oi.get(t)?.has(e)}function wi(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(Xn(t.stateElement,$o(e,o)))}function vi(t,e){if(!Zr||t===e)return;const n=si.get(t);if(void 0===n)return;si.delete(t);const o=si.get(e);si.set(e,void 0===o?n:o.concat(n)),hn(e);for(const o of n){o.indexes=e;const n=ui(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&&!Je(t))for(const e of o.getters){const n=Xn(o.stateElement,$o(e,t));Lr(n),Kr().enqueueAbsoluteAddress(n,null),ei(n)}}}function _i(t,e){if(void 0!==t)for(const n of t)e.push(n)}function $i(t,e,n,o,s){const r=Jr.get(t),i=r?.byPath.get(e),a=oi.get(t)?.get(e);if(void 0===r||void 0===i&&void 0===a)return li;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&&_i(i.get(o),u),h&&_i(i.get(c),u),d&&_i(i.get(s),u)),void 0!==a)for(const t of a)n&&wi(t,o,u),h&&wi(t,c,u),d&&wi(t,s,u);return u}function xi(t,e){return!0===ai.get(t)?.has(e)}function Si(t,e){let n=t;for(const t of e){if("object"!=typeof n||null===n)return;n=n[t]}return n}function Ii(t,e,n,o,s=!0){const r=ot(e).segments.length,i=[];for(const a of ai.get(t).get(e)){const e=ot(a).segments.slice(r);if(e.includes(c)){Pi(t,a,i);continue}const l=s?Si(n,e):void 0;for(const n of $i(t,a,s,l,Si(o,e)))i.push(n)}return i}function Pi(t,e,n){const o=Jr.get(t).byPath.get(e);if(void 0!==o)for(const t of o.values())_i(t,n);const s=oi.get(t)?.get(e);if(void 0!==s)for(const t of s)for(let e=0;e<t.indexes.length;e++)wi(t,e,n)}function ki(t){const e=Yr.get(t.levelListIndex),n=e.indexOf(t);e.splice(n,1)}function Ni(t){const e=Xr.get(t);if(void 0!==e){Xr.delete(t),function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){const n=ri.get(e);void 0!==n&&(n.delete(t),0===n.size&&ri.delete(e))}}(t);for(const t of e){const{stateElement:e,path:n,absAddress:o}=t,s=Qr.get(o),r=s.get(n);s.delete(n),hi(Jr.get(e).byPath.get(n),r,o),null!==t.levelListIndex&&ki(t)}}}function Ai(t){const e=ii.get(t);if(void 0!==e){ii.delete(t);for(const t of e){const e=oi.get(t.stateElement),n=e.get(t.path);n.delete(t),0===n.size&&e.delete(t.path);const o=si.get(t.indexes);o.splice(o.indexOf(t),1),0===o.length&&si.delete(t.indexes)}}}function Ei(t){if(!Zr)return;Ni(t),Ai(t);const e=ri.get(t);if(void 0!==e){ri.delete(t);for(const t of e)Ni(t),Ai(t),ri.delete(t)}}function Ci(t,e,n){if(!Zr)return;const o=Yr.get(t);if(void 0!==o)for(const{stateElement:t,path:s,absAddress:r}of o){const o=Jr.get(t),i=o.byPath.get(s);hi(i,e,r),di(i,n,r),Qr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,e)||Object.is(a,n))&&(Lr(r),Kr().enqueueAbsoluteAddress(r,null),ei(r))}}const Mi=new WeakMap,Ti=Object.freeze([]),Oi=new Set,Li=new WeakMap,Ri=new WeakMap;function ji(t,e){Ri.set(t,new WeakRef(Object(e)))}function Wi(t){return Ri.get(t)?.deref()}function Di(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}function zi(t){!function(t){for(const e of t)ze.add(e)}(t);for(const e of t)Ei(e)}function Bi(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:Ti,s=Array.isArray(n)&&n.length>0?n:Ti,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:Ti,o=Array.isArray(e)&&e.length>0?e:Ti;let s=Mi.get(n);return s&&s.get(o)||null}(o,s);if(r&&r.newIndexes===un(s,t))return r;const i=un(o,t)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Oi,deleteIndexSet:new Set(i),addIndexSet:Oi};let e=un(s,t);if(null===e&&null!==t&&function(t,e){const n=rn.get(t);for(const o of n??[])if(tn(t,o))n.delete(o);else if(o!==e)return!0;return!1}(o,t)&&ji(s,o),0===o.length||null===e&&Wi(s)===o){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=Ce(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:Oi,deleteIndexSet:new Set(i),addIndexSet:new Set(e)}}if(Di(o,s)&&(e??i)===i)return o!==s&&Fi(o,i,t),a={oldIndexes:i,newIndexes:i,changeIndexSet:Oi,deleteIndexSet:Oi,addIndexSet:Oi};if(null!==e)return Hi(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,l=new Set;let c=!1;for(let o=0;o<s.length;o++){const a=s[o],u=n.get(a),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=Ce(t,o);e.push(n),l.add(n)}else{const t=i[d];c=!0,d!==o&&r.add(t),e.push(t)}}return c&&Fi(o,e,t),a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(function(t,e,n){let o=Mi.get(t);o||(o=new WeakMap,Mi.set(t,o)),o.set(e,n)}(o,s,a),hn(i),fn(s,a.newIndexes))}}(t,e,n);return function(t,e){const n=t.newIndexes;let o;for(let t=0;t<n.length;t++){if(n[t].index!==t){const e=n[t].index;n[t].index=t,Ci(n[t],e,t)}Re(n[t],e[t])&&(o??=[]).push(n[t])}const s=Li.get(e);s?.[0]===qe&&(o=o?s[1].concat(o):s[1]),o&&Li.set(e,[qe,o]),t.valueChangeIndexes=o}(o,Array.isArray(n)&&n.length>0?n:Ti),function(t){for(const e of t)ze.delete(e)}(o.newIndexes),Wi(n)!==e&&(zi(o.deleteIndexSet),vi(o.oldIndexes,o.newIndexes)),o}function Fi(t,e,n){var o;if(o=t,ln.add(o),null!==n)for(const t of e)Oe(t,n)}function Hi(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}}const qi=new WeakMap;function Ui(t){return qi.get(t)??null}function Vi(t,e){qi.set(t,e)}const Gi=new WeakMap,Ki=new WeakMap;function Ji(t,e){for(let n=0;n<t.length;n++)if(e.has(t[n]))return!0;return!1}function Qi(t,e,n){Nr(t,e);const o=xr(t),s=Ui(t);if(null!==s&&(s.activate(o,n.rootNode),null!==e&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(t){return Gi.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=Ki.get(t);void 0===o&&Ki.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,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let t=0;t<e.length;t++){const u=e[t];if(!n.shouldApplyState(u))continue;const d=r[t];if(null===d||Ji(d.prefixes,i)){ul(u,s);continue}if(s.appliedBindingSet.has(u))continue;c||(l=s.state[Wn](o),c=!0);const h=d.tail;let f=l,p=!1;for(let t=0;t<h.length;t++){if(null==f){f=void 0;break}if(a&&!(h[t]in Object(f))){p=!0;break}f=f[h[t]]}p?ul(u,s):(s.appliedBindingSet.add(u),cl(u,s,f))}}(r,o,s,e,n)}for(const t of o)null===s&&po(uo(t),t),(null===s||s.shouldApplyState(t))&&ul(t,n);t.spreads&&fl(t.spreads,e,s,o,Er(t))}function Xi(t){if(!t.mounted)return;const e=xr(t),n=Ui(t);for(let t=0;t<e.length;t++){const o=e[t];null!==n?n.disposeBinding(o):mo(uo(o),o)}!function(t){const e=Pr(t);for(let t=0;t<e.length;t++)xe(e[t],null)}(t)}const Yi=new WeakMap,Zi=Object.freeze(new Set);function ta(t,e){const n=Yi.get(t);n?n.add(e):Yi.set(t,new Set([e]))}function ea(t){const e=Yi.get(t);return void 0!==e?e:Zi}function na(t,e){const n=Yi.get(t);n&&(n.delete(e),0===n.size&&Yi.delete(t))}const oa=new Set(["if","elseif","else","for"]);class sa{_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];Es(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){Es(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=Ui(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRow(xr(this));const e=this._childNodeArray;for(let t=0;t<e.length;t++){const n=e[t];null!==n.parentNode&&(Is(n),n.parentNode.removeChild(n))}const n=xr(this);for(let t=0;t<n.length;t++){const e=n[t];oa.has(e.bindingType)&&ea(e.node).forEach(t=>{t.tryDestroy()||t.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const t=Ui(this);null!==t&&(t.isRowSession?t.disposeBindings(xr(this)):t.dispose())}this._teardownBindings()}_teardownBindings(){const t=xr(this);for(let e=0;e<t.length;e++){const n=t[e];oa.has(n.bindingType)&&ea(n.node).forEach(t=>{t.unmount()}),Io(n),ho(n)}}unmount(){{const t=Ui(this);null!==t&&(t.isRowSession?t.disposeBindings(xr(this)):t.dispose())}for(const t of this._childNodeArray)null!==t.parentNode&&(Is(t),t.parentNode.removeChild(t));const t=xr(this);for(let e=0;e<t.length;e++){const n=t[e];oa.has(n.bindingType)&&ea(n.node).forEach(t=>{t.unmount()}),Io(n),ho(n)}this._mounted=!1}}function ra(t){return 1<<Math.min(t,31)}function ia(t){let e=t.indexBits;if(void 0===e){e=0;for(const n of t.nodeInfos)for(const t of n.parseBindTextResults)t.statePathName in A&&(e|=ra(A[t.statePathName])),"string"==typeof t.uuid&&(e|=ia(Tl(t.uuid)));t.indexBits=e}return e}function aa(t){return ia(Tl(t.uuid))}function la(t,e){return t.statePathName in A||oa.has(t.bindingType)&&0!==(aa(t)&e)}function ca(t,e){const n=document.createDocumentFragment(),o=new sa(n,e);return o._childNodeArray=t,o._firstNode=t.length>0?t[0]:null,o._lastNode=t.length>0?t[t.length-1]:null,o._mounted=!0,o}function ua(t){void 0!==t.uuid&&null!==t.uuid||tt("BindingInfo.uuid is null.");const n=Tl(t.uuid);n||tt(`Fragment with UUID "${t.uuid}" not found.`);const o=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${s.commentForPrefix}|${s.commentIfPrefix}|${s.commentElseIfPrefix}|${s.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!==s.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=s.enableDirectionalInitialSync,n=[],o=t.nodeInfos;for(let e=0;e<o.length;e++){const s=o[e],r=re(t.fragment,s.nodePath);if(null===r)return null;for(const t of s.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!==Gt(r))return null;if("prop"===o&&Zo(r,t.propName))return null;const i=ae(t);let a;try{a=qs({...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 A,policy:a,authority:a.authority})}}return 0===n.length?null:{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=re(o,s[t].nodePath);null===e&&tt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),be(e),Ut(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=ml.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new mr,ml.set(n,o)),o.initializeRow(t,e),o}(n,a,t.node),u=new sa(o);return Vi(u,c),Sr(u,a),function(t,e){Gi.set(t,e)}(u,n),Cr(u,l),kr(u,r),ta(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o,s]=function(t,e){const n=[],o=[],s=[];for(const r of e){const e=re(t,r.nodePath);if(null===e&&tt(`Node not found by path [${r.nodePath.join(", ")}] in fragment.`),pe.has(e))continue;const i=me(e,r.parseBindTextResults,{allowDeferred:!0});null!==i.deferred&&(s.push(i.deferred),pe.add(e)),o.push(...i.bindings),n.push(e)}return[n,o,s]}(t,e),r=new mr;return{nodes:n,bindingInfos:r.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:r,spreads:s}}(i,n.nodeInfos);o&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new sa(i,o);a.spreads.length>0&&(l.spreads=a.spreads),Vi(l,a.bindingSession),Sr(l,a.bindingInfos);const c="for"===t.bindingType?(u=t.statePathInfo.wildcardCount+1,2**Math.min(u,32)-1):-1;var u;const d=[];for(const t of a.bindingInfos)la(t,c)&&d.push(t);return Cr(l,d),kr(l,a.nodes),ta(t.node,l),l}const da=new WeakSet,ha=Symbol.for("wcstack.state.view-transition-naming");function fa(){const t=jr("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function pa(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||da.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[ha]??={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.`)):(da.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 ma=new WeakMap,ga=new WeakMap,ya=new WeakMap,ba=new WeakMap,wa=new WeakMap,va=new WeakMap;function _a(t,e,n,o){let s=va.get(t);void 0===s&&(s=[document.createComment(""),document.createComment("")],va.set(t,s));const[r,i]=s;r.data=`@@wcs-for-start:${o}`,i.data=`@@wcs-for-end:${o}`,t.mounted||(r.remove(),i.remove());const a=null===n?null:n.nextSibling;if(null===r.parentNode)e.insertBefore(r,a),e.insertBefore(i,a),t.mountAfter(r);else if(a!==r){let t=r;for(;t!==i;){const n=t.nextSibling;e.insertBefore(t,a),t=n}e.insertBefore(i,a)}return i}function $a(t,e,n){!function(t,e,n){let o=ga.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,ga.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function xa(t,e){ma.set(t,e)}function Sa(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 Ia(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 Pa=new Set(["if","elseif","else","for"]);function ka(t,e){for(const n of xr(t))if(e.appliedBindingSet.delete(n),Pa.has(n.bindingType))for(const t of ea(n.node))ka(t,e)}function Na(t,e,n){for(const o of Er(t))if(Pa.has(o.bindingType)){if(o.statePathName in A&&ul(o,e),0!==(aa(o)&n))for(const t of ea(o.node))t.mounted&&Na(t,e,n)}else ul(o,e)}function Aa(t){for(const e of xr(t)){if(!Pa.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of ea(e.node))Aa(n),t&&n.mounted&&(Xi(n),n.unmount(),na(e.node,n),wa.delete(e.node),ga.delete(e.node))}}function Ea(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function Ca(t,o,r){const i=Boolean(r);let a;const l=ea(t.node);a=0===l.size?ua(t):l.values().next().value;const c=e(),u=t.uuid??"",d=t.bindingType;if(i||(s.debug&&console.log(`unmount if content : ${Ea(t)}`),c&&a.mounted&&(n.seen=!0),Xi(a),a.unmount()),i){s.debug&&console.log(`mount if content : ${Ea(t)}`);const e=$e(t.node);if(Nr(a,e),c){if(!a.mounted){const e=document.createComment(`@@wcs-${d}-start:${u}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),a.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${u}:${t.statePathName}`),o=a.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}}else a.mountAfter(t.node);Qi(a,e,o);const n=fa();null!==n&&pa(a,"branch",n)}}const Ma=new WeakMap;function Ta(t){return Ma.get(t)??[]}const Oa=new Set;function La(){Oa.clear()}const Ra=Symbol.for("wcstack.trustedTypes.policy");function ja(){const t=globalThis[Ra];return null===t||"object"!=typeof t?null:t}let Wa,Da=!1;const za={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")}};function Ba(t,n,o){if(1===t.propSegments.length){const e=t.propSegments[0];"textContent"===e||"innerText"===e?o=null==o?"":String(o):void 0===o&&"innerHTML"===e&&(o="")}if(void 0===o)return void(s.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!==o){null!==br&&null!==u&&"object"==typeof u&&null!==o&&"object"==typeof o&&null!==Gt(r)&&br.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=ja(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(o):o,t=!0}catch(t){e&&function(t,e){if(Da)return;if(!function(){if(void 0!==Wa)return Wa;if(!("trustedTypes"in globalThis))return Wa=!1,Wa;try{document.createElement("div").innerHTML="<i></i>",Wa=!1}catch{Wa=!0}return Wa}())return;Da=!0;const n="function"==typeof ja()?.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),s.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:o,error:t})}if(t){const t=function(t,e){const n=Gt(t);if(null===n)return null;const o=Jt(t)?.get(n);if(void 0===o)return null;const s=Xt(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,o)}catch(e){s.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:o,error:e})}}};if(s.enablePropagationContext&&Zo(r,c)){const e=ss(r,c,t.statePathName),s=rs(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??us()??as(e);if(a.visitedEdges.has(s))null!==Se&&Se({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:s,node:r,member:c});else{const t=ls(a,s);ds(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:ns++,writtenValue:n};hs.push({receipt:i,node:t});try{return r()}finally{hs.pop()}}(r,c,o,e,t.transactionId,i))}}else i()}if(e()){const t=za[c];t?t(r,o):(function(t,e,n){let o=Ma.get(t);o||(o=[],Ma.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,o),a=r,Oa.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!==o){if(Object.isFrozen(u))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:o}));null!==br&&2===i.length&&"object"==typeof u&&null!==u&&null!==Gt(r)&&(d in u?br.rememberOverwrittenValue(r,c,d,u[d]):br.recordInjectedKey(r,c,d));try{u[d]=o}catch(t){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:o,error:t})}}}const Fa=new WeakSet;function Ha(t,e,n){}function qa(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)}}const Ua=new WeakMap;function Va(t,e,n,o){const s=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),r=e.length>0?e+l:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(l)&&!Ua.has(qa(o,t)?.get)&&s.push(e)}return s}const Ga={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Ka={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Ja(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}.${at}`}function Qa(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 Xa(t,e){return`$setAll("${t}") ${e}`}function Ya(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.${at}`}const Za=new WeakSet;function tl(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const el=Object.freeze({[I]:function(t,e,n){const o=t.node,s=t.propSegments[1];null!=n?("boolean"!=typeof n&&tt(`Invalid value for class application: expected boolean, got ${typeof n}. Write "|truthy" if you mean to coerce.`),o.classList.toggle(s,n)):o.classList.toggle(s,!1)},[P]:function(t,e,n){const o=t.node,s=t.propSegments[1];if(null==n)return void(o.hasAttribute(s)&&o.removeAttribute(s));const r=String(n);o.getAttribute(s)!==r&&o.setAttribute(s,r)},[k]: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){zo(n)||tt("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=_r.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||tt('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Gt(t);if(null===e)return null;const n=Jt(t)?.get(e);return void 0===n&&tt(`Custom element <${e}> is not defined for command binding.`),Xt(t)}(r);null===a&&tt(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||tt(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${it(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),_r.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 _r.delete(t);const o=n[i];return"function"!=typeof o&&tt(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),_r.set(t,{token:o,unsubscribe:c,elementRef:l})}}),nl={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Fa.has(t.replaceNode)){Fa.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,o,s){const r=t.statePathInfo,i=ao(t),a=uo(t),l=xn(a),u=wa.get(t.node);let d,h;const f=void 0!==u&&function(t,e){const n=_n.get(t);return void 0!==n&&(n===e||cn(e)===cn(n))}(a,s),p=f||void 0===u||u.value===l?null:Bi(i,l,s);f?(d=u.value,h=Hi(cn(d),cn(s))):null!==p&&p.newIndexes.every(t=>t.parentListIndex===i||Je(t.parentListIndex)||!Ze(s,t.parentListIndex))?(d=u.value,h=Hi(cn(d)??[],p.newIndexes)):(d=l.length>0&&!ga.has(t.node)?[]:l,h=Bi(i,d,s));const m=Array.isArray(s)?s:[];o.newListValueByAbsAddress.set(a,m),wa.set(t.node,mn(m));let g=ga.get(t.node);const y=void 0!==g?function(t,e,n){if(!Ge(e))return null;let o=null;for(let e=0;e<n.newIndexes.length;e++){const s=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(s)&&n.deleteIndexSet.has(r)?t.get(r):void 0;void 0!==i&&(o??={byAddedIndex:new Map,reused:new Set},o.byAddedIndex.set(s,i),o.reused.add(i))}return o}(g,d,h):null,b=Array.isArray(d)&&d.length===h.deleteIndexSet.size&&h.deleteIndexSet.size>0;if(b&&null===y&&null!==t.node.parentNode){let e=ba.get(t.node);if(void 0===e){const n=ma.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(Sa(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Sa(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n.parentNode===t.node.parentNode?n:t.node),ba.set(t.node,e)}if(e){const e=t.node.parentNode;!function(t,e){ks.set(t,(ks.get(t)??0)+e)}(e,e.childNodes.length),e.textContent="",e.appendChild(t.node)}}let w=b?1e3-function(t){return ya.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;const v=e();if(void 0!==g){const e=g;h.deleteIndexSet.forEach(o=>{const s=e.get(o);void 0!==s&&(v&&(va.get(s)?.forEach(t=>t.remove()),n.seen=!0),null!==y&&y.reused.has(s)?(Xi(s),Aa(s),s.unmountInPlace()):w<=0&&s.tryDestroy()?na(t.node,s):(Xi(s),s.unmount(),function(t,e){let n=ya.get(t.node);void 0===n&&(n=[],ya.set(t.node,n)),n.length<1e3?n.push(e):na(t.node,e)}(t,s),w-=1),b||e.delete(o))}),b&&(ga.delete(t.node),g=void 0)}let _=t.node;const $=ot(r.path+"."+c),x=o.stateElement.loopContextStack,S=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}(h);let I=null;h.newIndexes.length==h.addIndexSet.size&&h.newIndexes.length>0&&_.isConnected&&null===y&&(I=document.createDocumentFragment(),to(I,o.rootNode));const P=v?`${t.uuid}:${r.path}:`:"",k=fa(),N=ya.get(t.node);for(const e of h.newIndexes){let n;if(h.addIndexSet.has(e)){const s=$o($,e);if(x.createLoopContext(s,s=>{n=y?.byAddedIndex.get(e)??(void 0!==N?N.pop():void 0),void 0===n?n=ua(t):(ka(n,o),Nr(n,s)),v?_=null!==I?_a(n,I,null,P+e.index):_a(n,_.parentNode,_,P+e.index):null!==I?n.appendTo(I):_.nextSibling!==n.firstNode&&n.mountAfter(_),Qi(n,s,o),null!==k&&pa(n,"row",k)}),void 0===n&&tt(`Content not found for ListIndex: ${e.index} at path "${r.path}"`),null!==y&&y.reused.has(n)){const t=o.stateElement.addressHooks;if(t){const e=t.rowReused;for(let t=0;t<e.length;t++)e[t](o.stateElement,n)}}}else{n=void 0!==g?g.get(e)??null:null,h.changeIndexSet.has(e)&&Na(n,o,ra(r.wildcardCount)),null===n&&tt(`Content not found for ListIndex: ${e.index} at path "${r.path}"`);const t=!n.mounted;if(v?_=_a(n,_.parentNode,_,P+e.index):null!==S&&S.has(e)&&Ia(_,n.firstNode)||_.nextSibling===n.firstNode||n.mountAfter(_),t){const t=n,s=$o($,e);x.createLoopContext(s,e=>{Qi(t,e,o)})}}v||(_=n.lastNode||_),void 0===g&&(g=new WeakMap,ga.set(t.node,g)),g.set(e,n)}ma.set(t.node,_),null!==I&&(t.node.parentNode.insertBefore(I,t.node.nextSibling),to(I,null))},if:Ca,else:Ca,elseif:Ca,radio:function(t,e,n){const o=t.node,s=wr(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=wr(o.value,t.inFilters),r=Array.isArray(n)?n:vr;o.checked=r.includes(s)}},ol=new WeakMap,sl=new WeakMap,rl=new WeakMap;function il(){}function al(t){const e=br;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return Ha;if(e.isDeclared(n,o))return il}return Ba}function ll(t,e){cl(t,e,function(t,e){const n=So(e);if(n.pathInfo.path in A){const t=$e(e.node);return null===t&&tt(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&tt("ListIndex not found for loopContext:");const n=A[e];void 0===n&&tt(`Invalid index name: ${e}`);const o=so(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&tt(Ya(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Wn](n)}(e.state,t))}function cl(t,e,n){const o=wr(n,t.outFilters);if(!0===sl.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=ol.get(t);if(void 0===s){if(ol.has(t))return s=al(t),s===Ha&&ol.set(t,s),void s(t,e,o);if(s=nl[t.bindingType],void 0===s){const e=t.propSegments[0];s=el[e],ol.set(t,s),void 0===s&&(Gt(t.replaceNode)?(s=al(t),s===Ha&&ol.set(t,s)):(s=Ba,ol.set(t,s)))}if(s===Ba&&"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 sl.set(t,!0)}s(t,e,o)}else s(t,e,o)}function ul(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=uo(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=yr(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==rl.get(t)){const e=Gt(t.replaceNode);if(e&&(void 0===Jt(t.replaceNode)?.get(e)||function(t){return"waiting-definition"===Ys.get(t)?.phase}(t)))return void function(t,e){if(Za.has(t))return;Za.add(t);const n=()=>{Za.delete(t);const e=yr(t);(null===e||e.shouldApplyState(t))&&hl([t])},o=n=>{Za.delete(t),tl(e,n)},s=yr(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Za.delete(t),r()})||(Za.delete(t),r()))}const r=Jt(t.replaceNode);if(null===r)return Za.delete(t),void tl(e,new Error("CustomElementRegistry is unavailable."));js(r).wait(e,()=>{t.replaceNode.isConnected?n():Za.delete(t)},o)}(t,e);rl.set(t,!0)}if(!0===e.sameRootVerified)return void ll(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=eo(o),null===o&&tt("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Pl(o);null===n&&tt("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};ll(t,r)})}else ll(t,e)}function dl(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!==Se&&Se({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function hl(t,e,n){let o=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;o<t.length;){let n=t[o];if(!1===n.replaceNode.isConnected){s.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),o++;continue}let u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=eo(u),null===u&&tt("Root node for fragment not found for binding."));const d=Pl(u);null===d&&tt("No state tree found on this root for binding."),d.createState("readonly",s=>{const h={rootNode:u,stateElement:d,state:s,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{ul(n,h)}catch(t){dl(n,t,d,c)}o++;const e=t[o];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{Ba(t,{propagationContextByBinding:e},n)}catch(e){dl(t,e,o??null,c)}for(const[t,e]of i.entries())Sn(t,e),Tn(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[Fn](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[Hn](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 fl(t,e,n,o,s){for(const r of t)r.cancel?.(),r.cancel=n.deferUntilDefined(r.node,r.tagName,()=>{const i=we(r);o&&(t.splice(t.indexOf(r),1),o.push(...i),s.push(...i.filter(t=>t.statePathName in A))),0!==i.length&&(xe(r.node,e),hl(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1})))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,t)})}function pl(t,e,n){const[o,s,r]=ge(t,n),i=gr(t);for(const t of o)xe(t,e);hl(i.initialize(s)),fl(r,e,i)}const ml=new WeakMap;async function gl(t){const e=t.querySelectorAll(s.tagNames.state),n=[],o=Jt(t);null===o&&tt(`CustomElementRegistry is unavailable for <${s.tagNames.state}>.`),await o.whenDefined(s.tagNames.state);for(const t of e){if(ue(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function yl(t){if(t===document)await gl(document),Y(document),Yl(document,document),pl(document.body,null);else{const e=t;e.host.hasAttribute(s.bindAttributeName)&&await qt(e.host),await gl(e),Y(e),Yl(e,e),pl(e,null)}}const bl={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function wl(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${bl[t]??t}" before the state is defined.`}let vl=null;function _l(t){return null===vl&&tt(wl("ssr",t)),vl}const $l=new WeakMap,xl=new WeakMap,Sl=new Set,Il=[];function Pl(t){return $l.get(t)??null}function kl(t){return xl.get(t)??Promise.resolve()}const Nl=new WeakSet;function Al(t){Nl.add(t)}function El(t,n){const o=$l.get(t);if(null===n){if(void 0===o)return;$l.delete(t),Sl.delete(o),null!==Se&&Se({type:"state:element-unregistered",rootNode:t,element:o}),s.debug&&console.debug("State element unregistered")}else{if(o===n)return;if(void 0===o){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 _l('the "enable-ssr" attribute').hydrate(t)||await yl(t),Al(t),sc(),e()}catch(t){n(t)}})});xl.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await yl(t),Al(t),sc(),e()}catch(t){n(t)}})});xl.set(t,e)}}void 0!==o&&tt('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="...">.'),$l.set(t,n),Sl.add(n);for(let e=0;e<Il.length;e++)Il[e](t,n);null!==Se&&Se({type:"state:element-registered",rootNode:t,element:n}),s.debug&&console.debug("State element registered",n)}}const Cl=new Map;function Ml(t,e,n){if(null===n)Cl.delete(t);else{Cl.set(t,n);const o=Pl(e);null===o&&tt("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 Tl(t){return Cl.get(t)||null}function Ol(t){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=Lt(e.getAttribute(s.bindAttributeName)||"");if(e.localName===s.tagNames.state){if(e.hasAttribute("mount"))return n.filter(t=>t.propSegments[0]!==x);const t=n.find(t=>t.propSegments[0]===x);if(void 0!==t){const e=`on a volume element — a <${s.tagNames.state}> with a "mount" attribute`;tt(1===t.propSegments.length?`[wcs/mount-path-invalid] "${t.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${x}.<key>: <path>") ${e}.`:`[wcs/mount-path-invalid] "${t.propName}: ${t.statePathName}" is a volume injection declaration, and it can only be written ${e}. Add mount="<path>", or bind an element property instead.`)}}return n}if(t.nodeType===Node.COMMENT_NODE){const e=Dt(t);null===e&&tt("Comment node binding text not found.");const n=Tl(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=zt(e),s=null):s=e,[{...o,uuid:s}]}return[]}let Ll;function Rl(){return Ll??={filterName:"not",args:[]}}const jl=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Wl(t,e){const n=e+l+c,o=Pt(t,"|");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+l+s.slice(1)}return r.length>0?s+r:s}function Dl(t,e){const n=jl.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+Wl(s,e)+r}function zl(t,e){const n=kt(t,";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=Pt(n,":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Wl(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function Bl(t,e){return zl(t,e)}function Fl(t,e){const n=s.bindAttributeName,o=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const t=o.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=Dl(n.data,e);continue}const s=t;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const t=zl(r,e);t!==r&&s.setAttribute(n,t)}}}function Hl(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}const ql=new WeakMap;function Ul(t){return ql.get(t)??null}function Vl(t){const e=[],n=fe(t);for(const t of n){const n=Ol(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");ql.set(e,t.data),t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:Hl(o),parseBindTextResults:n})}return e}function Gl(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const Kl=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),Jl=Rl();function Ql(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Jl],bindingType:t}}function Xl(t,e,n,o,s,r=!0){Gl(e),"string"==typeof o&&Fl(e,o),Yl(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Vl(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 Yl(t,e,n,o){const r=s.commentElsePrefix,i=de(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(s.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(s.bindAttributeName)||"";"string"==typeof n&&(i=Bl(i,n));let a=Lt(i)[0];const u=Kl.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=Pe();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&tt("'else' binding found without preceding 'if' or 'elseif' binding."),a=Ql("else",l.parseBindTextResult),p=Xl(t,h,a,m,o,!1),Ml(f,t,p);const n=c.at(-1),s=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:Hl(s),parseBindTextResults:Ol(s)})):e.replaceWith(s)}else if("elseif"===d){null===l&&tt("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Xl(t,h,a,m,o),Ml(f,t,p);const n=document.createComment(`@@${u}:${f}`),s=Pe(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Ql("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Hl(n),parseBindTextResults:Ol(n)}),Ml(s,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${s}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:Hl(g),parseBindTextResults:Ol(g)})):e.replaceWith(g)}else{p=Xl(t,h,a,m,o),Ml(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 Zl=()=>`[${s.bindAttributeName}]`;function tc(t){if(or(t))return!0;if(!ec(t))return!1;if(t.hasAttribute(s.bindAttributeName))return!1;const e=t.querySelector(Zl());return null!==e&&or(e)}function ec(t){return 1===t.nodeType}function nc(t){if(tc(t))return;Y(t),Yl(t.getRootNode(),t);const e=t.hasAttribute(s.bindAttributeName),n=t.parentNode,o=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);pl(e&&o?n:t,null)}const oc=[];function sc(){const t=oc.splice(0,oc.length);for(const e of t)nc(e);!function(){const t=function(){const t=globalThis[r];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[i];return void 0===e&&(e=[],t[i]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[a];return void 0===e&&(e=new WeakSet,t[a]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const rc={protocol:"wcs-binder",version:1,bind:function(t){var e;ec(t)&&!tc(t)&&(e=t.getRootNode(),Nl.has(e)?nc(t):oc.push(t))}},ic="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let ac=0;async function lc(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++ac}\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 await new Promise(t=>setTimeout(t)),new Error(`[@wcstack/state] ${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: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src="./state.js") needs neither. See ${ic}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${ic}`}(e,t,s)}`,{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function cc(t){const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}class uc{_loopContextStack=Array(d).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&tt("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=d&&tt("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&&tt("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&&tt("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&&tt(`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 dc={$updatedCallback:M,$streams:B},hc=new WeakSet;function fc(t,e){let n=t;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,e);)n=Object.getPrototypeOf(n);return n}function pc(t){if((null===t||"object"!=typeof t&&"function"!=typeof t)&&tt(`The state must be an object, got ${null===t?"null":typeof t}. Check the source of the state element (json / src / the inline <script>).`),!hc.has(t)){dt?.state(t);for(const e of Object.keys(dc)){if(!(e in t))continue;const n=dc[e];n in t&&tt(`[wcs/declaration-alias] The state declares both "${e}" and "${n}". "${e}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${at}`),Object.isExtensible(t)||tt(`[wcs/declaration-alias] The state is not extensible, so the old name "${e}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${at}`);const o=fc(t,e),s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,n,{...s,configurable:!0}),o===t&&delete t[e]}hc.add(t)}}const mc=new WeakMap;function gc(t,e){let n=mc.get(t);void 0===n&&(n=new Map,mc.set(t,n));let o=n.get(e);return void 0===o&&(o=new Do(e,t),n.set(e,o)),o}const yc=new WeakMap;function bc(t){const e=yc.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 gc(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:gc(t,n)}},set(){tt("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){tt("$command namespace is read-only; deleting from it is not allowed.")}});return yc.set(t,n),n}const wc=Symbol("wcs.notHandled"),vc=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],_c=new Map;function $c(t,e){_c.set(t,e)}const xc=new Map;let Sc=[],Ic=[];function Pc(t,e){xc.set(t,e),Sc=Array.from(xc.values()).sort((t,e)=>t.order-e.order),Ic=Sc.slice().reverse()}function kc(t){return xc.has(t)}function Nc(t,e){for(let n=0;n<Sc.length;n++)Sc[n].activate?.(t,e)}const Ac=new Map;class Ec{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=ot(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 Cc(t){let e;return Ac.get(t)??(Ac.set(t,e=new Ec(t)),e)}function Mc(t){"readonly"===t.mutability&&tt("This state is readonly.")}function Tc(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:so(n.listIndex,o,n.pathInfo.wildcardCount)}function Oc(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=oo(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?so(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?so(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}function Lc(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Rc(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!==wc)return a}}return wc}function jc(t,e,n,o,s){if(e.pathInfo.segments[0]===W)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}(bc(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){if(null===e.parentAddress){const r=Rc(s,e,null,n,o);if(r!==wc)return r;tt(function(t,e,n){return`[${Ga.binding}] Path "${t}" does not exist on the state tree.${it(t,Va(e,"",n,e))}${at}`}(e.pathInfo.path,t,s.getterPaths))}const r=zc(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!==c&&!(i in Object(r))){const t=Rc(s,e,Object(r),n,o);if(t!==wc)return t}if(i===c){const t=e.listIndex?.index??tt(Ya(`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()}}const Wc=new WeakSet;function Dc(t){return Wc.has(t)}function zc(t,e,n,o){Oc(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!==wc)return i}}return Lc(s,e)?function(t,e,n,o,s){const r=Xn(s,e),i=function(t){return Mr.get(t)??null}(r),a=s.stateGeneration,l=e.pathInfo.lastSegment===c?void 0:Le(e.listIndex);if(null!==i&&!1===i.dirty&&i.generation===a&&i.rowStamp===l)return i.value;const u=jc(t,e,n,o,s);"function"!=typeof u&&Or(r,{value:u,dirty:!1,generation:a,rowStamp:l});const d=i?.value;return Array.isArray(u)&&u!==d&&s.getterPaths.has(e.pathInfo.path)&&function(t,e,n,o,s,r){const{path:i,wildcardCount:a}=e.pathInfo;r.beginUntrack();try{for(const[l,c]of r.stateElement.dynamicDependency){const u=ot(l);if(!c.includes(i)||u.wildcardCount>a)continue;const d=zc(t,$o(u,so(e.listIndex,u.wildcardCount-1,a)),s,r);d===n?Wc.add(e.pathInfo):d===o&&ji(n,o)}}finally{r.endUntrack()}}(t,e,u,d,n,o),u}(t,e,n,o,s):jc(t,e,n,o,s)}function Bc(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=$o(h,r),p=Xn(n.stateElement,f),m=Mn(p),g=zc(t,f,e,n),y=Bi(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]??tt(`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())Tn(t,Array.isArray(e)?e:[]);return l}function Fc(t,e,n){const o=un(n,e.listIndex);if(null!==o)return o;const s=Xn(t.stateElement,e),r=Bi(e.listIndex,Mn(s),n);return Tn(s,Array.isArray(n)?n:[]),r.newIndexes}function Hc(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=$o(a,r),c=Fc(n,l,zc(t,l,e,n)),u=s[i];r=c[u]??tt(`ListIndex not found at index ${u} of ${a.path}`)}return r}function qc(t,e,n,o){"object"==typeof t&&null!==t||tt(`${V} 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&&tt(`${V} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Uc(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&tt(`${V} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Vc(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];qc(a,n,o,i);const l=Uc(a,e,n,o,i);r.has(l)&&tt(`${V} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Gc(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 Kc(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const r=zc(t,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=e.pathInfo.lastSegment;if(i===c){const t=e.listIndex?.index;return"number"==typeof t&&t in r}return i in r}const Jc=new WeakMap;function Qc(t){return Jc.get(t)??null}function Xc(t,e){null===e?Jc.delete(t):(hn(e.listIndexes),Jc.set(t,e))}function Yc(t,e,n){const o=$o(ot(t.wildcardParentPaths[e]),n),r=Xn(t.stateElement,o),i=Mn(r),a=t.stateProxy[Wn](o),l=Bi(o.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 s.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)Yc(t,e+1,n)}function Zc(t,e,n,o){n?t.result.has(e)||t.quiet.add(e):t.quiet.delete(e),t.result.add(e),o.push(e)}const tu=[];function eu(t,e,n){return"full"!==t.listExpansion&&t.listPathSet.has(e)?t.stateElement.crossRowListPaths?.has(e)?{fullRows:n.newIndexes,movedRows:null}:0===n.addIndexSet.size&&0===n.changeIndexSet.size?0===n.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:tu,movedRows:null}:{fullRows:n.newIndexes,movedRows:null}:{fullRows:tu,movedRows:null}:{fullRows:n.addIndexSet,movedRows:n.changeIndexSet}:{fullRows:n.newIndexes,movedRows:null}}const nu=[];function ou(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return nu;let s=null;const r=e+l;for(const t of o){if(t!==e&&!t.startsWith(r))continue;const o=ot(t);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??nu}function su(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),t.quiet.has(a)?Lr(Xn(t.stateElement,a)):n(a),i.length=0,ru(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}function ru(t,e,n){const o=e.pathInfo.path,s=t.quiet.has(e),r=t.staticMap.get(o);if(r)for(const i of r){const r=ot(i);if(r.lastSegment===c){const a=t.stateProxy[Wn](e),l=Array.isArray(a)?a:[],c=Xn(t.stateElement,e),u=Mn(c),d=t.listPathSet.has(o);if(!d&&"diff"===t.listExpansion&&(t.keyedMergePath===o||cn(l)?.length!==l.length&&!Di(u,l)))continue;const h=Bi(e.listIndex,u,l);t.observedListValueByAbsAddress.set(c,l);const f=eu(t,o,h);for(const e of f.fullRows)Zc(t,$o(r,e),s||!d,n);for(const e of h.valueChangeIndexes??tu)Zc(t,$o(r,e),s||!d,n);if(null!==f.movedRows){const e=ou(t,i,r);if(null===e)for(const e of f.movedRows)Zc(t,$o(r,e),s,n);else if(e.length>0)for(const o of f.movedRows)for(const r of e)Zc(t,$o(r,o),s,n)}}else Zc(t,$o(r,e.listIndex),s,n)}const i=t.dynamicMap.get(o);if(i)for(const o of i){const r=ot(o),i=[];if(r.wildcardCount>0){const n=oo(e.pathInfo,r);if(r.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&tt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=so(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const s={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:r.wildcardPaths,wildcardParentPaths:r.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Yc(s,n,o),i.push(...s.targetListIndexes)}else{null===e.listIndex&&tt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=so(e.listIndex,n-1,e.pathInfo.wildcardCount);i.push(t)}}else i.push(null);for(const e of i)Zc(t,$o(r,e),s,n)}}function iu(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&&tt(`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,quiet:new Set};su(d,e,a),function(t,e){for(let n=0;n<1e3;n++){const n=ni(t.stateElement);if(null===n)return;n.forEach(n=>{su(t,$o(n.absolutePathInfo.pathInfo,n.listIndex),e)})}}(d,a);for(const[t,e]of d.observedListValueByAbsAddress)Tn(t,e);return Array.from(d.result)}function au(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 lu(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 cu(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 uu(t,e,n,o,s,r){const i=bi(t,e),a=xi(t,e);if(!i&&!a)return null;const l=[],c=hu(l);return i&&$i(t,e,n,o,s).forEach(c),a&&Ii(t,e,n?o:r(),s).forEach(c),l}function du(){return s.enablePropagationContext?us()??null:null}function hu(t){const e=Kr(),n=du();return o=>{Lr(o),e.enqueueAbsoluteAddress(o,n),t.push(o)}}function fu(t,e,n){if(null===t||0===t.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=Kr(),a=du();for(let n=0;n<t.length;n++){const l=t[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const u=$o(l.pathInfo,t[n].listIndex);iu(o,u,s,r,o.listPaths,e,"new",t=>{if(t===u)return;const e=Xn(o,t);Lr(e),i.enqueueAbsoluteAddress(e,a)},{listExpansion:"diff"})}}function pu(t,e,n,o,r,i,a="diff"){const u=s.enablePropagationContext?us()??as(-1):null,d=Kr(),h=o.stateElement;d.enqueueAbsoluteAddress(e,u),i&&Lr(e);const f=e=>iu(h,e,h.staticDependency,h.dynamicDependency,h.listPaths,n,"new",e=>{if(e===t)return;const n=Xn(h,e);Lr(n),d.enqueueAbsoluteAddress(n,u)},{listExpansion:a,keyedMergePath:r});if(f(t),t.pathInfo.lastSegment!==c&&null!==t.listIndex&&null!==t.listIndex.parentListIndex){const e=t.listIndex,o=t.pathInfo.wildcardParentPathInfos[e.position],s=$o(o,e.parentListIndex),r=()=>n[Wn](s),i=t=>{Lr(t),d.enqueueRenderOnlyAddress(t)};for(const n of function(t,e){const n=(o=t,De(je.get(o.value),o));var o;if(0===n.length)return n;const s=new Set(Ke.get(e()));return n.filter(e=>e.position===t.position&&!s.has(e)&&!Be(e))}(e,r))i(Xn(h,$o(t.pathInfo,n)));const a=t.pathInfo.path.slice(t.pathInfo.wildcardPaths[e.position].length);for(const t of Pn(Xn(h,s),r())){const n=t.absolutePathInfo.pathInfo;n!==o&&n.wildcardCount===o.wildcardCount&&i(Yn(h,ot(n.path+l+c+a),e))}}const{path:p,lastSegment:m,wildcardCount:g,wildcardParentPaths:y,wildcardParentPathInfos:b}=t.pathInfo,w=t.listIndex;for(let t=0;w&&t<g;t++){const e=so(w,t-1,g);for(const o of h.dynamicDependency.get(y[t])??[]){const s=ot(o);if(h.listPaths.has(o)&&s.wildcardCount===t&&Dc(s)&&n[Wn]($o(s,e))===n[Wn]($o(b[t],e))){const e=$o(ot(o+p.slice(y[t].length)),w);f(e),m===c&&d.enqueueRenderOnlyAddress(Xn(h,e.parentAddress))}}}}function mu(t,e,n,o,s){s&&(t.getterPaths.has(e)?Lr(n):Or(n,{value:o,dirty:!1,generation:t.stateGeneration,rowStamp:n.absolutePathInfo.pathInfo.lastSegment===c?void 0:Le(n.listIndex)}))}function gu(t,e,n,o,s,r,i,a,l=!0){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const i=zc(t,n,s,r),a=e.pathInfo.segments[e.pathInfo.segments.length-1];if(a===c){const t=e.listIndex?.index??tt(Ya(`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{l&&pu(e,n,s,r,i,a)}}function yu(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=zc(t,e,o,s),a=function(t,e,n,o){const s=Vc(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Vc(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!==a)return function(t,e,n,o,s,r){const i=e.pathInfo.path,a=e.listIndex;null===cn(o)&&Bi(a,null,o);const u=Bi(a,o,n.list),d=bu(t,e,n.list,s,r,i),h=ot(i+l+c);for(const e of n.matched){const n=Gc(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const i of n)void 0!==o?yu(t,$o(ot(h.path+l+i.field),o),i.value,s,r):e.oldRow[i.field]=i.value}return d}(t,e,a,r,o,s)}}return bu(t,e,n,o,s,null)}function bu(t,e,n,o,r,i){const a=r.stateElement,u=e.pathInfo.path,d=a.addressHooks;if(d){const t=d.write;for(let s=0;s<t.length;s++){const i=t[s](a,e,n,o,r);if(i!==wc)return i}}const h=function(){const t=fs;return fs=0,t}(),f=h>1;if(!(u in t)&&null!==e.parentAddress&&!a.elementPaths.has(u)){const l=zc(t,e.parentAddress,o,r);if("object"==typeof l&&null!==l){const t=e.pathInfo.lastSegment,h=t===c?e.listIndex?.index:t;let p,m=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==h&&h in l,e=void 0!==h?l[h]:void 0;if(t&&Object.is(e,n))return!0;p=e,m=!0}t===c&&(e=function(t,e,n,o,s){const r=e.listIndex,i=cn(n);if(i?.[o]!==r||n[o]===s)return e;const a=Ce(r.parentListIndex,o,Te(r));if(function(t){return pn.has(t)}(n)){const t=Qc(n)??{value:n.slice(),listIndexes:i};fn(t.value,t.listIndexes),gn(n,t.value)}const l=function(t){return dn.has(t)}(i)?i:i.slice();l[o]=a,fn(n,l,!0),vi(i,l),zi([r]);const c=$o(e.pathInfo,a);return cu(t,Xn(t,c),Xn(t,e)),c}(a,e,l,h,n));const g=uu(a,u,m,p,n,()=>l[h]),y=Lc(a,e),b=Xn(a,e);null!==Se&&Se({type:"state:write",absoluteAddress:b,value:n,oldValue:p,hasOldValue:m}),au(a,u,b,p,m);let w=!1;try{if(void 0===h&&tt(Ya(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),d&&0!==d.writeMissing.length&&t!==c&&!(h in l)){const t=d.writeMissing;for(let s=0;s<t.length;s++){w=!0;const i=t[s](a,e,l,h,n,o,r);if(i!==wc)return i;w=!1}}if(t!==c&&null!==e.listIndex){const o=l[h];o!==n&&(function(t,e,n,o){if(!Ke.has(t))return!1;let s=!1;for(const e in n)s||=e!==o&&n[e]===t;if(!s){let n=Qe.get(e);void 0===n&&(n=new WeakSet,Qe.set(e,n)),n.add(t)}const r=Ke.get(t),i=Ye.get(t);if(r[0]?.parentListIndex===e&&(!s||i?.[0]!==e||i[1]!==qe))for(const n of rn.get(t)??[])if(n!==e&&n.position===e.position&&sn(t,n)&&Object(Fe(n))[o]===t){r.forEach(t=>Me(t,n)),Xe.set(t,[e,qe]);break}return s}(o,e.listIndex,l,t)&&Array.isArray(n)&&ji(n,o),function(t,e){Qe.get(e)?.delete(t);const n=Ke.get(t);if(void 0!==n){Ye.set(t,[e,qe]);const o=Xe.get(t);o?.[0]===e&&o[1]===qe&&n.forEach(t=>Me(t,e))}}(n,e.listIndex))}return Reflect.set(l,h,n)}finally{pu(e,b,o,r,i,y),fu(g,o,r),w?Lr(b):mu(a,u,b,n,y),lu(a,e.pathInfo,{value:n})}}}let p,m=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=zc(t,e,o,r);if(Kc(t,e,o,r)&&Object.is(s,n))return!0;p=s,m=!0}const g=uu(a,u,m,p,n,()=>zc(t,e,o,r)),y=a.elementPaths.has(e.pathInfo.path),b=Lc(a,e),w=Xn(a,e);null!==Se&&Se({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:m}),au(a,u,w,p,m);try{return y?function(t,e,n,o,s,r,i,a,u){const d=e.parentAddress??tt(`address.parentAddress is undefined path: ${e.pathInfo.path}`),h=zc(t,d,s,r)??[],f=Qc(h);if(u)return f&&(f.value[e.listIndex.index]=o),Re(e.listIndex,o),gu(t,e,n,o,s,r,i,a);const p=e.listIndex,m=f??{value:[...h],listIndexes:cn(h)??[],written:new Map};try{return gu(t,e,n,o,s,r,i,a,!1)}finally{const t=function(t,e,n){const{value:o,listIndexes:s}=t,r=new Map;s.forEach((t,n)=>{if(e[n]!==o[n]){const e=r.get(o[n]);e?e.push(t):r.set(o[n],[t])}});let i,a=0;const l=[];for(let t=0;t<s.length;t++){const n=e[t]===o[t]?s[t]:r.get(e[t])?.shift();if(!n&&(a++?(i??=new Set(o)).has(e[t]):o.includes(e[t])))return null;l.push(n)}return l.map((t,e)=>t??Ce(n,e))}(m,h,d.listIndex);if(null===t)Xc(h,m),Re(p,o),m.written.set(p,qe),function(t){en.set(t,qe)}(p),pu(e,n,s,r,i,a);else{Xc(h,null);const e=[p.index];nn(p),m.written.forEach((t,n)=>{nn(n),Re(n,m.value[n.index]),t===qe&&e.push(n.index)}),m.written.delete(p),t.forEach((t,e)=>{t.index=e}),fn(h,t),vi(m.listIndexes,t),function(t,e,n,o,s,r,i){const a=r.stateElement,u=Kr(),d=Xn(a,t);fn(e.value,e.listIndexes),Ve(e.value),gn(n,e.value),xn(d)===n&&Sn(d,e.value),u.enqueueRenderOnlyAddress(d);for(const t of Pn(d,n))kn(t,n)&&u.enqueueRenderOnlyAddress(t);const h=new Map;e.listIndexes.forEach((t,e)=>h.set(t,e));const f=ot(t.pathInfo.path+l+c);for(let t=0;t<o.length;t++){const n=o[t],i=h.get(n);if(i===t)continue;const l=$o(f,n),c=Xn(a,l);if(void 0===i){const n=Yn(a,f,e.listIndexes[t]);cu(a,c,n),pu(l,c,s,r,null,Lc(a,l),"full");continue}iu(a,l,a.staticDependency,a.dynamicDependency,a.listPaths,s,"new",t=>{const e=Xn(a,t);Lr(e),u.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}for(const t of i){const n=o[t];if(h.has(n)&&e.written.get(n)!==qe){const o=$o(f,n),i=Xn(a,o);cu(a,i,Yn(a,f,e.listIndexes[t])),pu(o,i,s,r,null,Lc(a,o))}}}(d,m,h,t,s,r,e)}}}(t,e,w,n,o,r,i,b,h):gu(t,e,w,n,o,r,i,b)}finally{fu(g,o,r),y||mu(a,u,w,n,b),lu(a,e.pathInfo,{value:n})}}function wu(t,e,n,o){return(e,s,...r)=>{Array.isArray(s)||tt(`$resolve("${e}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&tt(`$resolve("${e}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=ot(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&&tt(Ja("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=$o(i,Hc(t,n,o,i,s));if(0===r.length)return zc(t,a,n,o);Mc(o),yu(t,a,r[0],n,o)}}function vu(t,e,n,o){const s=wu(t,0,n,o);return(e,r)=>{const i=ot(e);if(void 0===r||Array.isArray(r)||tt(`$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&&tt(Ja("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Tc(o,i.wildcardPaths[t]);if(e){r=ro(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&&tt(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=Bc(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 _u(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Tc(o,s.wildcardPaths.at(-1)??tt(`lastWildcardPath is null: ${e.pathInfo.path}`))??tt(`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]??tt(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=$o(i,s),l=Fc(o,a,zc(t,a,n,o)),c=e.wildcardIndexes[r]??tt(`wildcardIndex is null: ${e.pathInfo.path}`);s=l[c]??tt(`ListIndex not found at index ${c} of ${i.path}`)}return s}case"partial":tt(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function $u(t,e,n,o){return(e,s,r,i)=>{Mc(o);const a=ot(e);Array.isArray(s)||tt(Xa(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&tt(Ja("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,u="function"==typeof r;l&&u&&tt(Xa(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&tt(Xa(e,"requires an array as the value when { spread: true } is set."));const d=Bc(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&tt(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,d.length,r.length));const h=[];for(let e=0;e<d.length;e++){const s=Hc(t,n,o,a,d[e]);h.push($o(a,s))}const f=a.lastSegment===c;let p=0;for(let e=0;e<h.length;e++){const s=f?$o(a,Hc(t,n,o,a,d[e])):h[e];let i;i=u?r(zc(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(yu(t,s,i,n,o),p++)}return p}}function xu(t,e){if("all"===Cc(e).wildcardType)return!0;const n=t.getterPaths;if(0===n.size)return!1;for(const t of ot(e).cumulativePaths)if(n.has(t))return!0;return!1}const Su=/^\$\d+$/,Iu=`${G}${l}`,Pu=`${K}${l}`,ku=new WeakMap;function Nu(t,e,n,o){const s=A[e];if(void 0===s&&"string"==typeof e&&36===e.charCodeAt(0)&&Su.test(e)&&tt(`[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&&tt(`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&&tt(`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=so(r,i,a.wildcardCount);return c?.index??tt(`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!==wc)return i}}if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>vu(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>$u(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=Cc(e),i=_u(t,r,n,o),a=$o(r.pathInfo,i),l=Xn(s,a),c=Kr();c.enqueueAbsoluteAddress(l),function(t,e,n,o,s){const r=bi(t,e),i=xi(t,e);if(!r&&!i)return;const a=n(),l=[],c=hu(l);r&&$i(t,e,!1,void 0,a).forEach(c),i&&Ii(t,e,void 0,a,!1).forEach(c),fu(l,o,s)}(s,r.pathInfo.path,()=>zc(t,a,n,o),n,o),iu(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Xn(s,t);Lr(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)=>wu(t,0,n,o)(e,s,...r);case"$trackDependency":dt?.renamed(e,"$dependOn");case"$dependOn":return t=>function(t,e,n,o){return t=>{-1!==t.indexOf(U)&&tt(`[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&&tt(`No active state reference to track dependency for path "${t}".`);const n=o.lastAddressStack?.pathInfo??tt("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(xu(o.stateElement,t))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&yi(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)&&gi(o.stateElement,t,e,Xn(o.stateElement,s),r),Object.is(r,e)};case"$eqPath":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=xu(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?yi(o.stateElement,t):gi(o.stateElement,t,i,Xn(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||tt(`$eqIndex("${t}") needs a list row scope.`);const r=so(s.listIndex,e-1,s.pathInfo.wildcardCount);if(null===r&&tt(`$eqIndex("${t}", ${e}): no list index at that level.`),xu(o.stateElement,t))return o.stateElement.getterPaths.has(s.pathInfo.path)&&(yi(o.stateElement,t),o.stateElement.addIndexDependentGetterPath?.(s.pathInfo.path)),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?cn(l):null;null!==e?function(t,e,n,o,s){Zr=!0,ui(t).lastValue.set(e,s),ci(t,e);let r=oi.get(t);void 0===r&&oi.set(t,r=new Map);let i=r.get(e);void 0===i&&r.set(e,i=new Set);let a,l=si.get(o);if(void 0===l?(si.set(o,l=[]),hn(o)):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);const n=o[0]?.parentListIndex??null;if(null!==n){let t=ii.get(n);void 0===t&&ii.set(n,t=new Set),t.add(a)}}a.getters.add(n)}(o.stateElement,t,s.pathInfo,e,a):function(t,e,n,o,s){Zr=!0;const r=ui(t);ci(t,e),mi(r,e,s,o,fi(r,e,n.index,o),{stateElement:t,path:e,absAddress:o,levelListIndex:n})}(o.stateElement,t,r,Xn(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":dt?.renamed(e,"$untracked");case"$untracked":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case W:return bc(o.stateElement)}if(!e.startsWith(Iu)&&!e.startsWith(Pu))return}const r=Cc(e),i=_u(t,r,n,o),a=$o(r.pathInfo,i);return zc(t,a,n,o)}if("symbol"==typeof e){const s=function(t){let e=ku.get(t);return void 0===e&&(e=new Map,ku.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case jn:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&tt("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 Wn:i=e=>zc(t,e,n,o);break;case Dn:i=e=>Kc(t,e,n,o);break;case zn:i=()=>async function(t,e,n){const o=Reflect.get(t,E);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Bn:i=()=>function(t,e,n){const o=Reflect.get(t,C);"function"==typeof o&&o.call(n)}(t,0,n);break;case Fn:i=e=>function(t,e,n,o){const s=Reflect.get(t,M);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=ro(n.listIndex,e.wildcardCount),o=i[s];void 0===o?i[s]=[t]:o.push(t)}}(t.size>0||0===e.length)&&(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 Hn: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}}class Au{_stateElement;_addressStack=Array(d).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Pl(t);null===n&&tt("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&&tt("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=d&&(this._hasRepeatedAddress()&&tt(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),tt(`[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&&tt(`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 Nu(t,e,n,this)}set(t,e,n,o){return Mc(this),function(t,e,n,o,s){if("string"==typeof e){const r=Cc(e),i=_u(t,r,o,s);return yu(t,$o(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)}deleteProperty(t,e){return Mc(this),Reflect.deleteProperty(t,e)}defineProperty(t,e,n){return Mc(this),Reflect.defineProperty(t,e,n)}}const Eu=Promise.resolve(),Cu=new Map;let Mu=[];function Tu(t,e){Cu.set(t,e),Mu=Array.from(Cu.values()).sort((t,e)=>t.order-e.order)}function Ou(t,e){return tt(wl(t,e))}const Lu="undefined"==typeof HTMLElement?class{}:HTMLElement;function Ru(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 ju=null;const Wu=new Set(["for","if","elseif","else"]);const Du=[[F,"watch"],[H,"scan"],[B,"streams"],[q,"recursion"]];class zu extends Lu{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return kl(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 uc}();_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&&tt(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){pc(t),function(t){for(let e=0;e<Du.length;e++){const[n,o]=Du[e];n in t&&!kc(o)&&tt(wl(o,`"${n}"`))}}(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<Sc.length;o++)Sc[o].validateEarly?.(t,e,n)}(this,t,n);const o=function(t){const e=new Set,n=t[j];if(void 0===n)return e;Array.isArray(n)||tt(`${j} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||tt(`${j} entries must be non-empty strings.`),t===W&&tt(`${j} entry "${t}" conflicts with the reserved namespace name "${W}".`),e.has(t)&&tt(`${j} entry "${t}" is duplicated.`),e.add(t);return e}(t),s=function(t){const e=new Set,n=t[D];if(void 0===n)return e;Array.isArray(n)||tt(`${D} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||tt(`${D} entries must be non-empty strings.`),e.has(t)&&tt(`${D} entry "${t}" is duplicated.`),e.add(t);return e}(t),r=function(t){const e=t[V];if(void 0===e)return null;"object"==typeof e&&null!==e||tt(`${V} 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&&tt(`${V} entry path must be a non-empty string.`);const e=t.split(l);e.some(t=>0===t.length)&&tt(`${V} entry "${t}" must not contain empty path segments.`),e[e.length-1]===c&&tt(`${V} entry "${t}" must be the list path itself, not the element path (drop the trailing "${l}${c}").`),-1!==t.indexOf(U)&&tt(`[wcs/recursion-unsupported] ${V} entry "${t}" uses "${U}", which ${V} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${l}${c}${l}children").`),"function"!=typeof o?("string"!=typeof o&&tt(`${V} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&tt(`${V} entry "${t}" key field name must be a non-empty string.`),(o.includes(l)||o.includes(c))&&tt(`${V} entry "${t}" key field name "${o}" must be a flat property name ("${l}" / "${c}" are not allowed).`),o in Object.prototype&&tt(`${V} 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<Sc.length;o++)Sc[o].validate?.(t,e,n)}(this,t,n),function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].preCommit?.(t,e,n)}(this,t,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=t,void 0!==e&&ju?.reset(this),this._hasUpdatedCallback=M in t,this._hasErrorCallback=T in t,Ro.delete(this),function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].applyEarly?.(t,e,n)}(this,t,n),function(t,e,n){const o=e[z];if(void 0!==o){"object"==typeof o&&null!==o||tt(`${z} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||tt(`${z} entry "${e}" is not declared in $eventTokens.${it(e,n)}`),"function"!=typeof s&&tt(`${z} entry "${e}" must be a function.`),jo(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=Ru(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<Sc.length;o++)Sc[o].apply?.(t,e,n)}(this,t,n),this._listKeys=r,this._rebuildPathInfo(),function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].register?.(t,e,n)}(this,t,n),Nc(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 <${s.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?_l('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);return e&&"application/json"===e.type?JSON.parse(e.textContent||"{}"):(console.warn(`[@wcstack/state] state="${t}": no <script type="application/json" id="${t}"> in the document (3.x does not look inside shadow roots), so the state starts empty.`),{})}(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 lc(t,s.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.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){let e;try{const n=await fetch(t);if(n.ok)return await n.json();e=`HTTP ${n.status} ${n.statusText}`}catch(t){e=t}return console.error(`[@wcstack/state] Failed to load JSON file "${t}", so the state starts empty (4.0 rejects instead):`,e),{}}(t);if(t&&t.endsWith(".js"))return await cc(t);tt(`Unsupported src file type: ${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&&(El(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),tt(t)}_failInitializeLoudly(t,e=!0){if(this._initializationLanded)throw t;this._initializeFailed=!0;const n=["state","src"].find(t=>this.hasAttribute(t));throw console.error(`[@wcstack/state] <${s.tagNames.state}${n?` ${n}="${this.getAttribute(n)}"`:""}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),e&&null!==this._rootNode&&null===Pl(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),xl.set(t,n)}(this._rootNode,t),function(t,e,n){for(let o=0;o<Mu.length;o++)Mu[o].initializeFailed?.(t,e,n)}(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{E in t&&await t[zn]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{C in t&&t[Bn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(t){for(let e=0;e<Mu.length;e++)if(!0===Mu[e].reconnecting?.(t))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Pl(this._rootNode)===this||El(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<Mu.length;e++){const n=Mu[e].connecting?.(t);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{Ou("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}const n=this.parentNode;if(n instanceof ShadowRoot&&n.host.hasAttribute(J))try{Ou("dcc",`a <${s.tagNames.state}> inside a [${J}] host`)}catch(t){this._failInitializeLoudly(t)}let o=!1;try{const t=function(t){for(let e=0;e<Mu.length;e++){const n=Mu[e].preparing?.(t);if(null!=n)return n}return null}(this);null===t&&this.hasAttribute("bind-component")&&Ou("scopes",'the "bind-component" attribute'),o=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(o)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 _l('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Nc(this,t),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!function(t){for(let e=0;e<Mu.length;e++)if(!0===Mu[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<Mu.length;n++)Mu[n].initializeFailureCleared?.(t,e)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{El(this.rootNode,null),yc.delete(this),function(t){for(let e=0;e<Ic.length;e++)Ic[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=>(dt?.volumeLoaded(t),pc(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",F)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&tt(`$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 qa(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&&tt("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=_c.get(t);return void 0===n&&tt(wl(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<vc.length;n++){const o=vc[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",L)}_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){if(!this._addDependency(this._dynamicDependency,t,e))return!1;const n=ot(t);for(let t=n.parentPathInfo;null!==t&&t.wildcardCount>0&&t.wildcardCount===n.wildcardCount;t=t.parentPathInfo)this._addDependency(this._dynamicDependency,t.path,e);return!0}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+"."+c)),!this._pathSet.has(t)){const e=ot(t);this._pathSet.add(t);const o=function(t,e){const n=Cc(e);return"all"===n.wildcardType&&1===n.wildcardIndexes.length&&isNaN(+n.segments[0])&&!e.includes("#")&&Object.isExtensible(t)&&!(e in t)}(this.__state,t);if(ju?.check(this,this.__state,t,n,o),o&&function(t,e){const{segments:n,cumulativePaths:o}=ot(e),s=n.length-1,r=(t,r,i)=>{let a,l=!1;for(let c=0;c<=s;c++){const u=n[c];if(l||=!(isNaN(+u)||Array.isArray(a)&&+u in a),r&&c===s)return l?a[u]=i:t[e]=i;a=l?a?.[u]:t[o[c]]}return a},i=function(){return r(this)};Ua.set(i,Cc(e).pathInfo.path),t.defineTreeAccessor(e,{get:i,set(t){r(this,!0,t)},configurable:!0})}(this,t),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=ot(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 Au(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&&tt(`<${s.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<Mu.length;e++)Mu[e].replacingState?.(t)}(this),(this._hasGraftedVolumes||this._hasMounts)&&tt("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(Ru(n)))t.startsWith("$")||t.includes(c)||"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=ot(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=Xn(t,e);if(i.has(n))return;i.add(n);const o=yo(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($o(n,e.listIndex))}};On();try{if(t.createState("readonly",e=>{for(const o of n){const n=$o(ot(o),null);a(n);try{iu(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)Wu.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=()=>{hl(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=Wr("state",s);void 0!==i&&i.catch(Vr)}finally{Ln()}}(this,t,this._pathRegistrations.keys())}}const Bu=[],Fu=[];function Hu(){const t=[];let e=0;for(let n=0;n<Fu.length;n++){const o=Fu[n].deref();void 0!==o&&(t.push(o),Fu[e++]=Fu[n])}return Fu.length=e,t}function qu(t,e){const n=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;n&&((i=n).tagNames&&Object.assign(o.tagNames,i.tagNames),"string"==typeof i.bindAttributeName&&(o.bindAttributeName=i.bindAttributeName),"string"==typeof i.commentTextPrefix&&(o.commentTextPrefix=i.commentTextPrefix),"string"==typeof i.commentForPrefix&&(o.commentForPrefix=i.commentForPrefix),"string"==typeof i.commentIfPrefix&&(o.commentIfPrefix=i.commentIfPrefix),"string"==typeof i.commentElseIfPrefix&&(o.commentElseIfPrefix=i.commentElseIfPrefix),"string"==typeof i.commentElsePrefix&&(o.commentElsePrefix=i.commentElsePrefix),"string"==typeof i.locale&&(o.locale=i.locale),"boolean"==typeof i.debug&&(o.debug=i.debug),"boolean"==typeof i.enableMustache&&(o.enableMustache=i.enableMustache),"boolean"==typeof i.enableDirectionalInitialSync&&(o.enableDirectionalInitialSync=i.enableDirectionalInitialSync),"boolean"==typeof i.enablePropagationContext&&(o.enablePropagationContext=i.enablePropagationContext),"boolean"==typeof i.enableContractAnalyzer&&(o.enableContractAnalyzer=i.enableContractAnalyzer),"boolean"==typeof i.sameValueGuard&&(o.sameValueGuard=i.sameValueGuard)),function(t=customElements){Hu().includes(t)||Fu.push(new WeakRef(t));for(let e=0;e<Bu.length;e++)Bu[e](t);t.get(s.tagNames.state)||t.define(s.tagNames.state,zu)}(e),function(){const t=globalThis;void 0===t[r]&&(t[r]=rc)}()}let Uu=null;function Vu(t){return Uu??tt(wl("watch",`"$watch" in <wcs-state mount="${t}">`))}let Gu=null;const Ku=Object.freeze([]),Ju="3.5.0",Qu=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Xu(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 Yu="__WCSTACK_DEVTOOLS_HOOK__";const Zu=t=>{null!==Se&&Se({type:"state:update-batch",addresses:t})};function td(t){const e=null!==Se;!function(t){Se=t}(t);const n=null!==t;n&&!e?Ur(Zu,0):!n&&e&&function(t){const e=Dr.findIndex(e=>e.listener===t);-1!==e&&Dr.splice(e,1)}(Zu)}function ed(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 nd(t){return Pl(t)??tt("devtools: no state tree on this root")}let od=null;function sd(){if(e())return;if(null!==od)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Ju,getStateElements(){const t=[];for(const e of Sl)t.push(ed(e));return t},overlays(t){return e=nd(t),null===Gu?Ku:Gu(e);var e},keyedSubscriptions:t=>function(t){const e=function(t){const e=Jr.get(t);return void 0===e?null:{byPath:e.byPath,lastValue:e.lastValue,tracked:e.tracked,watchers:oi.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}(nd(t)),keys(t){const e=nd(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 nd(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){nd(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,o=new Set,r=t=>{const o=function(t){const e=`${ut(t.inFilters)}\0${ut(t.outFilters)}`;return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(o.has(t))return;o.add(t);const e=Tl(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Xu(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(s.bindAttributeName);if(null===n||0===n.length)continue;try{const t=se(e,Lt(n));for(const o of t)r(Xu(e,o,"attribute",n))}catch{}continue}const e=Qu.exec(t.data.trim());if(null===e)continue;const n=e[1]||s.commentTextPrefix,o=e[2],a=Tl(o);if(null===a){if(n===s.commentTextPrefix)try{r(Xu(t,zt(o),"comment",o))}catch{}}else r(Xu(t,a.parseBindTextResult,"comment",o)),i(o)}return e}(t),_setSink:td};od=t,function(){const t=globalThis,e=t[Yu];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[Yu]=n,n}().register(t)}const rd={name:"devtools",install(){sd()}},id=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),ad=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])}),ld=new WeakMap,cd=new WeakMap,ud=new WeakSet,dd=new WeakMap;function hd(t,e,n,o){console.warn(`[@wcstack/state] [${Ga[n]}] ${Ka[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${it(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${at}`),null!==Se&&Se({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const fd={check:function(t,e,n,o,s){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const r=t.addressHooks;if(r){const e=r.suppressPathDiagnostic;for(let o=0;o<e.length;o++)if(e[o](t,n))return}const i=ot(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=ld.get(t);return void 0===n&&(n=new Set,ld.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const a=function(t,e,n,o){if(void 0!==qa(t,e))return ad;const s=ot(e).segments;let r=t,i="";for(let e=0;e<s.length;e++){const a=o&&Array.isArray(r)&&+s[e]>=0?c:s[e],u=i;i=0===e?a:i+l+a;const d=e>0&&qa(t,i),h=d&&Ua.get(d.get);if(d&&(!h||qa(t,h)))return e<s.length-1?id:ad;if(Object(r)!==r)return id;if(a===c){if(!Array.isArray(r)||0===r.length)return id;r=r[0];continue}const f=qa(r,a);if(void 0===f)return{existence:"missing",missingSegment:a,candidates:Va(r,u,n,t)};if("function"==typeof f.get)return e===s.length-1?ad:id;r=f.value}return ad}(e,n,t.getterPaths,s);"missing"===a.existence&&(function(t,e){return!0===dd.get(t)?.has(e)}(t,n)||("binding"!==o?hd(0,n,o,a):function(t,e,n){let o=cd.get(t);void 0===o&&(o=new Map,cd.set(t,o)),o.set(e,n),ud.has(t)||(ud.add(t),setTimeout(()=>function(t){ud.delete(t);const e=cd.get(t);if(void 0!==e){cd.delete(t);for(const[t,n]of e)hd(0,t,"binding",n)}}(t),0))}(t,n,a)))},reset:function(t){ld.delete(t),cd.delete(t)},markExported:function(t,e){let n=dd.get(t);void 0===n&&(n=new Set,dd.set(t,n)),n.add(e),cd.get(t)?.delete(e)}};let pd=!1;const md={name:"diagnostics",install(){pd||(pd=!0,ju=fd)}};function gd(t){tt(`filter ${t} requires at least one option`)}function yd(t){tt(`filter ${t} requires a number as option`)}function bd(t){tt(`filter ${t} requires a number value`)}function wd(t){tt(`filter ${t} requires a date value`)}const vd={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function _d(t){return!(!t||isNaN(Number(t)))}function $d(t,e){return _d(t)||yd(e),Number(t)}function xd(t,e,n){return $d(t?.[e]??gd(n),n)}const Sd=t=>e=>{const n=t(e);return t=>null==t?t:n(t)},Id={eq:(t,e)=>{const n=t?.[0]??gd("eq"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t===o:(_d(n)||yd("eq"),t===Number(n)):"string"==typeof t?t===n:t===o},ne:(t,e)=>{const n=t?.[0]??gd("ne"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t!==o:(_d(n)||yd("ne"),t!==Number(n)):"string"==typeof t?t!==n:t!==o},not:t=>t=>!t,lt:t=>{const e=xd(t,0,"lt");return t=>("number"!=typeof t&&bd("lt"),t<e)},le:t=>{const e=xd(t,0,"le");return t=>("number"!=typeof t&&bd("le"),t<=e)},gt:t=>{const e=xd(t,0,"gt");return t=>("number"!=typeof t&&bd("gt"),t>e)},ge:t=>{const e=xd(t,0,"ge");return t=>("number"!=typeof t&&bd("ge"),t>=e)},add:t=>{const e=xd(t,0,"add");return t=>("number"!=typeof t&&bd("add"),t+e)},sub:t=>{const e=xd(t,0,"sub");return t=>("number"!=typeof t&&bd("sub"),t-e)},mul:t=>{const e=xd(t,0,"mul");return t=>("number"!=typeof t&&bd("mul"),t*e)},div:t=>{const e=xd(t,0,"div");return t=>("number"!=typeof t&&bd("div"),t/e)},mod:t=>{const e=xd(t,0,"mod");return t=>("number"!=typeof t&&bd("mod"),t%e)},abs:t=>t=>("number"!=typeof t&&bd("abs"),Math.abs(t)),clamp:t=>{const e=xd(t,0,"clamp"),n=xd(t,1,"clamp");return t=>("number"!=typeof t&&bd("clamp"),Math.min(Math.max(t,e),n))},toFixed:t=>{const e=$d(t?.[0]??"0","toFixed");return t=>("number"!=typeof t&&bd("toFixed"),t.toFixed(e))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&bd("locale"),t.toLocaleString(e??s.locale))},upper:Sd(t=>t=>String(t).toUpperCase()),lower:Sd(t=>t=>String(t).toLowerCase()),capitalize:Sd(t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)}),trim:Sd(t=>t=>String(t).trim()),slice:Sd(t=>{const e=[xd(t,0,"slice")],n=t?.[1];return void 0!==n&&e.push($d(n,"slice")),t=>String(t).slice(...e)}),substr:Sd(t=>{dt?.removed("substr");const e=xd(t,0,"substr"),n=xd(t,1,"substr");return t=>String(t).substr(e,n)}),padStart:Sd(t=>{const e=xd(t,0,"padStart"),n=t?.[1]??"0";return t=>String(t).padStart(e,n)}),padEnd:Sd(t=>{const e=xd(t,0,"padEnd"),n=t?.[1]??" ";return t=>String(t).padEnd(e,n)}),repeat:Sd(t=>{const e=xd(t,0,"repeat");return t=>String(t).repeat(e)}),reverse:Sd(t=>t=>String(t).split("").reverse().join("")),truncate:Sd(t=>{const e=xd(t,0,"truncate"),n=t?.[1]??"…";return t=>{const o=String(t);return o.length<=e?o:o.slice(0,e)+n}}),join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||tt("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=Math.pow(10,$d(t?.[0]??"0","round"));return t=>("number"!=typeof t&&bd("round"),Math.round(t*e)/e)},floor:t=>{const e=Math.pow(10,$d(t?.[0]??"0","floor"));return t=>("number"!=typeof t&&bd("floor"),Math.floor(t*e)/e)},ceil:t=>{const e=Math.pow(10,$d(t?.[0]??"0","ceil"));return t=>("number"!=typeof t&&bd("ceil"),Math.ceil(t*e)/e)},percent:t=>{const e=$d(t?.[0]??"0","percent");return t=>("number"!=typeof t&&bd("percent"),`${(100*t).toFixed(e)}%`)},unit:Sd(t=>{const e=t?.[0]??gd("unit");return t=>String(t)+e}),date:t=>{const e=t?.[0];return t=>(t instanceof Date||wd("date"),t.toLocaleDateString(e??s.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||wd("time"),t.toLocaleTimeString(e??s.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||wd("datetime"),t.toLocaleString(e??s.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||wd("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||wd("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]??gd("defaults"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t||o},coalesce:(t,e)=>{const n=t?.[0]??gd("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},Pd={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:[2,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,1],time:[0,1],datetime:[0,1],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]},kd=Id,Nd=Id;let Ad=!1;const Ed={name:"formats",install(){Ad||(Ad=!0,bt("input",Nd,Pd,vd),bt("output",kd,Pd,vd))}};function Cd(t){return-1!==t.indexOf(U)}function Md(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+l;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(Cd(o))return null;const s=o.slice(1).split(l);return s[0]===c||s.some(t=>0===t.length)?null:o}function Td(t){return 0===t.length?t:l+Rd(t.slice(1))}function Od(t,e,n){const o=l+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 Ld(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(l,o-1))if(Od(t,e,n.slice(0,o)))return!0;return!1}function Rd(t){const e=t.split(l);for(let t=0;t<e.length;t++)e[t]===c||Number.isNaN(Number(e[t]))||(e[t]=c);return e.join(l)}function jd(t,e){const n=t.repeat.split(l),o=l+t.repeat;let s=e;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===l+t.repeatList+l+"length")return!0;for(let t=1;t<n.length;t++)if(s===l+n.slice(0,t).join(l))return!0;return!1}function Wd(t,e,n){n<0&&tt(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=l+t.repeat;const s=o+e;let r=0;for(const t of s.split(l))t===c&&r++;return r>u&&tt(`[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 Dd(t,e){return Wd(t,"",e)}function zd(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=l+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 Bd(t,e,n){const o=t.recursionRegistry,s=Md(o.spec,n);null===s&&tt(Qa(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=l+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&&tt(`[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 Fd(t,e,n,o,s){const r=o.spec,i=[],a=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($o(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 l=$o(o,s),c=Xn(n.stateElement,l),d=zc(t,l,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)&&tt(`[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)&&tt(`[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=Bi(s,Mn(c),d);return a.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:a}=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:ot(n),childListPathInfo:ot(r+l+u)};return c[t]=i,i})(t),y=a;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($o(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,ot(d),null);for(const[t,e]of a)Tn(t,e);return i}const Hd={write(t,e){if(!0!==t.hasRecursion)return wc;const n=t.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);return null!==n&&tt(`[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.`),wc},get(t,e,n,o){if(!0!==t.stateElement.hasRecursion)return wc;if("$getAll"===e)return(e,s)=>{if(Cd(e)){if(void 0!==s)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=Md(r.spec,o);null===i&&tt(Qa(o,r.spec.recursiveAnchor)),Array.isArray(s)||tt(`[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&&tt(`[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=Fd(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(zc(t,a[o],e,n));return l}(o,n,t,e,s);e=Bd(t.stateElement,t,e)}return vu(o,0,n,t)(e,s)};if("$setAll"===e)return(e,s,r,i)=>Cd(e)?function(t,e,n,o,s,r,i){Mc(n);const a=n.stateElement.recursionRegistry,l=Md(a.spec,o);null===l&&tt(Qa(o,a.spec.recursiveAnchor));const c=Td(l);Array.isArray(s)||tt(Xa(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&tt(`[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&&tt(Xa(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&tt(Xa(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){jd(t,n)&&tt(`[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&&tt(`[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=Fd(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(yu(t,d[o],r,e,n),h++);return h}(o,n,t,e,s,r,i):$u(o,0,n,t)(e,s,r,i);if(36!==e.charCodeAt(0)&&Cd(e)){const s=Cc(Bd(t.stateElement,t,e)),r=_u(o,s,n,t);return zc(o,$o(s.pathInfo,r),n,t)}return wc}};let qd=!1;function Ud(t,e){"string"==typeof e&&0!==e.length||tt(`[wcs/recursion-declaration-invalid] ${q} ${t} must be a non-empty string.`);const n=e.split(l);n.some(t=>0===t.length)&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain empty path segments.`),n.length<2&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must name a list element: a property path ending with "${l}${c}" (for example "nodes${l}${c}").`),n[n.length-1]!==c&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must end with "${l}${c}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===c&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must have exactly one "${c}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===U&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain "${U}" — the declaration is what gives "${U}" its meaning.`),isNaN(Number(n[o]))||tt(`[wcs/recursion-declaration-invalid] ${q} ${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 Vd=new WeakSet;function Gd(t){return"function"==typeof t.get&&Vd.has(t.get)}const Kd="[wcs/recursion-declaration-invalid]";class Jd{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=Ru(e);for(const[e,o]of Object.entries(n)){if(!Cd(e))continue;"function"==typeof o.set&&tt(`${Kd} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&tt(`${Kd} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Md(t,e);null===n&&tt(Qa(e,t.recursiveAnchor)),0===n.length&&tt(`${Kd} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${l}total"), not the node.`),jd(t,Td(n))&&tt(`${Kd} "${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}${l}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(Cd(e)||Gd(n))continue;const t=this._matchExpansion(e);null!==t&&tt(`${Kd} "${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++)Od(this.spec,t[e].suffix,t[n].suffix)&&tt(`${Kd} "${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(Ld(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=Rd(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(l);null===s&&t>this.spec.anchor.length;t=n.lastIndexOf(l,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!==zd(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=zd(this.spec,t.suffix,e);null!==n&&(null!==o&&tt(`"${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||Gd(s)||tt(`"${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,Vd.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(Dd(t,o)+l+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&&Gd(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))}}}}(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=Wd(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 Qd="recursionSpec",Xd="recursionRegistry",Yd={order:5,validateEarly(t,e,n){const o=function(t){const e=t[q];if(void 0===e)return null;"object"==typeof e&&null!==e||tt(`[wcs/recursion-declaration-invalid] ${q} 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&&tt(`[wcs/recursion-declaration-invalid] ${q} must declare exactly one anchor; it is empty.`),n.length>1&&tt(`[wcs/recursion-declaration-invalid] ${q} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Ud("anchor",o),"string"!=typeof s&&tt(`[wcs/recursion-declaration-invalid] ${q} entry "${o}" must map to the repeating sub-path as a string (for example "children${l}${c}").`),Ud("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(l)),i=s.slice(0,s.lastIndexOf(l)),a=r+l+U;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(e);n.set(Qd,o),n.set(Xd,null===o?null:new Jd(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(Xd)??null;t.setRecursionRegistry?.(s),null!==s&&t.attachAddressHooks?.("recursion",q)},apply(t,e,n){const o=n.get(Qd)??null;null!==o&&t.addListPath(o.anchorList)}};let Zd=!1;const th={name:"recursion",install(){Zd||(Zd=!0,qd||(qd=!0,$c("recursion",Hd)),Pc("recursion",Yd))}},eh={written:function(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1&&-1===e.path.indexOf("#")?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 nh=!1;function oh(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 sh(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 rh(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 ih(t){return t.startsWith("$")}function ah(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 lh(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||tt(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||tt(`${e} entries must be non-empty strings.`),t.startsWith("$")&&tt(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&tt(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function ch(t,e,n){const o=t.tagName.toLowerCase();o.includes("-")||tt(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const r=Jt(t);null!==r&&"function"==typeof r.define||tt(`DCC: CustomElementRegistry is unavailable for "${o}".`),r.get(o)&&tt(`DCC: "${o}" 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){pc(t);const e=lh(t,L)??[],n=lh(t,R)??[],o=Ru(t),s=function(t){const e=t[B];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}tt(`${L} entry "${t}" is not declared on the state.${it(t,ah(o,"value"))}`)}"function"==typeof e.value&&tt(`${L} entry "${t}" is a method. Declare it in ${R} instead.`)}for(const t of n){const e=o[t];void 0===e&&tt(`${R} entry "${t}" is not declared on the state.${it(t,ah(o,"method"))}`),"function"!=typeof e.value&&tt(`${R} entry "${t}" is not a method. Declare it in ${L} 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}}(o,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(o,c):{},p=s.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(J))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=Jt(this._shadow);return null!==t&&Qt(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?(nh||(nh=!0,$c("dcc",eh)),e.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${L} but its template has no <${s.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=Ru(n);for(const[t,e]of Object.entries(g)){if(ih(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=rh(t,o)}else n.get=oh(t),n.set=sh(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:oh(t),set:sh(t)});r.define(o,m)}const uh={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(J)?async function(t,e,n){const o=t;try{o.hasAttribute("bind-component")&&tt(`"bind-component" cannot be used inside a [${J}] host. DCC state comes from the template, not from a component property.`);const s=await async function(t,e){if(t.hasAttribute("src")){const e=t.getAttribute("src");if(e.endsWith(".js"))return await cc(e);tt(`DCC: Unsupported src type: ${e}`)}const n=t.querySelector('script[type="module"]');if(n)return await lc(n,e.tagName.toLowerCase());tt(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}(o,e);ch(e,n,s),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}(t,e.host,e):null}};let dh=!1;function hh(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 fh(t,e){for(const n of t)if(hh(e,n.innerSegments))return n;return null}function ph(t,e){const n=e.slice(t.innerSegments.length);return 0===n.length?t.outerPathInfo.path:t.outerPathInfo.path+l+n.join(l)}const mh=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function gh(t,e,n){const o=mh.get(t);return void 0===o?null:(...t)=>{const s=t.slice();for(let t=0;t<o.length;t++){const n=o[t];"string"==typeof s[n]&&(s[n]=e(s[n]))}return n(s)}}const yh=new WeakMap;function bh(t,e,n){let o=yh.get(t);void 0===o&&(o=new Map,yh.set(t,o));null!=o.get(e)&&tt(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function wh(t,e){if(null===t)return!1;const n=yh.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+l)||t.startsWith(e+l))return!0;return!1}const vh=new WeakMap,_h=[];function $h(t,e,n,o){if(e.length>0){const s=n.split(l),r=fh(e,s);if(null!==r)return o&&r.readonly&&tt(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${x}.${r.innerSegments.join(l)}#${g}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${g} from the injection.`),ph(r,s)}return t+l+n}function xh(t,e,n){let o=-1,s=null;for(const t of e){const e=t.outerPathInfo.path;e.length<=o||(n===e?(o=e.length,s=t.innerSegments.join(l)):n.startsWith(e+l)&&(o=e.length,s=t.innerSegments.join(l)+n.slice(e.length)))}if(t.length>o){if(n===t)return"";if(n.startsWith(t+l))return n.slice(t.length+1)}return s}function Sh(t,e,n=_h){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]($h(t,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>e.$setAll($h(t,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>e.$resolve($h(t,n,o,s.length>1),...s);const o=gh(s,e=>$h(t,n,e,!1),t=>e[s](...t));return null!==o?o:e[s]}return e[$h(t,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(e[s]=r,!0):(e[$h(t,n,s,!0)]=r,!0)),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Ih=new WeakMap,Ph=[],kh=new WeakMap,Nh=new WeakSet;function Ah(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 Eh=null,Ch=0;const Mh=["$watch",B,"$scan","$listKeys",M,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Th=new Set;function Oh(t,e,n){const o=t.stateObject[e];if("function"==typeof o)try{const s=o.call(n());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 Lh(t){const e=t.indexOf(l);return-1===e?t:t.slice(0,e)}function Rh(t,e){const n=fh(t.entries,e);return null===n?null:ph(n,e)}function jh(t,e){return t.markerBasePath+l+e}function Wh(t,e,n,o){let s=t.accessorBySuffixByMarkerParent.get(e);void 0===s&&(s=new Map,t.accessorBySuffixByMarkerParent.set(e,s));const r=e+l+n;s.set(n,{accessorName:o,indexShift:ot(r).wildcardCount-ot(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(r),t.addedGetterPaths.add(r))}function Dh(t,e){return!t.injectedKeys.has(e)&&(!t.getterKeys.has(e)&&"function"==typeof t.stateObject[e]||!t.mappedKeys.has(e)&&Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function zh(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(l)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${Lh(e)}: path") or declare the key on the component state.`}const Bh=/^\$(\d+)$/;function Fh(t,e){if(!t.hasReadonlyEntries)return null;const n=e[0];if("$"===n||"#"===n)return null;if(t.getterKeys.has(e)||t.setterKeys.has(e))return null;const o=Lh(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||Dh(t,o))return null;const s=function(t,e){return fh(t.entries,e)}(t,e.split(l));return null!==s&&s.readonly?s:null}function Hh(t,e){const n=Fh(t,e);if(null!==n){const o=0===n.innerSegments.length?"":l+n.innerSegments.join(l);tt(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${g}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${g} from the mount.`)}return qh(t,e)}function qh(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(l);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===c){o=t;break}if(-1===o)return Wh(t,t.markerBasePath,e,e),jh(t,e);if(Dh(t,n[0]))return Wh(t,t.markerBasePath,e,e),jh(t,e);const s=n.slice(0,o+1),r=n.slice(o+1),i=Rh(t,s);null===i&&tt(zh(t,e)),0===r.length&&tt(`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 a=i+l+t.marker;return Wh(t,a,r.join(l),e),a+l+r.join(l)}(t,e);const o=Lh(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return jh(t,e);if(Dh(t,o))return jh(t,e);const s=Rh(t,e.split(l));if(null!==s)return s;tt(zh(t,e))}const Uh=new Set(["prop","radio","checkbox"]);function Vh(t,e,n,o,s){if(void 0===o)return;const r=ot(n).wildcardCount-ot(e).wildcardCount;return 0===r?o:(s.length<r&&tt(`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])}function Gh(t,e,n){if(-1!==t.indexOf(c))return e;const o=e.split(l);let s=0;for(let t=0;t<o.length&&s<n.length;t++)o[t]===c&&(o[t]=String(n[s++]));return o.join(l)}const Kh=new WeakMap,Jh=new WeakMap,Qh=new WeakMap,Xh=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)}),Yh=new WeakMap;function Zh(t){return Yh.get(t)??null}let tf=!1;function ef(t){return Kh.get(t)??null}function nf(t){return of(t).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join(l),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]}))}function of(t){const e=Qh.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 sf(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=Qh.get(t);if(void 0===o)return null;const s=e.indexOf(l,n),r=-1===s?e.slice(n):e.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const rf=new WeakMap,af=new Set;function lf(t,e,n,o){let s=rf.get(t);if(void 0===s){if(!o)return null;s=new Map,rf.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 cf(t,e){if(!t.component.isConnected)return!1;const n=$e(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 uf(t,e,n,o){const s=lf(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&&cf(n,e)?n:null}(r,o);if(null!==t)return{record:t,entry:r.entry}}let i=null,a=null;for(const t of s.holders){const r=t.ref.deref();void 0!==r?cf(r,o)&&(null!==a&&tt(`[wcs/mount-export-ambiguous] "${e}${l}${n}" is exported by two mounted components on the same instance: <${a.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,a=r):s.holders.delete(t)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function df(t){const e=t.parentStateElement,n=$e(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[jn](n,()=>{t.$postUpdate(o.exportedPath)})})}const hf=new WeakMap,ff=new WeakMap,pf=new WeakMap,mf=new WeakMap;function gf(t,e){ff.set(t,e);const n=[];for(let t=e?.listIndex.parentListIndex??null;null!==t;t=t.parentListIndex)n.push(t);mf.set(t,n)}function yf(t){return $e(t.component)??ff.get(t)??null}function bf(t){return yf(t)?.listIndex??null}function wf(t){tt(`The host row of <${t.component.tagName.toLowerCase()}> was removed.`)}function vf(t){for(;null!==t;t=t.parentListIndex)if(Je(t))return!0;return!1}function _f(t,e){return!t.component.isConnected&&(vf(e)||!0===mf.get(t)?.some(t=>Je(t)))}class $f{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(t,e,n,o,s,r,i,a=!1){this.record=t,this.markerParentPath=e,this.listIndex=n,this.hostRow=o,this.isBase=s,this.receiver=r,this.handler=i,this.authorFacing=a}authorThis(t,e){return this.authorFacing?e:new Proxy(t,new $f(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return $o(ot(this.markerParentPath+l+t),this.listIndex)}hostIndexes(){const t=this.listIndex??bf(this.record),e=this.hostRow??t;return(null===this.listIndex?e!==t||_f(this.record,e):vf(e))&&wf(this.record),e?.indexes??[]}resolveTreePath(t,e){return-1===e.indexOf(c)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==Cc(e).wildcardType&&!_f(this.record,this.listIndex)?e:Gh(t,e,this.hostIndexes())}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(this.resolveTreePath(t,qh(this.record,t)))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.hostIndexes(),o=this.receiver,s=this.handler,r=this.listIndex;if("$resolve"===e)return(e,s,...r)=>{const i=r.length>0?Hh(t,e):qh(t,e),a=Vh(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const i=e;return(e,a,...l)=>{const c="$setAll"===i?Hh(t,e):qh(t,e),u=Vh(0,e,c,void 0===a&&"$getAll"===i&&null===r&&null===Tc(s,ot(c).wildcardPaths[0])?[]:a,n);return o[i](c,u,...l)}}const t=this.record,n=this.receiver,o=gh(e,e=>this.resolveTreePath(e,qh(t,e)),t=>n[e](...t));return null!==o?o: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 Oc(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(this.authorThis(t,n))}return this.receiver[this.resolveTreePath(e,qh(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)||tt(`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,this.authorThis(t,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(t,e)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress($o(ot(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+l+e]=n}finally{this.handler.popAddress()}return!0}return t[e]=n,!0}return this.receiver[this.resolveTreePath(e,Hh(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 qh(this.record,e),!0}catch{return!1}}}function xf(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=hf.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},hf.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 $f(t,s,e.listIndex,e.listIndex??bf(t),r,n,o))}function Sf(t){if(null===bf(t))return t.component[t.stateProp];let e=pf.get(t);if(void 0===e){const n={row:null};pf.set(t,e=[If(t,n),n])}return e[0]}function If(t,e){const n=()=>{const n=yf(t);return void 0!==e&&pf.get(t)?.[0]!==i&&n.listIndex!==e.row&&wf(t),n},o=()=>{const e=n();return _f(t,e?.listIndex??null)&&wf(t),e?.listIndex.indexes??[]},s=(e,n)=>-1===n.indexOf(c)?n:"partial"===Cc(n).wildcardType?Gh(e,n,o()):-1===n.indexOf("#")&&_f(t,bf(t))?wf(t):n,r=(e,o)=>{let s;const r=n();return t.parentStateElement.createState(e,t=>{s=t[jn](r,()=>o(t))}),s},i=new Proxy({},{get(e,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(t,e,n,o,s){return"$postUpdate"===e?e=>n("readonly",n=>n.$postUpdate(s(e,qh(t,e)))):(s,r,...i)=>{const a="$setAll"===e||"$resolve"===e&&i.length>0,l=a?Hh(t,s):qh(t,s),c=Vh(0,s,l,"$resolve"===e?r??[]:r,o());return n(a?"writable":"readonly",t=>t[e](l,c,...i))}}(t,n,r,o,s);const i=gh(n,e=>s(e,qh(t,e)),t=>r("readonly",e=>e[n](...t)));if(null!==i)return i;const a=e=>e["$"===n[0]?n:s(n,qh(t,n))],l=r("readonly",a);return"$"===n[0]||t.getterKeys.has(n)||"function"!=typeof t.stateObject[n]?l:function(...t){return r("writable",e=>a(e).apply(this,t))}},set:(e,n,o)=>("string"==typeof n&&r("writable",e=>{e["$"===n[0]?n:s(n,Hh(t,n))]=o}),!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 qh(t,n),!0}catch{return!1}}});return i}function Pf(t,e){const n=ef(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&tt(`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&&gr(e).dispose(),function(t,e){tf||(tf=!0,_e=t=>Kh.has(t)?t.host:null),Kh.set(t,e),Yh.set(e,t);let n=Qh.get(e.parentStateElement);void 0===n&&(n=new Map,Qh.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=Jh.get(e.component);void 0===o&&(o=new Map,Jh.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&Xh.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=$l.get(t);if(void 0!==n){if(n===e)return;tt("A state tree is already registered on this root.")}$l.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const s=Bh.exec(e.statePathName);if(null!==s){const r=function(t,e){return void 0===e?t.delta:ot(qh(t,e)).wildcardCount-ot(e).wildcardCount}(t,n);o=0===r?e.statePathName:`$${Number(s[1])+r}`}else if(o=qh(t,e.statePathName),"for"===e.bindingType){const n=ot(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+l+c,n)}const r=e.propModifiers,i=null===s&&Array.isArray(r)&&Uh.has(e.bindingType??"")&&!r.includes(g)&&null!==Fh(t,e.statePathName);return o!==e.statePathName||i?{...e,statePathName:o,statePathInfo:ot(o),...i?{propModifiers:[...r,g]}:{}}:e}(t,e,n);Y(e);const o=$e(t.component);gf(t,o),Yl(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),pl(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=qh(t,n)}catch{continue}const o=e.indexOf(l+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)+l+r,a=ot(i);if(a.wildcardCount!==t.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:e,exportedPath:i};t.exports.set(i,c),lf(t.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,i),ju?.markExported(t.parentStateElement,i)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=$e(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(af.has(s))continue;const r=ot(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[jn](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(af.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),df(t),o=e,s=Promise.resolve(),xl.set(o,s),s.then(()=>Al(o),()=>{})}function kf(t,e){hl(Nf(t,e).rebindAddresses()),df(t)}function Nf(t,e){const n=gr(e),o=$e(t.component);return gf(t,o),n.forEachActiveBindingNode(t=>xe(t,o)),n}function Af(t){for(let e=t.parentNode;null!==e;e=e.parentNode){const t=ef(e);if(null!==t)return Af(t.component),void Nf(t,e)}}function Ef(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 Cf={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const s=sf(t,e.pathInfo.path);if(null!==s)return xf(s,e,n,o)}return wc},readMissing(t,e,n,o,s){if(null===n){if(wh(t.rootNode??null,e.pathInfo.path))return;return wc}if(!0===t.hasMounts){const n=uf(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s){const r=xf(t,$o(ot(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(n.record,n.entry,e.listIndex,o,s)}return wc},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=vh.get(t);if(void 0===n||0===n.size)return null;const o=e+l;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&tt(`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 wc},writeMissing(t,e,n,o,s,r,i){if(!0===t.hasMounts){const n=uf(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s,r){const i=xf(t,$o(ot(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(n.record,n.entry,e.listIndex,s,r,i)}return wc},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=sf(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(l,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=Kh.get(n);if(void 0!==t)return t;n=n.parentNode}return Kh.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 Ih.get(t)??Ph}(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=xh(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=ro(n.listIndex,a);(r[i]??=[]).push(t)}}if(o.size>0)try{s.callback.call(Sh(s.mountPath,n,s.injections),Array.from(o),r)}catch(t){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>wh(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(function(t){const e=Qh.get(t);return void 0!==e&&e.size>0}(e))for(const n of of(e)){if(!Ef(n.component,t))continue;const e=Zh(n);null!==e&&kf(n,e)}}(e,t)}};let Mf=!1;const Tf=new WeakMap;function Of(t){let e=Tf.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Tf.set(t,e)),e}function Lf(t,e){null!==e.slotRootNode&&(function(t,e,n){const o=yh.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function Rf(t,e,n){if(e.slotRootNode===n)return!0;const o=e.mountPath;try{bh(n,o,t)}catch{return console.error(`[@wcstack/state] <${s.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return Pl(n)?.markHasVolume?.(),e.slotRootNode=n,!0}const jf={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=Of(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{bh(n,e.mountPath,t),Pl(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,Eu}return async function(t,e){const n=t,o=t.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(t){0===t.length&&tt('"mount" requires a non-empty tree path.');const e=ot(t);for(const n of e.segments)0===n.length&&tt(`"mount" path "${t}" has an empty segment.`),n===c&&tt(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&tt(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),i=function(t,e){const n=[],o=new Set;let r;try{r=Lt(t)}catch(t){tt(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${e}"> has an invalid ${s.bindAttributeName}: ${t instanceof Error?t.message:String(t)}`)}for(const t of r){if(t.propSegments[0]!==x)continue;const r=t.propSegments.slice(1),i=t.statePathInfo,a=n=>tt(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${e}"> "${t.propName}: ${t.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==c&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${x}.<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)."),(t.inFilters.length>0||t.outFilters.length>0)&&a("an injection takes no filters."),t.propModifiers.some(t=>t!==g)&&a(`an injection accepts only #${g}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:t.propModifiers.includes(g)})}return n.sort((t,e)=>e.innerSegments.length-t.innerSegments.length),n}(n.getAttribute(s.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&tt('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${s.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),bh(o,r,t),Pl(o)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=o}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===Pl(o)&&function(t,e){const n=()=>{if(null!==Pl(t))return;const n=t.querySelectorAll(s.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${s.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${s.tagNames.state}> to this root node (an empty <${s.tagNames.state}></${s.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=t.ownerDocument??t;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&Lf(t,e),t.settleInitialization()};let l;try{await Promise.resolve(),l=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&&Rf(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?(cp(),function(t,e){if(Nh.has(t))return void Ah(e);let n=kh.get(t);void 0===n&&(n=[],kh.set(t,n)),n.push(e)}(t,a)):ap(e,a)}(u,Pl(u),r,l,a,()=>Rf(t,e,u),i):a(null)}(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=Of(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&Pl(n)===e.graftInfo.rootStateElement&&rp(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==Tf.get(t)?.initializing)return;const e=t.getAttribute("mount");tt(`Cannot replace the state of <${s.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){Nh.add(t);const e=kh.get(t);if(void 0!==e){kh.delete(t);for(const t of e)Ah(t)}}(e)},initializeFailureCleared(t,e){!function(t){Nh.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=Of(t);return null!==e.graftInfo&&rp(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,Lf(t,e)),t.clearConnectedRootNode(),!0}};let Wf=!1;const Df=new WeakMap;function zf(t,e){let n=Df.get(t);n||(n=new Set,Df.set(t,n)),n.add(e)}const Bf=new WeakMap,Ff=new WeakMap,Hf=new WeakMap,qf=new WeakMap,Uf={isComplete:function(t,e){return!0===Df.get(t)?.has(e)},isDeclared:function(t,e){return!0===Bf.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=Ff.get(t);o||(o=new Map,Ff.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=Hf.get(t);o||(o=new Map,Hf.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=qf.get(t);s||(s=new Map,qf.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}};const Vf=new WeakMap;class Gf{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=Vf.get(t);return n?n.get(e)??null:null}(t,e)??tt("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 Kf=t=>()=>t;function Jf(t,e,n,o){!function(t,e,n){let o=Vf.get(t);o||(o=new Map,Vf.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 Gf(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:Kf(s),enumerable:!0,configurable:!0}),zf(e,n),Qf(e,n)}function Qf(t,e){if(O in t){const n=t[O];"function"==typeof n?n.call(t,e).catch(t=>{tt(`Error in ${O}: ${t instanceof Error?t.message:String(t)}`)}):tt(`${O} is not a function.`)}}const Xf=new Set;function Yf(t,e){Xf.has(t)||(Xf.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Zf(t){const e=t.rootEntry,n=$e(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[jn](n,()=>{o=t[e.outerPathInfo.path]})}),o}const tp=new WeakMap;function ep(t,e){t.landInitialization(),tt(e)}async function np(t,e){const n=t;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,c=a?Gt(a):null;null!==a&&null!==c||tt(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(s.bindAttributeName)||ep(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&&tt(`"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=Bf.get(t);n||(n=new Set,Bf.set(t,n)),n.add(e)}(a,d);const h=Jt(a);null===h&&tt(`CustomElementRegistry is unavailable for <${c}>.`),await h.whenDefined(c.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await qt(a),d in a||tt(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||tt(`Component property "${d}" is not an object for state binding.`);const p=function(t,e){const n=Ff.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,d);if(void 0!==p&&function(t,e){if(!t.hasAttribute(s.bindAttributeName))return!1;const n=ce(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,d)&&(a[d]=p,f=p),e.boundComponent=a,e.boundComponentStateProp=d,t.setBoundComponent(a,d),i instanceof ShadowRoot||(ce(a)??[]).some(t=>t.propSegments[0]===d)||ep(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").`),a.hasAttribute(s.bindAttributeName)){const s=(ce(a)??[]).filter(t=>t.propSegments[0]===d);if(s.length>0){const u=Pl(a.getRootNode())??ep(t,`No state tree found on this root for mount host <${c}>.`);let h=(o=a,r=d,Jh.get(o)?.get(r)??null);const p=null!==h;if(null===h&&(function(t,e,n){const o=qf.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;qf.get(t).delete(e)}}(a,d,f),h=function(t,e,n,o,s,r=new Set){0===n.length&&tt(`Cannot build a mount record without host bindings for "${e}".`),pc(s);const i=[],a=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(l);a.has(n)&&tt("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(g)};i.push(o),0===e.length&&(c=o)}i.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++Ch,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Ru(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)1===t.innerSegments.length&&p.add(t.innerSegments[0]);const m={};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)||(m[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+l+d,stateObject:s,getterKeys:h,setterKeys:f,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(t=>t.readonly),privateSnapshot:m,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(a,d,s,u,f,function(t,e){return Hf.get(t)?.get(e)}(a,d)),function(t){!function(t){const e=t.component.tagName.toLowerCase(),n=t.stateProp;let o=null;for(const s of t.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=Ru(t.stateObject);const i=o[r];let a;if(t.getterKeys.has(r)||t.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)a="an accessor";else if("function"==typeof i?.value)a="a method";else{if(t.mappedKeys.has(r)||t.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(t.stateObject,r))continue;a="an own data key"}const c=s.innerSegments.join(l);Yf(`${e}|${n}|${c}|entry`,`<${e}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${c}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(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=Zf(t),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const e=t.rootEntry.outerPathInfo.path;Yf(`${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{Pf(h,i instanceof ShadowRoot?i:a)}catch(e){throw t.landInitialization(),e}if(!p){const t=If(h);Object.defineProperty(a,d,{get:()=>t,enumerable:!0,configurable:!0}),zf(a,d)}return Qf(a,d),function(t){const e=Mh.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(U)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Th.has(n)||(Th.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 Oh(h,"$connectedCallback",()=>Sf(h))}}Jf(t,e.boundComponent,e.boundComponentStateProp,f)}var o,r}const op={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=tp.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},tp.set(t,e)),e}(t);return np(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=tp.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&kf(n,o)}),t.isConnected&&(Af(n.component),Nf(n,o)),Oh(n,"$connectedCallback",()=>Sf(n)),!0},disconnecting(t){const e=tp.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord;return Oh(n,"$disconnectedCallback",()=>Sf(n)),function(t){const e=pf.get(t);void 0!==e&&(e[1].row=bf(t),pf.delete(t))}(n),df(e.mountRecord),t.clearConnectedRootNode(),!0}};let sp=!1;function rp(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(Sh(t.mountPath,o,t.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function ip(t,e,n,o=[]){pc(n),function(t,e,n,o){const s=0===o.length?null:Ru(n);for(const t of o){const n=t.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||tt(`[wcs/mount-path-invalid] Volume "${e}" declares "${n}" as an accessor or a method and also injects it ("${x}.${n}: ${t.outerPathInfo.path}"). Rename one of them.`)}const r=n[F];if(void 0!==r){"object"==typeof r&&null!==r||tt(`${F} must be an object mapping state paths to handler functions.`);const t=Vu(e);for(const[e,n]of Object.entries(r))"function"!=typeof n&&tt(`${F} entry "${e}" must be a function.`),t.assertValidPath(e)}const i=n[V];if(void 0!==i){"object"==typeof i&&null!==i||tt(`${V} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(i)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&tt(`${V} entry "${n}" must map a list path to a field name or a key function.`);const r=$h(e,o,n,!1);t.listKeys?.has(r)&&tt(`${V} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[B]&&tt(`Volume "${e}" declares ${B}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&tt(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[q]&&tt(`Volume "${e}" declares ${q}, 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(Ru(n)))-1!==t.indexOf(U)&&tt(`Volume "${e}" declares "${t}", which uses "${U}". 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(Ru(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=ot(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;tt(`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+l+o];n=""===n?o:n+l+o,s||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(a)return;tt(`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=vh.get(t);void 0===n&&(n=new Set,vh.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,s]of r){const r=e+l+n,i=s.get,a=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(Sh(e,this,o))}),"function"==typeof a&&(c.set=function(t){a.call(Sh(e,this,o),t)}),t.defineTreeAccessor(r,c)}!function(t,e,n,o){const s=n[F];if(void 0!==s){const n=Vu(e),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=$h(e,o,n,!1),c=function(t,n,...s){l.call(Sh(e,this,o),t,n,...s)};r.push({path:s,pathInfo:ot(s),handler:c,order:1e6+a++}),i.add(s),t.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(t,r),t.addVolumeWatchPaths?.(i),n.start(t))}const r=n[V];if(void 0!==r){const n=new Map;for(const[t,s]of Object.entries(r))n.set($h(e,o,t,!1),s);t.mergeVolumeListKeys?.(n)}const i=n[M];"function"==typeof i&&(function(t,e){let n=Ih.get(t);void 0===n&&(n=[],Ih.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.`);dt?.volume(e,n,o.length)}(t,e,n,o);const c=n.$connectedCallback;return"function"==typeof c&&t.createState("writable",t=>{let n;try{n=c.call(Sh(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 ap(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=ip(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 lp=!1;function cp(){var t;lp||(lp=!0,Mf||(Mf=!0,$c("scopes",Cf),Gu=nf),Wf||(Wf=!0,Tu("scopes",jf)),sp||(sp=!0,Tu("bindComponent",op),br=Uf),Eh=ap,t=up,Il.includes(t)||Il.push(t))}function up(t,e){(function(t){const e=yh.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){Nh.delete(t);const n=kh.get(t);if(void 0===n||0===n.length||null===Eh)return;kh.delete(t);const o=Eh;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const dp={name:"scopes",install(){cp(),dh||(dh=!0,Tu("dcc",uh))}},hp=/^@@wcs-(?:for|if|elseif|else):[^-]/,fp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,pp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,mp=/^@@wcs-text-start:(.+)$/;function gp(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function yp(t,e){const n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const t=n.currentNode;e(t.data)&&o.push(t)}return o}const bp=t=>hp.test(t),wp=t=>fp.test(t),vp=t=>fp.test(t)||pp.test(t);function _p(t){if("else"===t.bindingType)return"else:";let e=`${t.bindingType}: ${t.statePathName}`;for(const n of t.outFilters){const t=n.literals??n.args;e+=`|${n.filterName}`,n.args.length>0&&(e+=`(${n.args.map((e,n)=>"string"==typeof t[n]?`'${e.split("'").join("'\"'\"'")}'`:e).join(",")})`)}return e}function $p(t){const e=t.fragment.cloneNode(!0);for(const n of t.nodeInfos){const o=Ul(re(t.fragment,n.nodePath));if(null===o)continue;const s=re(e,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return e}class xp extends Lu{_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=Ju.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=s.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,o){const r=o??t.ownerDocument;n.seen&&function(t){const e=new Map;for(const n of yp(t,wp)){if(null===n.parentNode)continue;const[,t,o]=fp.exec(n.data),s=o.split(":")[0],r=n.previousSibling?.data,i=`@@wcs-${t}-end:${o}`;if(r!==`@@wcs-${t}:${s}`&&e.get(r)!==s)for(let t=n;null!==t;){const e=t.nextSibling;t.remove(),t=t.data===i?null:e}else"for"===t&&e.set(i,s)}}(r);const i=document.createElement("script");i.setAttribute("type","application/json"),i.textContent=gp(JSON.stringify(e)),t.appendChild(i);for(const[e,n]of function(t){const e=new Map,n=[t];for(;n.length>0;)for(const t of yp(n.shift(),bp)){const o=t.data,s=o.slice(o.indexOf(":")+1);if(e.has(s))continue;const r=Tl(s);null!==r&&(e.set(s,r),n.push(r.fragment))}return e}(r)){const o=document.createElement("template");o.setAttribute("id",e),o.setAttribute(s.bindAttributeName,_p(n.parseBindTextResult)),o.content.appendChild($p(n)),t.appendChild(o)}const a=t.ownerDocument,l=Array.from(Oa);if(l.length>0){const e={};for(let t=0;t<l.length;t++){const n=l[t];if(!n.isConnected||n.ownerDocument!==a)continue;const o=Ta(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const t of o)r[t.propName]=t.value;e[s]=r}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=gp(JSON.stringify(e)),t.appendChild(n)}}La()}static removeBlockBoundaryComments(t){for(const e of yp(t,vp))e.remove()}static removeStructuralComments(t){for(const e of yp(t,bp))e.remove()}static restoreTextBindings(t){for(const e of yp(t,t=>mp.test(t))){const t=mp.exec(e.data)[1],n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;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(s.tagNames.ssr),o=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&o.set(e,t)}}for(const t of yp(e,wp)){const e=fp.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()}xp.restoreTextBindings(e);const r=t=>{for(const e of yp(t,bp)){const t=o.get(e.data.split(":")[1]);if(t){const n=document.createElement("template"),o=t.getAttribute(s.bindAttributeName);o&&n.setAttribute(s.bindAttributeName,o);const i=document.importNode(t.content,!0);if(i.childNodes.length>0)n.content.appendChild(i);else for(const e of Array.from(t.childNodes))n.content.appendChild(document.importNode(e,!0));r(n.content),e.parentNode.replaceChild(n,e)}}};r(e);const i=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of i)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const Sp={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=s.tagNames.state,n=s.tagNames.ssr,o=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of o){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Ju),xp.buildContent(o,xp.extractStateData(t),t.getRootNode()),t.parentNode?.insertBefore(o,t)}La()},reset:function(){Cl.clear(),La(),n.seen=!1}},Ip=new Set(["for","if","elseif","else"]);function Pp(t){const[,e,n]=fp.exec(t),[o,...s]=n.split(":");return"for"===e?{type:e,uuid:o,path:s[0],index:parseInt(s[1],10),nodes:[]}:{type:e,uuid:o,path:s.join(":"),index:null,nodes:[]}}function kp(t){const e=[];for(const n of t)if(n.nodeType===Node.ELEMENT_NODE){const t=n;t.hasAttribute(s.bindAttributeName)&&e.push(t),Array.from(t.children).some(t=>t.localName===s.tagNames.state&&ue(t))||e.push(...fe(t))}else null!==Dt(n)&&e.push(n);return e}function Np(t){const[e,n,o]=ye(t),s=new mr;return{bindingInfos:s.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:e,bindingSession:s,deferredSpreads:o}}const Ap=/^\s*@@\s*(?:wcs-text)?\s*:/;function Ep(t,e){for(const n of e)"event"===n.bindingType||Ip.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&Ap.test(n.node.data))&&t.push(n)}function Cp(t,e){const n=[];for(let o=0;o<t.nodes.length;o++){const s=e.get(t.nodes[o]);s?o+=s.nodes.length+1:n.push(t.nodes[o])}return n}function Mp(t,e,n,o,s,r){e.length>0&&(t.spreads=e);for(const t of e)be(t.node);fl(e,n,o,s,r)}function Tp(t,e){const n=Tl(e),o=Pl(t.getRootNode());let s=null;if(n&&o){const{statePathName:t,outFilters:e}=n.parseBindTextResult;o.createState("readonly",n=>{const o=wr(n[t],ie(e,"output"));Array.isArray(o)&&(s=o)})}return s}function Op(t,e){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[t]}:${e}`}function Lp(t,e,n){const o=Op(e,n);return yp(t,t=>t===o)[0]??null}function Rp(t,e){const n=t,o=e.templates,r=new Map;for(const[t,e]of o)for(const n of yp(e.content,bp))r.set(n.data.slice(n.data.indexOf(":")+1),t);const i=new Set(de(t));if(i.size>0)for(const t of yp(n,bp)){const e=t.data.slice(t.data.indexOf(":")+1);let n=t.parentNode;for(;null!==n&&!i.has(n);)n=n.parentNode;null===n||r.has(e)||r.set(e,n)}const a=new Map,l=[];for(const[t,e]of o){let n=Lt(e.getAttribute(s.bindAttributeName)||"")[0];const o=n.bindingType,i=r.get(t),c=a.get(i);"else"===o&&c&&(n={...c,outFilters:[...c.outFilters,Rl()],bindingType:"else"}),"if"===o||"elseif"===o?a.set(i,n):"else"===o&&a.set(i,null),l.push([t,e,n])}for(const[t,e,o]of l.reverse()){const s=document.importNode(e.content,!0),r="for"===o.bindingType?o.statePathName:void 0;Gl(s),"string"==typeof r&&Fl(s,r),Yl(n,s,r),Ml(t,n,{fragment:s,parseBindTextResult:o,nodeInfos:Vl(s)})}}const jp={hydrate:async function(t){await gl(t);const e=t.querySelectorAll(s.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="${Ju}". Falling back to full render.`),xp.cleanupDom(t),!1}const n=function(t){const e=[];for(const n of yp(t,vp)){if(!wp(n.data)){e.pop();continue}const t=Pp(n.data),o=e.at(-1);if("for"===t.type&&o&&o.uuid!==t.uuid)return[t,o];e.push(t)}return null}(document.body);if(null!==n){const[e,o]=n;return console.warn(`[@wcstack/state] SSR: "for: ${e.path}" in "${o.type}: ${o.path}" (known limitation). Falling back to full render.`),xp.cleanupDom(t),!1}for(const n of e)Rp(t,n);xp.restoreTextBindings(document.body);const o=function(t){const e=[];for(const n of yp(t,wp)){const t=Pp(n.data);t.start=n;const o=n.data.replace("-start:","-end:");let s=n.nextSibling;for(;s&&(s.nodeType!==Node.COMMENT_NODE||s.data!==o);)t.nodes.push(s),s=s.nextSibling;e.push(t)}return e}(document.body),r=new Map,i=function(t,e,n=new Map){const o=new Map,s=[],r=new Map(e.map(t=>[t.start,t])),i=new Set;for(let t=e.length-1;t>=0;t--){const n=kp(e[t].nodes).filter(t=>!i.has(t));for(const t of n)i.add(t);e[t].subscribers=n}for(const i of e){const e=Cp(i,r);if(0===e.length)continue;const a=e.some(t=>bp(t.data));if(a){const t=document.createComment(`wcs-row-end:${i.uuid}`);i.nodes[i.nodes.length-1].after(t),e.push(t)}const{bindingInfos:l,subscriberNodes:u,bindingSession:d,deferredSpreads:h}=Np(i.subscribers);for(const t of l)if(t.node!==t.replaceNode){const n=e.indexOf(t.node);n>=0&&(e[n]=t.replaceNode)}const f=ca(e,a);Vi(f,d),Sr(f,l),kr(f,u);const p=l.filter(t=>la(t,-1));if(Cr(f,p),"for"===i.type&&null!==i.index){const e=Lp(t,"for",i.uuid);if(e){let t=n.get(i.uuid);if(!t){const s=Tp(e,i.uuid)??i.path;t=o.get(s),t||o.set(s,t=[]),n.set(i.uuid,t)}const r=t[i.index]??=Ce(null,i.index);$a(e,r,f),xa(e,f.lastNode),ta(e,f);const a=$o(ot(i.path+"."+c),r);Nr(f,a),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ep(s,l),Mp(f,h,a,d,l,p)}}else{const e=i.start.previousSibling,n=e?.data===Op(i.type,i.uuid)?e:Lp(t,i.type,i.uuid);if(n){ta(n,f);const t=$e(n);Nr(f,t),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ep(s,l),Mp(f,h,t,d,l,p)}}}return s}(document.body,o,r);xp.removeBlockBoundaryComments(document.body);const a=[];for(const t of e)t.parentNode&&(a.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());const[,l,u]=ge(document.body),d=[],h=[],f=gr(document.body),p=f.initialize(l);fl(u,null,f);for(const t of p)if("event"!==t.bindingType)if(Ip.has(t.bindingType))h.push(t);else{if(t.statePathName.includes(c))continue;d.push(t)}for(const t of h)if("for"===t.bindingType){const e=uo(t),n=Pl(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=wr(n[t.statePathName],t.outFilters);if(Array.isArray(o)){const n=r.get(t.uuid);n&&fn(o,n),Sn(e,o),s=t.node,i=o,wa.set(s,mn(i)),Tn(e,o)}var s,i})}hl([...d,...i]);for(const{el:t,parent:e,next:n}of a)e.insertBefore(t,n);const m=new Map;for(const e of t.querySelectorAll("[data-wcs-ssr-id]"))m.set(e.getAttribute("data-wcs-ssr-id"),e);for(const e of t.querySelectorAll(s.tagNames.ssr))for(const[t,n]of Object.entries(e.hydrateProps)){const e=m.get(t);if(e)for(const[t,o]of Object.entries(n))br?.isDeclared(e,t)||(e[t]=o)}for(const e of t.querySelectorAll("[data-wcs-ssr-id]"))e.removeAttribute("data-wcs-ssr-id");return!0},loadState(t){const e=t.parentNode;if(!e)return null;const n=xp.find(e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(t){await kl(t.rootNode);const e=xp.extractStateData(t),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",Ju),xp.buildContent(n,e,t.rootNode),t.parentNode?.insertBefore(n,t)}};let Wp=!1;const Dp={name:"ssr",install(){Wp||(Wp=!0,vl=jp,function(t){if(!Bu.includes(t)){Bu.push(t);for(const e of Hu())t(e)}}(t=>{t.get(s.tagNames.ssr)||t.define(s.tagNames.ssr,xp)}),function(){const e=globalThis;void 0===e[t]&&(e[t]=Sp)}())}},zp=new WeakMap,Bp=new Set,Fp=new Set;function Hp(t){return t.byFromPath.size>0||t.byResetPath.size>0}function qp(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function Up(t){return zp.get(t)}function Vp(t){Gp(t),zp.delete(t)}function Gp(t){Bp.delete(t),Fp.delete(t)}const Kp=new WeakSet;let Jp=0;function Qp(t){return Up(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function Xp(t){if(0===Fp.size)return;if(e=t.absolutePathInfo.stateElement,!Fp.has(e))return;var e;const n=Qp(t);if(void 0!==n)for(const t of n)Yp(t)}function Yp(t){Kp.has(t)||(Kp.add(t),Jp++)}function Zp(t){return!!Kp.delete(t)&&(Jp--,!0)}const tm=/^(?:0|[1-9]\d*)$/;function em(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function nm(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&&tm.test(e)&&em(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&em(t,e))?null:"object"}function om(t,e){const n=nm(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]=om(o[t],e);return r}function sm(t){return om(t,new Map)}function rm(t,e,n){if(Object.is(t,e))return!0;const o=nm(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(nm(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(!rm(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&rm(s[t],r[t],n))}function im(t,e){return rm(t,e,new Map)}const am=new WeakMap;function lm(t,e){if("function"!=typeof e)return;const n=am.get(e);void 0===n?am.set(e,new Set([t])):n.add(t)}function cm(t,e){return"function"==typeof e&&!0===am.get(e)?.has(t)}const um={"read-source":t=>`${H} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-rows":t=>`${H} could not read the rows of "from" for "${t}". Nothing was folded or written.`,"read-output":t=>`${H} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${H} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${H} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${H} could not write the output "${t}".`},dm={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function hm(t,e,n){null!==Se&&Se({type:"state:watch-error",phase:e,path:`${H}.${t}`,error:n})}function fm(t,e,n){console.error(`[@wcstack/state] ${um[n](t)}`,e),hm(t,dm[n],e)}function pm(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function mm(t,e){e.then(void 0,()=>{}),fm(t,new TypeError(`${H} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const gm=new WeakSet,ym="[wcs/scan-declaration-invalid]",bm=Object.freeze([]);function wm(t){return`${H} entry "${t}"`}function vm(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function _m(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${c}${c}`)?`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.${at}`}function $m(t,e,n){0===n.length&&tt(`${ym} ${t} "${e}" must be a non-empty state path.${at}`),n.startsWith("$")&&tt(`${ym} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${at}`),n.includes("@")&&tt(`${ym} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${at}`),n in Object.prototype&&tt(`${ym} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${at}`);const o=ot(n);for(const s of o.segments)0===s.length&&tt(`${ym} ${t} ${e} "${n}" has an empty path segment.${at}`);return o.wildcardCount>u&&tt(`${ym} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function xm(t,e,n,o){const s=wm(t);0===t.length&&tt(`${ym} ${H} entry name must be a non-empty string.${at}`),(t.includes(l)||t.includes(c))&&tt(`${ym} ${s} must be a flat property name ("${l}" and "${c}" are not allowed). The output is a property the runtime owns.${at}`),t.startsWith("$")&&tt(`${ym} ${s} must not start with "$" (reserved namespace).${at}`),t in Object.prototype&&tt(`${ym} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${at}`),e.has(t)&&tt(`${ym} ${s} conflicts with a getter declared on the state.${at}`),n.has(t)&&tt(`${ym} ${s} conflicts with a setter declared on the state.${at}`),o.has(t)&&tt(`${ym} ${s} conflicts with the ${B} entry of the same name — each output has exactly one owner.${at}`)}function Sm(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!cm(t,o)&&tt(`${ym} ${wm(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${at}`)}function Im(t,e,n,o,s,r){const i=wm(t),a=void 0!==e.from,c=void 0!==e.on;if(a===c&&tt(`${ym} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${at}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||tt(`${ym} ${i} "on" must be a non-empty event-token name.${at}`),n.has(t)||tt(`${ym} ${i} on "${t}" is not declared in ${D}.${it(t,n)}${at}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&tt(`${ym} ${i} "from" must be a state path string.${at}`);const d=$m(i,"from",u),h=vm(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&tt(_m(i,"from",u,h));const f=vm(d,s);return null!==f&&tt(function(t,e,n){return`${ym} ${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.${at}`}(i,u,f)),(u===t||u.startsWith(t+l))&&tt(`${ym} ${i} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${at}`),{kind:"path",path:u,pathInfo:d}}function Pm(t,e,n,o){if(void 0===e)return bm;const s=wm(t);Array.isArray(e)||tt(`${ym} ${s} "resetOn" must be an array of state paths.${at}`);const r=[];for(const t of e){"string"!=typeof t&&tt(`${ym} ${s} "resetOn" must contain only state path strings.${at}`);const e=$m(s,"resetOn",t);e.wildcardCount>0&&tt(`${ym} ${s} resetOn "${t}" must not contain "${c}" — a reset returns the whole output to "initial".${at}`);const i=vm(e,o);null!==i&&tt(_m(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&tt(`${ym} ${s} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${at}`),"path"===n.kind&&t.startsWith(n.path+l)&&tt(`${ym} ${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.${at}`),r.push(t)}return r}function km(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 Kp.has(t)}(t),l=a&&!im(n,t.initial)?sm(t.initial):n,c=e(l,o,...s);if(pm(c))return void mm(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,lm(t.name,c)),a&&Zp(t)}catch(e){fm(t.name,e,i)}}}const Nm="scanEntries",Am={order:8,validate(t,e,n){const o=function(t,e,n=null){const o=t[H];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&tt(`${ym} ${H} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${at}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(Ru(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){pc(t);const e=t[B];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)){xm(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&tt(`${ym} ${wm(t)} must be an object ({ from | on, initial, fold, resetOn? }).${at}`);const o=d;Sm(t,a,o);const h=Im(t,o,e,s,i,n);"initial"in o||tt(`${ym} ${wm(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${at}`),"function"!=typeof o.fold&&tt(`${ym} ${wm(t)} fold must be a function.${at}`);const f=Pm(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=ot(t).segments[0];e.has(n)&&tt(`${ym} ${wm(o.name)} resetOn "${t}" reads the ${H} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${at}`)}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&&tt(`${ym} ${H} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${at}`),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(Nm,o)},applyEarly(t,e,n){const o=n.get(Nm)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=sm(n.initial);t[n.name]=e,lm(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&jo(t,n.source.tokenName).subscribe(km(n))}(t,o))},register(t,e,n){const o=n.get(Nm)??null,s=function(t){const e=new Map,n=Up(t);if(void 0!==n)for(const t of n.entries)Zp(t)&&e.set(t.name,t.resetOn);return Vp(t),e}(t);t.setScanPaths?.(null===o?null:function(t,e,n){const o=function(t,e){Vp(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&qp(n,t.source.path,t);for(const e of t.resetOn)qp(o,e,t),"event"===t.source.kind&&qp(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return zp.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)&&Kr().hasQueuedPath(t,n))&&Yp(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 Em=!1;const Cm=Object.freeze([]),Mm=Object.freeze([]);function Tm(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Cm,i=t.dynamicDependency.get(n)??Cm,a=e.byFromPath.get(n)??Mm;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const Om=Symbol("wcs-stream-last-notified-uncertain"),Lm=new WeakMap;function Rm(t,e){const n=Lm.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function jm(t,e){const n=Lm.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Om,error:Object.is(o.error,null)?null:Om})}const Wm=new Set;function Dm(t){Wm.delete(t)}const zm=new WeakMap;function Bm(t){return zm.get(t)??new Map}function Fm(t){Dm(t);const e=zm.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,jm(t,n.name)}const Hm=(t,e)=>e,qm=new Set;const Um=new WeakMap,Vm=new WeakMap;function Gm(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=Bm(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&Bm(t).has(n),ownKeys:()=>Array.from(Bm(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=Bm(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){tt(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){tt(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Km(t){const e=Um.get(t);if(void 0!==e)return e;const n=Gm(t,G,t=>t.status);return Um.set(t,n),n}function Jm(t){const e=Vm.get(t);if(void 0!==e)return e;const n=Gm(t,K,t=>t.error);return Vm.set(t,n),n}function Qm(t){Um.delete(t),Vm.delete(t)}let Xm=null;function Ym(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 Zm={read(t,e){!function(t,e){null!==Xm&&Xm.add(Xn(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===G?Ym(Km(t),e.pathInfo.segments):n===K?Ym(Jm(t),e.pathInfo.segments):wc},get:(t,e)=>e===G?Km(t.stateElement):e===K?Jm(t.stateElement):wc};let tg=0,eg=null,ng=0;const og=new WeakMap;function sg(t){tg=t+1}function rg(){tg=0}function ig(t){if(tg>0){const e=eg??=new Map;tg>(e.get(t)??0)&&e.set(t,tg),ng=Math.max(ng,tg)}}function ag(t,e){return og.get(t)?.get(e)??0}function lg(t){mg();const e=Bm(t);if(0!==e.size){!function(t){Wm.add(t)}(t);for(const n of e.values())cg(t,n)}}function cg(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=Xm,s=new Set;let r;Xm=s;try{t.createState("readonly",t=>{r=n(t)})}finally{Xm=o}r instanceof Promise&&tt(`${B} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${G}${l}${e.name}`,a=`${K}${l}${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!==a||tt(`${B} 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&&tt(`${B} 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=Up(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=Tm(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&tt(`[wcs/scan-feedback-loop] ${B} entry "${e.name}" args read "${n}", which is derived from the ${H} 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}),lm(e.name,e.definition.initial),ug(t,e,"active",null);const s=e.definition,r={fold(n){t.createState("writable",t=>{const o=s.fold(t[e.name],n);t[e.name]=o,lm(e.name,o)})},done(){ug(t,e,"done",null)},fail(o){ug(t,e,"error",o),n.abort()}};!async function(t,e,n,o){let s=null;const r=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",r,{once:!0});try{const i=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] ${B}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();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",r)}}(s.source,o,n.signal,r)}function ug(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return Lm.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=Lm.get(t);void 0===s&&(s=new Map,Lm.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${G}${l}${e.name}`),i&&t.$postUpdate(`${K}${l}${e.name}`)}))}function dg(t){const e=Wm;if(0===e.size)return;const n=[];for(const o of e)for(const e of Bm(o).values()){let s=-1;for(const n of e.depAddresses)t.has(n)&&(s=Math.max(s,ag(t,n)));s>=0&&s<=32&&n.push({stateElement:o,entry:e,depth:s})}try{for(const{stateElement:t,entry:o,depth:s}of n)if(e.has(t)&&Bm(t).get(o.name)===o){sg(s);try{cg(t,o)}catch(n){o.controller?.abort(),e.has(t)&&Bm(t).get(o.name)===o&&ug(t,o,"error",n)}}}finally{rg()}}let hg=!1;const fg=new WeakMap,pg={order:20,apply(t,e){var n;Qm(t),Fm(n=t),Dm(n),zm.delete(n),function(t,e){pc(e);const n=e[B];if(void 0===n)return void Rm(t,qm);"object"==typeof n&&null!==n||tt(`${B} must be an object mapping stream names to stream definitions.`);const o=new Map,s=Ru(e);for(const[r,i]of Object.entries(n)){0===r.length&&tt(`${B} entry name must be a non-empty string.`),r.includes(l)&&tt(`${B} entry "${r}" must be a flat property name ("${l}" is not allowed).`),r.includes(c)&&tt(`${B} entry "${r}" must be a flat property name ("${c}" is not allowed).`),r.startsWith("$")&&tt(`${B} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&tt(`${B} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(r)&&tt(`${B} entry "${r}" conflicts with a getter declared on the state.`),t.setterPaths.has(r)&&tt(`${B} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||tt(`${B} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||cm(r,a)||tt(`${B} entry "${r}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&tt(`${B} entry "${r}" source must be a function.`);const u=void 0!==n.fold;u&&"function"!=typeof n.fold&&tt(`${B} entry "${r}" fold must be a function.`),u&&!("initial"in n)&&tt(`${B} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&tt(`${B} entry "${r}" args must be a function.`);const d={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??Hm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in e||(e[r]=d.definition.initial,lm(r,d.definition.initial)),o.set(r,d)}!function(t,e){zm.set(t,e)}(t,o),Rm(t,new Set(o.keys()))}(t,e),void 0!==e[B]&&t.attachAddressHooks?.("streams",B)},activate(t,n){if(!e()&&null!=t.connectedRootNode){if(null===n){if(!0!==t.initialized)return;return lg(t),void fg.set(t,t.connectGeneration??0)}n===t.connectGeneration&&fg.get(t)!==n&&lg(t)}},deactivate(t){Fm(t),Qm(t)}};function mg(){hg||(hg=!0,$c("streams",Zm),Pc("streams",pg),Ur(dg,20))}const gg=new WeakMap;function yg(t,e,n){let o=gg.get(t);void 0===o&&(o=new Map,gg.set(t,o)),o.set(e,n)}const bg=new Map;function wg(t,e){bg.has(t)||bg.set(t,e)}function vg(t){return bg.get(t)}const _g=new WeakMap,$g=new WeakMap,xg=new Set,Sg=new Map;function Ig(t){return _g.get(t)??Sg}function Pg(t,e){let n=$g.get(t);void 0===n&&(n=new Map,$g.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)}}const kg=new Map;function Ng(t){return $g.get(t)??kg}function Ag(t){0===t.length&&tt(`[wcs/watch-declaration-invalid] ${F} entry name must be a non-empty state path.`),t.startsWith("$")&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not start with "$" (reserved namespace).${at}`),t.includes("@")&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${at}`),t in Object.prototype&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=ot(t);for(const n of e.segments)0===n.length&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" has an empty path segment.${at}`);return e.wildcardCount>u&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const Eg={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||wg(n,o)},swapped(t,e,n){var o;o=n,bg.has(o)&&wg(e,vg(n))}};function Cg(t){for(let e=t;null!==e;e=e.parentListIndex)if(Je(e))return!0;return!1}function Mg(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[Wn]($o(e.wildcardParentPathInfos[i],r)),l=cn(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=so(o,i,e.wildcardCount);if(l!==c&&!He(l,c)){if(Je(c))return"gone";s="replaced"}r=l}return s}function Tg(t,e,n){const o=new Map;for(const s of n){const n=Mg(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 Og=Object.freeze([]);function Lg(t,e,n,o){let s=t.get(n);return void 0===s&&(s={stateElement:e,entry:n,rows:[],reset:!1,depth:o},t.set(n,s)),s.depth=Math.max(s.depth,o),s}function Rg(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 jg(t,e){return e.has(t.stateElement)&&!0===Up(t.stateElement)?.entries.has(t.entry)}function Wg(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Dg(n,t))||Zp(e)}function Dg(t,e){return Kr().hasQueuedPath(t,e)}function zg(t,e){!function(t,e,n){if(0!==Jp)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=Qp(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||Zp(e)}}(t,e,Dg)}function Bg(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function Fg(t,e,n){if(!jg(t,n))return Wg(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(gm.has(t))return;gm.add(t);const o=`[wcs/scan-source-computed] ${H} 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}`),hm(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=Bm(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];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?t.rows:Tg(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(Rg)){let n;try{n=Bg(e,r,t)}catch(t){fm(s.name,t,"read-source");continue}const o=a(l,n,vg(t.absAddress),...t.indexes);if(pm(o))return void mm(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){fm(s.name,t,i.failure)}return i.plan}function Hg(t,e){const{group:n}=t;if(!jg(n,e))return void Wg(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Zp(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!im(o,s.initial):!Object.is(o,t.next)){const o=n.reset?sm(s.initial):t.next;e[s.name]=o,lm(s.name,o)}})}catch(t){fm(s.name,t,"write")}}function qg(t){Zg(),(0!==Ig(t).size||0!==Ng(t).size||function(t){const e=zp.get(t);return void 0!==e&&Hp(e)}(t))&&(function(t){xg.add(t),function(t){const e=zp.get(t);void 0!==e&&(Hp(e)&&Bp.add(t),function(t){return t.eventResetByPath.size>0}(e)&&Fp.add(t))}(t)}(t),function(t){const e=[];for(const n of Ig(t).values())Ug(t,n)&&e.push(n);for(const n of Ng(t).values())for(const o of n)Ug(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{yg(t,Yn(t,o.pathInfo,null),n[o.path])}catch(e){Gg(t,o.path,"prime",e)}})}(t))}function Ug(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Vg={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Gg(t,e,n,o){console.error(`[@wcstack/state] $watch ${Vg[n]} "${e}" threw.`,o),null!==Se&&Se({type:"state:watch-error",phase:n,path:e,error:o})}function Kg(t){const e=xg,n=function(t){const e=ng;return e>0&&(og.set(t,eg),eg=null,ng=0),e}(t);try{if(n>32){zg(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!==Se&&Se({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}if(0===e.size)return void zg(t,e);!function(t,e){if(0!==t.length)try{for(const n of t)sg(n.group.depth),Hg(n,e)}finally{rg()}}(function(t,e){if(zg(t,e),0===Bp.size)return Og;const n=new Map;for(const o of t){const s=o.absolutePathInfo.stateElement;if(!e.has(s))continue;const r=Up(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=ag(t,o),l=r.byFromPath.get(i.path);if(void 0!==l){let t=[];if(i.wildcardCount>0){if(null===o.listIndex)continue;t=ro(o.listIndex,i.wildcardCount)}for(const e of l)Lg(n,s,e,a).rows.push({absAddress:o,indexes:t})}const c=r.byResetPath.get(i.path);if(void 0!==c)for(const t of c)Lg(n,s,t,a).reset=!0}if(0===n.size)return Og;const o=Array.from(n.values()).sort((t,e)=>t.entry.order-e.entry.order),s=[];try{for(const n of o){sg(n.depth);const o=Fg(n,t,e);null!==o&&s.push(o)}}finally{rg()}return s}(t,e),e),function(t,e){const n=[],o=new Set;for(const s of t){const t=s.absolutePathInfo.stateElement;if(!e.has(t))continue;const r=s.absolutePathInfo.pathInfo.path;o.add(r);const i=Ig(t).get(r),a=Ng(t).get(r);if(void 0===i&&void 0===a)continue;const l=void 0===i?[]:[i];void 0!==a&&l.push(...a);for(const e of l){let o=[];if(e.pathInfo.wildcardCount>0){if(null===s.listIndex)continue;o=ro(s.listIndex,e.pathInfo.wildcardCount)}n.push({stateElement:t,entry:e,absAddress:s,indexes:o})}}if(0===n.length)return;n.sort(Qg);const s=function(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(0===s.entry.pathInfo.wildcardCount)continue;const r=t[o-1];(Cg(s.absAddress.listIndex)||r?.entry===s.entry&&Jg(r.indexes,s.indexes)||s.entry.pathInfo.wildcardParentPaths.some(t=>e.has(t)))&&(n??=new Set).add(s.entry)}if(null===n)return t;const o=new Set;for(const e of n){const n=t.filter(t=>t.entry===e),s=n[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(Tg(t,e.pathInfo,n));for(const t of n)s.has(t)||o.add(t)})}catch(t){Gg(0,e.path,"evaluate",t);for(const t of n)o.add(t)}}return t.filter(t=>!o.has(t))}(n,o);try{for(const n of s){if(!e.has(n.stateElement))continue;const o=Ig(n.stateElement).get(n.entry.path)===n.entry,s=!0===Ng(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(sg(ag(t,n.absAddress)),Xg(n))}}finally{rg()}}(t,e)}finally{bg.clear()}}function Jg(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Qg(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 Xg(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Ug(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 Gg(0,n.path,"evaluate",t)}const a=r?function(t,e){return gg.get(t)?.get(e)}(e,o):vg(o);r&&yg(e,o,i),null!==Se&&Se({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){Gg(0,n.path,"handler",t)}}let Yg=!1;function Zg(){Yg||(Yg=!0,$c("watch",Eg),Pc("watch",ty),Ur(Kg,10),qr(ig),Uu={assertValidPath:Ag,addEntries:Pg,start:qg})}const ty={order:10,register(t,e){var n;n=t,xg.delete(n),Gp(n),_g.delete(n),function(t){gg.delete(t)}(t);const o=function(t,e){const n=e[F];if(void 0===n)return null;"object"==typeof n&&null!==n||tt(`[wcs/watch-declaration-invalid] ${F} must be an object mapping state paths to handler functions.${at}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must be a function.${at}`);const n=Ag(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){_g.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?F:H)},activate(t,n){e()||null==t.connectedRootNode||(null===n?!0===t.initialized:n===t.connectGeneration)&&qg(t)},deactivate(t){var e;e=t,xg.delete(e),Gp(e)}},ey={name:"temporal",install(){Zg(),Em||(Em=!0,Pc("scan",Am),qr(Xp)),mg()}},ny=new Set,oy=new Set;function sy(t){ny.has(t)||(ny.add(t),console.warn(`[@wcstack/state] [wcs/v4-migration] ${t} See "Preparing for 4.0" in the @wcstack/state README.`))}const ry=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],iy=["formats","diagnostics","temporal","list-keys","scopes","recursion","ssr","devtools"],ay=(t,e,n)=>sy(`${t}: "${e}" is not one of its options, or not ${n}. 4.0 throws on it.`);function ly(t,e){oy.has(t)||(oy.add(t),sy(`${"$"===t[0]?"":"filter "}"${t}" is removed in 4.0: write "${e}" (its name since 3.2).`))}const cy={substr:'filter "substr" is removed in 4.0: write slice(start, start + length) — slice takes the end index, not a length.'},uy={$watch:"Move it to the root state, where its paths are absolute.",$listKeys:"Move it to the root state, where its paths are absolute.",$renderedCallback:"Move it to the root state, where it receives absolute paths.",$behavior:"Declare it on the root state.",$features:"Declare it on the root state."},dy=new WeakSet,hy={state(t){const e=t;for(const t of Object.keys(dc))void 0!==e[t]&&ly(t,dc[t]);var n;void 0!==e[H]&&sy(`"${H}" is removed in 4.0: rewrite it with $watch (state paths) or $on (event tokens).`),dy.has(t)||(function(t){if(null==t)return;if("object"!=typeof t)return void ay("state","$behavior","an object");const e=t;for(const t in e){const n=e[t];ry.includes(t)&&"boolean"==typeof n?n!==s[t]&&sy(`$behavior takes effect in 4.0; 3.x does not read it and runs this state with ${t}: ${!n}. Until you upgrade, pass bootstrapState({ ${t}: ${n} }).`):ay("$behavior",t,"a boolean")}}(e.$behavior),void 0!==(n=e.$features)&&(Array.isArray(n)&&!n.some(t=>!iy.includes(t))||sy(`$features is not an array of add-on names (${iy.join(", ")}). 4.0 throws on it.`)))},volumeLoaded(t){dy.add(t)},renamed:ly,removed(t){sy(cy[t])},volume(t,e,n){n>0&&sy(`volume "${t}" injects root paths (data-wcs="state.<key>: …"): 4.0 does not graft a volume with injections. Read the root path in a root getter instead.`);for(const n of Object.keys(uy))void 0!==e[n]&&sy(`volume "${t}" declares ${n}: 4.0 does not graft a volume that declares it. ${uy[n]}`)}};const fy=[Ed,ey,th,dp,Dp,rd,md];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(fy),dt=hy,void qu(void 0,void 0));const py={tagNames:{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"},enableShadowRoot:!1,basenameFileExtensions:[".html"]};function my(){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 gy(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let yy=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const by={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 wy(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function vy(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 _y={static:2,param:1,"catch-all":0};let $y=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&&gy(`${py.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&gy(`${py.tagNames.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+=_y[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(by).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||gy(`${py.tagNames.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:wy(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new yy("Navigation cancelled by guard.",o);if(!o)throw new yy("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new yy("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const xy="data-wcs-ssr",Sy="data-wcs-ssr-link",Iy="@@wcs-route-ph:",Py="@@wcs-route-start:",ky="@@wcs-route-end:";let Ny=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=my();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new $y(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||gy(`${py.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${ky}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t,e){for(this._childNodeArray=[...t],e&&(this._endMarker=e);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):gy(`${py.tagNames.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&&gy(`${py.tagNames.route} with fallback attribute must be a direct child of ${py.tagNames.router}.`),t.fallbackRoute&&gy(`${py.tagNames.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 Ay=Symbol.for("wcstack.trustedTypes.policy"),Ey=Symbol.for("wcstack.trustedTypes.internal"),Cy="wcstack";function My(){const t=globalThis[Ay];return null===t||"object"!=typeof t?null:t}let Ty=!1;function Oy(t){const e=function(){const t=globalThis,e=t[Ey];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Cy,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof My()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Cy}". Allow it in the CSP (\`trusted-types ${Cy};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[Ey]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=My(),s=o?.createHTML;return"function"==typeof s?(Ty||(Ty=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Cy}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Cy};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Ly=new Map;class Ry extends HTMLElement{_uuid=my();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||gy(`${py.tagNames.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Ly.set(t,n),n}catch(e){gy(`${py.tagNames.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(`${py.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Ly.has(t)?n.innerHTML=Oy(Ly.get(t)||""):n.innerHTML=Oy(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Oy(t):console.warn(`${py.tagNames.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")&&py.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class jy extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||gy(`${py.tagNames.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")&&py.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const Wy=new Set(["props","states","attr",""]);function Dy(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 zy(t,e){t.hasAttribute("data-bind")||gy(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Wy.has(n)||gy(`${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&&Dy(t,e,o)}).catch(()=>{gy(`Failed to define custom element: ${s}`)}):Dy(t,e,o)}const By=Symbol.for("wcstack.binder");function Fy(){const t=globalThis[By];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const Hy=Symbol.for("wcstack.binder.pending"),qy=Symbol.for("wcstack.binder.taken");function Uy(){const t=globalThis;let e=t[qy];return void 0===e&&(e=new WeakSet,t[qy]=e),e}function Vy(t,e){const n=Fy();return null===n?(function(){const t=globalThis;let e=t[Hy];return void 0===e&&(e=[],t[Hy]=e),e}().push(t),!1):(Uy().add(t),n.bind(t,e),!0)}const Gy={range:!0};function Ky(t,e){for(const n of t.routeChildNodes)e.add(n.placeHolder).add(n.endMarker),Ky(n,e);return e}function Jy(t){const e=t.placeHolder,n=t.endMarker,o=null!==n.parentNode&&n.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(n)),s=o?null:Ky(t,new Set),r=[];let i=0;for(let a=e.nextSibling;null!==a&&a!==n&&(null===s||8!==a.nodeType||!/^@@(route:|wcs-route-)/.test(a.data)||s.has(a));a=a.nextSibling)r.push(a),(o||t.childNodeArray.includes(a))&&(i=r.length);return r.length=i,r}let Qy=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||gy(`${py.tagNames.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(`${py.tagNames.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)}!function(t){if(null!==Fy())for(const e of t)1===e.nodeType&&Vy(e,Gy)}(Array.from(this.childNodes))}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=>{zy(e,t)}),e.hasAttribute("data-bind")&&zy(e,t))}};function Xy(){return document.createElement(py.tagNames.layoutOutlet)}const Yy="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Zy(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){await new Promise(t=>setTimeout(t)),gy(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: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${Yy}`:`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 ${Yy}`}(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 tb(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 eb(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===py.tagNames.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),tb(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===py.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Zy(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===py.tagNames.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=Xy();o.layout=n,i=o,a=e}}const c=await eb(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function nb(t){const e=new Map;return await eb(t,t.template.content,[],e)}function ob(t){return!1!==t.checkVisibility?.()}function sb(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=by[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)sb(s,e,n,o)}function rb(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)sb(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 ib=null,ab=null;function lb(){const t=py.basenameFileExtensions;return 0===t.length?null:(ib===t&&ab||(ib=t,ab=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),ab)}function cb(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=lb();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function ub(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function db(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=lb();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function hb(t){if(null!==t.held)return;const e=Jy(t),n=new Set(e),o=[...e,...t.childNodeArray];let s=null;for(const r of t.childNodeArray)n.has(r)?s=r:null===r.parentNode||o.some(t=>t!==r&&t.contains(r))||(e.splice(null===s?0:e.indexOf(s)+1,0,r),n.add(r),s=r);const r=document.createDocumentFragment();!function(t,e){const n=e.map(t=>t.parentNode);for(let o=0;o<e.length;o++)e[o].parentNode===n[o]&&t.appendChild(e[o])}(r,e),r.appendChild(t.endMarker),t.held=r}function fb(t){t.clearParams(),hb(t)}function pb(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=>{zy(e,t.typedParams)}),n.hasAttribute("data-bind")&&zy(n,t.typedParams),n.querySelectorAll(py.tagNames.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===py.tagNames.layoutOutlet&&n.assignParams(t.typedParams)}}const mb=new WeakSet;function gb(t){const e=t.placeHolder;null!==e.parentNode&&(mb.has(t)||null!==t.endMarker.parentNode?(hb(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),mb.add(t))}const yb=Symbol.for("wcstack.transition-runner");const bb=new WeakSet,wb="data-wcs";function vb(t,e,n){!bb.has(t)&&function(t){return t.hasAttribute(wb)||null!==t.querySelector(`[${wb}]`)}(t)&&(bb.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==Fy()||(o=t,Uy().has(o))||console.warn(`[@wcstack/router] ${e} contains ${wb} 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 _b(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(Vy(e,Gy))continue}else if(null!==Fy())continue;vb(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 $b(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 yy)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 xb(t,e,n,o,s=""){const r=ub(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=rb(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:gy(`${py.tagNames.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 $b(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||fb(t);const t=[];for(const n of e.routes)(t.length>0||!s.has(n)||n.shouldChange(e.params))&&(t.push(n),pb(n,e));let r=!1;for(const e of t){const t=s.has(e);t&&r||gb(e),r||=t,n.length>0&&!t&&_b(e)}};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[yb];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(ob(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(ob(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 Sb(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Ib(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 Pb(t){return"?"===t?"":t}function kb(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 Nb(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Ab=Object.freeze({});class Eb 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=Ab;_typedParams=Ab;_searchParams=Ab;_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 cb(t)}_normalizeBasename(t){return db(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(py.tagNames.outlet))return t;const e=document.createElement(py.tagNames.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||gy(`${py.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||gy(`${py.tagNames.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=wy(t.search),s=t.data??null,r=this._data!==s,i=!vy(this._params,e),a=this._routeName!==t.routeName,l=!vy(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(`${py.tagNames.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(`${py.tagNames.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=Ib(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Pb(n.search)+n.hash,r=Sb();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(ub(t,this._basename));await xb(this,this.outlet,t,this._path,Pb(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(ub(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await xb(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${py.tagNames.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 xb(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=Nb();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||gy(`${py.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||gy(`${py.tagNames.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await nb(this),r=!t&&this._outlet.hasAttribute(xy);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&&gy(`${py.tagNames.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(xy);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await xb(this,this.outlet,i,this._path,window.location.search||""),(r||null!==Fy())&&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(py.tagNames.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(Iy)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Py)){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(ky)){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=ub(t,this._basename);let d=rb(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(Py)){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()===py.tagNames.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o,n)}for(const{comment:t}of r.values())t.remove();this.outlet.removeAttribute(xy);for(const t of d.routes)pb(t,d);return this.outlet.lastRoutes=d.routes,!await $b(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=ub(t,this._basename),n=rb(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&gy(`${py.tagNames.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await xb(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${Iy}${t.absolutePath}`}),this.outlet.setAttribute(xy,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${Py}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&Vy(e,Gy)}_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(!kb(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),Nb()){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=Sb();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&&(Sb()?.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 Cb=["title","rel","target","download","hreflang","lang","dir"];class Mb extends HTMLElement{static get observedAttributes(){return["to",...Cb]}_childNodeArray=[];_uuid=my();_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(py.tagNames.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(py.tagNames.router);if(n)return this._router=n;gy(`${py.tagNames.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 cb(t)}_joinInternalPath(t,e){const n=db(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}=Ib(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+Pb(o)+s}else try{t.href=new URL(e).toString()}catch{gy(`[${py.tagNames.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){Nb()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Sy)?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(Sy),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-")||Cb.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,Nb())return this._updateActiveState(),void n.setAttribute(Sy,"");Sb()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Sb()?.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(){Sb()?.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(Cb.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}=Ib(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 Tb=[],Ob=new Map;let Lb=!1;const Rb=new WeakMap;class jb 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(),Lb||(this._captureInitialHead(),Lb=!0),Tb.push(this),this._reapplyHead()}disconnectedCallback(){const t=Tb.indexOf(this);-1!==t&&Tb.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||gy("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Rb.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Rb.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);Ob.has(t)||Ob.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Tb)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Ob.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=Tb.length-1;e>=0;e--){const o=Tb[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Ob.has(n)&&(t=Ob.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),Vy(t)||vb(t,`<${t.tagName.toLowerCase()}> inside <${py.tagNames.head}>`,`<${py.tagNames.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(py.tagNames.layout)||t.define(py.tagNames.layout,Ry),t.get(py.tagNames.layoutOutlet)||t.define(py.tagNames.layoutOutlet,Qy),t.get(py.tagNames.outlet)||t.define(py.tagNames.outlet,jy),t.get(py.tagNames.route)||t.define(py.tagNames.route,Ny),t.get(py.tagNames.router)||t.define(py.tagNames.router,Eb),t.get(py.tagNames.link)||t.define(py.tagNames.link,Mb),t.get(py.tagNames.head)||t.define(py.tagNames.head,jb)}(void 0);const Wb={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};let Db=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 zb(t,e){return e.every(e=>"available"===t.availability.get(e))}const Bb=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Fb=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 Db("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 zb(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}}(Bb,{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(!zb(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)}}},Hb=!1;function qb(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Wb.triggerAttribute}]`);if(!n)return;const o=n.getAttribute(Wb.triggerAttribute);if(!o)return;const s=customElements.get(Wb.tagNames.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function Ub(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 Vb=Symbol.for("wcstack.trustedTypes.policy");function Gb(){const t=globalThis[Vb];return null===t||"object"!=typeof t?null:t}let Kb,Jb=!1;let Qb=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Fb.wcBindable,properties:[...Fb.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 Fb(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(Wb.tagNames.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(Wb.tagNames.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=Gb(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Kb)return Kb;if(!("trustedTypes"in globalThis))return Kb=!1,Kb;try{document.createElement("div").innerHTML="<i></i>",Kb=!1}catch{Kb=!0}return Kb}())return void function(){if(Jb)return;Jb=!0;const t="function"==typeof Gb()?.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(!Ub(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Hb||(Hb=!0,document.addEventListener("click",qb)),!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 Xb extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}let Yb=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}};class Zb 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 Qb&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}!function(t=customElements){t.get(Wb.tagNames.fetch)||t.define(Wb.tagNames.fetch,Qb),t.get(Wb.tagNames.fetchHeader)||t.define(Wb.tagNames.fetchHeader,Xb),t.get(Wb.tagNames.fetchBody)||t.define(Wb.tagNames.fetchBody,Yb),t.get(Wb.tagNames.infiniteScroll)||t.define(Wb.tagNames.infiniteScroll,Zb)}(void 0);const tw={triggerAttribute:"data-storagetarget",tagNames:{storage:"wcs-storage"}},ew="wcs-storage:value-changed",nw="wcs-storage:loading-changed",ow="wcs-storage:error",sw="wcs-storage:error-info-changed",rw="wcs-storage:trigger-changed";let iw=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:ew,semantics:"state",getter:t=>t.detail},{name:"loading",event:nw,semantics:"state"},{name:"error",event:ow,semantics:"state"},{name:"errorInfo",event:sw,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(nw,{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(ow,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(sw,{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(ew,{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)}},aw=!1;function lw(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${tw.triggerAttribute}]`);if(!n)return;const o=n.getAttribute(tw.triggerAttribute);if(!o)return;const s=customElements.get(tw.tagNames.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function cw(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 uw=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...iw.wcBindable,properties:[...iw.wcBindable.properties,{name:"trigger",event:rw,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 iw(this),this._internals=this._initInternals(),this._wireStates({[nw]:t=>({loading:!0===t}),[ow]: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(rw,{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(!cw(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",aw||(aw=!0,document.addEventListener("click",lw)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(tw.tagNames.storage)||t.define(tw.tagNames.storage,uw)}(void 0);const dw="*",hw="vanilla",fw={scanImportmap:!0,loaders:{[hw]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[dw]:hw},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function pw(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 mw(t,e,n){let o;if(null===e||e===dw||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===dw)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[dw],"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 gw=new Set,yw=new Map;let bw=new WeakMap;function ww(t){if(t===globalThis.customElements)return yw;let e=bw.get(t);return void 0===e&&(e=new Map,bw.set(t,e)),e}const vw=new Map;async function _w(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 vw)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){gw.has(e)||(console.error(`Failed to eager load component '${e}':`,t),gw.add(e))}}function $w(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 xw(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&&vw.set(t,e)});const Sw=new WeakSet,Iw=new WeakSet;async function Pw(t,e,n){t.shadowRoot&&(Sw.has(t)||await async function(t,e,n){Sw.add(t),await Ew(t.shadowRoot,e,n)}(t,e,n))}async function kw(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=ww(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=mw("",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),gw.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Nw(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=xw(t);void 0===o.get(s.name)?(Iw.has(t)||(Iw.add(t),o.whenDefined(s.name).then(async()=>{await Pw(t,e,n)})),a.has(s.name)||gw.has(s.name)||(a.add(s.name),i.push(s))):await Pw(t,e,n)}let l=0;for(const t of i)await kw(t,e,n,o),l++;return l}async function Aw(t,e,n,o){for(;await Nw(t,e,n,o)>0;);}async function Ew(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 $w(e)}return $w(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Aw(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 Aw(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Cw extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Cw._instance)throw new Error(`${fw.tagNames.autoloader} can only be instantiated once.`);Cw._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=pw(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=mw(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(_w(s,o,r))}await Promise.all(n)}(n,fw.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 Ew(document,fw,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Cw._instance===this&&(Cw._instance=null)}}!function(t=customElements){t.get(fw.tagNames.autoloader)||t.define(fw.tagNames.autoloader,Cw)}(void 0);
2
2
  //# sourceMappingURL=auto.min.js.map