wcstack 3.5.1 → 3.5.3

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}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){const n=[],o=[];for(const s of t){if(pe.has(s))continue;const t=me(s,Tl(s),{allowDeferred:!0},e);null===t.deferred?n.push(...t.bindings):o.push(t.deferred)}return[t,n,o]}function ye(t){pe.add(t)}function be(t){const{node:e,parseResults:n,transform:o}=t;return function(t){pe.delete(t)}(e),me(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");let Ae=class{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=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 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=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(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=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??ys}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=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=Xt(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=Jt(t);null===s&&tt(`CustomElementRegistry is unavailable for <${e}>.`),a.cancel=Rs(s).wait(e,()=>{if(r())try{Qt(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=Gt(e),o=Jt(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===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=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=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;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=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&&Yo(r,t.propName))return null;const i=ae(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=re(o,s[t].nodePath);null===e&&tt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),ye(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=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=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 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!==Gt(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=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&&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!==Gt(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=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(),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&&(Gt(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=Gt(t.replaceNode);if(e&&(void 0===Jt(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=Jt(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,o=fe(t),s=mr(t)){const[r,i,a]=ge(function(t){return t.filter(t=>!pe.has(t))}(o),n);for(const t of r)$e(t,e);dl(s.initialize(i)),hl(a,e,s)}const pl=new WeakMap;async function ml(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 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 qt(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=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=Ml(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=zt(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=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 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=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=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=fe(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=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=zl(i,n));let a=Lt(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(!t.isConnected||Zl(t))return;const e=t.hasAttribute(s.bindAttributeName)?[t]:[];Array.from(t.children).some(t=>t.localName===s.tagNames.state&&ue(t))||(Y(t),Xl(t.getRootNode(),t),e.push(...fe(t))),fl(t,null,void 0,e,new pr)}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)&&t.isConnected&&!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 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 ${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){const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}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)){dt?.state(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"$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($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"$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 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(){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 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){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 lc(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&&(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;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===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=>(dt?.volumeLoaded(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.5.1",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=se(e,Lt(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,zt(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=>{dt?.removed("substr");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,bt("input",kd,Id,wd),bt("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=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){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=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?(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){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()}".`)}(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=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).`),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?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)||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=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=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=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)||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=(ce(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.`);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(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(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 $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&&ue(t))||e.push(...fe(t))}else null!==Dt(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],ie(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(de(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=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,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]=ge(fe(document.body),void 0),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={name:"temporal",install(){Yg(),Am||(Am=!0,Ic("scan",Nm),Hr(Qp)),pg()}},ey=new Set,ny=new Set;function oy(t){ey.has(t)||(ey.add(t),console.warn(`[@wcstack/state] [wcs/v4-migration] ${t} See "Preparing for 4.0" in the @wcstack/state README.`))}const sy=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],ry=["formats","diagnostics","temporal","list-keys","scopes","recursion","ssr","devtools"],iy=(t,e,n)=>oy(`${t}: "${e}" is not one of its options, or not ${n}. 4.0 throws on it.`);function ay(t,e){ny.has(t)||(ny.add(t),oy(`${"$"===t[0]?"":"filter "}"${t}" is removed in 4.0: write "${e}" (its name since 3.2).`))}const ly={substr:'filter "substr" is removed in 4.0: write slice(start, start + length) — slice takes the end index, not a length.'},cy={$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."},uy=new WeakSet,dy={state(t){const e=t;for(const t of Object.keys(uc))void 0!==e[t]&&ay(t,uc[t]);var n;void 0!==e[H]&&oy(`"${H}" is removed in 4.0: rewrite it with $watch (state paths) or $on (event tokens).`),uy.has(t)||(function(t){if(null==t)return;if("object"!=typeof t)return void iy("state","$behavior","an object");const e=t;for(const t in e){const n=e[t];sy.includes(t)&&"boolean"==typeof n?n!==s[t]&&oy(`$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} }).`):iy("$behavior",t,"a boolean")}}(e.$behavior),void 0!==(n=e.$features)&&(Array.isArray(n)&&!n.some(t=>!ry.includes(t))||oy(`$features is not an array of add-on names (${ry.join(", ")}). 4.0 throws on it.`)))},volumeLoaded(t){uy.add(t)},renamed:ay,removed(t){oy(ly[t])},volume(t,e,n){n>0&&oy(`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(cy))void 0!==e[n]&&oy(`volume "${t}" declares ${n}: 4.0 does not graft a volume that declares it. ${cy[n]}`)}};const hy=[Ad,ty,Zd,up,Wp,sd,pd];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(hy),dt=dy,void Hu(void 0,void 0));const fy={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 py(){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 my(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let gy=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const yy={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 by(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function wy(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 vy={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&&my(`${fy.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&my(`${fy.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+=vy[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(yy).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||my(`${fy.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:by(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new gy("Navigation cancelled by guard.",o);if(!o)throw new gy("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new gy("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const $y="data-wcs-ssr",xy="data-wcs-ssr-link",Sy="@@wcs-route-ph:",Iy="@@wcs-route-start:",Py="@@wcs-route-end:";let ky=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=py();_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||my(`${fy.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(`${Py}${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):my(`${fy.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&&my(`${fy.tagNames.route} with fallback attribute must be a direct child of ${fy.tagNames.router}.`),t.fallbackRoute&&my(`${fy.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 Ny=Symbol.for("wcstack.trustedTypes.policy"),Ay=Symbol.for("wcstack.trustedTypes.internal"),Ey="wcstack";function Cy(){const t=globalThis[Ny];return null===t||"object"!=typeof t?null:t}let My=!1;function Ty(t){const e=function(){const t=globalThis,e=t[Ay];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Ey,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof Cy()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Ey}". Allow it in the CSP (\`trusted-types ${Ey};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[Ay]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Cy(),s=o?.createHTML;return"function"==typeof s?(My||(My=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Ey}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Ey};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Oy=new Map;class Ly extends HTMLElement{_uuid=py();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||my(`${fy.tagNames.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Oy.set(t,n),n}catch(e){my(`${fy.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(`${fy.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Oy.has(t)?n.innerHTML=Ty(Oy.get(t)||""):n.innerHTML=Ty(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Ty(t):console.warn(`${fy.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")&&fy.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class Ry extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||my(`${fy.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")&&fy.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const jy=new Set(["props","states","attr",""]);function Wy(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 Dy(t,e){t.hasAttribute("data-bind")||my(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";jy.has(n)||my(`${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&&Wy(t,e,o)}).catch(()=>{my(`Failed to define custom element: ${s}`)}):Wy(t,e,o)}const zy=Symbol.for("wcstack.binder");function By(){const t=globalThis[zy];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const Fy=Symbol.for("wcstack.binder.pending"),Hy=Symbol.for("wcstack.binder.taken");function qy(){const t=globalThis;let e=t[Hy];return void 0===e&&(e=new WeakSet,t[Hy]=e),e}function Uy(t,e){const n=By();return null===n?(function(){const t=globalThis;let e=t[Fy];return void 0===e&&(e=[],t[Fy]=e),e}().push(t),!1):(qy().add(t),n.bind(t,e),!0)}const Vy={range:!0};function Gy(t,e){for(const n of t.routeChildNodes)e.add(n.placeHolder).add(n.endMarker),Gy(n,e);return e}function Ky(t){const e=t.placeHolder,n=t.endMarker,o=null!==n.parentNode&&n.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(n)),s=o?null:Gy(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 Jy=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||my(`${fy.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(`${fy.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!==By())for(const e of t)1===e.nodeType&&Uy(e,Vy)}(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=>{Dy(e,t)}),e.hasAttribute("data-bind")&&Dy(e,t))}};function Qy(){return document.createElement(fy.tagNames.layoutOutlet)}const Xy="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Yy(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)),my(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 ${Xy}`:`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 ${Xy}`}(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 Zy(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 tb(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===fy.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),Zy(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===fy.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Yy(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===fy.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=Qy();o.layout=n,i=o,a=e}}const c=await tb(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function eb(t){const e=new Map;return await tb(t,t.template.content,[],e)}function nb(t){return!1!==t.checkVisibility?.()}function ob(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=yy[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)ob(s,e,n,o)}function sb(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)ob(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 rb=null,ib=null;function ab(){const t=fy.basenameFileExtensions;return 0===t.length?null:(rb===t&&ib||(rb=t,ib=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),ib)}function lb(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=ab();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function cb(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function ub(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=ab();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function db(t){if(null!==t.held)return;const e=Ky(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 hb(t){t.clearParams(),db(t)}function fb(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=>{Dy(e,t.typedParams)}),n.hasAttribute("data-bind")&&Dy(n,t.typedParams),n.querySelectorAll(fy.tagNames.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===fy.tagNames.layoutOutlet&&n.assignParams(t.typedParams)}}const pb=new WeakSet;function mb(t){const e=t.placeHolder;null!==e.parentNode&&(pb.has(t)||null!==t.endMarker.parentNode?(db(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),pb.add(t))}const gb=Symbol.for("wcstack.transition-runner");const yb=new WeakSet,bb="data-wcs";function wb(t,e,n){!yb.has(t)&&function(t){return t.hasAttribute(bb)||null!==t.querySelector(`[${bb}]`)}(t)&&(yb.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==By()||(o=t,qy().has(o))||console.warn(`[@wcstack/router] ${e} contains ${bb} 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 vb(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(Uy(e,Vy))continue}else if(null!==By())continue;wb(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 gy)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 $b(t,e,n,o,s=""){const r=cb(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=sb(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:my(`${fy.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)||hb(t);const t=[];for(const n of e.routes)(t.length>0||!s.has(n)||n.shouldChange(e.params))&&(t.push(n),fb(n,e));let r=!1;for(const e of t){const t=s.has(e);t&&r||mb(e),r||=t,n.length>0&&!t&&vb(e)}};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[gb];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(nb(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(nb(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 xb(){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 Ib(t){return"?"===t?"":t}function Pb(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 kb(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Nb=Object.freeze({});class Ab 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=Nb;_typedParams=Nb;_searchParams=Nb;_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 lb(t)}_normalizeBasename(t){return ub(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(fy.tagNames.outlet))return t;const e=document.createElement(fy.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||my(`${fy.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||my(`${fy.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=by(t.search),s=t.data??null,r=this._data!==s,i=!wy(this._params,e),a=this._routeName!==t.routeName,l=!wy(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(`${fy.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(`${fy.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=Sb(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Ib(n.search)+n.hash,r=xb();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(cb(t,this._basename));await $b(this,this.outlet,t,this._path,Ib(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(cb(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await $b(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${fy.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 $b(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=kb();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||my(`${fy.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||my(`${fy.tagNames.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await eb(this),r=!t&&this._outlet.hasAttribute($y);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&&my(`${fy.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($y);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await $b(this,this.outlet,i,this._path,window.location.search||""),(r||null!==By())&&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(fy.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(Sy)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Iy)){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(Py)){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=cb(t,this._basename);let d=sb(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(Iy)){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()===fy.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($y);for(const t of d.routes)fb(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=cb(t,this._basename),n=sb(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&my(`${fy.tagNames.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await $b(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${Sy}${t.absolutePath}`}),this.outlet.setAttribute($y,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${Iy}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&Uy(e,Vy)}_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(!Pb(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),kb()){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=xb();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&&(xb()?.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 Eb=["title","rel","target","download","hreflang","lang","dir"];class Cb extends HTMLElement{static get observedAttributes(){return["to",...Eb]}_childNodeArray=[];_uuid=py();_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(fy.tagNames.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(fy.tagNames.router);if(n)return this._router=n;my(`${fy.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 lb(t)}_joinInternalPath(t,e){const n=ub(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+Ib(o)+s}else try{t.href=new URL(e).toString()}catch{my(`[${fy.tagNames.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){kb()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(xy)?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(xy),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-")||Eb.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,kb())return this._updateActiveState(),void n.setAttribute(xy,"");xb()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!xb()?.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(){xb()?.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(Eb.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 Mb=[],Tb=new Map;let Ob=!1;const Lb=new WeakMap;class Rb 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(),Ob||(this._captureInitialHead(),Ob=!0),Mb.push(this),this._reapplyHead()}disconnectedCallback(){const t=Mb.indexOf(this);-1!==t&&Mb.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||my("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Lb.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Lb.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);Tb.has(t)||Tb.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Mb)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Tb.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=Mb.length-1;e>=0;e--){const o=Mb[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Tb.has(n)&&(t=Tb.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),Uy(t)||wb(t,`<${t.tagName.toLowerCase()}> inside <${fy.tagNames.head}>`,`<${fy.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(fy.tagNames.layout)||t.define(fy.tagNames.layout,Ly),t.get(fy.tagNames.layoutOutlet)||t.define(fy.tagNames.layoutOutlet,Jy),t.get(fy.tagNames.outlet)||t.define(fy.tagNames.outlet,Ry),t.get(fy.tagNames.route)||t.define(fy.tagNames.route,ky),t.get(fy.tagNames.router)||t.define(fy.tagNames.router,Ab),t.get(fy.tagNames.link)||t.define(fy.tagNames.link,Cb),t.get(fy.tagNames.head)||t.define(fy.tagNames.head,Rb)}(void 0);const jb={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};let Wb=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 Db(t,e){return e.every(e=>"available"===t.availability.get(e))}const zb=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Bb=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 Wb("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 Db(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}}(zb,{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(!Db(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)}}},Fb=!1;function Hb(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${jb.triggerAttribute}]`);if(!n)return;const o=n.getAttribute(jb.triggerAttribute);if(!o)return;const s=customElements.get(jb.tagNames.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function qb(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 Ub=Symbol.for("wcstack.trustedTypes.policy");function Vb(){const t=globalThis[Ub];return null===t||"object"!=typeof t?null:t}let Gb,Kb=!1;let Jb=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Bb.wcBindable,properties:[...Bb.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 Bb(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(jb.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(jb.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=Vb(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Gb)return Gb;if(!("trustedTypes"in globalThis))return Gb=!1,Gb;try{document.createElement("div").innerHTML="<i></i>",Gb=!1}catch{Gb=!0}return Gb}())return void function(){if(Kb)return;Kb=!0;const t="function"==typeof Vb()?.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(!qb(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Fb||(Fb=!0,document.addEventListener("click",Hb)),!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 Qb extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}let Xb=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}};class Yb 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 Jb&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}!function(t=customElements){t.get(jb.tagNames.fetch)||t.define(jb.tagNames.fetch,Jb),t.get(jb.tagNames.fetchHeader)||t.define(jb.tagNames.fetchHeader,Qb),t.get(jb.tagNames.fetchBody)||t.define(jb.tagNames.fetchBody,Xb),t.get(jb.tagNames.infiniteScroll)||t.define(jb.tagNames.infiniteScroll,Yb)}(void 0);const Zb={triggerAttribute:"data-storagetarget",tagNames:{storage:"wcs-storage"}},tw="wcs-storage:value-changed",ew="wcs-storage:loading-changed",nw="wcs-storage:error",ow="wcs-storage:error-info-changed",sw="wcs-storage:trigger-changed";let rw=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:tw,semantics:"state",getter:t=>t.detail},{name:"loading",event:ew,semantics:"state"},{name:"error",event:nw,semantics:"state"},{name:"errorInfo",event:ow,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(ew,{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(nw,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(ow,{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(tw,{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)}},iw=!1;function aw(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Zb.triggerAttribute}]`);if(!n)return;const o=n.getAttribute(Zb.triggerAttribute);if(!o)return;const s=customElements.get(Zb.tagNames.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function lw(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 cw=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...rw.wcBindable,properties:[...rw.wcBindable.properties,{name:"trigger",event:sw,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 rw(this),this._internals=this._initInternals(),this._wireStates({[ew]:t=>({loading:!0===t}),[nw]: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(sw,{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(!lw(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",iw||(iw=!0,document.addEventListener("click",aw)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(Zb.tagNames.storage)||t.define(Zb.tagNames.storage,cw)}(void 0);const uw="*",dw="vanilla",hw={scanImportmap:!0,loaders:{[dw]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[uw]:dw},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function fw(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 pw(t,e,n){let o;if(null===e||e===uw||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===uw)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[uw],"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 mw=new Set,gw=new Map;let yw=new WeakMap;function bw(t){if(t===globalThis.customElements)return gw;let e=yw.get(t);return void 0===e&&(e=new Map,yw.set(t,e)),e}const ww=new Map;async function vw(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 ww)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){mw.has(e)||(console.error(`Failed to eager load component '${e}':`,t),mw.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 $w(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&&ww.set(t,e)});const xw=new WeakSet,Sw=new WeakSet;async function Iw(t,e,n){t.shadowRoot&&(xw.has(t)||await async function(t,e,n){xw.add(t),await Aw(t.shadowRoot,e,n)}(t,e,n))}async function Pw(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=bw(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=pw("",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),mw.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function kw(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=$w(t);void 0===o.get(s.name)?(Sw.has(t)||(Sw.add(t),o.whenDefined(s.name).then(async()=>{await Iw(t,e,n)})),a.has(s.name)||mw.has(s.name)||(a.add(s.name),i.push(s))):await Iw(t,e,n)}let l=0;for(const t of i)await Pw(t,e,n,o),l++;return l}async function Nw(t,e,n,o){for(;await kw(t,e,n,o)>0;);}async function Aw(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 Nw(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 Nw(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Ew extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Ew._instance)throw new Error(`${hw.tagNames.autoloader} can only be instantiated once.`);Ew._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=fw(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=pw(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(vw(s,o,r))}await Promise.all(n)}(n,hw.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 Aw(document,hw,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Ew._instance===this&&(Ew._instance=null)}}!function(t=customElements){t.get(hw.tagNames.autoloader)||t.define(hw.tagNames.autoloader,Ew)}(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="**",G="$listKeys",V="$streamStatus",K="$streamError",J="data-wc-definition",Q=/\{\{\s*(.+?)\s*\}\}/g,X=new Set(["SCRIPT","STYLE"]);function Y(t,e){if(!s.enableMustache)return;!function(t,e){const n=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const t of o)t.parentElement&&X.has(t.parentElement.tagName)||Z(t,e)}(t,e);const n=Array.from(t.querySelectorAll("template"));for(const t of n)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,e){const n=t.data;if(Q.lastIndex=0,!Q.test(n)||e?.(t))return;Q.lastIndex=0;const o=document.createDocumentFragment();let s,r=0;for(;null!==(s=Q.exec(n));){s.index>r&&o.appendChild(document.createTextNode(n.slice(r,s.index)));const t=s[1];o.appendChild(document.createComment(`@@: ${t}`)),r=s.index+s[0].length}r<n.length&&o.appendChild(document.createTextNode(n.slice(r))),t.parentNode.replaceChild(o,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 Gt=new WeakMap;function Vt(t){const e=Gt.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{Gt.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=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=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?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}}}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){const n=[],o=[];for(const s of t){if(pe.has(s))continue;const t=me(s,Tl(s),{allowDeferred:!0},e);null===t.deferred?n.push(...t.bindings):o.push(t.deferred)}return[t,n,o]}function ye(t){pe.add(t)}function be(t){const{node:e,parseResults:n,transform:o}=t;return function(t){pe.delete(t)}(e),me(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");let Ae=class{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 Ge(t){return qe.has(t)}const Ve=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=Ve.get(t);return void 0===e?null:e}function cn(t,e){const n=Ve.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&&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),Ve.set(e,n),mn(t,e);const o=n.map((e,n)=>{const o=Ee(r,n);return Le(o,t[n]),o});return Ve.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),Ve.set(t,e)):Ve.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 Gn(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 Vn=new WeakMap;function Kn(t,e){let n=Vn.get(t);void 0===n&&(n=new Map,Vn.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 Gn(Kn(t,e.pathInfo),e.listIndex)}function Xn(t,e,n){return Gn(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 Go=new Map,Vo=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=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 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=Jt(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=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!==Vt(t.node)){const e=Xt(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=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=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=Xt(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,Gs=null,Vs=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&&ml(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:Gn(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:Gn(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=Jt(t);null===s&&tt(`CustomElementRegistry is unavailable for <${e}>.`),a.cancel=Rs(s).wait(e,()=>{if(r())try{Qt(s,t),n()}catch(t){o(t)}},t=>{r()&&o(t)})},a={node:t,born:++Vs,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&&!rr(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 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=Vs;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=Vs;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&&ml(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,n){this.deferredByNode.get(t)?.forEach(t=>{t.born<=this.disposedAt||(this.deferred.add(t),t.arm())});const o=this.knownBindingsByNode.get(t);if(void 0===o)return;const s=o instanceof Map?o.values():[o];for(const o of s){const s=Xs.get(o);if("active"===s?.phase){this.settleConnectedSnapshot(s);continue}if("disposed"!==s?.phase)continue;const r=this.optionsByBinding.get(o);if(void 0!==r)try{this.start(o,r),(r.applyOnReconnect||s.pendingDefinitions>0&&s.generation>this.disposedAt)&&this.shouldApplyState(o)&&e.push(o)}catch(t){n?.(t)}}}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:++Vs,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=++Vs,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:++Vs,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=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=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})})},Go.set(s,r)),t.node.addEventListener(o,r),Vo.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=Go.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Vo.countOf(n)&&(Vo.remove(n,t)&&Go.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=Jt(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: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=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=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;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 Gr=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?ml(i,a):ml(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 Vr(){return Gr}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),Vr().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),Vr().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 Gi=new WeakMap,Vi=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 Gi.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=Vi.get(t);void 0===o&&Vi.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)){fl(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?fl(u,s):(s.appliedBindingSet.add(u),hl(u,s,f))}}(r,o,s,e,n)}for(const t of o)null===s&&fo(co(t),t),(null===s||s.shouldApplyState(t))&&fl(t,n);t.spreads&&gl(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=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!==Vt(r))return null;if("prop"===o&&Yo(r,t.propName))return null;const i=ae(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=re(o,s[t].nodePath);null===e&&tt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),ye(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=bl.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new pr,bl.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){Gi.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=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 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&&fl(o,e),0!==(ia(o)&n))for(const t of ta(o.node))t.mounted&&ka(t,e,n)}else fl(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=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&&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={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function Fa(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${Ba[t]??t}" before the state is defined.`}let Ha=null;function qa(t){return null===Ha&&tt(Fa("ssr",t)),Ha}const Ua=new WeakSet;function Ga(t,e,n){}function Va(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 Ka=new WeakMap;function Ja(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)&&!Ka.has(Va(o,t)?.get)&&s.push(e)}return s}const Qa={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Xa={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Ya(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 Za(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 tl(t,e){return`$setAll("${t}") ${e}`}function el(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 nl=new WeakSet;function ol(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const sl=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=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(),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})}}),rl={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Ua.has(t.replaceNode)){Ua.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=Ha?.textMarker(t)??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(!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=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)}},il=new WeakMap,al=new WeakMap,ll=new WeakMap;function cl(){}function ul(t){const e=yr;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return Ga;if(e.isDeclared(n,o))return cl}return za}function dl(t,e){hl(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(el(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[jn](n)}(e.state,t))}function hl(t,e,n){const o=br(n,t.outFilters);if(!0===al.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=il.get(t);if(void 0===s){if(il.has(t))return s=ul(t),s===Ga&&il.set(t,s),void s(t,e,o);if(s=rl[t.bindingType],void 0===s){const e=t.propSegments[0];s=sl[e],il.set(t,s),void 0===s&&(Vt(t.replaceNode)?(s=ul(t),s===Ga&&il.set(t,s)):(s=za,il.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 al.set(t,!0)}s(t,e,o)}else s(t,e,o)}function fl(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!==ll.get(t)){const e=Vt(t.replaceNode);if(e&&(void 0===Jt(t.replaceNode)?.get(e)||function(t){return"waiting-definition"===Xs.get(t)?.phase}(t)))return void function(t,e){if(nl.has(t))return;nl.add(t);const n=()=>{nl.delete(t);const e=gr(t);(null===e||e.shouldApplyState(t))&&ml([t])},o=n=>{nl.delete(t),ol(e,n)},s=gr(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{nl.delete(t),r()})||(nl.delete(t),r()))}const r=Jt(t.replaceNode);if(null===r)return nl.delete(t),void ol(e,new Error("CustomElementRegistry is unavailable."));Rs(r).wait(e,()=>{t.replaceNode.isConnected?n():nl.delete(t)},o)}(t,e);ll.set(t,!0)}if(!0===e.sameRootVerified)return void dl(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};dl(t,r)})}else dl(t,e)}function pl(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 ml(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{fl(n,h)}catch(t){pl(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){pl(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 gl(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),ml(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1})))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,t)})}function yl(t,e,n,o=fe(t),s=mr(t)){const[r,i,a]=ge(function(t){return t.filter(t=>!pe.has(t))}(o),n);for(const t of r)$e(t,e);ml(s.initialize(i)),gl(a,e,s)}const bl=new WeakMap;async function wl(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 vl(t){if(t===document)await wl(document),Y(document),Xl(document,document),yl(document.body,null);else{const e=t;e.host.hasAttribute(s.bindAttributeName)&&await qt(e.host),await wl(e),Y(e),Xl(e,e),yl(e,null)}}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 qa('the "enable-ssr" attribute').hydrate(t)||await vl(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 vl(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=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=Ml(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=zt(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=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 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=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=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=fe(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 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 Vl=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){Gl(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=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=zl(i,n));let a=Lt(i)[0];const u=Vl.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(!t.isConnected||Zl(t))return;const e=t.hasAttribute(s.bindAttributeName)?[t]:[];Array.from(t.children).some(t=>t.localName===s.tagNames.state&&ue(t))||(Y(t),Xl(t.getRootNode(),t),e.push(...fe(t))),yl(t,null,void 0,e,new pr)}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)&&t.isConnected&&!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 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 ${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){const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}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)){dt?.state(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`[${Qa.binding}] Path "${t}" does not exist on the state tree.${it(t,Ja(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(el(`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(`${G} 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(`${G} 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(`${G} 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(`${G} 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 Vc(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=Vr(),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=Vr(),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=Vr(),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(Ve.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(el(`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=Gc(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(el(`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(!Ve.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=Ve.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=Ve.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(Vc(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=Vr(),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(Ya("$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(Ya("$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(tl(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&tt(Ya("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,u="function"==typeof r;l&&u&&tt(tl(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&tt(tl(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=`${V}${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=Vr();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"$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($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"$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 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=>Vc(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(Fa(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(Fa(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[G];if(void 0===e)return null;"object"==typeof e&&null!==e||tt(`${G} 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(`${G} entry path must be a non-empty string.`);const e=t.split(l);e.some(t=>0===t.length)&&tt(`${G} entry "${t}" must not contain empty path segments.`),e[e.length-1]===c&&tt(`${G} 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] ${G} entry "${t}" uses "${U}", which ${G} 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(`${G} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&tt(`${G} entry "${t}" key field name must be a non-empty string.`),(o.includes(l)||o.includes(c))&&tt(`${G} entry "${t}" key field name "${o}" must be a flat property name ("${l}" / "${c}" are not allowed).`),o in Object.prototype&&tt(`${G} 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")?qa('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 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){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 lc(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&&(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;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===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 qa('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=>(dt?.volumeLoaded(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 Va(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(Fa(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)};Ka.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=()=>{ml(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(Fa("watch",`"$watch" in <wcs-state mount="${t}">`))}let Gu=null;const Vu=Object.freeze([]),Ku="3.5.3",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===Gu?Vu:Gu(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=se(e,Lt(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,zt(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] [${Qa[n]}] ${Xa[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!==Va(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&&Va(t,i),h=d&&Ka.get(d.get);if(d&&(!h||Va(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=Va(r,a);if(void 0===f)return{existence:"missing",missingSegment:a,candidates:Ja(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=>{dt?.removed("substr");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,bt("input",kd,Id,wd),bt("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(Za(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(Za(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(Za(o,a.spec.recursiveAnchor));const c=Md(l);Array.isArray(s)||tt(tl(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(tl(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&tt(tl(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 Gd(t){return"function"==typeof t.get&&Ud.has(t.get)}const Vd="[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(`${Vd} 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(`${Vd} "${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(Za(e,t.recursiveAnchor)),0===n.length&&tt(`${Vd} "${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(`${Vd} "${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)||Gd(n))continue;const t=this._matchExpansion(e);null!==t&&tt(`${Vd} "${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(`${Vd} "${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||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,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&&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=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=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){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=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?(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){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()}".`)}(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 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 Vh=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 Vh.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: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,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?Gh(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&&function(t){const e=mr(t);e.dispose();const n=[],o=document.createTreeWalker(t);for(;o.nextNode();)e.handleAddedNode(o.currentNode,n,t=>{console.error("[@wcstack/state] a binding failed to start again on the mount scope's re-initialization.",t)});ml(n)}(e),function(t,e){Zh||(Zh=!0,ve=t=>Vh.has(t)?t.host:null),Vh.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,n){const o=(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,n?t=>function(t,e){for(let n=t;n!==e;n=n.parentNode)if(nr(n))return!0;return!1}(t,e):void 0);const s=_e(t.component);mf(t,s),Xl(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,o),yl(e,s,o)}(t,e,null!==n),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){ml(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=Vh.get(n);if(void 0!==t)return t;n=n.parentNode}return Vh.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=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).`),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 Gf{_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 Vf=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 Gf(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:Vf(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=Jt(a);null===h&&tt(`CustomElementRegistry is unavailable for <${c}>.`);const f=t.connectGeneration;if(await h.whenDefined(c.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await qt(a),t.connectGeneration!==f)return!0;d in a||tt(`Component does not have property "${d}" for state binding.`);let p=a[d];"object"==typeof p&&null!==p||tt(`Component property "${d}" is not an object for state binding.`);const m=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!==m&&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]=m,p=m),e.boundComponent=a,e.boundComponentStateProp=d,t.setBoundComponent(a,d),i instanceof ShadowRoot||(ce(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=(ce(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 f=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,p),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,p,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!1;try{If(h,i instanceof ShadowRoot?i:a)}catch(e){throw t.landInitialization(),e}if(!f){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),Th(h,"$connectedCallback",()=>xf(h)),!1}}Kf(t,e.boundComponent,e.boundComponentStateProp,p)}var o,r;return!1}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(n=>!!n||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[G];if(void 0!==i){"object"==typeof i&&null!==i||tt(`${G} 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(`${G} 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(`${G} 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[G];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.`);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(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),Gu=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){return"else"===t.bindingType?"else:":`${t.bindingType}: ${_p(t.statePathName,t.outFilters)}`}function _p(t,e){let n=t;for(const t of e){const e=t.literals??t.args;n+=`|${t.filterName}`,t.args.length>0&&(n+=`(${t.args.map((t,n)=>"string"==typeof e[n]?`'${t.split("'").join("'\"'\"'")}'`:t).join(",")})`)}return n}const $p=/--|-$|[\0\n\r\u2028\u2029]/;function xp(t){const e=t.fragment.cloneNode(!0);for(const n of t.nodeInfos){const o=ql(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 Sp 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(xp(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()}Sp.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 Ip={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),Sp.buildContent(o,Sp.extractStateData(t),t.getRootNode()),t.parentNode?.insertBefore(o,t)}Oa()},reset:function(){El.clear(),Oa(),n.seen=!1}},Pp=new Set(["for","if","elseif","else"]);function kp(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 Np(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 Ap(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 Ep=/^\s*@@\s*(?:wcs-text)?\s*:/;function Cp(t,e){for(const n of e)"event"===n.bindingType||Pp.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&Ep.test(n.node.data))&&t.push(n)}function Mp(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 Tp(t,e,n,o,s,r){e.length>0&&(t.spreads=e);for(const t of e)ye(t.node);gl(e,n,o,s,r)}function Op(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],ie(e,"output"));Array.isArray(o)&&(s=o)})}return s}function Lp(t,e){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[t]}:${e}`}function Rp(t,e,n){const o=Lp(e,n);return gp(t,t=>t===o)[0]??null}function jp(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(de(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=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,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;Gl(s),"string"==typeof r&&Bl(s,r),Xl(n,s,r),Cl(t,n,{fragment:s,parseBindTextResult:o,nodeInfos:Ul(s)})}}const Wp={hydrate:async function(t){await wl(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.`),Sp.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=kp(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.`),Sp.cleanupDom(t),!1}for(const n of e)jp(t,n);Sp.restoreTextBindings(document.body);const o=function(t){const e=[];for(const n of gp(t,bp)){const t=kp(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=Np(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=Mp(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}=Ap(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=Rp(t,"for",i.uuid);if(e){let t=n.get(i.uuid);if(!t){const s=Op(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}),Cp(s,l),Tp(f,h,a,d,l,p)}}else{const e=i.start.previousSibling,n=e?.data===Lp(i.type,i.uuid)?e:Rp(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}),Cp(s,l),Tp(f,h,t,d,l,p)}}}return s}(document.body,o,r);Sp.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(fe(document.body),void 0),d=[],h=[],f=mr(document.body),p=f.initialize(l);gl(u,null,f);for(const t of p)if("event"!==t.bindingType)if(Pp.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})}ml([...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},textMarker:function(t){const e=t.node.nodeType===Node.COMMENT_NODE?Dt(t.node)??t.statePathName:_p(t.statePathName,t.outFilters);return $p.test(e)?t.statePathName:e},loadState(t){const e=t.parentNode;if(!e)return null;const n=Sp.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=Sp.extractStateData(t),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",Ku),Sp.buildContent(n,e,t.rootNode),t.parentNode?.insertBefore(n,t)}};let Dp=!1;const zp={name:"ssr",install(){Dp||(Dp=!0,Ha=Wp,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,Sp)}),function(){const e=globalThis;void 0===e[t]&&(e[t]=Ip)}())}},Bp=new WeakMap,Fp=new Set,Hp=new Set;function qp(t){return t.byFromPath.size>0||t.byResetPath.size>0}function Up(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function Gp(t){return Bp.get(t)}function Vp(t){Kp(t),Bp.delete(t)}function Kp(t){Fp.delete(t),Hp.delete(t)}const Jp=new WeakSet;let Qp=0;function Xp(t){return Gp(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function Yp(t){if(0===Hp.size)return;if(e=t.absolutePathInfo.stateElement,!Hp.has(e))return;var e;const n=Xp(t);if(void 0!==n)for(const t of n)Zp(t)}function Zp(t){Jp.has(t)||(Jp.add(t),Qp++)}function tm(t){return!!Jp.delete(t)&&(Qp--,!0)}const em=/^(?:0|[1-9]\d*)$/;function nm(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function om(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&&em.test(e)&&nm(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&nm(t,e))?null:"object"}function sm(t,e){const n=om(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]=sm(o[t],e);return r}function rm(t){return sm(t,new Map)}function im(t,e,n){if(Object.is(t,e))return!0;const o=om(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(om(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(!im(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&im(s[t],r[t],n))}function am(t,e){return im(t,e,new Map)}const lm=new WeakMap;function cm(t,e){if("function"!=typeof e)return;const n=lm.get(e);void 0===n?lm.set(e,new Set([t])):n.add(t)}function um(t,e){return"function"==typeof e&&!0===lm.get(e)?.has(t)}const dm={"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}".`},hm={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function fm(t,e,n){null!==xe&&xe({type:"state:watch-error",phase:e,path:`${H}.${t}`,error:n})}function pm(t,e,n){console.error(`[@wcstack/state] ${dm[n](t)}`,e),fm(t,hm[n],e)}function mm(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function gm(t,e){e.then(void 0,()=>{}),pm(t,new TypeError(`${H} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const ym=new WeakSet,bm="[wcs/scan-declaration-invalid]",wm=Object.freeze([]);function vm(t){return`${H} entry "${t}"`}function _m(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 xm(t,e,n){0===n.length&&tt(`${bm} ${t} "${e}" must be a non-empty state path.${at}`),n.startsWith("$")&&tt(`${bm} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${at}`),n.includes("@")&&tt(`${bm} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${at}`),n in Object.prototype&&tt(`${bm} ${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(`${bm} ${t} ${e} "${n}" has an empty path segment.${at}`);return o.wildcardCount>u&&tt(`${bm} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function Sm(t,e,n,o){const s=vm(t);0===t.length&&tt(`${bm} ${H} entry name must be a non-empty string.${at}`),(t.includes(l)||t.includes(c))&&tt(`${bm} ${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(`${bm} ${s} must not start with "$" (reserved namespace).${at}`),t in Object.prototype&&tt(`${bm} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${at}`),e.has(t)&&tt(`${bm} ${s} conflicts with a getter declared on the state.${at}`),n.has(t)&&tt(`${bm} ${s} conflicts with a setter declared on the state.${at}`),o.has(t)&&tt(`${bm} ${s} conflicts with the ${B} entry of the same name — each output has exactly one owner.${at}`)}function Im(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!um(t,o)&&tt(`${bm} ${vm(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${at}`)}function Pm(t,e,n,o,s,r){const i=vm(t),a=void 0!==e.from,c=void 0!==e.on;if(a===c&&tt(`${bm} ${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(`${bm} ${i} "on" must be a non-empty event-token name.${at}`),n.has(t)||tt(`${bm} ${i} on "${t}" is not declared in ${D}.${it(t,n)}${at}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&tt(`${bm} ${i} "from" must be a state path string.${at}`);const d=xm(i,"from",u),h=_m(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&tt($m(i,"from",u,h));const f=_m(d,s);return null!==f&&tt(function(t,e,n){return`${bm} ${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(`${bm} ${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 km(t,e,n,o){if(void 0===e)return wm;const s=vm(t);Array.isArray(e)||tt(`${bm} ${s} "resetOn" must be an array of state paths.${at}`);const r=[];for(const t of e){"string"!=typeof t&&tt(`${bm} ${s} "resetOn" must contain only state path strings.${at}`);const e=xm(s,"resetOn",t);e.wildcardCount>0&&tt(`${bm} ${s} resetOn "${t}" must not contain "${c}" — a reset returns the whole output to "initial".${at}`);const i=_m(e,o);null!==i&&tt($m(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&tt(`${bm} ${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(`${bm} ${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 Nm(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 Jp.has(t)}(t),l=a&&!am(n,t.initial)?rm(t.initial):n,c=e(l,o,...s);if(mm(c))return void gm(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,cm(t.name,c)),a&&tm(t)}catch(e){pm(t.name,e,i)}}}const Am="scanEntries",Em={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(`${bm} ${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)){Sm(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&tt(`${bm} ${vm(t)} must be an object ({ from | on, initial, fold, resetOn? }).${at}`);const o=d;Im(t,a,o);const h=Pm(t,o,e,s,i,n);"initial"in o||tt(`${bm} ${vm(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${at}`),"function"!=typeof o.fold&&tt(`${bm} ${vm(t)} fold must be a function.${at}`);const f=km(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(`${bm} ${vm(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(`${bm} ${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(Am,o)},applyEarly(t,e,n){const o=n.get(Am)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=rm(n.initial);t[n.name]=e,cm(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&Ro(t,n.source.tokenName).subscribe(Nm(n))}(t,o))},register(t,e,n){const o=n.get(Am)??null,s=function(t){const e=new Map,n=Gp(t);if(void 0!==n)for(const t of n.entries)tm(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&&Up(n,t.source.path,t);for(const e of t.resetOn)Up(o,e,t),"event"===t.source.kind&&Up(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return Bp.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)&&Vr().hasQueuedPath(t,n))&&Zp(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 Cm=!1;const Mm=Object.freeze([]),Tm=Object.freeze([]);function Om(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Mm,i=t.dynamicDependency.get(n)??Mm,a=e.byFromPath.get(n)??Tm;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const Lm=Symbol("wcs-stream-last-notified-uncertain"),Rm=new WeakMap;function jm(t,e){const n=Rm.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Wm(t,e){const n=Rm.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Lm,error:Object.is(o.error,null)?null:Lm})}const Dm=new Set;function zm(t){Dm.delete(t)}const Bm=new WeakMap;function Fm(t){return Bm.get(t)??new Map}function Hm(t){zm(t);const e=Bm.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Wm(t,n.name)}const qm=(t,e)=>e,Um=new Set;const Gm=new WeakMap,Vm=new WeakMap;function Km(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=Fm(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&Fm(t).has(n),ownKeys:()=>Array.from(Fm(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=Fm(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 Jm(t){const e=Gm.get(t);if(void 0!==e)return e;const n=Km(t,V,t=>t.status);return Gm.set(t,n),n}function Qm(t){const e=Vm.get(t);if(void 0!==e)return e;const n=Km(t,K,t=>t.error);return Vm.set(t,n),n}function Xm(t){Gm.delete(t),Vm.delete(t)}let Ym=null;function Zm(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 tg={read(t,e){!function(t,e){null!==Ym&&Ym.add(Qn(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===V?Zm(Jm(t),e.pathInfo.segments):n===K?Zm(Qm(t),e.pathInfo.segments):bc},get:(t,e)=>e===V?Jm(t.stateElement):e===K?Qm(t.stateElement):bc};let eg=0,ng=null,og=0;const sg=new WeakMap;function rg(t){eg=t+1}function ig(){eg=0}function ag(t){if(eg>0){const e=ng??=new Map;eg>(e.get(t)??0)&&e.set(t,eg),og=Math.max(og,eg)}}function lg(t,e){return sg.get(t)?.get(e)??0}function cg(t){gg();const e=Fm(t);if(0!==e.size){!function(t){Dm.add(t)}(t);for(const n of e.values())ug(t,n)}}function ug(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=Ym,s=new Set;let r;Ym=s;try{t.createState("readonly",t=>{r=n(t)})}finally{Ym=o}r instanceof Promise&&tt(`${B} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${V}${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=Gp(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=Om(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}),cm(e.name,e.definition.initial),dg(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,cm(e.name,o)})},done(){dg(t,e,"done",null)},fail(o){dg(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 dg(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return Rm.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=Rm.get(t);void 0===s&&(s=new Map,Rm.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${V}${l}${e.name}`),i&&t.$postUpdate(`${K}${l}${e.name}`)}))}function hg(t){const e=Dm;if(0===e.size)return;const n=[];for(const o of e)for(const e of Fm(o).values()){let s=-1;for(const n of e.depAddresses)t.has(n)&&(s=Math.max(s,lg(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)&&Fm(t).get(o.name)===o){rg(s);try{ug(t,o)}catch(n){o.controller?.abort(),e.has(t)&&Fm(t).get(o.name)===o&&dg(t,o,"error",n)}}}finally{ig()}}let fg=!1;const pg=new WeakMap,mg={order:20,apply(t,e){var n;Xm(t),Hm(n=t),zm(n),Bm.delete(n),function(t,e){fc(e);const n=e[B];if(void 0===n)return void jm(t,Um);"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||um(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??qm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in e||(e[r]=d.definition.initial,cm(r,d.definition.initial)),o.set(r,d)}!function(t,e){Bm.set(t,e)}(t,o),jm(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 cg(t),void pg.set(t,t.connectGeneration??0)}n===t.connectGeneration&&pg.get(t)!==n&&cg(t)}},deactivate(t){Hm(t),Xm(t)}};function gg(){fg||(fg=!0,_c("streams",tg),Ic("streams",mg),qr(hg,20))}const yg=new WeakMap;function bg(t,e,n){let o=yg.get(t);void 0===o&&(o=new Map,yg.set(t,o)),o.set(e,n)}const wg=new Map;function vg(t,e){wg.has(t)||wg.set(t,e)}function _g(t){return wg.get(t)}const $g=new WeakMap,xg=new WeakMap,Sg=new Set,Ig=new Map;function Pg(t){return $g.get(t)??Ig}function kg(t,e){let n=xg.get(t);void 0===n&&(n=new Map,xg.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 Ng=new Map;function Ag(t){return xg.get(t)??Ng}function Eg(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 Cg={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||vg(n,o)},swapped(t,e,n){var o;o=n,wg.has(o)&&vg(e,_g(n))}};function Mg(t){for(let e=t;null!==e;e=e.parentListIndex)if(Ke(e))return!0;return!1}function Tg(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 Og(t,e,n){const o=new Map;for(const s of n){const n=Tg(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 Lg=Object.freeze([]);function Rg(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 jg(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 Wg(t,e){return e.has(t.stateElement)&&!0===Gp(t.stateElement)?.entries.has(t.entry)}function Dg(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>zg(n,t))||tm(e)}function zg(t,e){return Vr().hasQueuedPath(t,e)}function Bg(t,e){!function(t,e,n){if(0!==Qp)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=Xp(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||tm(e)}}(t,e,zg)}function Fg(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function Hg(t,e,n){if(!Wg(t,n))return Dg(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(ym.has(t))return;ym.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}`),fm(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=Fm(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:Og(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(jg)){let n;try{n=Fg(e,r,t)}catch(t){pm(s.name,t,"read-source");continue}const o=a(l,n,_g(t.absAddress),...t.indexes);if(mm(o))return void gm(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){pm(s.name,t,i.failure)}return i.plan}function qg(t,e){const{group:n}=t;if(!Wg(n,e))return void Dg(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||tm(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!am(o,s.initial):!Object.is(o,t.next)){const o=n.reset?rm(s.initial):t.next;e[s.name]=o,cm(s.name,o)}})}catch(t){pm(s.name,t,"write")}}function Ug(t){ty(),(0!==Pg(t).size||0!==Ag(t).size||function(t){const e=Bp.get(t);return void 0!==e&&qp(e)}(t))&&(function(t){Sg.add(t),function(t){const e=Bp.get(t);void 0!==e&&(qp(e)&&Fp.add(t),function(t){return t.eventResetByPath.size>0}(e)&&Hp.add(t))}(t)}(t),function(t){const e=[];for(const n of Pg(t).values())Gg(t,n)&&e.push(n);for(const n of Ag(t).values())for(const o of n)Gg(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{bg(t,Xn(t,o.pathInfo,null),n[o.path])}catch(e){Kg(t,o.path,"prime",e)}})}(t))}function Gg(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 Kg(t,e,n,o){console.error(`[@wcstack/state] $watch ${Vg[n]} "${e}" threw.`,o),null!==xe&&xe({type:"state:watch-error",phase:n,path:e,error:o})}function Jg(t){const e=Sg,n=function(t){const e=og;return e>0&&(sg.set(t,ng),ng=null,og=0),e}(t);try{if(n>32){Bg(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 Bg(t,e);!function(t,e){if(0!==t.length)try{for(const n of t)rg(n.group.depth),qg(n,e)}finally{ig()}}(function(t,e){if(Bg(t,e),0===Fp.size)return Lg;const n=new Map;for(const o of t){const s=o.absolutePathInfo.stateElement;if(!e.has(s))continue;const r=Gp(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=lg(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)Rg(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)Rg(n,s,t,a).reset=!0}if(0===n.size)return Lg;const o=Array.from(n.values()).sort((t,e)=>t.entry.order-e.entry.order),s=[];try{for(const n of o){rg(n.depth);const o=Hg(n,t,e);null!==o&&s.push(o)}}finally{ig()}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=Pg(t).get(r),a=Ag(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(Xg);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];(Mg(s.absAddress.listIndex)||r?.entry===s.entry&&Qg(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(Og(t,e.pathInfo,n));for(const t of n)s.has(t)||o.add(t)})}catch(t){Kg(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=Pg(n.stateElement).get(n.entry.path)===n.entry,s=!0===Ag(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(rg(lg(t,n.absAddress)),Yg(n))}}finally{ig()}}(t,e)}finally{wg.clear()}}function Qg(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Xg(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 Yg(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Gg(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 Kg(0,n.path,"evaluate",t)}const a=r?function(t,e){return yg.get(t)?.get(e)}(e,o):_g(o);r&&bg(e,o,i),null!==xe&&xe({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){Kg(0,n.path,"handler",t)}}let Zg=!1;function ty(){Zg||(Zg=!0,_c("watch",Cg),Ic("watch",ey),qr(Jg,10),Hr(ag),qu={assertValidPath:Eg,addEntries:kg,start:Ug})}const ey={order:10,register(t,e){var n;n=t,Sg.delete(n),Kp(n),$g.delete(n),function(t){yg.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=Eg(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)&&Ug(t)},deactivate(t){var e;e=t,Sg.delete(e),Kp(e)}},ny={name:"temporal",install(){ty(),Cm||(Cm=!0,Ic("scan",Em),Hr(Yp)),gg()}},oy=new Set,sy=new Set;function ry(t){oy.has(t)||(oy.add(t),console.warn(`[@wcstack/state] [wcs/v4-migration] ${t} See "Preparing for 4.0" in the @wcstack/state README.`))}const iy=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],ay=["formats","diagnostics","temporal","list-keys","scopes","recursion","ssr","devtools"],ly=(t,e,n)=>ry(`${t}: "${e}" is not one of its options, or not ${n}. 4.0 throws on it.`);function cy(t,e){sy.has(t)||(sy.add(t),ry(`${"$"===t[0]?"":"filter "}"${t}" is removed in 4.0: write "${e}" (its name since 3.2).`))}const uy={substr:'filter "substr" is removed in 4.0: write slice(start, start + length) — slice takes the end index, not a length.'},dy={$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."},hy=new WeakSet,fy={state(t){const e=t;for(const t of Object.keys(uc))void 0!==e[t]&&cy(t,uc[t]);var n;void 0!==e[H]&&ry(`"${H}" is removed in 4.0: rewrite it with $watch (state paths) or $on (event tokens).`),hy.has(t)||(function(t){if(null==t)return;if("object"!=typeof t)return void ly("state","$behavior","an object");const e=t;for(const t in e){const n=e[t];iy.includes(t)&&"boolean"==typeof n?n!==s[t]&&ry(`$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} }).`):ly("$behavior",t,"a boolean")}}(e.$behavior),void 0!==(n=e.$features)&&(Array.isArray(n)&&!n.some(t=>!ay.includes(t))||ry(`$features is not an array of add-on names (${ay.join(", ")}). 4.0 throws on it.`)))},volumeLoaded(t){hy.add(t)},renamed:cy,removed(t){ry(uy[t])},volume(t,e,n){n>0&&ry(`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(dy))void 0!==e[n]&&ry(`volume "${t}" declares ${n}: 4.0 does not graft a volume that declares it. ${dy[n]}`)}};const py=[Ad,ny,Zd,up,zp,sd,pd];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(py),dt=fy,void Hu(void 0,void 0));const my={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 gy(){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 yy(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let by=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const wy={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 vy(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function _y(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 xy=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&&yy(`${my.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&yy(`${my.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(wy).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||yy(`${my.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:vy(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new by("Navigation cancelled by guard.",o);if(!o)throw new by("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new by("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const Sy="data-wcs-ssr",Iy="data-wcs-ssr-link",Py="@@wcs-route-ph:",ky="@@wcs-route-start:",Ny="@@wcs-route-end:";let Ay=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=gy();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new xy(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||yy(`${my.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(`${Ny}${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):yy(`${my.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&&yy(`${my.tagNames.route} with fallback attribute must be a direct child of ${my.tagNames.router}.`),t.fallbackRoute&&yy(`${my.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 Ey=Symbol.for("wcstack.trustedTypes.policy"),Cy=Symbol.for("wcstack.trustedTypes.internal"),My="wcstack";function Ty(){const t=globalThis[Ey];return null===t||"object"!=typeof t?null:t}let Oy=!1;function Ly(t){const e=function(){const t=globalThis,e=t[Cy];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 Ty()?.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[Cy]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Ty(),s=o?.createHTML;return"function"==typeof s?(Oy||(Oy=!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 Ry=new Map;class jy extends HTMLElement{_uuid=gy();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||yy(`${my.tagNames.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Ry.set(t,n),n}catch(e){yy(`${my.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(`${my.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Ry.has(t)?n.innerHTML=Ly(Ry.get(t)||""):n.innerHTML=Ly(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Ly(t):console.warn(`${my.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")&&my.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class Wy extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||yy(`${my.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")&&my.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const Dy=new Set(["props","states","attr",""]);function zy(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 By(t,e){t.hasAttribute("data-bind")||yy(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Dy.has(n)||yy(`${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&&zy(t,e,o)}).catch(()=>{yy(`Failed to define custom element: ${s}`)}):zy(t,e,o)}const Fy=Symbol.for("wcstack.binder");function Hy(){const t=globalThis[Fy];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const qy=Symbol.for("wcstack.binder.pending"),Uy=Symbol.for("wcstack.binder.taken");function Gy(){const t=globalThis;let e=t[Uy];return void 0===e&&(e=new WeakSet,t[Uy]=e),e}function Vy(t,e){const n=Hy();return null===n?(function(){const t=globalThis;let e=t[qy];return void 0===e&&(e=[],t[qy]=e),e}().push(t),!1):(Gy().add(t),n.bind(t,e),!0)}const Ky={range:!0};function Jy(t,e){for(const n of t.routeChildNodes)e.add(n.placeHolder).add(n.endMarker),Jy(n,e);return e}function Qy(t){const e=t.placeHolder,n=t.endMarker,o=null!==n.parentNode&&n.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(n)),s=o?null:Jy(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 Xy=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||yy(`${my.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(`${my.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!==Hy())for(const e of t)1===e.nodeType&&Vy(e,Ky)}(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=>{By(e,t)}),e.hasAttribute("data-bind")&&By(e,t))}};function Yy(){return document.createElement(my.tagNames.layoutOutlet)}const Zy="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function tb(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)),yy(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 ${Zy}`:`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 ${Zy}`}(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 eb(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 nb(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===my.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),eb(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===my.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&tb(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===my.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=Yy();o.layout=n,i=o,a=e}}const c=await nb(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function ob(t){const e=new Map;return await nb(t,t.template.content,[],e)}function sb(t){return!1!==t.checkVisibility?.()}function rb(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=wy[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)rb(s,e,n,o)}function ib(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)rb(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 ab=null,lb=null;function cb(){const t=my.basenameFileExtensions;return 0===t.length?null:(ab===t&&lb||(ab=t,lb=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),lb)}function ub(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=cb();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function db(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function hb(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=cb();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function fb(t){if(null!==t.held)return;const e=Qy(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 pb(t){t.clearParams(),fb(t)}function mb(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=>{By(e,t.typedParams)}),n.hasAttribute("data-bind")&&By(n,t.typedParams),n.querySelectorAll(my.tagNames.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===my.tagNames.layoutOutlet&&n.assignParams(t.typedParams)}}const gb=new WeakSet;function yb(t){const e=t.placeHolder;null!==e.parentNode&&(gb.has(t)||null!==t.endMarker.parentNode?(fb(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),gb.add(t))}const bb=Symbol.for("wcstack.transition-runner");const wb=new WeakSet,vb="data-wcs";function _b(t,e,n){!wb.has(t)&&function(t){return t.hasAttribute(vb)||null!==t.querySelector(`[${vb}]`)}(t)&&(wb.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==Hy()||(o=t,Gy().has(o))||console.warn(`[@wcstack/router] ${e} contains ${vb} 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,Ky))continue}else if(null!==Hy())continue;_b(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 xb(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 by)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 Sb(t,e,n,o,s=""){const r=db(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=ib(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:yy(`${my.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 xb(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||pb(t);const t=[];for(const n of e.routes)(t.length>0||!s.has(n)||n.shouldChange(e.params))&&(t.push(n),mb(n,e));let r=!1;for(const e of t){const t=s.has(e);t&&r||yb(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[bb];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(sb(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(sb(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 Ib(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Pb(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 kb(t){return"?"===t?"":t}function Nb(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 Eb=Object.freeze({});class Cb 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=Eb;_typedParams=Eb;_searchParams=Eb;_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 ub(t)}_normalizeBasename(t){return hb(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(my.tagNames.outlet))return t;const e=document.createElement(my.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||yy(`${my.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||yy(`${my.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=vy(t.search),s=t.data??null,r=this._data!==s,i=!_y(this._params,e),a=this._routeName!==t.routeName,l=!_y(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(`${my.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(`${my.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=Pb(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+kb(n.search)+n.hash,r=Ib();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(db(t,this._basename));await Sb(this,this.outlet,t,this._path,kb(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(db(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await Sb(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${my.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 Sb(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||yy(`${my.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||yy(`${my.tagNames.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await ob(this),r=!t&&this._outlet.hasAttribute(Sy);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&&yy(`${my.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(Sy);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await Sb(this,this.outlet,i,this._path,window.location.search||""),(r||null!==Hy())&&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(my.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(Py)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(ky)){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(Ny)){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=db(t,this._basename);let d=ib(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(ky)){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()===my.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(Sy);for(const t of d.routes)mb(t,d);return this.outlet.lastRoutes=d.routes,!await xb(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=db(t,this._basename),n=ib(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&yy(`${my.tagNames.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await Sb(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${Py}${t.absolutePath}`}),this.outlet.setAttribute(Sy,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${ky}${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,Ky)}_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(!Nb(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=Ib();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&&(Ib()?.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 Tb extends HTMLElement{static get observedAttributes(){return["to",...Mb]}_childNodeArray=[];_uuid=gy();_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(my.tagNames.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(my.tagNames.router);if(n)return this._router=n;yy(`${my.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 ub(t)}_joinInternalPath(t,e){const n=hb(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}=Pb(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+kb(o)+s}else try{t.href=new URL(e).toString()}catch{yy(`[${my.tagNames.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(Iy)?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(Iy),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(Iy,"");Ib()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Ib()?.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(){Ib()?.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}=Pb(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 Ob=[],Lb=new Map;let Rb=!1;const jb=new WeakMap;class Wb 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(),Rb||(this._captureInitialHead(),Rb=!0),Ob.push(this),this._reapplyHead()}disconnectedCallback(){const t=Ob.indexOf(this);-1!==t&&Ob.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||yy("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=jb.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return jb.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);Lb.has(t)||Lb.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Ob)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Lb.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=Ob.length-1;e>=0;e--){const o=Ob[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Lb.has(n)&&(t=Lb.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)||_b(t,`<${t.tagName.toLowerCase()}> inside <${my.tagNames.head}>`,`<${my.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(my.tagNames.layout)||t.define(my.tagNames.layout,jy),t.get(my.tagNames.layoutOutlet)||t.define(my.tagNames.layoutOutlet,Xy),t.get(my.tagNames.outlet)||t.define(my.tagNames.outlet,Wy),t.get(my.tagNames.route)||t.define(my.tagNames.route,Ay),t.get(my.tagNames.router)||t.define(my.tagNames.router,Cb),t.get(my.tagNames.link)||t.define(my.tagNames.link,Tb),t.get(my.tagNames.head)||t.define(my.tagNames.head,Wb)}(void 0);const Db={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};let zb=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 Bb(t,e){return e.every(e=>"available"===t.availability.get(e))}const Fb=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Hb=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 zb("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 Bb(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}}(Fb,{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(!Bb(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)}}},qb=!1;function Ub(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Db.triggerAttribute}]`);if(!n)return;const o=n.getAttribute(Db.triggerAttribute);if(!o)return;const s=customElements.get(Db.tagNames.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function Gb(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 Kb(){const t=globalThis[Vb];return null===t||"object"!=typeof t?null:t}let Jb,Qb=!1;let Xb=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Hb.wcBindable,properties:[...Hb.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 Hb(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(Db.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(Db.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=Kb(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Jb)return Jb;if(!("trustedTypes"in globalThis))return Jb=!1,Jb;try{document.createElement("div").innerHTML="<i></i>",Jb=!1}catch{Jb=!0}return Jb}())return void function(){if(Qb)return;Qb=!0;const t="function"==typeof Kb()?.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(!Gb(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",qb||(qb=!0,document.addEventListener("click",Ub)),!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 Yb extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}let Zb=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}};class tw 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 Xb&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}!function(t=customElements){t.get(Db.tagNames.fetch)||t.define(Db.tagNames.fetch,Xb),t.get(Db.tagNames.fetchHeader)||t.define(Db.tagNames.fetchHeader,Yb),t.get(Db.tagNames.fetchBody)||t.define(Db.tagNames.fetchBody,Zb),t.get(Db.tagNames.infiniteScroll)||t.define(Db.tagNames.infiniteScroll,tw)}(void 0);const ew={triggerAttribute:"data-storagetarget",tagNames:{storage:"wcs-storage"}},nw="wcs-storage:value-changed",ow="wcs-storage:loading-changed",sw="wcs-storage:error",rw="wcs-storage:error-info-changed",iw="wcs-storage:trigger-changed";let aw=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:nw,semantics:"state",getter:t=>t.detail},{name:"loading",event:ow,semantics:"state"},{name:"error",event:sw,semantics:"state"},{name:"errorInfo",event:rw,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(ow,{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(sw,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(rw,{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(nw,{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)}},lw=!1;function cw(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${ew.triggerAttribute}]`);if(!n)return;const o=n.getAttribute(ew.triggerAttribute);if(!o)return;const s=customElements.get(ew.tagNames.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function uw(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 dw=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...aw.wcBindable,properties:[...aw.wcBindable.properties,{name:"trigger",event:iw,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 aw(this),this._internals=this._initInternals(),this._wireStates({[ow]:t=>({loading:!0===t}),[sw]: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(iw,{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(!uw(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",lw||(lw=!0,document.addEventListener("click",cw)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(ew.tagNames.storage)||t.define(ew.tagNames.storage,dw)}(void 0);const hw="*",fw="vanilla",pw={scanImportmap:!0,loaders:{[fw]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[hw]:fw},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function mw(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 gw(t,e,n){let o;if(null===e||e===hw||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===hw)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[hw],"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 yw=new Set,bw=new Map;let ww=new WeakMap;function vw(t){if(t===globalThis.customElements)return bw;let e=ww.get(t);return void 0===e&&(e=new Map,ww.set(t,e)),e}const _w=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 _w)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){yw.has(e)||(console.error(`Failed to eager load component '${e}':`,t),yw.add(e))}}function xw(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 Sw(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&&_w.set(t,e)});const Iw=new WeakSet,Pw=new WeakSet;async function kw(t,e,n){t.shadowRoot&&(Iw.has(t)||await async function(t,e,n){Iw.add(t),await Cw(t.shadowRoot,e,n)}(t,e,n))}async function Nw(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=vw(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=gw("",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),yw.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Aw(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=Sw(t);void 0===o.get(s.name)?(Pw.has(t)||(Pw.add(t),o.whenDefined(s.name).then(async()=>{await kw(t,e,n)})),a.has(s.name)||yw.has(s.name)||(a.add(s.name),i.push(s))):await kw(t,e,n)}let l=0;for(const t of i)await Nw(t,e,n,o),l++;return l}async function Ew(t,e,n,o){for(;await Aw(t,e,n,o)>0;);}async function Cw(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 xw(e)}return xw(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Ew(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 Ew(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Mw extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Mw._instance)throw new Error(`${pw.tagNames.autoloader} can only be instantiated once.`);Mw._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=mw(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=gw(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,pw.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 Cw(document,pw,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Mw._instance===this&&(Mw._instance=null)}}!function(t=customElements){t.get(pw.tagNames.autoloader)||t.define(pw.tagNames.autoloader,Mw)}(void 0);
2
2
  //# sourceMappingURL=auto.min.js.map