wcstack 3.3.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n,s=Symbol.for("wcstack.binder"),r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");const a=".",l="*",c=128,u=128,d="#",h="|",f="prevent",p="stop",m="ro",g="init",y="sync",b="else",w="...",v="on",_="eventToken",$="state",S="command",x="class",P="attr",k="style",I={};for(let t=0;t<c;t++)I[`$${t+1}`]=t;const N=Object.freeze(I),A="$connectedCallback",E="$disconnectedCallback",C="$renderedCallback",T="$errorCallback",M="$stateReadyCallback",O="$bindables",L="$commands",R="$commandTokens",j="$command",D="$eventTokens",W="$on",z="$stream",B="$watch",F="$scan",H="$recursion",q="**",U="$listKeys",V="$streamStatus",G="$streamError",K="data-wc-definition",J=/\{\{\s*(.+?)\s*\}\}/g,Q=new Set(["SCRIPT","STYLE"]);function X(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&Q.has(t.parentElement.tagName)||Y(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),X(e.content)}else X(t.content)}function Y(t){const e=t.data;if(J.lastIndex=0,!J.test(e))return;J.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=J.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}function Z(t){throw new Error(`[@wcstack/state] ${t}`)}const tt=new Map;let et=0;function nt(t){let e=tt.get(t);if(void 0!==e)return e;-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] "${t}" uses "${q}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`);const n=function(t){let e=1;for(let n=0;n<t.length;n++)t[n]===a&&e++;return e}(t);return n>512&&Z(`[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 ot(t)),tt.set(t,e),e}class ot{id=++et;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:nt(e),n=t.split("."),o=[],s=[],r=[],i={},a=[],c=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===l&&(r.push(h),i[h]=p,a.push(e(h)),c.push(f),u.push(e(f)),d.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=u,this.wildcardParentPathInfoSet=new Set(u),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}}function st(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function rt(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=st(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const it=" Validate statically: npx @wcstack/lint <file>.",at=new Set(["if","elseif","else","for"]);function lt(t,e){return`${JSON.stringify(t)}${JSON.stringify(e)}`}function ct(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}(${lt(o.args,o.literals??o.args)})`}return e}const ut=new Map([["not",()=>t=>!t]]),dt=new Map([["not",[0,0]]]),ht={input:new Map,output:new Map},ft={input:new Map,output:new Map},pt={input:new Map,output:new Map},mt=new Map;function gt(t,e,n,o){const s=ht[t],r=ft[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=pt[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]);mt.clear()}function yt(t,e,n,o=e){const s=pt[n].get(t)??t,r=`${s}${lt(e,o)}:${n}`,i=mt.get(r);if(void 0!==i)return i;const a=ht[n].get(s)??ut.get(s);if(void 0===a){const e=0===ht[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";Z(`[wcs/filter-unknown] filter not found: ${t}.${rt(t,function(t){return[...new Set([...ut.keys(),...ht[t].keys()])]}(n))}${e}${it}`)}const l=ft[n].get(s)??dt.get(s);void 0!==l&&(e.length<l[0]||e.length>l[1])&&Z(e.length<l[0]?`[wcs/filter-arity] filter "${t}" requires at least ${l[0]} argument(s) (${e.length} given).${it}`:`[wcs/filter-arity] filter "${t}" accepts at most ${l[1]} argument(s) (${e.length} given).${it}`);const c=a(e,o);return mt.set(r,c),c}function bt(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 wt=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function vt(t,e){return e?t:"true"===t||"false"!==t&&("null"===t?null:wt.test(t)?Number(t):t)}function _t(t){const e=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const t=bt(o,i,a);e.push(t),n.push(vt(t,r)),o="",r=!1,i=-1,a=-1};for(let e=0;e<t.length;e++){const n=t[e];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&Z(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${t})". Close the quote.${it}`);const c=bt(o,i,a);return(c||r)&&(e.push(c),n.push(vt(c,r))),{args:e,literals:n}}const $t=t=>t.trim(),St=t=>"'"===t||'"'===t;function xt(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(null!==n)s===n&&(n=null);else if(St(s))n=s;else if(s===e)return o}return-1}function Pt(t,e){const n=[];let o=null,s=0;for(let r=0;r<t.length;r++){const i=t[r];null!==o?i===o&&(o=null):St(i)?o=i:i===e&&(n.push(t.slice(s,r)),s=r+1)}return n.push(t.slice(s)),n}function kt(t,e,n){const o=n??t.join("|");return t.map(t=>{const n=xt(t,"(");let s=function(t){let e=null,n=-1;for(let o=0;o<t.length;o++){const s=t[o];null!==e?s===e&&(e=null):St(s)?e=s:")"===s&&(n=o)}return n}(t);if(-1===s&&(s=t.lastIndexOf(")")),-1!==n&&-1===s&&Z(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${t}".${it}`),-1!==s&&-1===n&&Z(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${t}".${it}`),-1!==s&&s<n&&Z(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${t}".${it}`),-1!==s&&t.slice(s+1).trim().length>0){const e=t.slice(s+1).trim();Z(`[wcs/binding-syntax] "${t}": unexpected "${e}" after the filter's closing ")" — separate filters with "|" (write "${t.slice(0,s+1)}|${e}").${it}`)}const r=(-1===n?t:t.substring(0,n)).trim();if(0===r.length&&Z(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${it}`),r.includes(d)){const[t,n]=r.split(d);Z("input"===e?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${d}${n}" comes before the input filters, not inside one — write "<property>${d}${n}|${t}".${it}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${d}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${t}" here.${it}`)}return-1===n?{filterName:r,args:[],literals:[]}:{filterName:r,..._t(t.substring(n+1,s))}})}const It=new Map;function Nt(t){const e=xt(t,h);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),It.has(s)?r=It.get(s):(o=Pt(s,h).map($t),r=kt(o,"input",t),It.set(s,r))):n=t.trim();const i=n.split(d).map($t);i.length>2&&Z(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${d}" — write "${i[0]}${d}${i.slice(1).join(",")}".${it}`);const[l,c]=i,u=l.split(a).map($t);return u.length>1&&""===u[0]||0!==l.length&&!u.some(t=>0===t.length)||Z(`[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).${it}`),{propName:l,propSegments:u,propModifiers:c?c.split(",").map($t):[],inFilters:r}}const At=new Map;function Et(t){const e=xt(t,h);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=Pt(s,h).map($t),r=kt(o,"output",t),At.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&Z(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);const i=n,l=i.startsWith(a),c=l?i.slice(1):i;return(c.length>0&&c.split(a).some(t=>0===t.length)||!l&&0===c.length)&&Z(`[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).${it}`),{statePathName:i,statePathInfo:nt(i),outFilters:r}}const Ct=new Set([b,"if","elseif","for",w]),Tt=new Set([x,P,k,S,_,$]);function Mt(t){const[...e]=function(t){return Pt(t,";")}(t).map($t).filter(t=>t.length>0),n=e.map(t=>{const e=xt(t,":");-1===e&&Z(`[wcs/binding-syntax] Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.${it}`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim(),s=n.split(d)[0].split(h)[0].trim();if(s!==n&&Ct.has(s)&&Z(`[wcs/binding-syntax] "${t}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${it}`),n===b){o.length>0&&Z(`[wcs/binding-syntax] "${t}": "else" takes no value — write "else:".${it}`);const e=nt("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===w){0===o.length&&Z(`[wcs/binding-syntax] Invalid spread binding "${t}": spread target path is required.${it}`);const e=Et(o);return e.outFilters.length>0&&Z(`[wcs/binding-syntax] Invalid spread binding "${t}": filters are not allowed on spread targets.${it}`),{propName:w,propSegments:[w],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Et(o),bindingType:n};if("radio"===s||"checkbox"===s){const t=Et(o);return{...Nt(n),...t,bindingType:s}}{const t=Et(o),e=Nt(n);if(""===e.propSegments[0]&&e.propSegments.length>1){const o=e.propSegments.slice(1);return(o.includes("")||Tt.has(o[0]))&&Z(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Tt].join(", ")}).${it}`),{...e,propName:o.join(a),propSegments:o,...t,bindingType:"prop"}}return e.propSegments[0]===_||e.propSegments[0].startsWith(v)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>at.has(t.bindingType))&&Z(`[wcs/template-syntax] Invalid bindText: "${t}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${it}`),n}const Ot=new WeakMap,Lt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Rt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function jt(t){const e=Ot.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Rt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Lt.has(r)?(Ot.set(t,s[2]),s[2]):null}function Dt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Et(t),bindingType:"text"}}const Wt=new WeakMap,zt=new WeakSet;let Bt=0;async function Ft(t){const e=function(t){let e,n=Wt.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++Bt,promise:o,resolve:e},Wt.set(t,n),zt.has(t)&&n.resolve(),n}(t);await e.promise}function Ht(t){const e=Wt.get(t);void 0===e?zt.add(t):e.resolve()}const qt=new WeakMap;function Ut(t){const e=qt.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{qt.set(t,n)}}function Vt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Gt(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Vt(e);if(void 0!==n)return Vt(n)}return Vt(globalThis.customElements)}function Kt(t,e){t.upgrade?.(e)}function Jt(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=Zt(s.properties,Qt);if(null===r)return null;const i=void 0===s.inputs?new Map:Zt(s.inputs,Xt);if(null===i)return null;const a=void 0===s.commands?new Map:Zt(s.commands,Yt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Qt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function Xt(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 Yt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function Zt(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 te(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:nt(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ee(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function ne(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&Z("Spread binding requires an element node.");const e=t,o=Ut(e);null===o&&Z(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Gt(e);if(null===a&&Z(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||Z(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Kt(a,e);const l=Jt(e);null===l&&Z(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=te(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=te(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=ee(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=ee(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function oe(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 se(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:yt(s.filterName,s.args,e,r)})}return n}function re(t){return{...t,inFilters:se(t.inFilters,"input"),outFilters:se(t.outFilters,"output")}}const ie=new WeakMap;function ae(t){return ie.get(t)||null}function le(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function ce(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!le(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function ue(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 de(t){const e=[],n=ce(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==jt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&ue(t,n)||e.push(t)}return e}const he=new WeakSet;function fe(t,e,n,o){const s=ne(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Ut(t):null;return null===n&&Z("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}he.add(t);const r=function(t,e){const n=[];for(const o of e){const e=se(o.inFilters,"input"),s=se(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){ie.set(t,e)}(t,r),Ht(t),{bindings:r,deferred:null}}function pe(t,e){const n=de(t),o=[],s=[];for(const t of n){if(he.has(t))continue;const n=fe(t,xa(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function me(t){he.add(t)}function ge(t){const{node:e,parseResults:n,transform:o}=t;return function(t){he.delete(t)}(e),fe(e,n,{allowDeferred:!1},o).bindings}const ye=new WeakMap;let be=null;function we(t){let e=t;for(;e;){const t=ye.get(e);if(t)return t;let n=e.parentNode;null===n&&null!==be&&e instanceof ShadowRoot&&(n=be(e)),e=n}return null}function ve(t,e){null!==e?ye.set(t,e):ye.delete(t)}let _e=null;const $e=new WeakMap;function Se(t){return $e.get(t)??[]}function xe(t,e){$e.set(t,e)}function Pe(t){return $e.has(t)}const ke=new WeakMap;let Ie=null,Ne=0;function Ae(t){return ke.get(t)??[]}function Ee(t,e){null===Ie?ke.set(t,e):Ie.set(t,e)}function Ce(){Ne++,null===Ie&&(Ie=new Map)}function Te(){if(0!==Ne&&(Ne--,!(Ne>0||null===Ie))){for(const[t,e]of Ie)ke.set(t,e);Ie=null}}function Me(t){return(Ie?.has(t)??!1)||ke.has(t)}const Oe=Symbol("$$setLoopContext"),Le=Symbol("$$getByAddress"),Re=Symbol("$$hasByAddress"),je=Symbol("$$connectedCallback"),De=Symbol("$$disconnectedCallback"),We=Symbol("$$updatedCallback"),ze=Symbol("$$errorCallback"),Be=new WeakMap,Fe=new WeakMap;class He{absolutePathInfo;listIndex;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}}function qe(t,e){if(null===e){let e=Fe.get(t);return void 0!==e||(e=new He(t,null),Fe.set(t,e)),e}{let n=Be.get(e);void 0===n&&(n=new WeakMap,Be.set(e,n));let o=n.get(t);return void 0!==o||(o=new He(t,e),n.set(t,o)),o}}const Ue=new WeakMap;function Ve(t,e){let n=Ue.get(t);void 0===n&&(n=new Map,Ue.set(t,n));let o=n.get(e);return void 0===o&&(o=Object.freeze(new Ge(t,e)),n.set(e,o)),o}class Ge{pathInfo;stateElement;constructor(t,e){this.pathInfo=e,this.stateElement=t}}function Ke(t,e){return qe(Ve(t,e.pathInfo),e.listIndex)}function Je(t,e,n){return qe(Ve(t,e),n)}const Qe=new WeakMap;function Xe(t,e){null===e?Qe.delete(t):Qe.set(t,e)}function Ye(t){return Qe.get(t)||null}const Ze=new Map;function tn(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=Ze.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Ze.set(s,r)),r}function en(t,e,n){return e<0||e>=n?null:t.at(e-n)}function nn(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const on=new WeakMap;function sn(t){const e=we(t.node);if(null===e)return null;let n=on.get(e);if(void 0===n)n=new WeakMap,on.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=tn(e.pathInfo,t.statePathInfo);return n>0&&(o=en(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const rn=new WeakMap;function an(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Ye(n);null===e?Z(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function ln(t,e){let n=null;if(n=rn.get(t)||null,null!==n)return n;const o=an(t,e),s=sn(t),r=ga(o);return null===r&&Z("No state tree found on this root for binding."),n=Je(r,t.statePathInfo,s),rn.set(t,n),n}function cn(t){rn.delete(t)}const un=new WeakMap;function dn(t,e){const n=un.get(t);void 0===n?un.set(t,e):n instanceof Set?n.add(e):n!==e&&un.set(t,new Set([n,e])),null!==_e&&_e({type:"state:binding-added",absoluteAddress:t,binding:e})}function hn(t,e){const n=un.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&un.delete(t),null!==_e&&_e({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const fn=new WeakMap;function pn(t){const e=un.get(t);return void 0!==e?e:null!==t.listIndex?fn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const mn=new WeakMap,gn=new WeakMap;class yn{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=bn(t,e)}}function bn(t,e){if(null===e){let e=gn.get(t);return void 0!==e||(e=new yn(t,null),gn.set(t,e)),e}{let n=mn.get(e);void 0===n&&(n=new WeakMap,mn.set(e,n));let o=n.get(t);return void 0!==o||(o=new yn(t,e),n.set(t,o)),o}}const wn=new WeakMap;function vn(t){let e=null;if(e=wn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=sn(t);null===n&&Z(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=bn(t.statePathInfo,n)}else e=bn(t.statePathInfo,null);return wn.set(t,e),e}function _n(t){wn.delete(t)}function $n(){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 Sn=new Map,xn=$n();function Pn(t,e){const n=ct(t.inFilters);return`${t.statePathName}::${e}::${n}`}function kn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}function In(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function Nn(t,e){console.error(`[wcstack/state] ${e} rejected.`,t)}function An(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)In(t)&&Promise.resolve(t).catch(t=>Nn(t,e))}class En{_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 Cn extends En{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==_e&&_e({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const Tn=new WeakMap;function Mn(t,e){let n=Tn.get(t);void 0===n&&(n=new Map,Tn.set(t,n));let o=n.get(e);return void 0===o&&(o=new Cn(e,t),n.set(e,o)),o}const On=new WeakMap;class Ln extends En{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==_e&&_e({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function Rn(t){return t instanceof Ln}const jn=new Map,Dn=$n();function Wn(t){const e=t.propModifiers.filter(t=>t===f||t===p).sort().join(",");return`${t.statePathName}::${e}`}function zn(t){return"event"===t.bindingType&&t.propName.startsWith(v)}function Bn(t){if(!zn(t))return!1;const e=Wn(t);let n=jn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(f)&&o.preventDefault(),e.includes(p)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ga(r);null===i&&Z("No state tree found on this root for event handler.");const a=we(s),l=t.startsWith(j+".");i.createStateAsync("writable",async e=>{const c=e[Oe](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?nn(a.listIndex,c):[];if(l){const s=e[Le](bn(n,null));return Rn(s)||Z(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...u)}const d=e[t];return"function"!=typeof d&&Z(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});An(c,`"${t}"`)}).catch(e=>Nn(e,`"${t}"`))})(t.statePathName,t.propModifiers,t.statePathInfo),jn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Dn.add(e,t),!0}function Fn(t){if(!zn(t))return!1;const e=Wn(t),n=jn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);return t.node.removeEventListener(o,n),0!==Dn.countOf(e)&&(Dn.remove(e,t)&&jn.delete(e),!0)}const Hn=new Map,qn=$n();function Un(t,e){const n=ct(t.inFilters);return`${t.statePathName}::${e}::${n}`}function Vn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}const Gn=new Set(["radio","checkbox"]),Kn=new Set(["value","valueAsNumber","valueAsDate"]);function Jn(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(Gn.has(t)&&"checked"===e)return!0;if(Kn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Ut(n);if(null!==s){const t=Gt(n)?.get(s);void 0===t&&Z(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Jt(n);if(o?.knownProperties.has(e))return!0}return!1}let Qn=1,Xn=1,Yn=1;const Zn=new WeakMap;function to(t,e,n){let o=Zn.get(t);void 0===o&&(o=new Map,Zn.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=Qn++,o.set(s,r)),r}function eo(t,e){return"to-element"===e?2*t:2*t+1}const no=new Set;function oo(t){return{transactionId:Xn++,originBindingId:t,visitedEdges:no,hop:0}}function so(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 ro=null;function io(){return ro}function ao(t,e){const n=ro;ro=t;try{return e()}finally{ro=n}}const lo=[];let co=!1;const uo=new Map,ho=$n(),fo=new WeakMap,po=t=>t.detail,mo=new WeakMap,go=new WeakMap;let yo=0;const bo=new WeakMap;function wo(t){const e=Ut(t.node);if(null!==e){const n=Gt(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&Z(`CustomElementRegistry is unavailable for <${e}>.`))}if(Jn(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const e=function(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Ut(t.node);if(null!==n){const o=Gt(t.node)?.get(n);void 0===o&&Z(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Jt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}(t),n=function(t){if(null!==Ut(t.node)){const e=Jt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??po}return null}(t),s=function(t){if(null===Ut(t.node))return!1;const e=Jt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}(t),r=function(t,e,n,o){const s=ct(t.inFilters);return`${t.propName}::${t.statePathName}::${e}::${s}::${function(t){if(null===t)return"n";let e=go.get(t);return void 0===e&&go.set(t,e=++yo),`g${e}`}(n)}::${o?"o":"s"}`}(t,e,n,s);bo.set(t,{key:r,eventName:e});let i=uo.get(r);void 0===i&&(i=((t,e,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==po||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=mo.get(t);void 0===r&&(r=new Set,mo.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=fo.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(o.enablePropagationContext){const n=to(a,t,e),s=function(t,e){for(let n=lo.length-1;n>=0;n--){const o=lo[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==_e&&_e({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:eo(n,"to-state"),node:a,member:t}));const r=eo(n,"to-state"),i=io();if(null!==i&&i.visitedEdges.has(r))return void(null!==_e&&_e({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=so(i??oo(n),r)}const h=ga(a.getRootNode());null===h&&Z("No state tree found on this root for two-way binding.");const f=we(a),p=()=>{r&&(co=!0);try{h.createState("writable",t=>{t[Oe](f,()=>{t[e]=c})})}finally{r&&(co=!1)}};null!==d?ao(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),uo.set(r,i)),t.node.addEventListener(e,i),ho.add(r,t)}}const vo=new WeakSet;function _o(t){vo.add(t)}function $o(t){return!!vo.has(t)&&(vo.delete(t),!0)}const So=new WeakMap;function xo(t,e){const n=So.get(t);return!(void 0===n||n<e||(n===e?So.delete(t):So.set(t,n-e),0))}const Po=new WeakSet;function ko(t){Po.add(t)}function Io(t){return!!Po.has(t)&&(Po.delete(t),!0)}let No=0;function Ao(){No--}function Eo(){return No>0}class Co{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 To=new WeakMap;function Mo(t){let e=To.get(t);return void 0===e&&(e=new Co(t),To.set(t,e)),e}const Oo=new Set([x,P,k,S]);function Lo(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==g&&s!==y&&Z(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&Z(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Ro(t){return t.propModifiers.some(t=>t.includes("="))}const jo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Do=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Wo(t,e){return"state"===t&&"call"===e?jo:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function zo(t){if(!o.enableDirectionalInitialSync)return Ro(t)&&Z("init=/sync= modifiers require enableDirectionalInitialSync."),jo;const e=null===(n=Lo(t,g))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:Z(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":Z(`Invalid sync modifier value "${t}".`)}(Lo(t,y));if("event"===t.bindingType)return null!==e&&"none"!==e&&Z("Event bindings only allow init=none."),"call"===s?Do:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(Oo.has(t.propSegments[0]))return Wo("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&Z(`Binding type "${t.bindingType}" does not support init=${e}.`),Wo(e??"state",s);const r=Jt(t.node);if(null===r)return Wo(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||Z(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||Z(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||Z(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let Bo=0,Fo=0;const Ho=["active","disposed","failed"],qo=new WeakMap,Uo=new WeakMap,Vo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,Jo=new WeakMap;function Qo(t,e){const n=Jo.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Jo.set(t,new Set([n,e]))):Jo.set(t,e)}function Xo(t){return Jo.has(t)}function Yo(t,e){const n=Jo.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Zo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Zo(n,e)}function ts(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class es{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||!xo(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)$o(t)||Zo(t,t=>{Yo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)Io(t)&&!Eo()||Zo(t,t=>{Yo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&na(o)}}const ns=new WeakMap;function os(t){let e=ns.get(t);return void 0===e&&(e=new es(t),ns.set(t,e)),e}function ss(t){const e=ct(t.inFilters),n=ct(t.outFilters);return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function rs(t,e,n){const o=ga(an(t,n));null===o&&Z("No state tree found on this root for binding.");const s=Ve(o,t.statePathInfo);return function(t,e,n){let o=fn.get(t);void 0===o&&(o=new WeakMap,fn.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!==_e&&_e({type:"state:binding-added",absoluteAddress:qe(t,e),binding:n})}(s,e,t),s}function is(t,e){const n=ln(t,e);return dn(n,t),n}function as(t,e,n,o){null!==e?hn(e,t):function(t,e,n){const o=fn.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!==_e&&_e({type:"state:binding-removed",absoluteAddress:qe(t,e),binding:n}))}(n,o,t),_n(t),cn(t)}function ls(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class cs{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=this.rowOf(t),i=null===o?-1:o.bindings.indexOf(t);if(null!==o&&0===o.phases[i]){const e=o;this.observe(t.replaceNode),s.registerAddress&&null===e.addresses[i]&&null===e.patternPathInfos[i]&&(e.registered=!0,this.registerRowSlot(e,i));continue}const a=Vo.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(ts(e)&&os(e),null===this.rowPlan)for(const n of t){const t=Vo.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return Ro(t)&&zo(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=Vo.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=Uo.get(e);return void 0===o&&Uo.set(e,o=[]),{id:o[n]??(o[n]=++Bo),info:t,generation:e.generation,phase:Ho[e.phases[n]],teardowns:null}}const o=Vo.get(t);return o?.session===this?o:null}addTeardown(t,e){const n=Vo.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(ls(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=Gt(t);null===s&&Z(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Qo(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Mo(s).wait(e,()=>{if(a())try{Kt(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0)return void this.disposeRowSlot(e,n)}const n=Vo.get(t);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(t){for(let e=0;e<t.length;e++)this.disposeBinding(t[e]);if(!(this.rows.size>0))for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}destroyRow(t){const e=t.length>0?this.rowOf(t[0]):null;null!==e?(this.destroyRowRecord(e),this.rows.delete(e)):this.destroyRecords()}destroyRowRecord(t){for(let e=0;e<t.bindings.length;e++){const n=t.addresses[e];null!==n&&(hn(n,t.bindings[e]),t.addresses[e]=null),t.phases[e]=1}}dispose(){for(const t of Array.from(this.rows))for(let e=0;e<t.bindings.length;e++)this.disposeRowSlot(t,e);for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.rows)this.destroyRowRecord(t);this.rows.clear();for(const t of this.records)null!==t.address&&(hn(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?ln(n):null;if(as(n,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null,this.registerAddress(e),null!==o){const t=ln(n);t!==o&&Pe(o)&&xe(t,Se(o)),t!==o&&Me(o)&&Ee(t,Ae(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return ts(e)?e:null}(t);null!==e&&os(e)}handleMutations(t,e,n){for(const n of e)Zo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Zo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&na(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Vo.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=Ko.get(e);void 0===t&&(t=ss(e),Ko.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Qo(n,this);const o=this.knownMapFor(n);let s=Ko.get(t);void 0===s&&(s=ss(t),Ko.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:++Bo,session:this,generation:++Fo,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(Qo(r,this),this.addKnownRowBinding(r,o,t),qo.set(o,s),n[t].isEvent){let n=!1;try{n=Bn(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=++Fo,r=!0,this.rows.add(o)),o.phases[t]=0,o.flags[t]=0,s[t].isEvent){let n=!1;try{n=Bn(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=qo.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=sn(o);null!==s?(t.patternPathInfos[e]=rs(o,s,n),t.patternListIndexes[e]=s):t.addresses[e]=is(o,n)}unregisterRowSlot(t,e){const n=t.addresses[e],o=t.patternPathInfos[e];null===n&&null===o||(as(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{Fn(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:++Bo,info:t,generation:++Fo,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};Vo.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;Bn(e)?t.eventAttached=!0:e.propSegments[0]!==_?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=Vn(t),s=Un(t,o);let r=Hn.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=ga(o.getRootNode());null===r&&Z("No state tree found on this root for two-way binding.");const i=we(o);r.createState("writable",t=>{t[Oe](i,()=>{t[e]=s})})},Hn.set(s,r)),t.node.addEventListener(o,r),qn.add(s,t),!0}var e,n;return!1}(e)&&ls(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=Vn(t),n=Un(t,e),o=Hn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==qn.countOf(n)&&(qn.remove(n,t)&&Hn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=kn(t),s=Pn(t,o);let r=Sn.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=ga(o.getRootNode());null===i&&Z("No state tree found on this root for two-way binding.");const a=we(o);i.createState("writable",t=>{t[Oe](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]:[]})})},Sn.set(s,r)),t.node.addEventListener(o,r),xn.add(s,t),!0}var e,n;return!1}(e)&&ls(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=kn(t),n=Pn(t,e),o=Sn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==xn.countOf(n)&&(xn.remove(n,t)&&Sn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Jn(e.node,e.propName)&&-1===e.propModifiers.indexOf(m)){const n=function(t,e,n){let o=fo.get(t);void 0===o&&(o=new Map,fo.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&&fo.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});ls(t,n)}wo(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==_)return!1;const e=t.node,n=Ut(e),o=Gt(e);if(null!==n&&void 0===o?.get(n))return null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(On.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||Z('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Ut(t)?null:Jt(t)}(e);null===r&&Z(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&Z(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${rt(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,c=t.propModifiers,u=t=>{c.includes(f)&&t.preventDefault(),c.includes(p)&&t.stopPropagation();const n=ga(e.getRootNode());null===n&&Z("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||Z(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${rt(l,n.eventTokenNames)}${it}`);const o=we(e);n.createStateAsync("writable",async e=>{An(e[Oe](o,()=>{const s=null!==o?nn(o.listIndex,o.pathInfo.wildcardCount):[];return Mn(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,u),On.set(t,{eventName:a,handler:u}),!0})(e)&&ls(t,()=>function(t){if(t.propSegments[0]!==_)return!1;const e=On.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),On.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Ut(t.info.node);if(null===n)return void e();const o=Gt(t.info.node);if(null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=Mo(o).wait(n,()=>{if(this.isAlive(t,s))try{Kt(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});ls(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=zo(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=ga(t.replaceNode.getRootNode());null===e&&Z("No state tree found on this root for binding.");const n=vn(t);let o=!1;return e.createState("readonly",t=>{o=t[Re](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 No++;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,Ao()),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=ga(t.node.getRootNode());null===o&&Z("No state tree found on this root for initial binding sync.");const s=we(t.node);o.createState("writable",e=>{e[Oe](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=sn(n);if(null!==o?(t.patternPathInfo=rs(n,o,e),t.patternListIndex=o):t.address=is(n,e),!t.options.registerPathInfo)return;const s=ga(n.replaceNode.getRootNode());null===s&&Z("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Vo.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,Ao());const e=t.info;if(null!==t.address||null!==t.patternListIndex)try{as(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=bo.get(t);if(void 0===e)return;bo.delete(t);const n=uo.get(e.key);void 0!==n&&(t.node.removeEventListener(e.eventName,n),ho.remove(e.key,t)&&uo.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{Fn(e)}catch{}}}}function us(t){let e=Go.get(t);return void 0===e&&(e=new cs(t),Go.set(t,e)),e}function ds(t){return Vo.get(t)?.session??qo.get(t)?.session??null}let hs=null;function fs(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const ps=Object.freeze([]),ms=new WeakMap,gs=new WeakMap;function ys(t){return gs.get(t)??[]}function bs(t,e){gs.set(t,e)}const ws=new WeakMap;function vs(t){return ws.get(t)??[]}function _s(t,e){ws.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let $s=0;function Ss(){return`u${($s++).toString(36)}`}let xs=0,Ps=0;const ks=Symbol("wcs.listIndex.noValue");class Is{uuid=Ss();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=ks,this._index=e,this._version=xs,this._chainGeneration=Ps}get index(){return this._index}set index(t){this._index=t,this._version=++xs,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(t){this._value=t}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=xs),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Ps||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Ps),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++xs,Ps++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function Ns(t,e,n=t){return new Is(t,e,n)}function As(t,e){t.reparent(e)}function Es(t){return t.homeParentListIndex}function Cs(t,e){t.value=e}function Ts(t,e){const n=t.value;return n!==ks&&n===e.value}const Ms=new WeakMap,Os=new WeakSet;function Ls(t){return Os.has(t)}function Rs(t){const e=Ms.get(t);return void 0===e?null:e}function js(t,e){const n=Ms.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o){const t=function(t,e){const n=Es(t),o=t.parentListIndex;return null===n||n===o||Os.has(n)?function(t,e,n){return null!==t&&null!==n&&n!==e&&!!Os.has(t)&&!Os.has(n)&&n.position===t.position&&Ts(n,t)}(n,o,e)||function(t,e){return t!==e&&null!==t&&null!==e&&t.position===e.position&&Os.has(t)&&!Os.has(e)}(o,e)?e:null:n}(o,e);if(null!==t)for(const e of n)As(e,t)}return n}function Ds(t,e){null!==e?Ms.set(t,e):Ms.delete(t)}const Ws=new WeakMap;function zs(t,e){null===e?Ws.delete(t):Ws.set(t,e)}function Bs(t){const e=Ws.get(t);e&&(e.dirty=!0)}const Fs=Symbol.for("wcstack.transition-runner");function Hs(t){const e=globalThis[Fs];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 qs(t,e,n){const o=Hs(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const Us=[],Vs=[];function Gs(t){Vs.includes(t)||Vs.push(t)}function Ks(t,e=0){const n=Us.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Us.push(o):Us.splice(n,0,o)}function Js(t){queueMicrotask(()=>{throw t})}const Qs=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){for(let e=0;e<Vs.length;e++)Vs[e](t);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(t){const e=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(t),e&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Ce(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(t,e)})}hasQueuedPath(t,e){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===t&&n.absoluteAddress.absolutePathInfo.pathInfo.path===e)}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t,n=[]){const o=new Map,s=new Set;for(let e=0;e<t.length;e++){const n=t[e],r=o.get(n.absoluteAddress);null!==_e&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&_e({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let t=0;t<n.length;t++){const e=n[t];o.has(e)||o.set(e,null)}const r=[],i=new Map;o.forEach((t,e)=>{if(null!==t&&t.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,transactionId:t.transactionId,hop:t.hop,maxHops:32}),void(null!==_e&&_e({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop}));const n=pn(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(r.push(e),null!==t&&i.set(e,t));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==t&&i.set(n,t))});try{const t=()=>{i.size>0?na(r,i):na(r)};if(e()||0===r.length)t();else{const e=qs("state",t);void 0!==e&&e.catch(Js)}}finally{Te(),function(t){for(const e of Us.slice())e.listener(t)}(s)}}};function Xs(){return Qs}const Ys=new WeakMap,Zs=new WeakMap,tr=new WeakMap,er=new WeakMap;let nr=!1;const or=new WeakMap;function sr(t){const e=t.absolutePathInfo.stateElement;let n=or.get(e);void 0===n&&or.set(e,n=new Set),n.add(t)}function rr(t){const e=or.get(t);return void 0===e?null:(or.delete(t),e)}const ir=new WeakMap,ar=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=[];function hr(t,e){const n=fr(t);if(n.recorded.has(e))return;n.recorded.add(e);const o=nt(e).cumulativePaths;if(o.length<2)return;let s=ur.get(t);void 0===s&&ur.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 fr(t){let e=Ys.get(t);return void 0===e&&Ys.set(t,e={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),e}function pr(t,e,n){let o=t.get(e);void 0===o&&t.set(e,o=new Set),o.add(n)}function mr(t,e,n){const o=t.get(e);o.delete(n),0===o.size&&t.delete(e)}function gr(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=Zs.get(o);if(void 0===r&&Zs.set(o,r=new Map),r.has(e)){const t=r.get(e);return Object.is(t,n)||(mr(s,t,o),r.set(e,n),pr(s,n,o)),!1}return r.set(e,n),pr(s,n,o),!0}function yr(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):(o.push(n),!1)}function br(t,e,n,o,s,r){t.lastValue.set(e,n),s&&(null!==o.listIndex&&yr(tr,o.listIndex,r)&&function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){let n=lr.get(e);void 0===n&&lr.set(e,n=new Set),n.add(t)}}(o.listIndex),null!==r.levelListIndex&&yr(er,r.levelListIndex,r))}function wr(t,e,n,o,s){nr=!0;const r=fr(t);hr(t,e),br(r,e,s,o,gr(r,e,n,o),{stateElement:t,path:e,absAddress:o,levelListIndex:null})}function vr(t,e){fr(t).tracked.add(e)}function _r(t,e){return!0===Ys.get(t)?.byPath.has(e)||!0===ir.get(t)?.has(e)}function $r(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(Ke(t.stateElement,bn(e,o)))}function Sr(t,e){if(void 0!==t)for(const n of t)e.push(n)}function xr(t,e,n,o,s){const r=Ys.get(t),i=r?.byPath.get(e),a=ir.get(t)?.get(e);if(void 0===r||void 0===i&&void 0===a)return dr;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&&Sr(i.get(o),u),h&&Sr(i.get(c),u),d&&Sr(i.get(s),u)),void 0!==a)for(const t of a)n&&$r(t,o,u),h&&$r(t,c,u),d&&$r(t,s,u);return u}function Pr(t,e){return!0===ur.get(t)?.has(e)}function kr(t,e){let n=t;for(const t of e){if("object"!=typeof n||null===n)return;n=n[t]}return n}function Ir(t,e,n,o,s=!0){const r=nt(e).segments.length,i=[];for(const a of ur.get(t).get(e)){const e=nt(a).segments.slice(r);if(e.includes(l)){Nr(t,a,i);continue}const c=s?kr(n,e):void 0;for(const n of xr(t,a,s,c,kr(o,e)))i.push(n)}return i}function Nr(t,e,n){const o=Ys.get(t).byPath.get(e);if(void 0!==o)for(const t of o.values())Sr(t,n);const s=ir.get(t)?.get(e);if(void 0!==s)for(const t of s)for(let e=0;e<t.indexes.length;e++)$r(t,e,n)}function Ar(t){const e=er.get(t.levelListIndex),n=e.indexOf(t);e.splice(n,1)}function Er(t){const e=tr.get(t);if(void 0!==e){tr.delete(t),function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){const n=lr.get(e);void 0!==n&&(n.delete(t),0===n.size&&lr.delete(e))}}(t);for(const t of e){const{stateElement:e,path:n,absAddress:o}=t,s=Zs.get(o),r=s.get(n);s.delete(n),mr(Ys.get(e).byPath.get(n),r,o),null!==t.levelListIndex&&Ar(t)}}}function Cr(t){const e=cr.get(t);if(void 0!==e){cr.delete(t);for(const t of e){const e=ir.get(t.stateElement),n=e.get(t.path);n.delete(t),0===n.size&&e.delete(t.path);const o=ar.get(t.indexes);o.splice(o.indexOf(t),1),0===o.length&&ar.delete(t.indexes)}}}function Tr(t){if(!nr)return;Er(t),Cr(t);const e=lr.get(t);if(void 0!==e){lr.delete(t);for(const t of e)Er(t),Cr(t),lr.delete(t)}}function Mr(t,e,n){if(!nr)return;const o=er.get(t);if(void 0!==o)for(const{stateElement:t,path:s,absAddress:r}of o){const o=Ys.get(t),i=o.byPath.get(s);mr(i,e,r),pr(i,n,r),Zs.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,e)||Object.is(a,n))&&(Bs(r),Xs().enqueueAbsoluteAddress(r,null),sr(r))}}const Or=new WeakMap,Lr=Object.freeze([]),Rr=new Set;function jr(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:Lr,s=Array.isArray(n)&&n.length>0?n:Lr,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:Lr,o=Array.isArray(e)&&e.length>0?e:Lr;let s=Or.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=js(o,t)||[],a=i.length>0?Es(i[0]):t;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Rr,deleteIndexSet:new Set(i),addIndexSet:Rr};let e=js(s,t);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=Ns(t,n,a);e.push(o)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:Rr,deleteIndexSet:Rr,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:Rr,deleteIndexSet:Rr,addIndexSet:Rr};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],u=n.get(l),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=Ns(t,o,a);e.push(n),c.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:c}}finally{void 0!==l&&(function(t,e,n){let o=Or.get(t);o||(o=new WeakMap,Or.set(t,o)),o.set(e,n)}(o,s,l),Ds(s,l.newIndexes))}}(t,e,n);!function(t,e){for(let n=0;n<t.length;n++){if(t[n].index!==n){const e=t[n].index;t[n].index=n,Mr(t[n],e,n)}Cs(t[n],e[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Lr),function(t){for(const e of t)Os.add(e)}(o.deleteIndexSet);for(const t of o.deleteIndexSet)Tr(t);return function(t){for(const e of t)Os.delete(e)}(o.newIndexes),function(t,e){if(!nr||t===e)return;const n=ar.get(t);if(void 0===n)return;ar.delete(t);const o=ar.get(e);ar.set(e,void 0===o?n:o.concat(n));for(const o of n){o.indexes=e;const n=fr(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&&!Ls(t))for(const e of o.getters){const n=Ke(o.stateElement,bn(e,t));Bs(n),Xs().enqueueAbsoluteAddress(n,null),sr(n)}}}(o.oldIndexes,o.newIndexes),o}const Dr=new WeakSet,Wr=new WeakMap;function zr(t){return Wr.get(t)??null}function Br(t,e){Wr.set(t,e)}const Fr=new WeakMap;function Hr(t){return Fr.get(t)??[]}function qr(t,e){Fr.set(t,e)}function Ur(t,e){const n=Hr(t);for(const t of n)ve(t,e)}const Vr=new WeakMap,Gr=new WeakMap;function Kr(t,e){for(let n=0;n<t.length;n++)if(e.has(t[n]))return!0;return!1}function Jr(t,e,n){Ur(t,e);const o=ys(t),s=zr(t);if(null!==s&&(s.activate(o,n.rootNode),null!==e&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(t){return Vr.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=Gr.get(t);void 0===o&&Gr.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||Kr(d.prefixes,i)){ta(u,s);continue}if(s.appliedBindingSet.has(u))continue;c||(l=s.state[Le](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?ta(u,s):(s.appliedBindingSet.add(u),Zi(u,s,f))}}(r,o,s,e,n)}for(const t of o)null===s&&dn(ln(t),t),(null===s||s.shouldApplyState(t))&&ta(t,n)}function Qr(t){if(!t.mounted)return;const e=ys(t),n=zr(t);for(let t=0;t<e.length;t++){const o=e[t];null!==n?n.disposeBinding(o):hn(ln(o),o)}!function(t){const e=Hr(t);for(let t=0;t<e.length;t++)ve(e[t],null)}(t)}const Xr=new WeakMap,Yr=Object.freeze(new Set);function Zr(t,e){const n=Xr.get(t);n?n.add(e):Xr.set(t,new Set([e]))}function ti(t){const e=Xr.get(t);return void 0!==e?e:Yr}function ei(t,e){const n=Xr.get(t);n&&(n.delete(e),0===n.size&&Xr.delete(t))}const ni=new Set(["if","elseif","else","for"]);class oi{_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];ko(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){ko(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=zr(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRow(ys(this));const e=this._childNodeArray;for(let t=0;t<e.length;t++){const n=e[t];null!==n.parentNode&&(_o(n),n.parentNode.removeChild(n))}const n=ys(this);for(let t=0;t<n.length;t++){const e=n[t];ni.has(e.bindingType)&&ti(e.node).forEach(t=>{t.tryDestroy()||t.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const t=zr(this);null!==t&&(t.isRowSession?t.disposeBindings(ys(this)):t.dispose())}this._teardownBindings()}_teardownBindings(){const t=ys(this);for(let e=0;e<t.length;e++){const n=t[e];ni.has(n.bindingType)&&ti(n.node).forEach(t=>{t.unmount()}),_n(n),cn(n)}}unmount(){{const t=zr(this);null!==t&&(t.isRowSession?t.disposeBindings(ys(this)):t.dispose())}for(const t of this._childNodeArray)null!==t.parentNode&&(_o(t),t.parentNode.removeChild(t));const t=ys(this);for(let e=0;e<t.length;e++){const n=t[e];ni.has(n.bindingType)&&ti(n.node).forEach(t=>{t.unmount()}),_n(n),cn(n)}this._mounted=!1}}function si(t){const e=document.createDocumentFragment(),n=new oi(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function ri(t){void 0!==t.uuid&&null!==t.uuid||Z("BindingInfo.uuid is null.");const n=Sa(t.uuid);n||Z(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=oe(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===S||s===_)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ut(r))return null;if("prop"===o&&Jn(r,t.propName))return null;const i=re(t);let a;try{a=zo({...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 N,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=oe(o,s[t].nodePath);null===e&&Z(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),me(e),Ht(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=ra.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new cs,ra.set(n,o)),o.initializeRow(t,e),o}(n,a,t.node),u=new oi(o);return Br(u,c),bs(u,a),function(t,e){Vr.set(t,e)}(u,n),_s(u,l),qr(u,r),Zr(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=oe(t,s.nodePath);if(null===e&&Z(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),he.has(e))continue;const r=fe(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new cs;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new oi(i,s);Br(l,a.bindingSession),bs(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in N&&c.push(t);return _s(l,c),qr(l,a.nodes),Zr(t.node,l),l}const ii=new WeakSet,ai=Symbol.for("wcstack.state.view-transition-naming");function li(){const t=Hs("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function ci(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||ii.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[ai]??={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.`)):(ii.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 ui=new WeakMap,di=new WeakMap,hi=new WeakMap,fi=new WeakMap;function pi(t,e,n){!function(t,e,n){let o=di.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,di.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function mi(t,e){ui.set(t,e)}function gi(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 yi(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 bi=new Set(["if","elseif","else","for"]);function wi(t,e){for(const n of ys(t))if(e.appliedBindingSet.delete(n),bi.has(n.bindingType))for(const t of ti(n.node))wi(t,e)}function vi(t){for(const e of ys(t)){if(!bi.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of ti(e.node))vi(n),t&&n.mounted&&(Qr(n),n.unmount(),ei(e.node,n))}}function _i(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function $i(t,n,s){const r=Boolean(s);let i;const a=ti(t.node);i=0===a.size?ri(t):a.values().next().value;const l=e(),c=t.uuid??"",u=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${_i(t)}`),Qr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${_i(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);Jr(i,we(t.node),n);const e=li();null!==e&&ci(i,"branch",e)}}const Si=new WeakMap;function xi(t){return Si.get(t)??[]}const Pi=new Set;function ki(){Pi.clear()}const Ii=Symbol.for("wcstack.trustedTypes.policy");function Ni(){const t=globalThis[Ii];return null===t||"object"!=typeof t?null:t}let Ai,Ei=!1;const Ci={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 Ti(t,n,s){if(1===t.propSegments.length){const e=t.propSegments[0];"textContent"===e||"innerText"===e?s=null==s?"":String(s):void 0===s&&"innerHTML"===e&&(s="")}if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0],u=r[c];if(u!==s){null!==hs&&null!==u&&"object"==typeof u&&null!==s&&"object"==typeof s&&null!==Ut(r)&&hs.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=Ni(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(Ei)return;if(!function(){if(void 0!==Ai)return Ai;if(!("trustedTypes"in globalThis))return Ai=!1,Ai;try{document.createElement("div").innerHTML="<i></i>",Ai=!1}catch{Ai=!0}return Ai}())return;Ei=!0;const n="function"==typeof Ni()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${e}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:t,property:e})}(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=Ut(t);if(null===n)return null;const o=Gt(t)?.get(n);if(void 0===o)return null;const s=Jt(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&Jn(r,c)){const e=to(r,c,t.statePathName),o=eo(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??io()??oo(e);if(a.visitedEdges.has(o))null!==_e&&_e({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=so(a,o);ao(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Yn++,writtenValue:n};lo.push({receipt:i,node:t});try{return r()}finally{lo.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=Ci[c];t?t(r,s):(function(t,e,n){let o=Si.get(t);o||(o=[],Si.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,s),a=r,Pi.add(a))}return}var a,l;const c=i[0];let u=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==u)return;u=u[e]}const d=i[i.length-1],h=u[d];if(h!==s){if(Object.isFrozen(u))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:s}));null!==hs&&2===i.length&&"object"==typeof u&&null!==u&&null!==Ut(r)&&(d in u?hs.rememberOverwrittenValue(r,c,d,u[d]):hs.recordInjectedKey(r,c,d));try{u[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:s,error:t})}}}const Mi=new WeakSet;function Oi(t,e,n){}function Li(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function Ri(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),s=e.length>0?e+a:"";for(const t of n){if(s.length>0&&!t.startsWith(s))continue;const e=t.slice(s.length);e.length>0&&-1===e.indexOf(a)&&o.push(e)}return o}const ji={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Di={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Wi(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${it}`}function zi(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 Bi(t,e){return`$setAll("${t}") ${e}`}function Fi(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${it}`}const Hi=new WeakSet;function qi(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Ui=Object.freeze({[x]:function(t,e,n){const o=t.node,s=t.propSegments[1];null!=n?("boolean"!=typeof n&&Z(`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){Rn(n)||Z("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ms.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||Z('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Ut(t);if(null===e)return null;const n=Gt(t)?.get(e);return void 0===n&&Z(`Custom element <${e}> is not defined for command binding.`),Jt(t)}(r);null===a&&Z(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||Z(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${rt(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ms.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 ms.delete(t);const o=n[i];return"function"!=typeof o&&Z(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),ms.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Vi={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Mi.has(t.replaceNode)){Mi.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,r=sn(t),i=ln(t),a=Se(i),c=a.length>0&&!di.has(t.node)?[]:a,u=jr(r,c,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let d=di.get(t.node);const h=void 0!==d?function(t,e,n){if(o=e,!Dr.has(o))return null;var o;let s=null;for(let e=0;e<n.newIndexes.length;e++){const o=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?t.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}(d,c,u):null,f=Array.isArray(c)&&c.length===u.deleteIndexSet.size&&u.deleteIndexSet.size>0;if(f&&null===h&&null!==t.node.parentNode){let e=fi.get(t.node);if(void 0===e){const n=ui.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(gi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(gi(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n),fi.set(t.node,e)}if(e){const e=t.node.parentNode;!function(t,e){So.set(t,(So.get(t)??0)+e)}(e,e.childNodes.length),e.textContent="",e.appendChild(t.node)}}let p=f?1e3-function(t){return hi.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==d){const e=d;u.deleteIndexSet.forEach(n=>{const o=e.get(n);void 0!==o&&(null!==h&&h.reused.has(o)?(Qr(o),vi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?ei(t.node,o):(Qr(o),o.unmount(),function(t,e){let n=hi.get(t.node);void 0===n&&(n=[],hi.set(t.node,n)),n.length<1e3?n.push(e):ei(t.node,e)}(t,o),p-=1),f||e.delete(n))}),f&&(di.delete(t.node),d=void 0)}let m=t.node;const g=nt(s.path+"."+l),y=n.stateElement.loopContextStack,b=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const t of i)a.add(n[t]);return a}(u);let w=null;u.newIndexes.length==u.addIndexSet.size&&u.newIndexes.length>0&&m.isConnected&&null===h&&(w=document.createDocumentFragment(),Xe(w,n.rootNode));const v=e(),_=li(),$=t.uuid??"",S=hi.get(t.node);for(const e of u.newIndexes){let o;if(u.addIndexSet.has(e)){const r=bn(g,e);if(y.createLoopContext(r,r=>{if(o=h?.byAddedIndex.get(e)??(void 0!==S?S.pop():void 0),void 0===o?o=ri(t):wi(o,n),null!==w)v&&w.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`)),o.appendTo(w),v&&w.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const t=document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`);m.parentNode.insertBefore(t,m.nextSibling),m=t}o.mountAfter(m)}if(v){const t=document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`),n=o.lastNode??m;n.parentNode.insertBefore(t,n.nextSibling)}}Jr(o,r,n),null!==_&&ci(o,"row",_)}),void 0===o&&Z(`Content not found for ListIndex: ${e.index} at path "${s.path}"`),null!==h&&h.reused.has(o)){const t=n.stateElement.addressHooks;if(t){const e=t.rowReused;for(let t=0;t<e.length;t++)e[t](n.stateElement,o)}}}else{if(o=void 0!==d?d.get(e)??null:null,u.changeIndexSet.has(e)){const t=vs(o);for(const e of t)ta(e,n)}null===o&&Z(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==b&&b.has(e)&&yi(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),t){const t=o,s=bn(g,e);y.createLoopContext(s,e=>{Jr(t,e,n)})}}m=o.lastNode||m,void 0===d&&(d=new WeakMap,di.set(t.node,d)),d.set(e,o)}ui.set(t.node,m),null!==w&&(t.node.parentNode.insertBefore(w,t.node.nextSibling),Xe(w,null))},if:$i,else:$i,elseif:$i,radio:function(t,e,n){const o=t.node,s=fs(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=fs(o.value,t.inFilters),r=Array.isArray(n)?n:ps;o.checked=r.includes(s)}},Gi=new WeakMap,Ki=new WeakMap,Ji=new WeakMap;function Qi(){}function Xi(t){const e=hs;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return Oi;if(e.isDeclared(n,o))return Qi}return Ti}function Yi(t,e){Zi(t,e,function(t,e){const n=vn(e);if(n.pathInfo.path in N){const t=we(e.node);return null===t&&Z(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&Z("ListIndex not found for loopContext:");const n=N[e];void 0===n&&Z(`Invalid index name: ${e}`);const o=en(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&Z(Fi(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Le](n)}(e.state,t))}function Zi(t,e,n){const o=fs(n,t.outFilters);if(!0===Ki.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=Gi.get(t);if(void 0===s){if(Gi.has(t))return s=Xi(t),s===Oi&&Gi.set(t,s),void s(t,e,o);if(s=Vi[t.bindingType],void 0===s){const e=t.propSegments[0];s=Ui[e],Gi.set(t,s),void 0===s&&(Ut(t.replaceNode)?(s=Xi(t),s===Oi&&Gi.set(t,s)):(s=Ti,Gi.set(t,s)))}if(s===Ti&&"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 Ki.set(t,!0)}s(t,e,o)}else s(t,e,o)}function ta(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=ln(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=ds(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Ji.get(t)){const e=Ut(t.replaceNode);if(e&&void 0===Gt(t.replaceNode)?.get(e))return void function(t,e){if(Hi.has(t))return;Hi.add(t);const n=()=>{Hi.delete(t);const e=ds(t);(null===e||e.shouldApplyState(t))&&na([t])},o=n=>{Hi.delete(t),qi(e,n)},s=ds(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Hi.delete(t),r()})||(Hi.delete(t),r()))}const r=Gt(t.replaceNode);if(null===r)return Hi.delete(t),void qi(e,new Error("CustomElementRegistry is unavailable."));Mo(r).wait(e,()=>{t.replaceNode.isConnected?n():Hi.delete(t)},o)}(t,e);Ji.set(t,!0)}if(!0===e.sameRootVerified)return void Yi(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Ye(o),null===o&&Z("Root node for fragment not found for binding.")),o!==e.rootNode){const n=ga(o);null===n&&Z("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};Yi(t,r)})}else Yi(t,e)}function ea(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!==_e&&_e({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function na(t,e,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<t.length;){let n=t[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=Ye(u),null===u&&Z("Root node for fragment not found for binding."));const d=ga(u);null===d&&Z("No state tree found on this root for binding."),d.createState("readonly",o=>{const h={rootNode:u,stateElement:d,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{ta(n,h)}catch(t){ea(n,t,d,c)}s++;const e=t[s];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{Ti(t,{propagationContextByBinding:e},n)}catch(e){ea(t,e,o??null,c)}for(const[t,e]of i.entries())xe(t,e),Ee(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[We](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[ze](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 oa(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=ge(o);0!==t.length&&(ve(o.node,e),na(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}function sa(t,e,n){const[o,s,r]=pe(t,n),i=us(t);for(const t of o)ve(t,e);na(i.initialize(s)),oa(r,e,i)}const ra=new WeakMap;async function ia(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Gt(t);null===s&&Z(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(le(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function aa(t){if(t===document)await ia(document),X(document),Fa(document,document),sa(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await Ft(e.host),await ia(e),X(e),Fa(e,e),sa(e,null)}}const la={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function ca(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${la[t]??t}" before the state is defined.`}let ua=null;function da(t){return null===ua&&Z(ca("ssr",t)),ua}const ha=new WeakMap,fa=new WeakMap,pa=new Set,ma=[];function ga(t){return ha.get(t)??null}function ya(t){return fa.get(t)??Promise.resolve()}const ba=new WeakSet;function wa(t){ba.add(t)}function va(t,n){const s=ha.get(t);if(null===n){if(void 0===s)return;ha.delete(t),pa.delete(s),null!==_e&&_e({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{o&&await da('the "enable-ssr" attribute').hydrate(t)||await aa(t),wa(t),Ka(),e()}catch(t){n(t)}})});fa.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await aa(t),wa(t),Ka(),e()}catch(t){n(t)}})});fa.set(t,e)}}void 0!==s&&Z('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),ha.set(t,n),pa.add(n);for(let e=0;e<ma.length;e++)ma[e](t,n);null!==_e&&_e({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}const _a=new Map;function $a(t,e,n){if(null===n)_a.delete(t);else{_a.set(t,n);const o=ga(e);null===o&&Z("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function Sa(t){return _a.get(t)||null}function xa(t){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=Mt(e.getAttribute(o.bindAttributeName)||"");if(e.localName===o.tagNames.state){if(e.hasAttribute("mount"))return n.filter(t=>t.propSegments[0]!==$);const t=n.find(t=>t.propSegments[0]===$);if(void 0!==t){const e=`on a volume element — a <${o.tagNames.state}> with a "mount" attribute`;Z(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 ("${$}.<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=jt(t);null===e&&Z("Comment node binding text not found.");const n=Sa(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Dt(e),s=null):s=e,[{...o,uuid:s}]}return[]}let Pa;function ka(){return Pa??={filterName:"not",args:[]}}const Ia=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Na(t,e){const n=e+a+l,o=xt(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+a+s.slice(1)}return r.length>0?s+r:s}function Aa(t,e){const n=Ia.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+Na(s,e)+r}function Ea(t,e){const n=Pt(t,";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=xt(n,":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Na(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function Ca(t,e){return Ea(t,e)}function Ta(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=Aa(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=Ea(r,e);t!==r&&o.setAttribute(n,t)}}}function Ma(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 Oa=new WeakMap;function La(t){return Oa.get(t)??null}function Ra(t){const e=[],n=de(t);for(const t of n){const n=xa(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");Oa.set(e,t.data),t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:Ma(o),parseBindTextResults:n})}return e}function ja(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const Da=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Wa=ka();function za(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Wa],bindingType:t}}function Ba(t,e,n,o,s,r=!0){ja(e),"string"==typeof o&&Ta(e,o),Fa(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ra(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 Fa(t,e,n,s){const r=o.commentElsePrefix,i=ce(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],u=[];for(;a.nextNode();){const t=a.currentNode;u.push(t)}for(const e of u){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=Ca(i,n));let a=Mt(i)[0];const u=Da.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=Ss();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&Z("'else' binding found without preceding 'if' or 'elseif' binding."),a=za("else",l.parseBindTextResult),p=Ba(t,h,a,m,s,!1),$a(f,t,p);const n=c.at(-1),o=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Ma(o),parseBindTextResults:xa(o)})):e.replaceWith(o)}else if("elseif"===d){null===l&&Z("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ba(t,h,a,m,s),$a(f,t,p);const n=document.createComment(`@@${u}:${f}`),o=Ss(),i={fragment:document.createDocumentFragment(),parseBindTextResult:za("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Ma(n),parseBindTextResults:xa(n)}),$a(o,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:Ma(g),parseBindTextResults:xa(g)})):e.replaceWith(g)}else{p=Ba(t,h,a,m,s),$a(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 Ha=()=>`[${o.bindAttributeName}]`;function qa(t){if(Xo(t))return!0;if(!Ua(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(Ha());return null!==e&&Xo(e)}function Ua(t){return 1===t.nodeType}function Va(t){if(qa(t))return;X(t),Fa(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);sa(e&&s?n:t,null)}const Ga=[];function Ka(){const t=Ga.splice(0,Ga.length);for(const e of t)Va(e);!function(){const t=function(){const t=globalThis[s];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[r];return void 0===e&&(e=[],t[r]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[i];return void 0===e&&(e=new WeakSet,t[i]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const Ja={protocol:"wcs-binder",version:1,bind:function(t){var e;Ua(t)&&!qa(t)&&(e=t.getRootNode(),ba.has(e)?Va(t):Ga.push(t))}},Qa="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Xa=0;async function Ya(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++Xa}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${Qa}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${Qa}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Za(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){Z(`Failed to load script file: ${t}`)}}class tl{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&Z("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=u&&Z("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&Z("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&Z("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&Z(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const el={$updatedCallback:C,$streams:z},nl=new WeakSet;function ol(t,e){let n=t;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,e);)n=Object.getPrototypeOf(n);return n}function sl(t){if((null===t||"object"!=typeof t&&"function"!=typeof t)&&Z(`The state must be an object, got ${null===t?"null":typeof t}. Check the source of the state element (json / src / the inline <script>).`),!nl.has(t)){for(const e of Object.keys(el)){if(!(e in t))continue;const n=el[e];n in t&&Z(`[wcs/declaration-alias] The state declares both "${e}" and "${n}". "${e}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${it}`),Object.isExtensible(t)||Z(`[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).${it}`);const o=ol(t,e),s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,n,{...s,configurable:!0}),o===t&&delete t[e]}nl.add(t)}}const rl=new WeakMap;function il(t,e){let n=rl.get(t);void 0===n&&(n=new Map,rl.set(t,n));let o=n.get(e);return void 0===o&&(o=new Ln(e,t),n.set(e,o)),o}const al=new WeakMap;function ll(t){const e=al.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 il(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:il(t,n)}},set(){Z("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){Z("$command namespace is read-only; deleting from it is not allowed.")}});return al.set(t,n),n}const cl=Symbol("wcs.notHandled"),ul=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],dl=new Map;function hl(t,e){dl.set(t,e)}const fl=new Map;let pl=[],ml=[];function gl(t,e){fl.set(t,e),pl=Array.from(fl.values()).sort((t,e)=>t.order-e.order),ml=pl.slice().reverse()}function yl(t){return fl.has(t)}function bl(t,e){for(let n=0;n<pl.length;n++)pl[n].activate?.(t,e)}function wl(t){"readonly"===t.mutability&&Z("This state is readonly.")}const vl=new Map;class _l{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=nt(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function $l(t){let e;return vl.get(t)??(vl.set(t,e=new _l(t)),e)}function Sl(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:en(n.listIndex,o,n.pathInfo.wildcardCount)}function xl(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=tn(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?en(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?en(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}function Pl(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function kl(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!==cl)return a}}return cl}function Il(t,e,n,o,s){if(e.pathInfo.segments[0]===j)return function(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}(ll(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){if(null===e.parentAddress){const r=kl(s,e,null,n,o);if(r!==cl)return r;Z(function(t,e,n){return`[${ji.binding}] Path "${t}" does not exist on the state tree.${rt(t,Ri(e,"",n))}${it}`}(e.pathInfo.path,t,s.getterPaths))}const r=Nl(t,e.parentAddress,n,o);if(null==r)return;const i=e.pathInfo.segments[e.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==l&&!(i in Object(r))){const t=kl(s,e,Object(r),n,o);if(t!==cl)return t}if(i===l){const t=e.listIndex?.index??Z(Fi(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(r,t)}return Reflect.get(r,i)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}function Nl(t,e,n,o){xl(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!==cl)return i}}return Pl(s,e)?function(t,e,n,o,s){const r=Ke(s,e),i=function(t){return Ws.get(t)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Il(t,e,n,o,s);return zs(r,{value:l,dirty:!1,generation:a}),l}(t,e,n,o,s):Il(t,e,n,o,s)}function Al(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=bn(h,r),p=Ke(n.stateElement,f),m=Ae(p),g=Nl(t,f,e,n),y=jr(r,m,g).newIndexes,b=l[c]??null;if(i.set(p,g),null===b)for(let t=0;t<y.length;t++){const e=y[t];a(o,s+1,e,l,c+1,u.concat(e.index),d)}else{const t=y[b]??Z(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,u.concat(t.index),d):d.push(u.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Ee(t,Array.isArray(e)?e:[]);return l}function El(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=js(Nl(t,bn(a,r),e,n),r);null==l&&Z(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??Z(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Cl(t,e,n,o){"object"==typeof t&&null!==t||Z(`${U} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&Z(`${U} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Tl(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&Z(`${U} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Ml(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];Cl(a,n,o,i);const l=Tl(a,e,n,o,i);r.has(l)&&Z(`${U} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Ol(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 Ll(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const r=Nl(t,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=e.pathInfo.lastSegment;if(i===l){const t=e.listIndex?.index;return"number"==typeof t&&t in r}return i in r}const Rl=new WeakMap;function jl(t,e){null===e?Rl.delete(t):Rl.set(t,e)}function Dl(t,e,n){const s=bn(nt(t.wildcardParentPaths[e]),n),r=Ke(t.stateElement,s),i=Ae(r),a=t.stateProxy[Le](s),l=jr(s.listIndex,i,a);t.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(l,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)Dl(t,e+1,n)}const Wl=[];function zl(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:Wl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Wl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Bl=[];function Fl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Bl;let s=null;const r=e+a;for(const t of o){if(t!==e&&!t.startsWith(r))continue;const o=nt(t);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Bl}function Hl(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,ql(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}function ql(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const r of s){const s=nt(r);if(t.listPathSet.has(o)&&s.lastSegment===l){const i=t.stateProxy[Le](e),a=Ke(t.stateElement,e),l=Ae(a),c=jr(e.listIndex,l,i);t.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const u=zl(t,o,0,0,c);for(const e of u.fullRows){const o=bn(s,e);t.result.add(o),n.push(o)}if(null!==u.movedRows){const e=Fl(t,r,s);if(null===e)for(const e of u.movedRows){const o=bn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of u.movedRows)for(const s of e){const e=bn(s,o);t.result.add(e),n.push(e)}}}else{const o=bn(s,e.listIndex);t.result.add(o),n.push(o)}}const r=t.dynamicMap.get(o);if(r)for(const o of r){const s=nt(o),r=[];if(s.wildcardCount>0){const n=tn(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=en(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Dl(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=en(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=bn(s,e);t.result.add(o),n.push(o)}}}function Ul(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&Z(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),d={ranks:u,stateElement:t,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};Hl(d,e,a),function(t,e){for(let n=0;n<1e3;n++){const n=rr(t.stateElement);if(null===n)return;n.forEach(n=>{Hl(t,bn(n.absolutePathInfo.pathInfo,n.listIndex),e)})}}(d,a);for(const[t,e]of d.observedListValueByAbsAddress)Ee(t,e);return Array.from(d.result)}function Vl(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 Gl(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 Kl(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 Jl(t,e,n,o,s,r){const i=_r(t,e),a=Pr(t,e);if(!i&&!a)return null;const l=[],c=Xl(l);return i&&xr(t,e,n,o,s).forEach(c),a&&Ir(t,e,n?o:r(),s).forEach(c),l}function Ql(){return o.enablePropagationContext?io()??null:null}function Xl(t){const e=Xs(),n=Ql();return o=>{Bs(o),e.enqueueAbsoluteAddress(o,n),t.push(o)}}function Yl(t,e,n){if(null===t||0===t.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=Xs(),a=Ql();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=bn(l.pathInfo,t[n].listIndex);Ul(o,u,s,r,o.listPaths,e,"new",t=>{if(t===u)return;const e=Ke(o,t);Bs(e),i.enqueueAbsoluteAddress(e,a)},{listExpansion:"diff"})}}function Zl(t,e,n,s,r,i,a="diff"){const l=o.enablePropagationContext?io()??oo(-1):null,c=Xs();c.enqueueAbsoluteAddress(e,l),i&&Bs(e),Ul(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=Ke(s.stateElement,e);Bs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function tc(t,e,n,o,s){s&&(t.getterPaths.has(e)?Bs(n):zs(n,{value:o,dirty:!1,generation:t.stateGeneration}))}function ec(t,e,n,o,s,r,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const i=Nl(t,n,s,r),a=e.pathInfo.segments[e.pathInfo.segments.length-1];if(a===l){const t=e.listIndex?.index??Z(Fi(`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{Zl(e,n,s,r,i,a)}}function nc(t,e,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(e.pathInfo.path);if(void 0!==i){const r=Nl(t,e,o,s),c=function(t,e,n,o){const s=Ml(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Ml(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,i,r,n);if(null!==c)return function(t,e,n,o,s,r){const i=e.pathInfo.path,c=e.listIndex;null===Rs(o)&&jr(c,null,o);const u=jr(c,o,n.list),d=oc(t,e,n.list,s,r,i),h=nt(i+a+l);for(const e of n.matched){const n=Ol(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const i of n)void 0!==o?nc(t,bn(nt(h.path+a+i.field),o),i.value,s,r):e.oldRow[i.field]=i.value}return d}(t,e,c,r,o,s)}}return oc(t,e,n,o,s,null)}function oc(t,e,n,s,r,i){const c=r.stateElement,u=e.pathInfo.path,d=c.addressHooks;if(d){const t=d.write;for(let o=0;o<t.length;o++){const i=t[o](c,e,n,s,r);if(i!==cl)return i}}const h=!!co&&(co=!1,!0);if(!(u in t)&&null!==e.parentAddress&&!c.elementPaths.has(u)){const a=Nl(t,e.parentAddress,s,r);if("object"==typeof a&&null!==a){const t=e.pathInfo.lastSegment,f=t===l?e.listIndex?.index:t;let p,m=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==f&&f in a,e=void 0!==f?a[f]:void 0;if(t&&Object.is(e,n))return!0;p=e,m=!0}const g=Jl(c,u,m,p,n,()=>a[f]),y=Pl(c,e),b=Ke(c,e);null!==_e&&_e({type:"state:write",absoluteAddress:b,value:n,oldValue:p,hasOldValue:m}),Vl(c,u,b,p,m);let w=!1;try{if(void 0===f&&Z(Fi(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),d&&0!==d.writeMissing.length&&t!==l&&!(f in a)){const t=d.writeMissing;for(let o=0;o<t.length;o++){w=!0;const i=t[o](c,e,a,f,n,s,r);if(i!==cl)return i;w=!1}}return Reflect.set(a,f,n)}finally{Zl(e,b,s,r,i,y),Yl(g,s,r),w?Bs(b):tc(c,u,b,n,y),Gl(c,e.pathInfo,{value:n})}}}let f,p=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Nl(t,e,s,r);if(Ll(t,e,s,r)&&Object.is(o,n))return!0;f=o,p=!0}const m=Jl(c,u,p,f,n,()=>Nl(t,e,s,r)),g=c.elementPaths.has(e.pathInfo.path),y=Pl(c,e),b=Ke(c,e);null!==_e&&_e({type:"state:write",absoluteAddress:b,value:n,oldValue:f,hasOldValue:p}),Vl(c,u,b,f,p);try{return g?function(t,e,n,o,s,r,i,c){const u=e.parentAddress??Z(`address.parentAddress is undefined path: ${e.pathInfo.path}`),d=Nl(t,u,s,r)??[];let h=(f=d,Rl.get(f)??null);var f;if(null===h){const t=Rs(d)??[];h={value:[...d],listIndexes:[...t]},jl(d,h)}try{return ec(t,e,n,o,s,r,i,c)}finally{const n=h.value.indexOf(o),i=Nl(t,u,s,r)??[],c=Array.isArray(i)?Rs(i)??[]:[],f=e.listIndex.index,p=-1!==n?h.listIndexes[n]:Ns(u.listIndex,-1);if(c[f]=p,new Set(i).size===h.value.length){for(let t=0;t<c.length;t++)c[t].index=t;jl(d,null),function(t,e,n,o,s,r){const i=r.stateElement,c=Xs(),u=Ke(i,t);Se(u)===n&&(Ds(e.value,e.listIndexes),xe(u,e.value),function(t){Dr.add(t)}(e.value)),c.enqueueRenderOnlyAddress(u);const d=new Map;e.listIndexes.forEach((t,e)=>d.set(t,e));const h=nt(t.pathInfo.path+a+l);for(let t=0;t<o.length;t++){const n=o[t],a=d.get(n);if(a===t)continue;const l=bn(h,n),u=Ke(i,l);if(void 0===a){const n=Je(i,h,e.listIndexes[t]??null);Kl(i,u,n),Zl(l,u,s,r,null,Pl(i,l),"full");continue}Ul(i,l,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",t=>{const e=Ke(i,t);Bs(e),c.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}}(u,h,i,c,s,r)}}}(t,e,b,n,s,r,i,y):ec(t,e,b,n,s,r,i,y)}finally{Yl(m,s,r),g||tc(c,u,b,n,y),Gl(c,e.pathInfo,{value:n})}}function sc(t,e,n,o){return(e,s,...r)=>{Array.isArray(s)||Z(`$resolve("${e}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&Z(`$resolve("${e}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=nt(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&Z(Wi("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=bn(i,El(t,n,o,i,s));if(0===r.length)return Nl(t,a,n,o);wl(o),nc(t,a,r[0],n,o)}}function rc(t,e,n,o){const s=sc(t,0,n,o);return(e,r)=>{const i=nt(e);if(void 0===r||Array.isArray(r)||Z(`$getAll("${e}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&Z(Wi("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Sl(o,i.wildcardPaths[t]);if(e){r=nn(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&Z(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(e,t.pathInfo.path)),r=[]}}const a=Al(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 ic(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Sl(o,s.wildcardPaths.at(-1)??Z(`lastWildcardPath is null: ${e.pathInfo.path}`))??Z(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??Z(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=js(Nl(t,bn(i,s),n,o),s)??Z(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??Z(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??Z(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":Z(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function ac(t,e,n,o){return(e,s,r,i)=>{wl(o);const a=nt(e);Array.isArray(s)||Z(Bi(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&Z(Wi("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&Z(Bi(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&Z(Bi(e,"requires an array as the value when { spread: true } is set."));const u=Al(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&Z(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,u.length,r.length));const d=[];for(let e=0;e<u.length;e++){const s=El(t,n,o,a,u[e]);d.push(bn(a,s))}let h=0;for(let e=0;e<d.length;e++){const s=d[e];let i;i=c?r(Nl(t,s,n,o),...u[e]):l?r[e]:r,void 0!==i&&(nc(t,s,i,n,o),h++)}return h}}function lc(t,e){const n=t.getterPaths;if(0===n.size)return!1;for(const t of nt(e).cumulativePaths)if(n.has(t))return!0;return!1}const cc=/^\$\d+$/,uc=`${V}${a}`,dc=`${G}${a}`,hc=new WeakMap;function fc(t,e,n,o){const s=N[e];if(void 0===s&&"string"==typeof e&&36===e.charCodeAt(0)&&cc.test(e)&&Z(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&Z(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&Z(`ListIndex not found: ${e.toString()}`);let i=s;const a=t.pathInfo,l=o.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let n=0;n<e.length;n++)i+=e[n](o,t)}const c=en(r,i,a.wildcardCount);return c?.index??Z(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,e,n,t);if(i!==cl)return i}}if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>rc(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>ac(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=$l(e),i=ic(t,r,n,o),a=bn(r.pathInfo,i),l=Ke(s,a),c=Xs();c.enqueueAbsoluteAddress(l),function(t,e,n,o,s){const r=_r(t,e),i=Pr(t,e);if(!r&&!i)return;const a=n(),l=[],c=Xl(l);r&&xr(t,e,!1,void 0,a).forEach(c),i&&Ir(t,e,void 0,a,!1).forEach(c),Yl(l,o,s)}(s,r.pathInfo.path,()=>Nl(t,a,n,o),n,o),Ul(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Ke(s,t);Bs(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)=>sc(t,0,n,o)(e,s,...r);case"$dependOn":case"$trackDependency":return t=>function(t,e,n,o){return t=>{-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] ${String(e)}("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&Z(`No active state reference to track dependency for path "${t}".`);const n=o.lastAddressStack?.pathInfo??Z("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==t&&s.addDynamicDependency(t,n.path)}}(0,e,0,o)(t);case"$eq":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(lc(o.stateElement,t))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&vr(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)&&wr(o.stateElement,t,e,Ke(o.stateElement,s),r),Object.is(r,e)};case"$eqPath":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=lc(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?vr(o.stateElement,t):wr(o.stateElement,t,i,Ke(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(t,e=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||Z(`$eqIndex("${t}") needs a list row scope.`);const r=en(s.listIndex,e-1,s.pathInfo.wildcardCount);if(null===r&&Z(`$eqIndex("${t}", ${e}): no list index at that level.`),lc(o.stateElement,t))return o.stateElement.getterPaths.has(s.pathInfo.path)&&vr(o.stateElement,t),Object.is(n[t],r.index);const i=e===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[t],i&&(l=n[s.pathInfo.wildcardParentPaths[e-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const e=i?Rs(l):null;null!==e?function(t,e,n,o,s){nr=!0,fr(t).lastValue.set(e,s),hr(t,e);let r=ir.get(t);void 0===r&&ir.set(t,r=new Map);let i=r.get(e);void 0===i&&r.set(e,i=new Set);let a,l=ar.get(o);if(void 0===l?ar.set(o,l=[]):a=l.find(n=>n.stateElement===t&&n.path===e),void 0===a){a={stateElement:t,path:e,indexes:o,getters:new Set},l.push(a),i.add(a);const n=o[0]?.parentListIndex??null;if(null!==n){let t=cr.get(n);void 0===t&&cr.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){nr=!0;const r=fr(t);hr(t,e),br(r,e,s,o,gr(r,e,n.index,o),{stateElement:t,path:e,absAddress:o,levelListIndex:n})}(o.stateElement,t,r,Ke(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untracked":case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case j:return ll(o.stateElement)}if(!e.startsWith(uc)&&!e.startsWith(dc))return}const r=$l(e),i=ic(t,r,n,o),a=bn(r.pathInfo,i);return Nl(t,a,n,o)}if("symbol"==typeof e){const s=function(t){let e=hc.get(t);return void 0===e&&(e=new Map,hc.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case Oe:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&Z("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case Le:i=e=>Nl(t,e,n,o);break;case Re:i=e=>Ll(t,e,n,o);break;case je:i=()=>async function(t,e,n){const o=Reflect.get(t,A);"function"==typeof o&&await o.call(n)}(t,0,n);break;case De:i=()=>function(t,e,n){const o=Reflect.get(t,E);"function"==typeof o&&o.call(n)}(t,0,n);break;case We:i=e=>function(t,e,n,o){const s=Reflect.get(t,C);let r;if("function"==typeof s){const t=new Set,i={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,s=e.path;if(-1===s.indexOf("#")&&(t.add(s),e.wildcardCount>0)){const t=nn(n.listIndex,e.wildcardCount),o=i[s];void 0===o?i[s]=[t]:o.push(t)}}r=s.call(n,Array.from(t),i)}const i=o.stateElement?.addressHooks;if(i){const t=i.updated;for(let s=0;s<t.length;s++)t[s](o.stateElement,e,n)}return r}(t,e,n,o);break;case ze: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 pc{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=ga(t);null===n&&Z("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&Z("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&Z(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),Z(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const n=this._addressStack[e];if(n){if(t.has(n))return!0;t.add(n)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&Z(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return fc(t,e,n,this)}set(t,e,n,o){return wl(this),function(t,e,n,o,s){if("string"==typeof e){const r=$l(e),i=ic(t,r,o,s);return nc(t,bn(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 wl(this),Reflect.deleteProperty(t,e)}defineProperty(t,e,n){return wl(this),Reflect.defineProperty(t,e,n)}}const mc=Promise.resolve(),gc=new Map;let yc=[];function bc(t,e){gc.set(t,e),yc=Array.from(gc.values()).sort((t,e)=>t.order-e.order)}function wc(t,e){return Z(ca(t,e))}const vc="undefined"==typeof HTMLElement?class{}:HTMLElement;function _c(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 $c=null;const Sc=new Set(["for","if","elseif","else"]);const xc=[[B,"watch"],[F,"scan"],[z,"streams"],[H,"recursion"]];class Pc extends vc{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return ya(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 tl}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&Z(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){sl(t),function(t){for(let e=0;e<xc.length;e++){const[n,o]=xc[e];n in t&&!yl(o)&&Z(ca(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<pl.length;o++)pl[o].validateEarly?.(t,e,n)}(this,t,n);const o=function(t){const e=new Set,n=t[R];if(void 0===n)return e;Array.isArray(n)||Z(`${R} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Z(`${R} entries must be non-empty strings.`),t===j&&Z(`${R} entry "${t}" conflicts with the reserved namespace name "${j}".`),e.has(t)&&Z(`${R} entry "${t}" is duplicated.`),e.add(t);return e}(t),s=function(t){const e=new Set,n=t[D];if(void 0===n)return e;Array.isArray(n)||Z(`${D} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Z(`${D} entries must be non-empty strings.`),e.has(t)&&Z(`${D} entry "${t}" is duplicated.`),e.add(t);return e}(t),r=function(t){const e=t[U];if(void 0===e)return null;"object"==typeof e&&null!==e||Z(`${U} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&Z(`${U} entry path must be a non-empty string.`);const e=t.split(a);e.some(t=>0===t.length)&&Z(`${U} entry "${t}" must not contain empty path segments.`),e[e.length-1]===l&&Z(`${U} entry "${t}" must be the list path itself, not the element path (drop the trailing "${a}${l}").`),-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] ${U} entry "${t}" uses "${q}", which ${U} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${a}${l}${a}children").`),"function"!=typeof o?("string"!=typeof o&&Z(`${U} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&Z(`${U} entry "${t}" key field name must be a non-empty string.`),(o.includes(a)||o.includes(l))&&Z(`${U} entry "${t}" key field name "${o}" must be a flat property name ("${a}" / "${l}" are not allowed).`),o in Object.prototype&&Z(`${U} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t);n.set("eventTokenNames",s),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].validate?.(t,e,n)}(this,t,n),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].preCommit?.(t,e,n)}(this,t,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=t,void 0!==e&&$c?.reset(this),this._hasUpdatedCallback=C in t,this._hasErrorCallback=T in t,Tn.delete(this),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].applyEarly?.(t,e,n)}(this,t,n),function(t,e,n){const o=e[W];if(void 0!==o){"object"==typeof o&&null!==o||Z(`${W} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||Z(`${W} entry "${e}" is not declared in $eventTokens.${rt(e,n)}`),"function"!=typeof s&&Z(`${W} entry "${e}" must be a function.`),Mn(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=_c(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<pl.length;o++)pl[o].apply?.(t,e,n)}(this,t,n),this._listKeys=r,this._rebuildPathInfo(),function(t,e,n){for(let o=0;o<pl.length;o++)pl[o].register?.(t,e,n)}(this,t,n),bl(this,null),this._resolveLoading?.()}attributeChangedCallback(t,e,n){this._initialized&&e!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===e?"absent":`"${e}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?da('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){Z("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await Ya(t,o.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||Z(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await Za(t);Z(`Unsupported src file type: ${t}`)}}catch(t){Z(`Failed to initialize state: ${t}`)}}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}return await this._loadingPromise,null!==this._rootNode&&(va(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),Z(t)}_failInitializeLoudly(t,e=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),e&&null!==this._rootNode&&null===ga(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),fa.set(t,n)}(this._rootNode,t),function(t,e,n){for(let o=0;o<yc.length;o++)yc[o].initializeFailed?.(t,e,n)}(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{A in t&&await t[je]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{E in t&&t[De]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(t){for(let e=0;e<yc.length;e++)if(!0===yc[e].reconnecting?.(t))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||ga(this._rootNode)===this||va(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<yc.length;e++){const n=yc[e].connecting?.(t);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{wc("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}const n=this.parentNode;if(n instanceof ShadowRoot&&n.host.hasAttribute(K))try{wc("dcc",`a <${o.tagNames.state}> inside a [${K}] host`)}catch(t){this._failInitializeLoudly(t)}let s=!1;try{const t=function(t){for(let e=0;e<yc.length;e++){const n=yc[e].preparing?.(t);if(null!=n)return n}return null}(this);null===t&&this.hasAttribute("bind-component")&&wc("scopes",'the "bind-component" attribute'),s=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(s)return;let r=!1;try{r=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!r)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!e()||t!==this._connectGeneration||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await da('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}bl(this,t),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!function(t){for(let e=0;e<yc.length;e++)if(!0===yc[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<yc.length;n++)yc[n].initializeFailureCleared?.(t,e)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{va(this.rootNode,null),al.delete(this),function(t){for(let e=0;e<ml.length;e++)ml[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=>(sl(t),t))}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e,this.attachAddressHooks("watch",B)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&Z(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return Li(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&Z("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const n=function(t,e){const n=dl.get(t);return void 0===n&&Z(ca(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<ul.length;n++){const o=ul[n],s=e[o];if(void 0===s)continue;const r=t[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",O)}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(t);void 0===o?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:o.bound||"binding"===n})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+l)),!this._pathSet.has(t)){const e=nt(t);if(this._pathSet.add(t),$c?.check(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=nt(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,n){try{const o=function(t,e,n){const o=new pc(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&Z(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);!function(t){for(let e=0;e<yc.length;e++)yc[e].replacingState?.(t)}(this),(this._hasGraftedVolumes||this._hasMounts)&&Z("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const e=this.__state;this._state=t;const n=function(t){const e=new Set;for(const n of t)if(void 0!==n)for(const[t,o]of Object.entries(_c(n)))t.startsWith("$")||t.includes(l)||"function"==typeof o.value||e.add(t);return e}([e,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){!function(t,n,o){const s=new Map;for(const t of o){const e=nt(t);if(null===e.lastWildcardPath)continue;const n=s.get(e.lastWildcardPath);void 0===n?s.set(e.lastWildcardPath,[e]):n.push(e)}const r=[],i=new Set,a=e=>{const n=Ke(t,e);if(i.has(n))return;i.add(n);const o=pn(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(bn(n,e.listIndex))}};Ce();try{if(t.createState("readonly",e=>{for(const o of n){const n=bn(nt(o),null);a(n);try{Ul(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)Sc.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=()=>{na(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=qs("state",s);void 0!==i&&i.catch(Js)}finally{Te()}}(this,t,this._pathRegistrations.keys())}}const kc=[],Ic=[];function Nc(){const t=[];let e=0;for(let n=0;n<Ic.length;n++){const o=Ic[n].deref();void 0!==o&&(t.push(o),Ic[e++]=Ic[n])}return Ic.length=e,t}function Ac(t,e){const r=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(t);var i;r&&((i=r).tagNames&&Object.assign(n.tagNames,i.tagNames),"string"==typeof i.bindAttributeName&&(n.bindAttributeName=i.bindAttributeName),"string"==typeof i.commentTextPrefix&&(n.commentTextPrefix=i.commentTextPrefix),"string"==typeof i.commentForPrefix&&(n.commentForPrefix=i.commentForPrefix),"string"==typeof i.commentIfPrefix&&(n.commentIfPrefix=i.commentIfPrefix),"string"==typeof i.commentElseIfPrefix&&(n.commentElseIfPrefix=i.commentElseIfPrefix),"string"==typeof i.commentElsePrefix&&(n.commentElsePrefix=i.commentElsePrefix),"string"==typeof i.locale&&(n.locale=i.locale),"boolean"==typeof i.debug&&(n.debug=i.debug),"boolean"==typeof i.enableMustache&&(n.enableMustache=i.enableMustache),"boolean"==typeof i.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=i.enableDirectionalInitialSync),"boolean"==typeof i.enablePropagationContext&&(n.enablePropagationContext=i.enablePropagationContext),"boolean"==typeof i.enableContractAnalyzer&&(n.enableContractAnalyzer=i.enableContractAnalyzer),"boolean"==typeof i.sameValueGuard&&(n.sameValueGuard=i.sameValueGuard)),function(t=customElements){Nc().includes(t)||Ic.push(new WeakRef(t));for(let e=0;e<kc.length;e++)kc[e](t);t.get(o.tagNames.state)||t.define(o.tagNames.state,Pc)}(e),function(){const t=globalThis;void 0===t[s]&&(t[s]=Ja)}()}let Ec=null;function Cc(t){return Ec??Z(ca("watch",`"$watch" in <wcs-state mount="${t}">`))}let Tc=null;const Mc=Object.freeze([]),Oc="3.3.0",Lc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Rc(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 jc="__WCSTACK_DEVTOOLS_HOOK__";const Dc=t=>{null!==_e&&_e({type:"state:update-batch",addresses:t})};function Wc(t){const e=null!==_e;!function(t){_e=t}(t);const n=null!==t;n&&!e?Ks(Dc,0):!n&&e&&function(t){const e=Us.findIndex(e=>e.listener===t);-1!==e&&Us.splice(e,1)}(Dc)}function zc(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 Bc(t){return ga(t)??Z("devtools: no state tree on this root")}let Fc=null;function Hc(){if(e())return;if(null!==Fc)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Oc,getStateElements(){const t=[];for(const e of pa)t.push(zc(e));return t},overlays(t){return e=Bc(t),null===Tc?Mc:Tc(e);var e},keyedSubscriptions:t=>function(t){const e=function(t){const e=Ys.get(t);return void 0===e?null:{byPath:e.byPath,lastValue:e.lastValue,tracked:e.tracked,watchers:ir.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}(Bc(t)),keys(t){const e=Bc(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 Bc(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){Bc(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=`${ct(t.inFilters)}\0${ct(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(s.has(t))return;s.add(t);const e=Sa(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Rc(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=ne(e,Mt(n));for(const o of t)r(Rc(e,o,"attribute",n))}catch{}continue}const e=Lc.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=Sa(s);if(null===a){if(n===o.commentTextPrefix)try{r(Rc(t,Dt(s),"comment",s))}catch{}}else r(Rc(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:Wc};Fc=t,function(){const t=globalThis,e=t[jc];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[jc]=n,n}().register(t)}const qc={name:"devtools",install(){Hc()}},Uc=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Vc=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])}),Gc=new WeakMap,Kc=new WeakMap,Jc=new WeakSet,Qc=new WeakMap;function Xc(t,e,n,o){console.warn(`[@wcstack/state] [${ji[n]}] ${Di[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${rt(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${it}`),null!==_e&&_e({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const Yc={check:function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=t.addressHooks;if(s){const e=s.suppressPathDiagnostic;for(let o=0;o<e.length;o++)if(e[o](t,n))return}const r=nt(n).segments;if("binding"===o&&r.length<2)return;if(function(t,e){let n=Gc.get(t);return void 0===n&&(n=new Set,Gc.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const i=function(t,e,n){if(void 0!==Li(t,e))return Vc;const o=nt(e).segments;let s=t,r="";for(let e=0;e<o.length;e++){const i=o[e],c=r;if(r=0===e?i:r+a+i,e>0&&e<o.length-1&&void 0!==Li(t,r))return Uc;if(Object(s)!==s)return Uc;if(i===l){if(!Array.isArray(s)||0===s.length)return Uc;s=s[0];continue}const u=Li(s,i);if(void 0===u)return{existence:"missing",missingSegment:i,candidates:Ri(s,c,n)};if("function"==typeof u.get)return e===o.length-1?Vc:Uc;s=u.value}return Vc}(e,n,t.getterPaths);"missing"===i.existence&&(function(t,e){return!0===Qc.get(t)?.has(e)}(t,n)||("binding"!==o?Xc(0,n,o,i):function(t,e,n){let o=Kc.get(t);void 0===o&&(o=new Map,Kc.set(t,o)),o.set(e,n),Jc.has(t)||(Jc.add(t),setTimeout(()=>function(t){Jc.delete(t);const e=Kc.get(t);if(void 0!==e){Kc.delete(t);for(const[t,n]of e)Xc(0,t,"binding",n)}}(t),0))}(t,n,i)))},reset:function(t){Gc.delete(t),Kc.delete(t)},markExported:function(t,e){let n=Qc.get(t);void 0===n&&(n=new Set,Qc.set(t,n)),n.add(e),Kc.get(t)?.delete(e)}};let Zc=!1;const tu={name:"diagnostics",install(){Zc||(Zc=!0,$c=Yc)}};function eu(t){Z(`filter ${t} requires at least one option`)}function nu(t){Z(`filter ${t} requires a number as option`)}function ou(t){Z(`filter ${t} requires a number value`)}function su(t){Z(`filter ${t} requires a date value`)}const ru={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function iu(t){return!(!t||isNaN(Number(t)))}function au(t,e){return iu(t)||nu(e),Number(t)}function lu(t,e,n){return au(t?.[e]??eu(n),n)}const cu=t=>e=>{const n=t(e);return t=>null==t?t:n(t)},uu={eq:(t,e)=>{const n=t?.[0]??eu("eq"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t===o:(iu(n)||nu("eq"),t===Number(n)):"string"==typeof t?t===n:t===o},ne:(t,e)=>{const n=t?.[0]??eu("ne"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t!==o:(iu(n)||nu("ne"),t!==Number(n)):"string"==typeof t?t!==n:t!==o},not:t=>t=>!t,lt:t=>{const e=lu(t,0,"lt");return t=>("number"!=typeof t&&ou("lt"),t<e)},le:t=>{const e=lu(t,0,"le");return t=>("number"!=typeof t&&ou("le"),t<=e)},gt:t=>{const e=lu(t,0,"gt");return t=>("number"!=typeof t&&ou("gt"),t>e)},ge:t=>{const e=lu(t,0,"ge");return t=>("number"!=typeof t&&ou("ge"),t>=e)},add:t=>{const e=lu(t,0,"add");return t=>("number"!=typeof t&&ou("add"),t+e)},sub:t=>{const e=lu(t,0,"sub");return t=>("number"!=typeof t&&ou("sub"),t-e)},mul:t=>{const e=lu(t,0,"mul");return t=>("number"!=typeof t&&ou("mul"),t*e)},div:t=>{const e=lu(t,0,"div");return t=>("number"!=typeof t&&ou("div"),t/e)},mod:t=>{const e=lu(t,0,"mod");return t=>("number"!=typeof t&&ou("mod"),t%e)},abs:t=>t=>("number"!=typeof t&&ou("abs"),Math.abs(t)),clamp:t=>{const e=lu(t,0,"clamp"),n=lu(t,1,"clamp");return t=>("number"!=typeof t&&ou("clamp"),Math.min(Math.max(t,e),n))},toFixed:t=>{const e=au(t?.[0]??"0","toFixed");return t=>("number"!=typeof t&&ou("toFixed"),t.toFixed(e))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&ou("locale"),t.toLocaleString(e??o.locale))},upper:cu(t=>t=>String(t).toUpperCase()),lower:cu(t=>t=>String(t).toLowerCase()),capitalize:cu(t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)}),trim:cu(t=>t=>String(t).trim()),slice:cu(t=>{const e=[lu(t,0,"slice")],n=t?.[1];return void 0!==n&&e.push(au(n,"slice")),t=>String(t).slice(...e)}),substr:cu(t=>{const e=lu(t,0,"substr"),n=lu(t,1,"substr");return t=>String(t).substr(e,n)}),padStart:cu(t=>{const e=lu(t,0,"padStart"),n=t?.[1]??"0";return t=>String(t).padStart(e,n)}),padEnd:cu(t=>{const e=lu(t,0,"padEnd"),n=t?.[1]??" ";return t=>String(t).padEnd(e,n)}),repeat:cu(t=>{const e=lu(t,0,"repeat");return t=>String(t).repeat(e)}),reverse:cu(t=>t=>String(t).split("").reverse().join("")),truncate:cu(t=>{const e=lu(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)||Z("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=Math.pow(10,au(t?.[0]??"0","round"));return t=>("number"!=typeof t&&ou("round"),Math.round(t*e)/e)},floor:t=>{const e=Math.pow(10,au(t?.[0]??"0","floor"));return t=>("number"!=typeof t&&ou("floor"),Math.floor(t*e)/e)},ceil:t=>{const e=Math.pow(10,au(t?.[0]??"0","ceil"));return t=>("number"!=typeof t&&ou("ceil"),Math.ceil(t*e)/e)},percent:t=>{const e=au(t?.[0]??"0","percent");return t=>("number"!=typeof t&&ou("percent"),`${(100*t).toFixed(e)}%`)},unit:cu(t=>{const e=t?.[0]??eu("unit");return t=>String(t)+e}),date:t=>{const e=t?.[0];return t=>(t instanceof Date||su("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||su("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||su("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||su("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||su("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]??eu("defaults"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t||o},coalesce:(t,e)=>{const n=t?.[0]??eu("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},du={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]},hu=uu,fu=uu;let pu=!1;const mu={name:"formats",install(){pu||(pu=!0,gt("input",fu,du,ru),gt("output",hu,du,ru))}};function gu(t){return-1!==t.indexOf(q)}function yu(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+a;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(gu(o))return null;const s=o.slice(1).split(a);return s[0]===l||s.some(t=>0===t.length)?null:o}function bu(t){return 0===t.length?t:a+_u(t.slice(1))}function wu(t,e,n){const o=a+t.repeat,s=e.length<=n.length?e:n,r=e.length<=n.length?n:e;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let t=0;t<i.length;t+=o.length)if(!i.startsWith(o,t))return!1;return!0}function vu(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(a,o-1))if(wu(t,e,n.slice(0,o)))return!0;return!1}function _u(t){const e=t.split(a);for(let t=0;t<e.length;t++)e[t]===l||Number.isNaN(Number(e[t]))||(e[t]=l);return e.join(a)}function $u(t,e){const n=t.repeat.split(a),o=a+t.repeat;let s=e;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===a+t.repeatList+a+"length")return!0;for(let t=1;t<n.length;t++)if(s===a+n.slice(0,t).join(a))return!0;return!1}function Su(t,e,n){n<0&&Z(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=a+t.repeat;const s=o+e;let r=0;for(const t of s.split(a))t===l&&r++;return r>c&&Z(`[wcs/recursion-depth-exceeded] Recursion on "${t.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function xu(t,e){return Su(t,"",e)}function Pu(t,e,n){if(!n.startsWith(t.anchor))return null;if(e.length>0&&!n.endsWith(e))return null;if(n.length<t.anchor.length+e.length)return null;const o=n.slice(t.anchor.length,n.length-e.length);if(0===o.length)return 0;const s=a+t.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function ku(t,e,n){const o=t.recursionRegistry,s=yu(o.spec,n);null===s&&Z(zi(n,o.spec.recursiveAnchor));const r=function(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=e.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(t,e){const n=t.spec;if(!e.startsWith(n.anchor))return null;const o=a+n.repeat;let s=0,r=n.anchor.length;for(;e.startsWith(o,r);)r+=o.length,s++;return r!==e.length&&46!==e.charCodeAt(r)?null:s}(e,n.pathInfo.path)}(e,o);return null===r&&Z(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function Iu(t,e,n,o,s){const r=o.spec,i=[],l=new Map,c=[],u=r.repeatList,d=r.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void i.push(bn(t,n));const s=m(o[e],n,null).rows;for(let n=0;n<s.length;n++)p(t,e+1,s[n])};function m(o,s,i){const a=bn(o,s),c=Ke(n.stateElement,a),d=Nl(t,a,e,n),f=null===i?null:((t,e,n)=>{if(!Array.isArray(e)||0===e.length)return null;const o=e;return h.has(o)&&Z(`[wcs/recursion-cycle] "${t}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&Z(`[wcs/recursion-shared-list] "${t}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${u}" array.`),o})(o.path,d,i),p=jr(s,Ae(c),d);return l.set(c,Array.isArray(d)?d:[]),null!==f&&null!==i&&i.add(f),{rows:p.newIndexes,tracked:f}}const g=(t,e,n)=>{const{rows:r,tracked:l}=m(e,n,f);if(0===r.length)return;const d=(t=>{const e=c[t];if(void 0!==e)return e;const n=o.concretePathAt(s,t),r=0===s.length?n:o.concretePathAt("",t),i={nodePath:r,concretePathInfo:nt(n),childListPathInfo:nt(r+a+u)};return c[t]=i,i})(t),y=l;h.add(y);const b=d.concretePathInfo.wildcardCount===t+1;for(let e=0;e<r.length;e++){const n=r[e];b?i.push(bn(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,nt(d),null);for(const[t,e]of l)Ee(t,e);return i}const Nu={write(t,e){if(!0!==t.hasRecursion)return cl;const n=t.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);return null!==n&&Z(`[wcs/recursion-readonly] "${e.pathInfo.path}" writes into the recursive getter "${n}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),cl},get(t,e,n,o){if(!0!==t.stateElement.hasRecursion)return cl;if("$getAll"===e)return(e,s)=>{if(gu(e)){if(void 0!==s)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=yu(r.spec,o);null===i&&Z(zi(o,r.spec.recursiveAnchor)),Array.isArray(s)||Z(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&Z(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=Iu(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Nl(t,a[o],e,n));return l}(o,n,t,e,s);e=ku(t.stateElement,t,e)}return rc(o,0,n,t)(e,s)};if("$setAll"===e)return(e,s,r,i)=>gu(e)?function(t,e,n,o,s,r,i){wl(n);const a=n.stateElement.recursionRegistry,l=yu(a.spec,o);null===l&&Z(zi(o,a.spec.recursiveAnchor));const c=bu(l);Array.isArray(s)||Z(Bi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&Z(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&Z(Bi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&Z(Bi(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){$u(t,n)&&Z(`[wcs/recursion-structural-write] "${e}" writes the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const u=a.conflictingRecursiveGetter(c);null!==u&&Z(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${u}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const d=Iu(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(nc(t,d[o],r,e,n),h++);return h}(o,n,t,e,s,r,i):ac(o,0,n,t)(e,s,r,i);if(36!==e.charCodeAt(0)&&gu(e)){const s=$l(ku(t.stateElement,t,e)),r=ic(o,s,n,t);return Nl(o,bn(s.pathInfo,r),n,t)}return cl}};let Au=!1;function Eu(t,e){"string"==typeof e&&0!==e.length||Z(`[wcs/recursion-declaration-invalid] ${H} ${t} must be a non-empty string.`);const n=e.split(a);n.some(t=>0===t.length)&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain empty path segments.`),n.length<2&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must name a list element: a property path ending with "${a}${l}" (for example "nodes${a}${l}").`),n[n.length-1]!==l&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must end with "${a}${l}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===l&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must have exactly one "${l}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===q&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain "${q}" — the declaration is what gives "${q}" its meaning.`),isNaN(Number(n[o]))||Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const Cu=new WeakSet;function Tu(t){return"function"==typeof t.get&&Cu.has(t.get)}const Mu="[wcs/recursion-declaration-invalid]";class Ou{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=_c(e);for(const[e,o]of Object.entries(n)){if(!gu(e))continue;"function"==typeof o.set&&Z(`${Mu} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&Z(`${Mu} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=yu(t,e);null===n&&Z(zi(e,t.recursiveAnchor)),0===n.length&&Z(`${Mu} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${a}total"), not the node.`),$u(t,bu(n))&&Z(`${Mu} "${e}" names the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${t.recursiveAnchor}${a}total").`),this._definitions.set(e,{recursivePath:e,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(t){for(const[e,n]of Object.entries(t)){if(gu(e)||Tu(n))continue;const t=this._matchExpansion(e);null!==t&&Z(`${Mu} "${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++)wu(this.spec,t[e].suffix,t[n].suffix)&&Z(`${Mu} "${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(vu(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=_u(t),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let t=n.lastIndexOf(a);null===s&&t>this.spec.anchor.length;t=n.lastIndexOf(a,t-1))s=this._matchExpansion(n.slice(0,t))}return this._ownerByPath.set(n,s),s}_matchExpansion(t){for(const e of this._definitions.values())if(null!==Pu(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=Pu(this.spec,t.suffix,e);null!==n&&(null!==o&&Z(`"${e}" matches both "${o.recursivePath}" and "${t.recursivePath}".`),o=t,s=n)}return null===o?null:this._define(t,o,s,e)}_define(t,e,n,o){const s=t.findStateDescriptor(o);void 0===s||Tu(s)||Z(`"${o}" is already defined on the state, so the recursive getter "${e.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:e.recursivePath,depth:n}),i=e.get,a=function(){return i.call(this)};var l;return l=a,Cu.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(xu(t,o)+a+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){const n=new Set(this._accessors.keys());return function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&Tu(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=Su(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 Lu="recursionSpec",Ru="recursionRegistry",ju={order:5,validateEarly(t,e,n){const o=function(t){const e=t[H];if(void 0===e)return null;"object"==typeof e&&null!==e||Z(`[wcs/recursion-declaration-invalid] ${H} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(e);0===n.length&&Z(`[wcs/recursion-declaration-invalid] ${H} must declare exactly one anchor; it is empty.`),n.length>1&&Z(`[wcs/recursion-declaration-invalid] ${H} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Eu("anchor",o),"string"!=typeof s&&Z(`[wcs/recursion-declaration-invalid] ${H} entry "${o}" must map to the repeating sub-path as a string (for example "children${a}${l}").`),Eu("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(a)),i=s.slice(0,s.lastIndexOf(a)),c=r+a+q;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:c,anchorList:r,repeatList:i})}(e);n.set(Lu,o),n.set(Ru,null===o?null:new Ou(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(Ru)??null;t.setRecursionRegistry?.(s),null!==s&&t.attachAddressHooks?.("recursion",H)},apply(t,e,n){const o=n.get(Lu)??null;null!==o&&t.addListPath(o.anchorList)}};let Du=!1;const Wu={name:"recursion",install(){Du||(Du=!0,Au||(Au=!0,hl("recursion",Nu)),gl("recursion",ju))}},zu={written:function(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let Bu=!1;function Fu(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 Hu(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 qu(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 Uu(t){return t.startsWith("$")}function Vu(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 Gu(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||Z(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||Z(`${e} entries must be non-empty strings.`),t.startsWith("$")&&Z(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&Z(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function Ku(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||Z(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Gt(t);null!==r&&"function"==typeof r.define||Z(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&Z(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const t of Array.from(e.childNodes))i.content.appendChild(a.importNode(t,!0));const l=e.mode,{bindables:c,commands:u,streamBackedBindables:d}=function(t){sl(t);const e=Gu(t,O)??[],n=Gu(t,L)??[],o=_c(t),s=function(t){const e=t[z];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}Z(`${O} entry "${t}" is not declared on the state.${rt(t,Vu(o,"value"))}`)}"function"==typeof e.value&&Z(`${O} entry "${t}" is a method. Declare it in ${L} instead.`)}for(const t of n){const e=o[t];void 0===e&&Z(`${L} entry "${t}" is not declared on the state.${rt(t,Vu(o,"method"))}`),"function"!=typeof e.value&&Z(`${L} entry "${t}" is not a method. Declare it in ${O} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||u.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(K))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=Gt(this._shadow);return null!==t&&Kt(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?(Bu||(Bu=!0,hl("dcc",zu)),e.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${O} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=_c(n);for(const[t,e]of Object.entries(g)){if(Uu(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=qu(t,o)}else n.get=Fu(t),n.set=Hu(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:Fu(t),set:Hu(t)});r.define(s,m)}const Ju={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(K)?async function(t,e,n){const o=t;try{o.hasAttribute("bind-component")&&Z(`"bind-component" cannot be used inside a [${K}] host. DCC state comes from the template, not from a component property.`);const s=await async function(t,e){try{if(t.hasAttribute("src")){const e=t.getAttribute("src");if(e.endsWith(".js"))return await Za(e);Z(`DCC: Unsupported src type: ${e}`)}const n=t.querySelector('script[type="module"]');if(n)return await Ya(n,e.tagName.toLowerCase());Z(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}catch(t){Z(`DCC: Failed to load state: ${t}`)}}(o,e);Ku(e,n,s),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}(t,e.host,e):null}};let Qu=!1;function Xu(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 Yu(t,e){for(const n of t)if(Xu(e,n.innerSegments))return n;return null}function Zu(t,e){const n=e.slice(t.innerSegments.length);return 0===n.length?t.outerPathInfo.path:t.outerPathInfo.path+a+n.join(a)}const td=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function ed(t,e,n){const o=td.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 nd=new WeakMap;function od(t,e,n){let o=nd.get(t);void 0===o&&(o=new Map,nd.set(t,o));null!=o.get(e)&&Z(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function sd(t,e){if(null===t)return!1;const n=nd.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+a)||t.startsWith(e+a))return!0;return!1}const rd=new WeakMap,id=[];function ad(t,e,n,o){if(e.length>0){const s=n.split(a),r=Yu(e,s);if(null!==r)return o&&r.readonly&&Z(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${$}.${r.innerSegments.join(a)}#${m}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${m} from the injection.`),Zu(r,s)}return t+a+n}function ld(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(a)):n.startsWith(e+a)&&(o=e.length,s=t.innerSegments.join(a)+n.slice(e.length)))}if(t.length>o){if(n===t)return"";if(n.startsWith(t+a))return n.slice(t.length+1)}return s}function cd(t,e,n=id){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](ad(t,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>e.$setAll(ad(t,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>e.$resolve(ad(t,n,o,s.length>1),...s);const o=ed(s,e=>ad(t,n,e,!1),t=>e[s](...t));return null!==o?o:e[s]}return e[ad(t,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(e[s]=r,!0):(e[ad(t,n,s,!0)]=r,!0)),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const ud=new WeakMap,dd=[],hd=new WeakMap,fd=new WeakSet;function pd(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 md=null,gd=0;const yd=["$watch",z,"$scan","$listKeys",C,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],bd=new Set;function wd(t,e){const n=t.stateObject[e];if("function"==typeof n)try{const o=t.component[t.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function vd(t){const e=t.indexOf(a);return-1===e?t:t.slice(0,e)}function _d(t,e){const n=Yu(t.entries,e);return null===n?null:Zu(n,e)}function $d(t,e){return t.markerBasePath+a+e}function Sd(t,e,n,o){let s=t.accessorBySuffixByMarkerParent.get(e);void 0===s&&(s=new Map,t.accessorBySuffixByMarkerParent.set(e,s));const r=e+a+n;s.set(n,{accessorName:o,indexShift:nt(r).wildcardCount-nt(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(r),t.addedGetterPaths.add(r))}function xd(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 Pd(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(a)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${vd(e)}: path") or declare the key on the component state.`}const kd=/^\$(\d+)$/;function Id(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=vd(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||xd(t,o))return null;const s=function(t,e){return Yu(t.entries,e)}(t,e.split(a));return null!==s&&s.readonly?s:null}function Nd(t,e){const n=Id(t,e);if(null!==n){const o=0===n.innerSegments.length?"":a+n.innerSegments.join(a);Z(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${m}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${m} from the mount.`)}return Ad(t,e)}function Ad(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(a);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===l){o=t;break}if(-1===o)return Sd(t,t.markerBasePath,e,e),$d(t,e);if(xd(t,n[0]))return Sd(t,t.markerBasePath,e,e),$d(t,e);const s=n.slice(0,o+1),r=n.slice(o+1),i=_d(t,s);null===i&&Z(Pd(t,e)),0===r.length&&Z(`Wildcard-terminal accessor "${e}" on mounted <${t.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const c=i+a+t.marker;return Sd(t,c,r.join(a),e),c+a+r.join(a)}(t,e);const o=vd(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return $d(t,e);if(xd(t,o))return $d(t,e);const s=_d(t,e.split(a));if(null!==s)return s;Z(Pd(t,e))}const Ed=new Set(["prop","radio","checkbox"]);function Cd(t,e,n,o,s){if(void 0===o)return;const r=nt(n).wildcardCount-nt(e).wildcardCount;return 0===r?o:(s.length<r&&Z(`Cannot resolve "${e}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const Td=new WeakMap,Md=new WeakMap,Od=new WeakMap,Ld=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)}),Rd=new WeakMap;function jd(t){return Rd.get(t)??null}let Dd=!1;function Wd(t){return zd(t).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join(a),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]}))}function zd(t){const e=Od.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 Bd(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=Od.get(t);if(void 0===o)return null;const s=e.indexOf(a,n),r=-1===s?e.slice(n):e.slice(n,s),i=o.get(r);if(void 0===i)return null;const l=i.deref();return void 0===l?(o.delete(r),null):l}const Fd=new WeakMap,Hd=new Set;function qd(t,e,n,o){let s=Fd.get(t);if(void 0===s){if(!o)return null;s=new Map,Fd.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 Ud(t,e){if(!t.component.isConnected)return!1;const n=we(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 Vd(t,e,n,o){const s=qd(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&&Ud(n,e)?n:null}(r,o);if(null!==t)return{record:t,entry:r.entry}}let i=null,l=null;for(const t of s.holders){const r=t.ref.deref();void 0!==r?Ud(r,o)&&(null!==l&&Z(`[wcs/mount-export-ambiguous] "${e}${a}${n}" is exported by two mounted components on the same instance: <${l.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=t,l=r):s.holders.delete(t)}return null===i||null===l?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:l,entry:i.entry})}function Gd(t){const e=t.parentStateElement,n=we(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[Oe](n,()=>{t.$postUpdate(o.exportedPath)})})}const Kd=new WeakMap;class Jd{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,s,r){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return bn(nt(this.markerParentPath+a+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(Ad(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,s,...r)=>{const i=r.length>0?Nd(t,e):Ad(t,e),a=Cd(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a="$setAll"===s?Nd(t,e):Ad(t,e),l=Cd(0,e,a,r,n);return o[s](a,l,...i)}}const t=this.record,n=this.receiver,o=ed(e,e=>Ad(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 xl(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[Ad(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||Z(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(t,e)?(t[e]=n,!0):(this.receiver[Nd(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 Ad(this.record,e),!0}catch{return!1}}}function Qd(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=Kd.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Kd.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 Jd(t,s,e.listIndex,r,n,o))}function Xd(t,e){const n=function(t){return Td.get(t)??null}(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&Z(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&us(e).dispose(),function(t,e){Dd||(Dd=!0,be=t=>Td.has(t)?t.host:null),Td.set(t,e),Rd.set(e,t);let n=Od.get(e.parentStateElement);void 0===n&&(n=new Map,Od.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=Md.get(e.component);void 0===o&&(o=new Map,Md.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&Ld.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=ha.get(t);if(void 0!==n){if(n===e)return;Z("A state tree is already registered on this root.")}ha.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const s=kd.exec(e.statePathName);if(null!==s){const r=function(t,e){return void 0===e?t.delta:nt(Ad(t,e)).wildcardCount-nt(e).wildcardCount}(t,n);o=0===r?e.statePathName:`$${Number(s[1])+r}`}else if(o=Ad(t,e.statePathName),"for"===e.bindingType){const n=nt(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+a+l,n)}const r=e.propModifiers,i=null===s&&Array.isArray(r)&&Ed.has(e.bindingType??"")&&!r.includes(m)&&null!==Id(t,e.statePathName);return o!==e.statePathName||i?{...e,statePathName:o,statePathInfo:nt(o),...i?{propModifiers:[...r,m]}:{}}:e}(t,e,n);X(e);const o=we(t.component);Fa(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),sa(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=Ad(t,n)}catch{continue}const o=e.indexOf(a+t.marker);if(-1===o)continue;const s=e.slice(0,o+1+t.marker.length),r=e.slice(s.length+1),i=e.slice(0,o)+a+r,l=nt(i);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:e,exportedPath:i};t.exports.set(i,c),qd(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,i),$c?.markExported(t.parentStateElement,i)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=we(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(Hd.has(s))continue;const r=nt(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[Oe](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Hd.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),Gd(t),o=e,s=Promise.resolve(),fa.set(o,s),s.then(()=>wa(o),()=>{})}function Yd(t,e){const n=us(e),o=we(t.component);n.forEachActiveBindingNode(t=>ve(t,o)),na(n.rebindAddresses()),Gd(t)}function Zd(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 th={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const s=Bd(t,e.pathInfo.path);if(null!==s)return Qd(s,e,n,o)}return cl},readMissing(t,e,n,o,s){if(null===n){if(sd(t.rootNode??null,e.pathInfo.path))return;return cl}if(!0===t.hasMounts){const n=Vd(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s){const r=Qd(t,bn(nt(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(n.record,n.entry,e.listIndex,o,s)}return cl},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=rd.get(t);if(void 0===n||0===n.size)return null;const o=e+a;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&Z(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return cl},writeMissing(t,e,n,o,s,r,i){if(!0===t.hasMounts){const n=Vd(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s,r){const i=Qd(t,bn(nt(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(n.record,n.entry,e.listIndex,s,r,i)}return cl},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=Bd(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(a,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const s=-1===o?e:e.slice(0,o),r=-1===o?"":e.slice(o+1),i=t.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:t.delta}(t,o)}return 0},handlerScope(t,e,n,o,s){if(!0!==t.hasMounts)return s;const r=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=Td.get(n);if(void 0!==t)return t;n=n.parentNode}return Td.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 ud.get(t)??dd}(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=ld(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=nn(n.listIndex,a);(r[i]??=[]).push(t)}}if(o.size>0)try{s.callback.call(cd(s.mountPath,n,s.injections),Array.from(o),r)}catch(t){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>sd(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(function(t){const e=Od.get(t);return void 0!==e&&e.size>0}(e))for(const n of zd(e)){if(!Zd(n.component,t))continue;const e=jd(n);null!==e&&Yd(n,e)}}(e,t)}};let eh=!1;const nh=new WeakMap;function oh(t){let e=nh.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},nh.set(t,e)),e}function sh(t,e){null!==e.slotRootNode&&(function(t,e,n){const o=nd.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function rh(t,e,n){if(e.slotRootNode===n)return!0;const s=e.mountPath;try{od(n,s,t)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return ga(n)?.markHasVolume?.(),e.slotRootNode=n,!0}const ih={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=oh(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{od(n,e.mountPath,t),ga(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,mc}return async function(t,e){const n=t,s=t.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(t){0===t.length&&Z('"mount" requires a non-empty tree path.');const e=nt(t);for(const n of e.segments)0===n.length&&Z(`"mount" path "${t}" has an empty segment.`),n===l&&Z(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&Z(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),i=function(t,e){const n=[],s=new Set;let r;try{r=Mt(t)}catch(t){Z(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${e}"> has an invalid ${o.bindAttributeName}: ${t instanceof Error?t.message:String(t)}`)}for(const t of r){if(t.propSegments[0]!==$)continue;const r=t.propSegments.slice(1),i=t.statePathInfo,a=n=>Z(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${e}"> "${t.propName}: ${t.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==l&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${$}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(t.inFilters.length>0||t.outFilters.length>0)&&a("an injection takes no filters."),t.propModifiers.some(t=>t!==m)&&a(`an injection accepts only #${m}.`),s.has(r[0])&&a(`"${r[0]}" is injected twice.`),s.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:t.propModifiers.includes(m)})}return n.sort((t,e)=>e.innerSegments.length-t.innerSegments.length),n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&Z('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),od(s,r,t),ga(s)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=s}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===ga(s)&&function(t,e){const n=()=>{if(null!==ga(t))return;const n=t.querySelectorAll(o.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=t.ownerDocument??t;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&sh(t,e),t.settleInitialization()};let c;try{await Promise.resolve(),c=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void a(null)}const u=t.connectedRootNode??null;null!==u&&rh(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?(Th(),function(t,e){if(fd.has(t))return void pd(e);let n=hd.get(t);void 0===n&&(n=[],hd.set(t,n)),n.push(e)}(t,a)):Eh(e,a)}(u,ga(u),r,c,a,()=>rh(t,e,u),i):a(null)}(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=oh(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&ga(n)===e.graftInfo.rootStateElement&&Nh(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==nh.get(t)?.initializing)return;const e=t.getAttribute("mount");Z(`Cannot replace the state of <${o.tagNames.state} mount="${e}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){fd.add(t);const e=hd.get(t);if(void 0!==e){hd.delete(t);for(const t of e)pd(t)}}(e)},initializeFailureCleared(t,e){!function(t){fd.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=oh(t);return null!==e.graftInfo&&Nh(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,sh(t,e)),t.clearConnectedRootNode(),!0}};let ah=!1;const lh=new WeakMap;function ch(t,e){let n=lh.get(t);n||(n=new Set,lh.set(t,n)),n.add(e)}const uh=new WeakMap,dh=new WeakMap,hh=new WeakMap,fh=new WeakMap,ph={isComplete:function(t,e){return!0===lh.get(t)?.has(e)},isDeclared:function(t,e){return!0===uh.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=dh.get(t);o||(o=new Map,dh.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=hh.get(t);o||(o=new Map,hh.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=fh.get(t);s||(s=new Map,fh.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}};const mh=new WeakMap;class gh{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=mh.get(t);return n?n.get(e)??null:null}(t,e)??Z("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const yh=t=>()=>t;function bh(t,e,n,o){!function(t,e,n){let o=mh.get(t);o||(o=new Map,mh.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 gh(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:yh(s),enumerable:!0,configurable:!0}),ch(e,n),wh(e,n)}function wh(t,e){if(M in t){const n=t[M];"function"==typeof n?n.call(t,e).catch(t=>{Z(`Error in ${M}: ${t instanceof Error?t.message:String(t)}`)}):Z(`${M} is not a function.`)}}const vh=new Set;function _h(t,e){vh.has(t)||(vh.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function $h(t){const e=t.rootEntry,n=we(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Oe](n,()=>{o=t[e.outerPathInfo.path]})}),o}const Sh=new WeakMap;function xh(t,e){t.landInitialization(),Z(e)}async function Ph(t,e){const n=t;if(n.hasAttribute("bind-component")){const i=n.parentNode,l=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,c=l?Ut(l):null;null!==l&&null!==c||Z(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||l.hasAttribute(o.bindAttributeName)||xh(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const u=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&u.push('<script type="module">'),u.length>0&&Z(`"bind-component" cannot be combined with ${u.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(t,e){let n=uh.get(t);n||(n=new Set,uh.set(t,n)),n.add(e)}(l,d);const h=Gt(l);null===h&&Z(`CustomElementRegistry is unavailable for <${c}>.`),await h.whenDefined(c.toLowerCase()),l.hasAttribute(o.bindAttributeName)&&await Ft(l),d in l||Z(`Component does not have property "${d}" for state binding.`);let f=l[d];"object"==typeof f&&null!==f||Z(`Component property "${d}" is not an object for state binding.`);const p=function(t,e){const n=dh.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(l,d);if(void 0!==p&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=ae(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(l,d)&&(l[d]=p,f=p),e.boundComponent=l,e.boundComponentStateProp=d,t.setBoundComponent(l,d),i instanceof ShadowRoot||(ae(l)??[]).some(t=>t.propSegments[0]===d)||xh(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${d}: path").`),l.hasAttribute(o.bindAttributeName)){const o=(ae(l)??[]).filter(t=>t.propSegments[0]===d);if(o.length>0){const u=ga(l.getRootNode())??xh(t,`No state tree found on this root for mount host <${c}>.`);let h=(s=l,r=d,Md.get(s)?.get(r)??null);const p=null!==h;if(null===h&&(function(t,e,n){const o=fh.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;fh.get(t).delete(e)}}(l,d,f),h=function(t,e,n,o,s,r=new Set){0===n.length&&Z(`Cannot build a mount record without host bindings for "${e}".`),sl(s);const i=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(a);l.has(n)&&Z("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(m)};i.push(o),0===e.length&&(c=o)}i.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++gd,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=_c(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 g={};for(const t of Object.keys(s))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof s[t]&&(r.has(t)||p.has(t)||(g[t]=s[t]));return{id:u,marker:d,component:t,stateProp:e,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?d:c.outerPathInfo.path+a+d,stateObject:s,getterKeys:h,setterKeys:f,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(t=>t.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(l,d,o,u,f,function(t,e){return hh.get(t)?.get(e)}(l,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??=_c(t.stateObject);const i=o[r];let l;if(t.getterKeys.has(r)||t.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)l="an accessor";else if("function"==typeof i?.value)l="a method";else{if(t.mappedKeys.has(r)||t.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(t.stateObject,r))continue;l="an own data key"}const c=s.innerSegments.join(a);_h(`${e}|${n}|${c}|entry`,`<${e}>.${n} declares "${r}" as ${l}, 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=$h(t),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const e=t.rootEntry.outerPathInfo.path;_h(`${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{Xd(h,i instanceof ShadowRoot?i:l)}catch(e){throw t.landInitialization(),e}if(!p){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=we(t.component);let s;return e[Oe](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(t,e,n){const o=t.parentStateElement,s=(t,e)=>{let s;return o.createState(t,t=>{s=n(t,()=>e(t))}),s};return"$postUpdate"===e?e=>s("readonly",n=>n.$postUpdate(Ad(t,e))):(n,o,...r)=>{const i="$setAll"===e||"$resolve"===e&&r.length>0,a=i?Nd(t,n):Ad(t,n),l=we(t.component)?.listIndex.indexes??[],c=Cd(0,n,a,"$resolve"===e?o??[]:o,l);return s(i?"writable":"readonly",t=>t[e](a,c,...r))}}(t,s,n);const r=ed(s,e=>Ad(t,e),t=>{let o;return e.createState("readonly",e=>{o=n(e,()=>e[s](...t))}),o});if(null!==r)return r;let i;return e.createState("readonly",e=>{i=n(e,()=>e["$"===s[0]?s:Ad(t,s)])}),i},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:Nd(t,s)]=r})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return Ad(t,n),!0}catch{return!1}}})}(h);Object.defineProperty(l,d,{get:()=>t,enumerable:!0,configurable:!0}),ch(l,d)}return wh(l,d),function(t){const e=yd.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(q)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;bd.has(n)||(bd.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 wd(h,"$connectedCallback")}}bh(t,e.boundComponent,e.boundComponentStateProp,f)}var s,r}const kh={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=Sh.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Sh.set(t,e)),e}(t);return Ph(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=Sh.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&Yd(n,o)}),wd(n,"$connectedCallback"),!0},disconnecting(t){const e=Sh.get(t);return void 0!==e&&null!==e.mountRecord&&(wd(e.mountRecord,"$disconnectedCallback"),Gd(e.mountRecord),t.clearConnectedRootNode(),!0)}};let Ih=!1;function Nh(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(cd(t.mountPath,o,t.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function Ah(t,e,n,o=[]){sl(n),function(t,e,n,o){const s=0===o.length?null:_c(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||Z(`[wcs/mount-path-invalid] Volume "${e}" declares "${n}" as an accessor or a method and also injects it ("${$}.${n}: ${t.outerPathInfo.path}"). Rename one of them.`)}const r=n[B];if(void 0!==r){"object"==typeof r&&null!==r||Z(`${B} must be an object mapping state paths to handler functions.`);const t=Cc(e);for(const[e,n]of Object.entries(r))"function"!=typeof n&&Z(`${B} entry "${e}" must be a function.`),t.assertValidPath(e)}const i=n[U];if(void 0!==i){"object"==typeof i&&null!==i||Z(`${U} 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)&&Z(`${U} entry "${n}" must map a list path to a field name or a key function.`);const r=ad(e,o,n,!1);t.listKeys?.has(r)&&Z(`${U} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[z]&&Z(`Volume "${e}" declares ${z}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&Z(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[H]&&Z(`Volume "${e}" declares ${H}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys(_c(n)))-1!==t.indexOf(q)&&Z(`Volume "${e}" declares "${t}", which uses "${q}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n,o);const{data:s,accessors:r}=function(t,e){const n={},o=new Map;for(const[s,r]of Object.entries(_c(t)))s.startsWith("$")||e.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(t=>t.innerSegments[0]))),i=nt(e),l=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(l)return;Z(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],s=""===n?o in t:void 0!==t[n+a+o];n=""===n?o:n+a+o,s||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(l)return;Z(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=s}),function(t,e){let n=rd.get(t);void 0===n&&(n=new Set,rd.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,s]of r){const r=e+a+n,i=s.get,l=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(cd(e,this,o))}),"function"==typeof l&&(c.set=function(t){l.call(cd(e,this,o),t)}),t.defineTreeAccessor(r,c)}!function(t,e,n,o){const s=n[B];if(void 0!==s){const n=Cc(e),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=ad(e,o,n,!1),c=function(t,n,...s){l.call(cd(e,this,o),t,n,...s)};r.push({path:s,pathInfo:nt(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[U];if(void 0!==r){const n=new Map;for(const[t,s]of Object.entries(r))n.set(ad(e,o,t,!1),s);t.mergeVolumeListKeys?.(n)}const i=n[C];"function"==typeof i&&(function(t,e){let n=ud.get(t);void 0===n&&(n=[],ud.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,injections:o,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}(t,e,n,o);const c=n.$connectedCallback;return"function"==typeof c&&t.createState("writable",t=>{let n;try{n=c.call(cd(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 Eh(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=Ah(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 Ch=!1;function Th(){var t;Ch||(Ch=!0,eh||(eh=!0,hl("scopes",th),Tc=Wd),ah||(ah=!0,bc("scopes",ih)),Ih||(Ih=!0,bc("bindComponent",kh),hs=ph),md=Eh,t=Mh,ma.includes(t)||ma.push(t))}function Mh(t,e){(function(t){const e=nd.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){fd.delete(t);const n=hd.get(t);if(void 0===n||0===n.length||null===md)return;hd.delete(t);const o=md;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const Oh={name:"scopes",install(){Th(),Qu||(Qu=!0,bc("dcc",Ju))}},Lh=/^@@wcs-(?:for|if|elseif|else):[^-]/,Rh=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,jh=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Dh=/^@@wcs-text-start:(.+)$/;function Wh(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function zh(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 Bh=t=>Lh.test(t),Fh=t=>Rh.test(t);function Hh(t){const e=t.fragment.cloneNode(!0);for(const n of t.nodeInfos){const o=La(oe(t.fragment,n.nodePath));if(null===o)continue;const s=oe(e,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return e}class qh extends vc{_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=Oc.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=o.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(e,t);if(void 0!==o&&"function"==typeof o.get)continue;const s=e[t];"function"!=typeof s&&(n[t]=s)}return n}static buildContent(t,e,n){const s=n??t.ownerDocument,r=document.createElement("script");r.setAttribute("type","application/json"),r.textContent=Wh(JSON.stringify(e)),t.appendChild(r);for(const[e,n]of function(t){const e=new Map,n=[t];for(;n.length>0;)for(const t of zh(n.shift(),Bh)){const o=t.data,s=o.slice(o.indexOf(":")+1);if(e.has(s))continue;const r=Sa(s);null!==r&&(e.set(s,r),n.push(r.fragment))}return e}(s)){const s=document.createElement("template");s.setAttribute("id",e);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i),s.content.appendChild(Hh(n)),t.appendChild(s)}const i=t.ownerDocument,a=Array.from(Pi);if(a.length>0){const e={};for(let t=0;t<a.length;t++){const n=a[t];if(!n.isConnected||n.ownerDocument!==i)continue;const o=xi(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=Wh(JSON.stringify(e)),t.appendChild(n)}}ki()}static removeBlockBoundaryComments(t){for(const e of zh(t,t=>Rh.test(t)||jh.test(t)))e.remove()}static removeStructuralComments(t){for(const e of zh(t,Bh))e.remove()}static restoreTextBindings(t){for(const e of zh(t,t=>Dh.test(t))){const t=Dh.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(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}for(const t of zh(e,Fh)){const e=Rh.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()}qh.restoreTextBindings(e);for(const t of zh(e,Bh)){const e=s.get(t.data.split(":")[1]);if(e){const n=document.createElement("template"),s=e.getAttribute(o.bindAttributeName);s&&n.setAttribute(o.bindAttributeName,s);const r=document.importNode(e.content,!0);if(r.childNodes.length>0)n.content.appendChild(r);else for(const t of Array.from(e.childNodes))n.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(n,t)}}const r=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of r)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const Uh={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of s){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Oc),qh.buildContent(o,qh.extractStateData(t),t.getRootNode()),t.parentNode?.insertBefore(o,t)}ki()},reset:function(){_a.clear(),ki()}},Vh=new Set(["for","if","elseif","else"]);function Gh(t){const e=new cs;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e,deferredSpreads:[]};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i,a]=pe(s),l=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:l,subscriberNodes:r,bindingSession:e,deferredSpreads:a}}const Kh=/^\s*@@\s*(?:wcs-text)?\s*:/;function Jh(t,e,n){for(const o of e)"event"===o.bindingType||Vh.has(o.bindingType)||(o.node.nodeType!==Node.COMMENT_NODE||"text"===o.bindingType&&Kh.test(o.node.data))&&(o.statePathName in N||nt(o.statePathName).wildcardCount>n||t.push(o))}function Qh(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`;return zh(t,t=>t===r)[0]??null}function Xh(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Mt(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,ka()],bindingType:"else"}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;ja(a),"string"==typeof l&&Ta(a,l),Fa(n,a,l),$a(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:Ra(a)})}}const Yh={hydrate:async function(t){await ia(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${Oc}". Falling back to full render.`),qh.cleanupDom(t),!1}for(const n of e)Xh(t,n);qh.restoreTextBindings(document.body);const n=function(t){const e=[];for(const n of zh(t,Fh)){const t=Rh.exec(n.data),o=t[1],s=t[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let u=n.nextSibling;const d=`@@wcs-${o}-end:${s}`;for(;u&&(u.nodeType!==Node.COMMENT_NODE||u.data!==d);)c.push(u),u=u.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body),s=function(t,e){const n=new Map,o=[];for(const s of e){if(0===s.nodes.length)continue;const e=si(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a,deferredSpreads:c}=Gh(s.nodes);Br(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");bs(e,r),qr(e,i);const u=[];for(const t of r)t.statePathName in N&&u.push(t);if(_s(e,u),"for"===s.type&&null!==s.index){const i=Qh(t,"for",s.uuid);if(i){const t=Ns(null,s.index);pi(i,t,e),mi(i,s.nodes[s.nodes.length-1]),Zr(i,e);const u=nt(s.path+"."+l),d=bn(u,t);Ur(e,d),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Jh(o,r,u.wildcardCount),oa(c,d,a);let h=n.get(s.uuid);h||(h=[],n.set(s.uuid,h)),h.push(t)}}else{const n=Qh(t,s.type,s.uuid);n&&(Zr(n,e),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Jh(o,r,0),oa(c,null,a))}}for(const[e,o]of n){const n=Qh(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Sa(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ga(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&Ds(e,o)})}return o}(document.body,n);qh.removeBlockBoundaryComments(document.body);const r=[];for(const t of e)t.parentNode&&(r.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());const[i,a,c]=pe(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(ve(t,null),e.setAttribute("data-wcs-completed",""))}else ve(t,null);const u=[],d=[],h=us(document.body),f=h.initialize(a);oa(c,null,h);for(const t of f)if("event"!==t.bindingType)if(Vh.has(t.bindingType))d.push(t);else{if(t.statePathName.includes(l))continue;u.push(t)}for(const t of d)if("for"===t.bindingType){const e=ln(t),n=ga(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&(xe(e,o),Ee(e,o))})}na([...u,...s]);for(const{el:t,parent:e,next:n}of r)e.insertBefore(t,n);const p=new Map;for(const e of t.querySelectorAll("[data-wcs-ssr-id]"))p.set(e.getAttribute("data-wcs-ssr-id"),e);for(const e of t.querySelectorAll(o.tagNames.ssr))for(const[t,n]of Object.entries(e.hydrateProps)){const e=p.get(t);if(e)for(const[t,o]of Object.entries(n))e[t]=o}for(const e of t.querySelectorAll("[data-wcs-completed],[data-wcs-ssr-id]"))e.removeAttribute("data-wcs-completed"),e.removeAttribute("data-wcs-ssr-id");return!0},loadState(t){const e=t.parentNode;if(!e)return null;const n=qh.find(e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(t){await ya(t.rootNode);const e=qh.extractStateData(t),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",Oc),qh.buildContent(n,e,t.rootNode),t.parentNode?.insertBefore(n,t)}};let Zh=!1;const tf={name:"ssr",install(){Zh||(Zh=!0,ua=Yh,function(t){if(!kc.includes(t)){kc.push(t);for(const e of Nc())t(e)}}(t=>{t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,qh)}),function(){const e=globalThis;void 0===e[t]&&(e[t]=Uh)}())}},ef=new WeakMap,nf=new Set,of=new Set;function sf(t){return t.byFromPath.size>0||t.byResetPath.size>0}function rf(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function af(t){return ef.get(t)}function lf(t){cf(t),ef.delete(t)}function cf(t){nf.delete(t),of.delete(t)}const uf=new WeakSet;let df=0;function hf(t){return af(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function ff(t){if(0===of.size)return;if(e=t.absolutePathInfo.stateElement,!of.has(e))return;var e;const n=hf(t);if(void 0!==n)for(const t of n)pf(t)}function pf(t){uf.has(t)||(uf.add(t),df++)}function mf(t){return!!uf.delete(t)&&(df--,!0)}const gf=/^(?:0|[1-9]\d*)$/;function yf(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function bf(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&&gf.test(e)&&yf(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&yf(t,e))?null:"object"}function wf(t,e){const n=bf(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]=wf(o[t],e);return r}function vf(t){return wf(t,new Map)}function _f(t,e,n){if(Object.is(t,e))return!0;const o=bf(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(bf(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(!_f(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&_f(s[t],r[t],n))}function $f(t,e){return _f(t,e,new Map)}const Sf=new WeakMap;function xf(t,e){if("function"!=typeof e)return;const n=Sf.get(e);void 0===n?Sf.set(e,new Set([t])):n.add(t)}function Pf(t,e){return"function"==typeof e&&!0===Sf.get(e)?.has(t)}const kf={"read-source":t=>`${F} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-rows":t=>`${F} could not read the rows of "from" for "${t}". Nothing was folded or written.`,"read-output":t=>`${F} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${F} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${F} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${F} could not write the output "${t}".`},If={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Nf(t,e,n){null!==_e&&_e({type:"state:watch-error",phase:e,path:`${F}.${t}`,error:n})}function Af(t,e,n){console.error(`[@wcstack/state] ${kf[n](t)}`,e),Nf(t,If[n],e)}function Ef(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function Cf(t,e){e.then(void 0,()=>{}),Af(t,new TypeError(`${F} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Tf=new WeakSet,Mf="[wcs/scan-declaration-invalid]",Of=Object.freeze([]);function Lf(t){return`${F} entry "${t}"`}function Rf(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function jf(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${l}${l}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${it}`}function Df(t,e,n){0===n.length&&Z(`${Mf} ${t} "${e}" must be a non-empty state path.${it}`),n.startsWith("$")&&Z(`${Mf} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${it}`),n.includes("@")&&Z(`${Mf} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${it}`),n in Object.prototype&&Z(`${Mf} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${it}`);const o=nt(n);for(const s of o.segments)0===s.length&&Z(`${Mf} ${t} ${e} "${n}" has an empty path segment.${it}`);return o.wildcardCount>c&&Z(`${Mf} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function Wf(t,e,n,o){const s=Lf(t);0===t.length&&Z(`${Mf} ${F} entry name must be a non-empty string.${it}`),(t.includes(a)||t.includes(l))&&Z(`${Mf} ${s} must be a flat property name ("${a}" and "${l}" are not allowed). The output is a property the runtime owns.${it}`),t.startsWith("$")&&Z(`${Mf} ${s} must not start with "$" (reserved namespace).${it}`),t in Object.prototype&&Z(`${Mf} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${it}`),e.has(t)&&Z(`${Mf} ${s} conflicts with a getter declared on the state.${it}`),n.has(t)&&Z(`${Mf} ${s} conflicts with a setter declared on the state.${it}`),o.has(t)&&Z(`${Mf} ${s} conflicts with the ${z} entry of the same name — each output has exactly one owner.${it}`)}function zf(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!Pf(t,o)&&Z(`${Mf} ${Lf(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${it}`)}function Bf(t,e,n,o,s,r){const i=Lf(t),l=void 0!==e.from,c=void 0!==e.on;if(l===c&&Z(`${Mf} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${it}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||Z(`${Mf} ${i} "on" must be a non-empty event-token name.${it}`),n.has(t)||Z(`${Mf} ${i} on "${t}" is not declared in ${D}.${rt(t,n)}${it}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&Z(`${Mf} ${i} "from" must be a state path string.${it}`);const d=Df(i,"from",u),h=Rf(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&Z(jf(i,"from",u,h));const f=Rf(d,s);return null!==f&&Z(function(t,e,n){return`${Mf} ${t} from "${e}" ${n===e?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${it}`}(i,u,f)),(u===t||u.startsWith(t+a))&&Z(`${Mf} ${i} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${it}`),{kind:"path",path:u,pathInfo:d}}function Ff(t,e,n,o){if(void 0===e)return Of;const s=Lf(t);Array.isArray(e)||Z(`${Mf} ${s} "resetOn" must be an array of state paths.${it}`);const r=[];for(const t of e){"string"!=typeof t&&Z(`${Mf} ${s} "resetOn" must contain only state path strings.${it}`);const e=Df(s,"resetOn",t);e.wildcardCount>0&&Z(`${Mf} ${s} resetOn "${t}" must not contain "${l}" — a reset returns the whole output to "initial".${it}`);const i=Rf(e,o);null!==i&&Z(jf(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&Z(`${Mf} ${s} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${it}`),"path"===n.kind&&t.startsWith(n.path+a)&&Z(`${Mf} ${s} resetOn "${t}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${it}`),r.push(t)}return r}function Hf(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 uf.has(t)}(t),l=a&&!$f(n,t.initial)?vf(t.initial):n,c=e(l,o,...s);if(Ef(c))return void Cf(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,xf(t.name,c)),a&&mf(t)}catch(e){Af(t.name,e,i)}}}const qf="scanEntries",Uf={order:8,validate(t,e,n){const o=function(t,e,n=null){const o=t[F];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&Z(`${Mf} ${F} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${it}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(_c(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){sl(t);const e=t[z];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];let u=0;for(const[t,d]of Object.entries(o)){Wf(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&Z(`${Mf} ${Lf(t)} must be an object ({ from | on, initial, fold, resetOn? }).${it}`);const o=d;zf(t,a,o);const h=Bf(t,o,e,s,i,n);"initial"in o||Z(`${Mf} ${Lf(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${it}`),"function"!=typeof o.fold&&Z(`${Mf} ${Lf(t)} fold must be a function.${it}`);const f=Ff(t,o.resetOn,h,s);c.push({name:t,source:h,fold:o.fold,initial:o.initial,resetOn:f,order:u++})}return function(t){const e=new Set(t.map(t=>t.name)),n=new Map;for(const o of t){for(const t of o.resetOn){const n=nt(t).segments[0];e.has(n)&&Z(`${Mf} ${Lf(o.name)} resetOn "${t}" reads the ${F} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${it}`)}if("path"===o.source.kind){const t=o.source.pathInfo.segments[0];e.has(t)&&n.set(o.name,t)}}for(const t of n.keys()){const o=[t];let s=n.get(t);for(;void 0!==s&&o.length<=e.size;)s===t&&Z(`${Mf} ${F} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${it}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}(e,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(qf,o)},applyEarly(t,e,n){const o=n.get(qf)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=vf(n.initial);t[n.name]=e,xf(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&Mn(t,n.source.tokenName).subscribe(Hf(n))}(t,o))},register(t,e,n){const o=n.get(qf)??null,s=function(t){const e=new Map,n=af(t);if(void 0!==n)for(const t of n.entries)mf(t)&&e.set(t.name,t.resetOn);return lf(t),e}(t);t.setScanPaths?.(null===o?null:function(t,e,n){const o=function(t,e){lf(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&rf(n,t.source.path,t);for(const e of t.resetOn)rf(o,e,t),"event"===t.source.kind&&rf(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return ef.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)&&Xs().hasQueuedPath(t,n))&&pf(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 Vf=!1;const Gf=Object.freeze([]),Kf=Object.freeze([]);function Jf(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Gf,i=t.dynamicDependency.get(n)??Gf,a=e.byFromPath.get(n)??Kf;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const Qf=Symbol("wcs-stream-last-notified-uncertain"),Xf=new WeakMap;function Yf(t,e){const n=Xf.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Zf(t,e){const n=Xf.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Qf,error:Object.is(o.error,null)?null:Qf})}const tp=new Set;function ep(t){tp.delete(t)}const np=new WeakMap;function op(t){return np.get(t)??new Map}function sp(t){ep(t);const e=np.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Zf(t,n.name)}const rp=(t,e)=>e,ip=new Set;const ap=new WeakMap,lp=new WeakMap;function cp(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=op(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&op(t).has(n),ownKeys:()=>Array.from(op(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=op(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){Z(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){Z(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function up(t){const e=ap.get(t);if(void 0!==e)return e;const n=cp(t,V,t=>t.status);return ap.set(t,n),n}function dp(t){const e=lp.get(t);if(void 0!==e)return e;const n=cp(t,G,t=>t.error);return lp.set(t,n),n}function hp(t){ap.delete(t),lp.delete(t)}let fp=null;function pp(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 mp={read(t,e){!function(t,e){null!==fp&&fp.add(Ke(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===V?pp(up(t),e.pathInfo.segments):n===G?pp(dp(t),e.pathInfo.segments):cl},get:(t,e)=>e===V?up(t.stateElement):e===G?dp(t.stateElement):cl};function gp(t){Sp();const e=op(t);if(0!==e.size){!function(t){tp.add(t)}(t);for(const n of e.values())yp(t,n)}}function yp(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=fp,s=new Set;let r;fp=s;try{t.createState("readonly",t=>{r=n(t)})}finally{fp=o}r instanceof Promise&&Z(`${z} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${V}${a}${e.name}`,l=`${G}${a}${e.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==i&&o.path!==l||Z(`${z} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&Z(`${z} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=s,r}(t,e);!function(t,e){const n=af(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=Jf(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&Z(`[wcs/scan-feedback-loop] ${z} entry "${e.name}" args read "${n}", which is derived from the ${F} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,e),t.createState("writable",t=>{t[e.name]=e.definition.initial}),xf(e.name,e.definition.initial),bp(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,xf(e.name,o)})},done(){bp(t,e,"done",null)},fail(o){bp(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] ${z}: 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 bp(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return Xf.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=Xf.get(t);void 0===s&&(s=new Map,Xf.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${V}${a}${e.name}`),i&&t.$postUpdate(`${G}${a}${e.name}`)}))}function wp(t){const e=tp;if(0===e.size)return;const n=[];for(const o of e)for(const e of op(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&op(t).get(o.name)===o)try{yp(t,o)}catch(n){o.controller?.abort(),e.has(t)&&op(t).get(o.name)===o&&bp(t,o,"error",n)}}let vp=!1;const _p=new WeakMap,$p={order:20,apply(t,e){var n;hp(t),sp(n=t),ep(n),np.delete(n),function(t,e){sl(e);const n=e[z];if(void 0===n)return void Yf(t,ip);"object"==typeof n&&null!==n||Z(`${z} must be an object mapping stream names to stream definitions.`);const o=new Map,s=_c(e);for(const[r,i]of Object.entries(n)){0===r.length&&Z(`${z} entry name must be a non-empty string.`),r.includes(a)&&Z(`${z} entry "${r}" must be a flat property name ("${a}" is not allowed).`),r.includes(l)&&Z(`${z} entry "${r}" must be a flat property name ("${l}" is not allowed).`),r.startsWith("$")&&Z(`${z} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&Z(`${z} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(r)&&Z(`${z} entry "${r}" conflicts with a getter declared on the state.`),t.setterPaths.has(r)&&Z(`${z} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||Z(`${z} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,c=s[r]?.value;"function"!=typeof c||c===n.initial||Pf(r,c)||Z(`${z} 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&&Z(`${z} entry "${r}" source must be a function.`);const u=void 0!==n.fold;u&&"function"!=typeof n.fold&&Z(`${z} entry "${r}" fold must be a function.`),u&&!("initial"in n)&&Z(`${z} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&Z(`${z} entry "${r}" args must be a function.`);const d={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??rp,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in e||(e[r]=d.definition.initial,xf(r,d.definition.initial)),o.set(r,d)}!function(t,e){np.set(t,e)}(t,o),Yf(t,new Set(o.keys()))}(t,e),void 0!==e[z]&&t.attachAddressHooks?.("streams",z)},activate(t,n){if(!e()&&null!=t.connectedRootNode){if(null===n){if(!0!==t.initialized)return;return gp(t),void _p.set(t,t.connectGeneration??0)}n===t.connectGeneration&&_p.get(t)!==n&&gp(t)}},deactivate(t){sp(t),hp(t)}};function Sp(){vp||(vp=!0,hl("streams",mp),gl("streams",$p),Ks(wp,20))}let xp=0,Pp=0;function kp(t){xp=t+1}function Ip(){xp=0}function Np(){xp>Pp&&(Pp=xp)}const Ap=new WeakMap;function Ep(t,e,n){let o=Ap.get(t);void 0===o&&(o=new Map,Ap.set(t,o)),o.set(e,n)}const Cp=new Map;function Tp(t,e){Cp.has(t)||Cp.set(t,e)}function Mp(t){return Cp.get(t)}const Op=new WeakMap,Lp=new WeakMap,Rp=new Set,jp=new Map;function Dp(t){return Op.get(t)??jp}function Wp(t,e){let n=Lp.get(t);void 0===n&&(n=new Map,Lp.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 zp=new Map;function Bp(t){return Lp.get(t)??zp}function Fp(t){0===t.length&&Z(`[wcs/watch-declaration-invalid] ${B} entry name must be a non-empty state path.`),t.startsWith("$")&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not start with "$" (reserved namespace).${it}`),t.includes("@")&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${it}`),t in Object.prototype&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=nt(t);for(const n of e.segments)0===n.length&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" has an empty path segment.${it}`);return e.wildcardCount>c&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const Hp={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||Tp(n,o)},swapped(t,e,n){var o;o=n,Cp.has(o)&&Tp(e,Mp(n))}};function qp(t){for(let e=t;null!==e;e=e.parentListIndex)if(Ls(e))return!0;return!1}function Up(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[Le](bn(e.wildcardParentPathInfos[i],r)),l=Rs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=en(o,i,e.wildcardCount);if(l!==c&&!Ts(l,c)){if(Ls(c))return"gone";s="replaced"}r=l}return s}function Vp(t,e,n){const o=new Map;for(const s of n){const n=Up(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 Gp=Object.freeze([]);function Kp(t,e,n){let o=t.get(n);return void 0===o&&(o={stateElement:e,entry:n,rows:[],reset:!1},t.set(n,o)),o}function Jp(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 Qp(t,e){return e.has(t.stateElement)&&!0===af(t.stateElement)?.entries.has(t.entry)}function Xp(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Yp(n,t))||mf(e)}function Yp(t,e){return Xs().hasQueuedPath(t,e)}function Zp(t,e){!function(t,e,n){if(0!==df)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=hf(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||mf(e)}}(t,e,Yp)}function tm(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function em(t,e,n){if(!Qp(t,n))return Xp(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(Tf.has(t))return;Tf.add(t);const o=`[wcs/scan-source-computed] ${F} entry "${e}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),Nf(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=op(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:Vp(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(Jp)){let n;try{n=tm(e,r,t)}catch(t){Af(s.name,t,"read-source");continue}const o=a(l,n,Mp(t.absAddress),...t.indexes);if(Ef(o))return void Cf(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){Af(s.name,t,i.failure)}return i.plan}function nm(t,e){const{group:n}=t;if(!Qp(n,e))return void Xp(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||mf(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!$f(o,s.initial):!Object.is(o,t.next)){const o=n.reset?vf(s.initial):t.next;e[s.name]=o,xf(s.name,o)}})}catch(t){Af(s.name,t,"write")}}function om(t){hm(),(0!==Dp(t).size||0!==Bp(t).size||function(t){const e=ef.get(t);return void 0!==e&&sf(e)}(t))&&(function(t){Rp.add(t),function(t){const e=ef.get(t);void 0!==e&&(sf(e)&&nf.add(t),function(t){return t.eventResetByPath.size>0}(e)&&of.add(t))}(t)}(t),function(t){const e=[];for(const n of Dp(t).values())sm(t,n)&&e.push(n);for(const n of Bp(t).values())for(const o of n)sm(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{Ep(t,Je(t,o.pathInfo,null),n[o.path])}catch(e){im(t,o.path,"prime",e)}})}(t))}function sm(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const rm={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function im(t,e,n,o){console.error(`[@wcstack/state] $watch ${rm[n]} "${e}" threw.`,o),null!==_e&&_e({type:"state:watch-error",phase:n,path:e,error:o})}function am(t){const e=Rp;try{if(0===e.size)return void Zp(t,e);const n=function(){const t=Pp;return Pp=0,t}();if(n>32){Zp(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!==_e&&_e({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}!function(t,e,n){if(0!==t.length){kp(n);try{for(const n of t)nm(n,e)}finally{Ip()}}}(function(t,e,n){if(Zp(t,e),0===nf.size)return Gp;const o=new Map;for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=af(t);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let e=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;e=nn(n.listIndex,r.wildcardCount)}for(const s of i)Kp(o,t,s).rows.push({absAddress:n,indexes:e})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const e of a)Kp(o,t,e).reset=!0}if(0===o.size)return Gp;const s=Array.from(o.values()).sort((t,e)=>t.entry.order-e.entry.order),r=[];kp(n);try{for(const n of s){const o=em(n,t,e);null!==o&&r.push(o)}}finally{Ip()}return r}(t,e,n),e,n),function(t,e,n){const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=Dp(t).get(s),i=Bp(t).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const e of a){let s=[];if(e.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=nn(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(cm);const s=function(t){let e=null;for(let n=0;n<t.length;n++){const o=t[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=t[n-1];(qp(o.absAddress.listIndex)||s?.entry===o.entry&&lm(s.indexes,o.indexes))&&(e??=new Set).add(o.entry)}if(null===e)return t;const n=new Set;for(const o of e){const e=t.filter(t=>t.entry===o),s=e[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(Vp(t,o.pathInfo,e));for(const t of e)s.has(t)||n.add(t)})}catch(t){im(0,o.path,"evaluate",t);for(const t of e)n.add(t)}}return t.filter(t=>!n.has(t))}(o);kp(n);try{for(const t of s){if(!e.has(t.stateElement))continue;const n=Dp(t.stateElement).get(t.entry.path)===t.entry,o=!0===Bp(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&um(t)}}finally{Ip()}}(t,e,n)}finally{Cp.clear()}}function lm(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function cm(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 um(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=sm(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 im(0,n.path,"evaluate",t)}const a=r?function(t,e){return Ap.get(t)?.get(e)}(e,o):Mp(o);r&&Ep(e,o,i),null!==_e&&_e({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){im(0,n.path,"handler",t)}}let dm=!1;function hm(){dm||(dm=!0,hl("watch",Hp),gl("watch",fm),Ks(am,10),Gs(Np),Ec={assertValidPath:Fp,addEntries:Wp,start:om})}const fm={order:10,register(t,e){var n;n=t,Rp.delete(n),cf(n),Op.delete(n),function(t){Ap.delete(t)}(t);const o=function(t,e){const n=e[B];if(void 0===n)return null;"object"==typeof n&&null!==n||Z(`[wcs/watch-declaration-invalid] ${B} must be an object mapping state paths to handler functions.${it}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${e}" must be a function.${it}`);const n=Fp(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){Op.set(t,e)}(t,o),s.size>0?s:null}(t,e);t.setWatchPaths?.(o),null===o&&null==t.scanPaths||t.attachAddressHooks?.("watch",null!==o?B:F)},activate(t,n){e()||null==t.connectedRootNode||(null===n?!0===t.initialized:n===t.connectGeneration)&&om(t)},deactivate(t){var e;e=t,Rp.delete(e),cf(e)}},pm=[mu,{name:"temporal",install(){hm(),Vf||(Vf=!0,gl("scan",Uf),Gs(ff)),Sp()}},Wu,Oh,tf,qc,tu];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(pm),void Ac(void 0,void 0));const mm={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"},gm=!1,ym=[".html"];function bm(){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 wm(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let vm=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const _m={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 $m(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function Sm(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 xm={static:2,param:1,"catch-all":0};let Pm=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&&wm(`${mm.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&wm(`${mm.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+=xm[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(_m).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||wm(`${mm.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:$m(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new vm("Navigation cancelled by guard.",o);if(!o)throw new vm("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new vm("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},km=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=bm();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new Pm(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||wm(`${mm.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):wm(`${mm.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&&wm(`${mm.route} with fallback attribute must be a direct child of ${mm.router}.`),t.fallbackRoute&&wm(`${mm.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 Im=Symbol.for("wcstack.trustedTypes.policy"),Nm=Symbol.for("wcstack.trustedTypes.internal"),Am="wcstack";function Em(){const t=globalThis[Im];return null===t||"object"!=typeof t?null:t}let Cm=!1;function Tm(t){const e=function(){const t=globalThis,e=t[Nm];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Am,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof Em()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Am}". Allow it in the CSP (\`trusted-types ${Am};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[Nm]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Em(),s=o?.createHTML;return"function"==typeof s?(Cm||(Cm=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Am}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Am};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Mm=new Map;let Om=class extends HTMLElement{_uuid=bm();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||wm(`${mm.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Mm.set(t,n),n}catch(e){wm(`${mm.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(`${mm.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Mm.has(t)?n.innerHTML=Tm(Mm.get(t)||""):n.innerHTML=Tm(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Tm(t):console.warn(`${mm.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")&&gm}get name(){return this.getAttribute("name")||""}},Lm=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||wm(`${mm.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")&&gm}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Rm=new Set(["props","states","attr",""]);function jm(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 Dm(t,e){t.hasAttribute("data-bind")||wm(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Rm.has(n)||wm(`${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&&jm(t,e,o)}).catch(()=>{wm(`Failed to define custom element: ${s}`)}):jm(t,e,o)}let Wm=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||wm(`${mm.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(`${mm.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{Dm(e,t)}),e.hasAttribute("data-bind")&&Dm(e,t))}};function zm(){return document.createElement(mm.layoutOutlet)}const Bm="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Fm(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){wm(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${Bm}`:`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 ${Bm}`}(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 Hm(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 qm(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===mm.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),Hm(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===mm.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Fm(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===mm.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=zm();o.layout=n,i=o,a=e}}const c=await qm(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function Um(t){const e=new Map;return await qm(t,t.template.content,[],e)}function Vm(t){return!1!==t.checkVisibility?.()}function Gm(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=_m[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)Gm(s,e,n,o)}function Km(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)Gm(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 Jm=null,Qm=null;function Xm(){const t=ym;return 0===t.length?null:(Jm===t&&Qm||(Jm=t,Qm=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Qm)}function Ym(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=Xm();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Zm(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function tg(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=Xm();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function eg(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function ng(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=>{Dm(e,t.typedParams)}),n.hasAttribute("data-bind")&&Dm(n,t.typedParams),n.querySelectorAll(mm.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===mm.layoutOutlet&&n.assignParams(t.typedParams)}}function og(t,e){ng(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const sg=Symbol.for("wcstack.transition-runner");const rg=Symbol.for("wcstack.binder");function ig(){const t=globalThis[rg];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const ag=Symbol.for("wcstack.binder.pending"),lg=Symbol.for("wcstack.binder.taken");function cg(){const t=globalThis;let e=t[lg];return void 0===e&&(e=new WeakSet,t[lg]=e),e}function ug(t){const e=ig();return null===e?(function(){const t=globalThis;let e=t[ag];return void 0===e&&(e=[],t[ag]=e),e}().push(t),!1):(cg().add(t),e.bind(t),!0)}const dg=new WeakSet,hg="data-wcs";function fg(t,e,n){!dg.has(t)&&function(t){return t.hasAttribute(hg)||null!==t.querySelector(`[${hg}]`)}(t)&&(dg.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==ig()||(o=t,cg().has(o))||console.warn(`[@wcstack/router] ${e} contains ${hg} 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 pg(t){for(const e of t.childNodeArray)1===e.nodeType&&(ug(e)||fg(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 mg(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 vm)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 gg(t,e,n,o,s=""){const r=Zm(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=Km(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:wm(`${mm.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 mg(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||eg(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=og(o,e),n.length>0&&!s.has(o)&&pg(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[sg];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(Vm(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(Vm(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 yg(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function bg(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 wg(t){return"?"===t?"":t}function vg(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 _g(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const $g="data-wcs-ssr",Sg="data-wcs-ssr-link",xg="@@wcs-route-ph:",Pg="@@wcs-route-start:",kg="@@wcs-route-end:",Ig=Object.freeze({});class Ng 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=Ig;_typedParams=Ig;_searchParams=Ig;_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 Ym(t)}_normalizeBasename(t){return tg(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(mm.outlet))return t;const e=document.createElement(mm.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||wm(`${mm.router} has no outlet.`),this._outlet}get template(){return this._template||wm(`${mm.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=$m(t.search),s=t.data??null,r=this._data!==s,i=!Sm(this._params,e),a=this._routeName!==t.routeName,l=!Sm(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(`${mm.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(`${mm.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=bg(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+wg(n.search)+n.hash,r=yg();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(Zm(t,this._basename));await gg(this,this.outlet,t,this._path,wg(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(Zm(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await gg(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${mm.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 gg(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=_g();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||wm(`${mm.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||wm(`${mm.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await Um(this),r=!t&&this._outlet.hasAttribute($g);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&&wm(`${mm.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($g);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await gg(this,this.outlet,i,this._path,window.location.search||""),(r||null!==ig())&&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(mm.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(xg)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Pg)){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(kg)){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=Zm(t,this._basename);let d=Km(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(Pg)){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()===mm.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute($g);for(const t of d.routes)ng(t,d);return this.outlet.lastRoutes=d.routes,!await mg(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=Zm(t,this._basename),n=Km(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&wm(`${mm.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await gg(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${xg}${t.absolutePath}`}),this.outlet.setAttribute($g,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${Pg}${t.absolutePath}`),s=document.createComment(`${kg}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&ug(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!vg(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),_g()){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=yg();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&&(yg()?.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 Ag=["title","rel","target","download","hreflang","lang","dir"];class Eg extends HTMLElement{static get observedAttributes(){return["to",...Ag]}_childNodeArray=[];_uuid=bm();_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(mm.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(mm.router);if(n)return this._router=n;wm(`${mm.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 Ym(t)}_joinInternalPath(t,e){const n=tg(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}=bg(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+wg(o)+s}else try{t.href=new URL(e).toString()}catch{wm(`[${mm.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){_g()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Sg)?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(Sg),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-")||Ag.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,_g())return this._updateActiveState(),void n.setAttribute(Sg,"");yg()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!yg()?.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(){yg()?.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(Ag.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}=bg(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 Cg=[],Tg=new Map;let Mg=!1;const Og=new WeakMap;class Lg 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(),Mg||(this._captureInitialHead(),Mg=!0),Cg.push(this),this._reapplyHead()}disconnectedCallback(){const t=Cg.indexOf(this);-1!==t&&Cg.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||wm("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Og.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Og.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);Tg.has(t)||Tg.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Cg)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Tg.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=Cg.length-1;e>=0;e--){const o=Cg[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Tg.has(n)&&(t=Tg.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),ug(t)||fg(t,`<${t.tagName.toLowerCase()}> inside <${mm.head}>`,`<${mm.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(mm.layout)||t.define(mm.layout,Om),t.get(mm.layoutOutlet)||t.define(mm.layoutOutlet,Wm),t.get(mm.outlet)||t.define(mm.outlet,Lm),t.get(mm.route)||t.define(mm.route,km),t.get(mm.router)||t.define(mm.router,Ng),t.get(mm.link)||t.define(mm.link,Eg),t.get(mm.head)||t.define(mm.head,Lg)}(void 0);const Rg="data-fetchtarget",jg={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Dg=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 Wg(t,e){return e.every(e=>"available"===t.availability.get(e))}const zg=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Bg=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 Dg("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 Wg(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}}(zg,{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(!Wg(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)}}},Fg=!1;function Hg(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Rg}]`);if(!n)return;const o=n.getAttribute(Rg);if(!o)return;const s=customElements.get(jg.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function qg(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 Ug=Symbol.for("wcstack.trustedTypes.policy");function Vg(){const t=globalThis[Ug];return null===t||"object"!=typeof t?null:t}let Gg,Kg=!1;let Jg=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Bg.wcBindable,properties:[...Bg.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 Bg(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(jg.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(jg.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=Vg(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Gg)return Gg;if(!("trustedTypes"in globalThis))return Gg=!1,Gg;try{document.createElement("div").innerHTML="<i></i>",Gg=!1}catch{Gg=!0}return Gg}())return void function(){if(Kg)return;Kg=!0;const t="function"==typeof Vg()?.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(!qg(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Fg||(Fg=!0,document.addEventListener("click",Hg)),!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 Qg extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class Xg extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Yg=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof Jg&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(jg.fetch)||t.define(jg.fetch,Jg),t.get(jg.fetchHeader)||t.define(jg.fetchHeader,Qg),t.get(jg.fetchBody)||t.define(jg.fetchBody,Xg),t.get(jg.infiniteScroll)||t.define(jg.infiniteScroll,Yg)}(void 0);const Zg="data-storagetarget",ty={storage:"wcs-storage"},ey="wcs-storage:value-changed",ny="wcs-storage:loading-changed",oy="wcs-storage:error",sy="wcs-storage:error-info-changed",ry="wcs-storage:trigger-changed";let iy=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:ey,semantics:"state",getter:t=>t.detail},{name:"loading",event:ny,semantics:"state"},{name:"error",event:oy,semantics:"state"},{name:"errorInfo",event:sy,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(ny,{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(oy,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(sy,{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(ey,{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)}},ay=!1;function ly(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Zg}]`);if(!n)return;const o=n.getAttribute(Zg);if(!o)return;const s=customElements.get(ty.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function cy(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 uy=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...iy.wcBindable,properties:[...iy.wcBindable.properties,{name:"trigger",event:ry,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 iy(this),this._internals=this._initInternals(),this._wireStates({[ny]:t=>({loading:!0===t}),[oy]: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(ry,{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(!cy(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",ay||(ay=!0,document.addEventListener("click",ly)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(ty.storage)||t.define(ty.storage,uy)}(void 0);const dy="*",hy="vanilla",fy={scanImportmap:!0,loaders:{[hy]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[dy]:hy},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function py(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 my(t,e,n){let o;if(null===e||e===dy||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===dy)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[dy],"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 gy=new Set,yy=new Map;let by=new WeakMap;function wy(t){if(t===globalThis.customElements)return yy;let e=by.get(t);return void 0===e&&(e=new Map,by.set(t,e)),e}const vy=new Map;async function _y(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 vy)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){gy.has(e)||(console.error(`Failed to eager load component '${e}':`,t),gy.add(e))}}function $y(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 Sy(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&&vy.set(t,e)});const xy=new WeakSet,Py=new WeakSet;async function ky(t,e,n){t.shadowRoot&&(xy.has(t)||await async function(t,e,n){xy.add(t),await Ey(t.shadowRoot,e,n)}(t,e,n))}async function Iy(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=wy(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=my("",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),gy.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Ny(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=Sy(t);void 0===o.get(s.name)?(Py.has(t)||(Py.add(t),o.whenDefined(s.name).then(async()=>{await ky(t,e,n)})),a.has(s.name)||gy.has(s.name)||(a.add(s.name),i.push(s))):await ky(t,e,n)}let l=0;for(const t of i)await Iy(t,e,n,o),l++;return l}async function Ay(t,e,n,o){for(;await Ny(t,e,n,o)>0;);}async function Ey(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 $y(e)}return $y(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Ay(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 Ay(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Cy extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Cy._instance)throw new Error(`${fy.tagNames.autoloader} can only be instantiated once.`);Cy._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=py(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=my(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(_y(s,o,r))}await Promise.all(n)}(n,fy.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 Ey(document,fy,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Cy._instance===this&&(Cy._instance=null)}}!function(t=customElements){t.get(fy.tagNames.autoloader)||t.define(fy.tagNames.autoloader,Cy)}(void 0);
1
+ const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const n={seen:!1},o={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},s=o,r=Symbol.for("wcstack.binder"),i=Symbol.for("wcstack.binder.pending"),a=Symbol.for("wcstack.binder.taken");const l=".",c="*",u=128,d=128,h="#",f="|",p="prevent",m="stop",g="ro",y="init",b="sync",w="else",v="...",_="on",$="eventToken",x="state",S="command",I="class",P="attr",k="style",N={};for(let t=0;t<u;t++)N[`$${t+1}`]=t;const A=Object.freeze(N),E="$connectedCallback",C="$disconnectedCallback",M="$renderedCallback",T="$errorCallback",O="$stateReadyCallback",L="$bindables",R="$commands",j="$commandTokens",W="$command",D="$eventTokens",z="$on",B="$stream",F="$watch",H="$scan",q="$recursion",U="**",V="$listKeys",G="$streamStatus",K="$streamError",J="data-wc-definition",Q=/\{\{\s*(.+?)\s*\}\}/g,X=new Set(["SCRIPT","STYLE"]);function Y(t){if(!s.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&X.has(t.parentElement.tagName)||Z(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),Y(e.content)}else Y(t.content)}function Z(t){const e=t.data;if(Q.lastIndex=0,!Q.test(e))return;Q.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Q.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}function tt(t){throw new Error(`[@wcstack/state] ${t}`)}const et=new Map;let nt=0;function ot(t){let e=et.get(t);if(void 0!==e)return e;-1!==t.indexOf(U)&&tt(`[wcs/recursion-unsupported] "${t}" uses "${U}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`);const n=function(t){let e=1;for(let n=0;n<t.length;n++)t[n]===l&&e++;return e}(t);return n>512&&tt(`[wcs/binding-syntax] "${t}" has ${n} path segments — the limit is 512. Every prefix of a path is interned, so the cost grows with the square of the depth.`),e=Object.freeze(new st(t)),et.set(t,e),e}class st{id=++nt;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:ot(e),n=t.split("."),o=[],s=[],r=[],i={},a=[],l=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===c&&(r.push(h),i[h]=p,a.push(e(h)),l.push(f),u.push(e(f)),d.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=l,this.wildcardParentPathSet=new Set(l),this.wildcardParentPathInfos=u,this.wildcardParentPathInfoSet=new Set(u),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}}function rt(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function it(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=rt(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const at=" Validate statically: npx @wcstack/lint <file>.",lt=new Set(["if","elseif","else","for"]);function ct(t,e){return`${JSON.stringify(t)}${JSON.stringify(e)}`}function ut(t){if(0===t.length)return"";let e="";for(let n=0;n<t.length;n++){const o=t[n];n>0&&(e+="|"),e+=`${o.filterName}(${ct(o.args,o.literals??o.args)})`}return e}let dt=null;const ht=new Map([["not",()=>t=>!t]]),ft=new Map([["not",[0,0]]]),pt={input:new Map,output:new Map},mt={input:new Map,output:new Map},gt={input:new Map,output:new Map},yt=new Map;function bt(t,e,n,o){const s=pt[t],r=mt[t];for(const t of Object.keys(e)){s.set(t,e[t]);const o=n?.[t];void 0===o?r.delete(t):r.set(t,o)}const i=o??{},a=gt[t];for(const[t,n]of[...a])Object.prototype.hasOwnProperty.call(e,n)&&i[t]!==n&&a.delete(t);for(const t of Object.keys(i))a.set(t,i[t]);yt.clear()}function wt(t,e,n,o=e){const s=gt[n].get(t);void 0!==s&&dt?.renamed(t,s);const r=s??t,i=`${r}${ct(e,o)}:${n}`,a=yt.get(i);if(void 0!==a)return a;const l=pt[n].get(r)??ht.get(r);if(void 0===l){const e=0===pt[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";tt(`[wcs/filter-unknown] filter not found: ${t}.${it(t,function(t){return[...new Set([...ht.keys(),...pt[t].keys()])]}(n))}${e}${at}`)}const c=mt[n].get(r)??ft.get(r);void 0!==c&&(e.length<c[0]||e.length>c[1])&&tt(e.length<c[0]?`[wcs/filter-arity] filter "${t}" requires at least ${c[0]} argument(s) (${e.length} given).${at}`:`[wcs/filter-arity] filter "${t}" accepts at most ${c[1]} argument(s) (${e.length} given).${at}`);const u=l(e,o);return yt.set(i,u),u}function vt(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const _t=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function $t(t,e){return e?t:"true"===t||"false"!==t&&("null"===t?null:_t.test(t)?Number(t):t)}function xt(t){const e=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const t=vt(o,i,a);e.push(t),n.push($t(t,r)),o="",r=!1,i=-1,a=-1};for(let e=0;e<t.length;e++){const n=t[e];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&tt(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${t})". Close the quote.${at}`);const c=vt(o,i,a);return(c||r)&&(e.push(c),n.push($t(c,r))),{args:e,literals:n}}const St=t=>t.trim(),It=t=>"'"===t||'"'===t;function Pt(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(null!==n)s===n&&(n=null);else if(It(s))n=s;else if(s===e)return o}return-1}function kt(t,e){const n=[];let o=null,s=0;for(let r=0;r<t.length;r++){const i=t[r];null!==o?i===o&&(o=null):It(i)?o=i:i===e&&(n.push(t.slice(s,r)),s=r+1)}return n.push(t.slice(s)),n}function Nt(t,e,n){const o=n??t.join("|");return t.map(t=>{const n=Pt(t,"(");let s=function(t){let e=null,n=-1;for(let o=0;o<t.length;o++){const s=t[o];null!==e?s===e&&(e=null):It(s)?e=s:")"===s&&(n=o)}return n}(t);if(-1===s&&(s=t.lastIndexOf(")")),-1!==n&&-1===s&&tt(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${t}".${at}`),-1!==s&&-1===n&&tt(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${t}".${at}`),-1!==s&&s<n&&tt(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${t}".${at}`),-1!==s&&t.slice(s+1).trim().length>0){const e=t.slice(s+1).trim();tt(`[wcs/binding-syntax] "${t}": unexpected "${e}" after the filter's closing ")" — separate filters with "|" (write "${t.slice(0,s+1)}|${e}").${at}`)}const r=(-1===n?t:t.substring(0,n)).trim();if(0===r.length&&tt(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${at}`),r.includes(h)){const[t,n]=r.split(h);tt("input"===e?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${h}${n}" comes before the input filters, not inside one — write "<property>${h}${n}|${t}".${at}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${h}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${t}" here.${at}`)}return-1===n?{filterName:r,args:[],literals:[]}:{filterName:r,...xt(t.substring(n+1,s))}})}const At=new Map;function Et(t){const e=Pt(t,f);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),At.has(s)?r=At.get(s):(o=kt(s,f).map(St),r=Nt(o,"input",t),At.set(s,r))):n=t.trim();const i=n.split(h).map(St);i.length>2&&tt(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${h}" — write "${i[0]}${h}${i.slice(1).join(",")}".${at}`);const[a,c]=i,u=a.split(l).map(St);return u.length>1&&""===u[0]||0!==a.length&&!u.some(t=>0===t.length)||tt(`[wcs/binding-syntax] "${t}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${at}`),{propName:a,propSegments:u,propModifiers:c?c.split(",").map(St):[],inFilters:r}}const Ct=new Map;function Mt(t){const e=Pt(t,f);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Ct.has(s)?r=Ct.get(s):(o=kt(s,f).map(St),r=Nt(o,"output",t),Ct.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&tt(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`);const i=n,a=i.startsWith(l),c=a?i.slice(1):i;return(c.length>0&&c.split(l).some(t=>0===t.length)||!a&&0===c.length)&&tt(`[wcs/binding-syntax] "${t}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).${at}`),{statePathName:i,statePathInfo:ot(i),outFilters:r}}const Tt=new Set([w,"if","elseif","for",v]),Ot=new Set([I,P,k,S,$,x]);function Lt(t){const[...e]=function(t){return kt(t,";")}(t).map(St).filter(t=>t.length>0),n=e.map(t=>{const e=Pt(t,":");-1===e&&tt(`[wcs/binding-syntax] Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.${at}`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim(),s=n.split(h)[0].split(f)[0].trim();if(s!==n&&Tt.has(s)&&tt(`[wcs/binding-syntax] "${t}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${at}`),n===w){o.length>0&&tt(`[wcs/binding-syntax] "${t}": "else" takes no value — write "else:".${at}`);const e=ot("#else");return{propName:w,propSegments:[w],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===v){0===o.length&&tt(`[wcs/binding-syntax] Invalid spread binding "${t}": spread target path is required.${at}`);const e=Mt(o);return e.outFilters.length>0&&tt(`[wcs/binding-syntax] Invalid spread binding "${t}": filters are not allowed on spread targets.${at}`),{propName:v,propSegments:[v],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Mt(o),bindingType:n};if("radio"===s||"checkbox"===s){const t=Mt(o);return{...Et(n),...t,bindingType:s}}{const t=Mt(o),e=Et(n);if(""===e.propSegments[0]&&e.propSegments.length>1){const o=e.propSegments.slice(1);return(o.includes("")||Ot.has(o[0]))&&tt(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Ot].join(", ")}).${at}`),{...e,propName:o.join(l),propSegments:o,...t,bindingType:"prop"}}return e.propSegments[0]===$||e.propSegments[0].startsWith(_)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>lt.has(t.bindingType))&&tt(`[wcs/template-syntax] Invalid bindText: "${t}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${at}`),n}const Rt=new WeakMap,jt=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),Wt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Dt(t){const e=Rt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),o=Wt.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return jt.has(r)?(Rt.set(t,o[2]),o[2]):null}function zt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Mt(t),bindingType:"text"}}const Bt=new WeakMap,Ft=new WeakSet;let Ht=0;async function qt(t){const e=function(t){let e,n=Bt.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++Ht,promise:o,resolve:e},Bt.set(t,n),Ft.has(t)&&n.resolve(),n}(t);await e.promise}function Ut(t){const e=Bt.get(t);void 0===e?Ft.add(t):e.resolve()}const Vt=new WeakMap;function Gt(t){const e=Vt.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{Vt.set(t,n)}}function Kt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Jt(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Kt(e);if(void 0!==n)return Kt(n)}return Kt(globalThis.customElements)}function Qt(t,e){t.upgrade?.(e)}function Xt(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=ee(s.properties,Yt);if(null===r)return null;const i=void 0===s.inputs?new Map:ee(s.inputs,Zt);if(null===i)return null;const a=void 0===s.commands?new Map:ee(s.commands,te);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Yt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function Zt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function te(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function ee(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function ne(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:ot(n),inFilters:[],outFilters:[],bindingType:"prop"}}function oe(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function se(t,e,n={}){const o=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&tt("Spread binding requires an element node.");const e=t,s=Gt(e);null===s&&tt(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Jt(e);if(null===a&&tt(`CustomElementRegistry is unavailable for <${s}>.`),void 0===a.get(s)){o||tt(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Qt(a,e);const l=Xt(e);null===l&&tt(`Spread binding "${n.statePathName}" requires <${s}> to expose a valid wcBindable declaration.`);const c=n.statePathName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=ne(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=ne(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=oe(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=oe(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(s.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function re(t,e){let n=t;for(let t=0;t<e.length;t++){let o=e[t];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function ie(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:wt(s.filterName,s.args,e,r)})}return n}function ae(t){return{...t,inFilters:ie(t.inFilters,"input"),outFilters:ie(t.outFilters,"output")}}const le=new WeakMap;function ce(t){return le.get(t)||null}function ue(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(s.bindAttributeName)}function de(t){const e=[],n=t.querySelectorAll(`${s.tagNames.state}[bind-component]`);for(const o of n){if(!ue(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function he(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function fe(t){const e=[],n=de(t),o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Dt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;o.nextNode();){const t=o.currentNode;n.length>0&&he(t,n)||e.push(t)}return e}const pe=new WeakSet;function me(t,e,n,o){const s=se(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Gt(t):null;return null===n&&tt("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}pe.add(t);const r=function(t,e){const n=[];for(const o of e){const e=ie(o.inFilters,"input"),s=ie(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:t});else{const r=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:r})}}return n}(t,function(t,e){return void 0===e?t:t.map(t=>null!=t.uuid?t:e(t))}(s,o));return function(t,e){le.set(t,e)}(t,r),Ut(t),{bindings:r,deferred:null}}function ge(t,e){return ye(fe(t),e)}function ye(t,e){const n=[],o=[];for(const s of t){if(pe.has(s))continue;const t=me(s,Ol(s),{allowDeferred:!0},e);null===t.deferred?n.push(...t.bindings):o.push(t.deferred)}return[t,n,o]}function be(t){pe.add(t)}function we(t){const{node:e,parseResults:n,transform:o}=t;return function(t){pe.delete(t)}(e),me(e,n,{allowDeferred:!1},o).bindings}const ve=new WeakMap;let _e=null;function $e(t){let e=t;for(;e;){const t=ve.get(e);if(t)return t;let n=e.parentNode;null===n&&null!==_e&&e instanceof ShadowRoot&&(n=_e(e)),e=n}return null}function xe(t,e){null!==e?ve.set(t,e):ve.delete(t)}let Se=null,Ie=0;function Pe(){return`u${(Ie++).toString(36)}`}let ke=0,Ne=0;const Ae=Symbol("wcs.listIndex.noValue");class Ee{uuid=Pe();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;cacheStamp=0;ref;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ae,this._index=e,this._version=ke,this._chainGeneration=Ne}get index(){return this._index}set index(t){this._index=t,this._version=++ke,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}set homeParentListIndex(t){this._homeParentListIndex=t}get value(){return this._value}set value(t){this._value=t}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=ke),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===Ne||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=Ne),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++ke,Ne++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function Ce(t,e,n=t){return new Ee(t,e,n)}function Me(t,e){t.reparent(e)}function Te(t){return t.homeParentListIndex}function Oe(t,e){t.homeParentListIndex=e}function Le(t){return t?.cacheStamp}function Re(t,e){const n=t,o=n.value,s=o!==Ae&&!Object.is(o,e);return o!==e&&(je.get(o)?.delete(n.ref),function(t,e){if("object"!=typeof t||null===t||null===e.parentListIndex)return;let n=je.get(t);void 0===n?(n=new Set,je.set(t,n)):n.size>=(We.get(n)??8)&&(De(n,e,!0),We.set(n,2*n.size+8)),n.add(e.ref??=new WeakRef(e))}(e,n)),n.value=e,s}const je=new WeakMap,We=new WeakMap;function De(t,e,n=!1){const o=[];return t?.forEach(s=>{const r=s.deref();void 0===r||n&&Be(r)?t.delete(s):r!==e&&o.push(r)}),o}const ze=new WeakSet;function Be(t){for(let e=t;null!==e;e=e.parentListIndex)if(ze.has(e))return!0;return!1}function Fe(t){return t.value}function He(t,e){const n=t.value;return n!==Ae&&n===e.value}let qe=0;const Ue=new WeakSet;function Ve(t){Ue.add(t)}function Ge(t){return Ue.has(t)}const Ke=new WeakMap;function Je(t){return ze.has(t)}const Qe=new WeakMap,Xe=new WeakMap,Ye=new WeakMap;function Ze(t,e){return!0===Qe.get(e)?.has(t)}function tn(t,e){return Ze(t,e)||Be(e)}const en=new WeakMap;function nn(t){en.delete(t)}function on(t,e,n){const o=Object(Fe(e)),s=Fe(n);for(const e in s)if(s[e]===t&&o[e]!==t)return!1;return!0}function sn(t,e){return!tn(t,e)&&en.get(e)!==qe}const rn=new WeakMap,an=new WeakMap,ln=new WeakSet;function cn(t){const e=Ke.get(t);return void 0===e?null:e}function un(t,e){const n=Ke.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o&&!Ge(t)){const s=null!==e&&o.parentListIndex!==e&&en.get(e)!==qe,r=function(t,e,n){const o=Te(e),s=e.parentListIndex;return null!==o&&o!==s&&!tn(t,o)&&on(t,o,s)?o:function(t,e,n,o){return null!==e&&null!==o&&o!==n&&!!ze.has(e)&&!(!sn(t,o)||o.position!==e.position)&&!Ze(t,e)&&He(o,e)}(t,o,s,n)||function(t,e,n){return e!==n&&null!==e&&null!==n&&e.position===n.position&&tn(t,e)&&sn(t,n)}(t,s,n)?n:null}(t,o,e);if(null!==r&&ln.has(t)){ln.delete(t);const e=[...t];Ve(e),Ke.set(e,n),gn(t,e);const o=n.map((e,n)=>{const o=Ce(r,n);return Re(o,t[n]),o});return Ke.set(t,o),o}if(null!==r)for(const t of n)Me(t,r);else if(s){!function(t,e){let n=rn.get(t);void 0===n?(n=new Set,rn.set(t,n)):n.size>=(an.get(t)??8)&&(n.forEach(e=>{tn(t,e)&&n.delete(e)}),an.set(t,2*n.size+8));for(const t of e)n.add(t)}(t,[o.parentListIndex,e]);const s=o.parentListIndex;if(null!==s&&s.position===e.position&&!on(t,s,e)&&on(t,e,s))for(const t of n)Me(t,e)}}return n}const dn=new WeakSet;function hn(t){dn.delete(t)}function fn(t,e,n=!1){null!==e?(n?dn.add(e):hn(e),Ke.set(t,e)):Ke.delete(t)}const pn=new WeakMap;function mn(t){let e=pn.get(t);return void 0===e&&(e={value:t},pn.set(t,e)),e}function gn(t,e){const n=pn.get(t);void 0!==n&&(n.value=e,pn.delete(t))}const yn=new WeakMap,bn=new WeakMap,wn=new Set,vn=new WeakMap,_n=new WeakMap;function $n(t){const e=t.absolutePathInfo.stateElement;let n=bn.get(e);return void 0===n&&(n=new WeakMap,bn.set(e,n)),n}function xn(t){return yn.get(t)??[]}function Sn(t,e){const n=yn.get(t);yn.set(t,e),_n.delete(t);const o=$n(t);n!==e&&void 0!==n&&o.get(n).delete(t);const s=o.get(e);void 0===s?o.set(e,new Set([t])):s.has(t)||(s.size>=(vn.get(s)??8)&&(s.forEach(t=>{In(t.listIndex)&&s.delete(t)}),vn.set(s,Math.max(8,2*s.size))),s.add(t))}function In(t){for(let e=t;null!==e;e=e.parentListIndex)if(Je(e))return!0;return!1}function Pn(t,e){const n=$n(t).get(e);return void 0===n?wn:(n.forEach(t=>{In(t.listIndex)&&n.delete(t)}),n)}function kn(t,e){return!_n.has(t)&&(_n.set(t,e),!0)}function Nn(t){return yn.has(t)}const An=new WeakMap;let En=null,Cn=0;function Mn(t){return An.get(t)??[]}function Tn(t,e){null===En?An.set(t,e):En.set(t,e)}function On(){Cn++,null===En&&(En=new Map)}function Ln(){if(0!==Cn&&(Cn--,!(Cn>0||null===En))){for(const[t,e]of En)An.set(t,e);En=null}}function Rn(t){return(En?.has(t)??!1)||An.has(t)}const jn=Symbol("$$setLoopContext"),Wn=Symbol("$$getByAddress"),Dn=Symbol("$$hasByAddress"),zn=Symbol("$$connectedCallback"),Bn=Symbol("$$disconnectedCallback"),Fn=Symbol("$$updatedCallback"),Hn=Symbol("$$errorCallback"),qn=new WeakMap,Un=new WeakMap;class Vn{absolutePathInfo;listIndex;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}}function Gn(t,e){if(null===e){let e=Un.get(t);return void 0!==e||(e=new Vn(t,null),Un.set(t,e)),e}{let n=qn.get(e);void 0===n&&(n=new WeakMap,qn.set(e,n));let o=n.get(t);return void 0!==o||(o=new Vn(t,e),n.set(t,o)),o}}const Kn=new WeakMap;function Jn(t,e){let n=Kn.get(t);void 0===n&&(n=new Map,Kn.set(t,n));let o=n.get(e);return void 0===o&&(o=Object.freeze(new Qn(t,e)),n.set(e,o)),o}class Qn{pathInfo;stateElement;constructor(t,e){this.pathInfo=e,this.stateElement=t}}function Xn(t,e){return Gn(Jn(t,e.pathInfo),e.listIndex)}function Yn(t,e,n){return Gn(Jn(t,e),n)}const Zn=new WeakMap;function to(t,e){null===e?Zn.delete(t):Zn.set(t,e)}function eo(t){return Zn.get(t)||null}const no=new Map;function oo(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=no.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,no.set(s,r)),r}function so(t,e,n){return e<0||e>=n?null:t.at(e-n)}function ro(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const io=new WeakMap;function ao(t){const e=$e(t.node);if(null===e)return null;let n=io.get(e);if(void 0===n)n=new WeakMap,io.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=oo(e.pathInfo,t.statePathInfo);return n>0&&(o=so(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const lo=new WeakMap;function co(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=eo(n);null===e?tt(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function uo(t,e){let n=null;if(n=lo.get(t)||null,null!==n)return n;const o=co(t,e),s=ao(t),r=Pl(o);return null===r&&tt("No state tree found on this root for binding."),n=Yn(r,t.statePathInfo,s),lo.set(t,n),n}function ho(t){lo.delete(t)}const fo=new WeakMap;function po(t,e){const n=fo.get(t);void 0===n?fo.set(t,e):n instanceof Set?n.add(e):n!==e&&fo.set(t,new Set([n,e])),null!==Se&&Se({type:"state:binding-added",absoluteAddress:t,binding:e})}function mo(t,e){const n=fo.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&fo.delete(t),null!==Se&&Se({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const go=new WeakMap;function yo(t){const e=fo.get(t);return void 0!==e?e:null!==t.listIndex?go.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const bo=new WeakMap,wo=new WeakMap;class vo{pathInfo;listIndex;_parentAddress;_rowAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e,this._rowAddress=null!==e&&t.lastSegment===c}get parentAddress(){const t=this._parentAddress;if(void 0!==t&&(!this._rowAddress||t.listIndex===this.listIndex.parentListIndex))return t;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let n=null;n=this.pathInfo.segments[this.pathInfo.segments.length-1]===c?this.listIndex?.parentListIndex??null:this.listIndex;const o=$o(e,n);return void 0!==t&&!_o(o,this.listIndex)&&_o(t,this.listIndex)?t:this._parentAddress=o}}function _o(t,e){const n=t.pathInfo;let o=Fe(t.listIndex);for(const t of n.segments.slice(n.wildcardPositions[n.wildcardCount-1]+1))o=Object(o)[t];return cn(o)?.[e.index]===e}function $o(t,e){if(null===e){let e=wo.get(t);return void 0!==e||(e=new vo(t,null),wo.set(t,e)),e}{let n=bo.get(e);void 0===n&&(n=new WeakMap,bo.set(e,n));let o=n.get(t);return void 0!==o||(o=new vo(t,e),n.set(t,o)),o}}const xo=new WeakMap;function So(t){let e=null;if(e=xo.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=ao(t);null===n&&tt(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=$o(t.statePathInfo,n)}else e=$o(t.statePathInfo,null);return xo.set(t,e),e}function Io(t){xo.delete(t)}function Po(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const ko=new Map,No=Po();function Ao(t,e){const n=ut(t.inFilters);return`${t.statePathName}::${e}::${n}`}function Eo(t){let e="input";for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}function Co(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function Mo(t,e){console.error(`[wcstack/state] ${e} rejected.`,t)}function To(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Co(t)&&Promise.resolve(t).catch(t=>Mo(t,e))}class Oo{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)try{e.push(n(...t))}catch(t){e.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,t)}return e}}class Lo extends Oo{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==Se&&Se({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const Ro=new WeakMap;function jo(t,e){let n=Ro.get(t);void 0===n&&(n=new Map,Ro.set(t,n));let o=n.get(e);return void 0===o&&(o=new Lo(e,t),n.set(e,o)),o}const Wo=new WeakMap;class Do extends Oo{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==Se&&Se({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function zo(t){return t instanceof Do}const Bo=new Map,Fo=Po();function Ho(t){const e=t.propModifiers.filter(t=>t===p||t===m).sort().join(",");return`${t.statePathName}::${e}`}function qo(t){return"event"===t.bindingType&&t.propName.startsWith(_)}function Uo(t){if(!qo(t))return!1;const e=Ho(t);let n=Bo.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(p)&&o.preventDefault(),e.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Pl(r);null===i&&tt("No state tree found on this root for event handler.");const a=$e(s),l=t.startsWith(W+".");i.createStateAsync("writable",async e=>{const c=e[jn](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const t=i.addressHooks;if(t){const e=t.handlerScope;for(let t=0;t<e.length;t++)c=e[t](i,s,r,a,c)}}const u=null!==a?ro(a.listIndex,c):[];if(l){const s=e[Wn]($o(n,null));return zo(s)||tt(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...u)}const d=e[t];return"function"!=typeof d&&tt(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});To(c,`"${t}"`)}).catch(e=>Mo(e,`"${t}"`))})(t.statePathName,t.propModifiers,t.statePathInfo),Bo.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Fo.add(e,t),!0}function Vo(t){if(!qo(t))return!1;const e=Ho(t),n=Bo.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);return t.node.removeEventListener(o,n),0!==Fo.countOf(e)&&(Fo.remove(e,t)&&Bo.delete(e),!0)}const Go=new Map,Ko=Po();function Jo(t,e){const n=ut(t.inFilters);return`${t.statePathName}::${e}::${n}`}function Qo(t){let e="input";for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}const Xo=new Set(["radio","checkbox"]),Yo=new Set(["value","valueAsNumber","valueAsDate"]);function Zo(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(Xo.has(t)&&"checked"===e)return!0;if(Yo.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Gt(n);if(null!==s){const t=Jt(n)?.get(s);void 0===t&&tt(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Xt(n);if(o?.knownProperties.has(e))return!0}return!1}let ts=1,es=1,ns=1;const os=new WeakMap;function ss(t,e,n){let o=os.get(t);void 0===o&&(o=new Map,os.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=ts++,o.set(s,r)),r}function rs(t,e){return"to-element"===e?2*t:2*t+1}const is=new Set;function as(t){return{transactionId:es++,originBindingId:t,visitedEdges:is,hop:0}}function ls(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let cs=null;function us(){return cs}function ds(t,e){const n=cs;cs=t;try{return e()}finally{cs=n}}const hs=[];let fs=0;function ps(t,e,n,o,s=!1){fs=s?2:1;try{t.createState("writable",t=>{t[jn](e,()=>{t[n]=o})})}finally{fs=0}}const ms=new Map,gs=Po(),ys=new WeakMap,bs=t=>t.detail,ws=new WeakMap,vs=new WeakMap;let _s=0;const $s=new WeakMap;function xs(t){const e=Gt(t.node);if(null!==e){const n=Jt(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&tt(`CustomElementRegistry is unavailable for <${e}>.`))}if(Zo(t.node,t.propName)&&-1===t.propModifiers.indexOf(g)){const e=function(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Gt(t.node);if(null!==n){const o=Jt(t.node)?.get(n);void 0===o&&tt(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Xt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(_)&&(e=n.slice(2));return e}(t),n=function(t){if(null!==Gt(t.node)){const e=Xt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??bs}return null}(t),o=function(t){if(null===Gt(t.node))return!1;const e=Xt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}(t),r=function(t,e,n,o){const s=ut(t.inFilters);return`${t.propName}::${t.statePathName}::${e}::${s}::${function(t){if(null===t)return"n";let e=vs.get(t);return void 0===e&&vs.set(t,e=++_s),`g${e}`}(n)}::${o?"o":"s"}`}(t,e,n,o);$s.set(t,{key:r,eventName:e});let i=ms.get(r);void 0===i&&(i=((t,e,n,o,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==o)l=o(i),o!==bs||r||function(t,e,n){const o=t[e];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${e} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,e)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${e}" key while element.${e} is ${typeof o}`),null===s)return;let r=ws.get(t);void 0===r&&(r=new Set,ws.set(t,r)),r.has(e)||(r.add(e),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${t.tagName.toLowerCase()}> "${e}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${e}, or (e) => e.target.${e}) on that wcBindable property.`))}(a,t,l);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const t of n)c=t.filterFn(c);const u=ys.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(s.enablePropagationContext){const n=ss(a,t,e),o=function(t,e){for(let n=hs.length-1;n>=0;n--){const o=hs[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==o&&Object.is(o.writtenValue,l))return s.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:o.transactionId,coveredBySameValueGuard:s.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==Se&&Se({type:"propagation:suppressed",reason:"confirmation",transactionId:o.transactionId,edgeId:rs(n,"to-state"),node:a,member:t}));const r=rs(n,"to-state"),i=us();if(null!==i&&i.visitedEdges.has(r))return void(null!==Se&&Se({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=ls(i??as(n),r)}const h=Pl(a.getRootNode());null===h&&tt("No state tree found on this root for two-way binding.");const f=$e(a),p=()=>ps(h,f,e,c,r);null!==d?ds(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,o),ms.set(r,i)),t.node.addEventListener(e,i),gs.add(r,t)}}const Ss=new WeakSet;function Is(t){Ss.add(t)}function Ps(t){return!!Ss.has(t)&&(Ss.delete(t),!0)}const ks=new WeakMap;function Ns(t,e){const n=ks.get(t);return!(void 0===n||n<e||(n===e?ks.delete(t):ks.set(t,n-e),0))}const As=new WeakSet;function Es(t){As.add(t)}function Cs(t){return!!As.has(t)&&(As.delete(t),!0)}let Ms=0;function Ts(){Ms--}function Os(){return Ms>0}class Ls{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const Rs=new WeakMap;function js(t){let e=Rs.get(t);return void 0===e&&(e=new Ls(t),Rs.set(t,e)),e}const Ws=new Set([I,P,k,S]);function Ds(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==y&&s!==b&&tt(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&tt(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function zs(t){return t.propModifiers.some(t=>t.includes("="))}const Bs=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Fs=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Hs(t,e){return"state"===t&&"call"===e?Bs:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function qs(t){if(!s.enableDirectionalInitialSync)return zs(t)&&tt("init=/sync= modifiers require enableDirectionalInitialSync."),Bs;const e=null===(n=Ds(t,y))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:tt(`Invalid init modifier value "${n}".`);var n;const o=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":tt(`Invalid sync modifier value "${t}".`)}(Ds(t,b));if("event"===t.bindingType)return null!==e&&"none"!==e&&tt("Event bindings only allow init=none."),"call"===o?Fs:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(Ws.has(t.propSegments[0]))return Hs("state",o);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&tt(`Binding type "${t.bindingType}" does not support init=${e}.`),Hs(e??"state",o);const r=Xt(t.node);if(null===r)return Hs(e??"state",o);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||tt(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||tt(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==o||i||tt(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:o,observable:i,outputOnly:i&&!a}}function Us(t){let e=t.getRootNode();return e instanceof DocumentFragment&&!(e instanceof ShadowRoot)&&(e=eo(e)),null===e?null:Pl(e)}let Vs=0,Gs=null,Ks=0;const Js=["active","disposed","failed"],Qs=new WeakMap,Xs=new WeakMap,Ys=new WeakMap,Zs=new WeakMap,tr=new WeakMap,er=new WeakMap;function nr(t,e){const n=er.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):er.set(t,new Set([n,e]))):er.set(t,e)}function or(t){return er.has(t)}function sr(t,e){const n=er.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function rr(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))rr(n,e)}function ir(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class ar{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.removedNodes;if(0===r.length||!Ns(s.target,r.length))for(let t=0;t<r.length;t++)e.push(r[t]);const i=s.addedNodes;for(let t=0;t<i.length;t++)n.push(i[t])}const o=[];for(const t of e)Ps(t)||rr(t,t=>{sr(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)Cs(t)&&!Os()||rr(t,t=>{sr(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&hl(o)}}const lr=new WeakMap;function cr(t){let e=lr.get(t);return void 0===e&&(e=new ar(t),lr.set(t,e)),e}function ur(t){const e=ut(t.inFilters),n=ut(t.outFilters);return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function dr(t,e,n){const o=Pl(co(t,n));null===o&&tt("No state tree found on this root for binding.");const s=Jn(o,t.statePathInfo);return function(t,e,n){let o=go.get(t);void 0===o&&(o=new WeakMap,go.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==Se&&Se({type:"state:binding-added",absoluteAddress:Gn(t,e),binding:n})}(s,e,t),s}function hr(t,e){const n=uo(t,e);return po(n,t),n}function fr(t,e,n,o){null!==e?mo(e,t):function(t,e,n){const o=go.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==Se&&Se({type:"state:binding-removed",absoluteAddress:Gn(t,e),binding:n}))}(n,o,t),Io(t),ho(t)}function pr(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class mr{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;disposedAt=0;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=this.rowOf(t),i=null===o?-1:o.bindings.indexOf(t);if(null!==o&&0===o.phases[i]){const e=o;this.observe(t.replaceNode),s.registerAddress&&null===e.addresses[i]&&null===e.patternPathInfos[i]&&(e.registered=!0,this.registerRowSlot(e,i));continue}const a=Ys.get(t);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(t,s,n),r.push(t)):(this.observe(a.anchor),s.registerAddress&&null===a.address&&null===a.patternListIndex&&(a.options.registerAddress=!0,this.registerAddress(a)),"active"===a.phase&&this.settleInitialRecord(a),this.settleConnectedSnapshot(a))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(ir(e)&&cr(e),null===this.rowPlan)for(const n of t){const t=Ys.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!s.enableDirectionalInitialSync)return zs(t)&&qs(t),!0;const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0){if(!e.registered)return!0;if(2===e.phases[n])return!1;const t=e.plan.slots[n];return 1&e.flags[n]?"state"===t.authority||!t.policy.outputOnly:(e.flags[n]|=1,"state"===t.authority)}}const n=Ys.get(t);return void 0===n||n.session!==this||!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority))}getRecord(t){const e=this.rowOf(t),n=null===e?-1:e.bindings.indexOf(t);if(null!==e&&n>=0){let o=Xs.get(e);return void 0===o&&Xs.set(e,o=[]),{id:o[n]??(o[n]=++Vs),info:t,generation:e.generation,phase:Js[e.phases[n]],teardowns:null}}const o=Ys.get(t);return o?.session===this?o:null}addTeardown(t,e){const n=Ys.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(pr(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=this.deferredByNode.get(t)??new Set,r=()=>s.delete(a)&&this.deferred.delete(a),i=()=>{const s=Jt(t);null===s&&tt(`CustomElementRegistry is unavailable for <${e}>.`),a.cancel=js(s).wait(e,()=>{if(r())try{Qt(s,t),n()}catch(t){o(t)}},t=>{r()&&o(t)})},a={node:t,born:++Ks,cancel:null,arm:()=>{if(null===a.cancel&&this.deferred.has(a))try{i()}catch(t){r(),o(t)}}},l=t.getRootNode();if(null!==Gs||11===l.nodeType&&!ir(l)){if(null===Gs){const t=Gs=[];queueMicrotask(()=>{Gs=null;for(let e=0;e<t.length;e++)t[e].arm()})}Gs.push(a)}else i();return ir(l)&&cr(l),nr(t,this),this.deferredByNode.set(t,s.add(a)),this.deferred.add(a),()=>{r(),a.cancel?.()}}disposeBinding(t){const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0)return void this.disposeRowSlot(e,n)}const n=Ys.get(t);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(t){for(let e=0;e<t.length;e++)this.disposeBinding(t[e]);if(!(this.rows.size>0))for(const t of Array.from(this.deferred))t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}destroyRow(t){const e=t.length>0?this.rowOf(t[0]):null;null!==e?(this.destroyRowRecord(e),this.rows.delete(e)):this.destroyRecords()}destroyRowRecord(t){for(let e=0;e<t.bindings.length;e++){const n=t.addresses[e];null!==n&&(mo(n,t.bindings[e]),t.addresses[e]=null),t.phases[e]=1}}dispose(){this.disposedAt=Ks;for(const t of Array.from(this.rows))for(let e=0;e<t.bindings.length;e++)this.disposeRowSlot(t,e);for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){this.disposedAt=Ks;for(const t of this.rows)this.destroyRowRecord(t);this.rows.clear();for(const t of this.records)null!==t.address&&(mo(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.rows)for(let n=0;n<e.bindings.length;n++)0===e.phases[n]&&t(e.bindings[n].node);for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];for(const e of this.rows)for(let n=0;n<e.bindings.length;n++){if(0!==e.phases[n])continue;if(null===e.addresses[n]&&null===e.patternPathInfos[n])continue;const o=e.bindings[n];this.unregisterRowSlot(e,n),this.registerRowSlot(e,n),this.shouldApplyState(o)&&t.push(o)}for(const e of this.records){if("active"!==e.phase)continue;const n=e.info;if(null===e.address&&null===e.patternListIndex)continue;const o="for"===n.bindingType?uo(n):null;if(fr(n,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null,this.registerAddress(e),null!==o){const t=uo(n);t!==o&&Nn(o)&&Sn(t,xn(o)),t!==o&&Rn(o)&&Tn(t,Mn(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return ir(e)?e:null}(t);null!==e&&cr(e)}handleMutations(t,e,n){for(const n of e)rr(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)rr(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&hl(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);this.deferredByNode.get(t)?.forEach(t=>{t.cancel?.(),t.cancel=null,this.deferred.delete(t)})}handleAddedNode(t,e){this.deferredByNode.get(t)?.forEach(t=>{t.born<=this.disposedAt||(this.deferred.add(t),t.arm())});const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Ys.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),(o.applyOnReconnect||n.pendingDefinitions>0&&n.generation>this.disposedAt)&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=tr.get(e);void 0===t&&(t=ur(e),tr.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;nr(n,this);const o=this.knownMapFor(n);let s=tr.get(t);void 0===s&&(s=ur(t),tr.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n=t.slots,o=e.length,s={id:++Vs,session:this,generation:++Ks,plan:t,bindings:e,registered:!1,phases:new Array(o).fill(0),flags:new Array(o).fill(0),addresses:new Array(o).fill(null),patternPathInfos:new Array(o).fill(null),patternListIndexes:new Array(o).fill(null)};this.rows.add(s);for(let t=0;t<o;t++){const o=e[t],r=o.replaceNode;if(nr(r,this),this.addKnownRowBinding(r,o,t),Qs.set(o,s),n[t].isEvent){let n=!1;try{n=Uo(o)}catch(e){throw s.phases[t]=2,e}n&&(s.flags[t]|=2)}}}activatePlanRows(t,e,n){const o=e.length>0?this.rowOf(e[0]):null;if(null===o||o.bindings!==e){for(const t of e)this.initialize([t],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=t.slots;let r=!1;for(let t=0;t<e.length;t++)if(0===o.phases[t])null===o.addresses[t]&&null===o.patternPathInfos[t]&&this.registerRowSlot(o,t,n);else{if(r||(o.generation=++Ks,r=!0,this.rows.add(o)),o.phases[t]=0,o.flags[t]=0,s[t].isEvent){let n=!1;try{n=Uo(e[t])}catch(e){throw o.phases[t]=2,this.runRowSlotTeardowns(o,t),e}n&&(o.flags[t]|=2)}this.registerRowSlot(o,t,n)}}rowOf(t){const e=Qs.get(t);return void 0!==e&&e.session===this?e:null}registerRowSlot(t,e,n){if(null!==t.addresses[e]||null!==t.patternPathInfos[e])return;const o=t.bindings[e],s=ao(o);null!==s?(t.patternPathInfos[e]=dr(o,s,n),t.patternListIndexes[e]=s):t.addresses[e]=hr(o,n)}unregisterRowSlot(t,e){const n=t.addresses[e],o=t.patternPathInfos[e];null===n&&null===o||(fr(t.bindings[e],n,o,t.patternListIndexes[e]),t.addresses[e]=null,t.patternPathInfos[e]=null,t.patternListIndexes[e]=null)}disposeRowSlot(t,e){if(1!==t.phases[e]){t.phases[e]=1,this.runRowSlotTeardowns(t,e);for(let e=0;e<t.phases.length;e++)if(0===t.phases[e])return;this.rows.delete(t)}}runRowSlotTeardowns(t,e){try{this.unregisterRowSlot(t,e)}catch{}if(2&t.flags[e]){t.flags[e]&=-3;try{Vo(t.bindings[e])}catch{}}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++Vs,info:t,generation:++Ks,phase:"discovered",teardowns:null,session:this,anchor:t.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Ys.set(t,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;Uo(e)?t.eventAttached=!0:e.propSegments[0]!==$?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const o=Qo(t),s=Jo(t,o);let r=Go.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const t of n)s=t.filterFn(s);const r=Pl(o.getRootNode());null===r&&tt("No state tree found on this root for two-way binding.");const i=$e(o);r.createState("writable",t=>{t[jn](i,()=>{t[e]=s})})},Go.set(s,r)),t.node.addEventListener(o,r),Ko.add(s,t),!0}var e,n;return!1}(e)&&pr(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const e=Qo(t),n=Jo(t,e),o=Go.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Ko.countOf(n)&&(Ko.remove(n,t)&&Go.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const o=Eo(t),s=Ao(t,o);let r=ko.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const t of n)r=t.filterFn(r);const i=Pl(o.getRootNode());null===i&&tt("No state tree found on this root for two-way binding.");const a=$e(o);i.createState("writable",t=>{t[jn](a,()=>{let n=t[e];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(t[e]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(t[e]=n.toSpliced(o,1))}else t[e]=s?[r]:[]})})},ko.set(s,r)),t.node.addEventListener(o,r),No.add(s,t),!0}var e,n;return!1}(e)&&pr(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(g)){const e=Eo(t),n=Ao(t,e),o=ko.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==No.countOf(n)&&(No.remove(n,t)&&ko.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(s.enableDirectionalInitialSync&&Zo(e.node,e.propName)&&-1===e.propModifiers.indexOf(g)){const n=function(t,e,n){let o=ys.get(t);void 0===o&&(o=new Map,ys.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&ys.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});pr(t,n)}xs(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==$)return!1;const e=t.node,n=Gt(e),o=Jt(e);if(null!==n&&void 0===o?.get(n))return null===o&&tt(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Wo.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||tt('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Gt(t)?null:Xt(t)}(e);null===r&&tt(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&tt(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${it(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,c=t.propModifiers,u=t=>{c.includes(p)&&t.preventDefault(),c.includes(m)&&t.stopPropagation();const n=Pl(e.getRootNode());null===n&&tt("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||tt(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${it(l,n.eventTokenNames)}${at}`);const o=$e(e);n.createStateAsync("writable",async e=>{To(e[jn](o,()=>{const s=null!==o?ro(o.listIndex,o.pathInfo.wildcardCount):[];return jo(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,u),Wo.set(t,{eventName:a,handler:u}),!0})(e)&&pr(t,()=>function(t){if(t.propSegments[0]!==$)return!1;const e=Wo.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),Wo.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Gt(t.info.node);if(null===n)return void e();const o=Jt(t.info.node);if(null===o&&tt(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation;pr(t,this.deferUntilDefined(t.info.node,n,()=>{this.isAlive(t,s)&&(e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t)))},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))}))}settleInitialRecord(t){if(s.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=qs(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=Us(t.replaceNode);null===e&&tt("No state tree found on this root for binding.");const n=So(t);let o=!1;return e.createState("readonly",t=>{o=t[Dn](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void Ms++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,Ts()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=Us(t.node);null===o&&tt("No state tree found on this root for initial binding sync."),ps(o,$e(t.node),t.statePathName,n)}(t.info,r))}settleConnectedSnapshot(t){if(s.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=ao(n);if(null!==o?(t.patternPathInfo=dr(n,o,e),t.patternListIndex=o):t.address=hr(n,e),!t.options.registerPathInfo)return;const s=Pl(n.replaceNode.getRootNode());null===s&&tt("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Ys.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,Ts());const e=t.info;if(null!==t.address||null!==t.patternListIndex)try{fr(e,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=$s.get(t);if(void 0===e)return;$s.delete(t);const n=ms.get(e.key);void 0!==n&&(t.node.removeEventListener(e.eventName,n),gs.remove(e.key,t)&&ms.delete(e.key))}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{Vo(e)}catch{}}}}function gr(t){let e=Zs.get(t);return void 0===e&&(e=new mr(t),Zs.set(t,e)),e}function yr(t){return Ys.get(t)?.session??Qs.get(t)?.session??null}let br=null;function wr(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const vr=Object.freeze([]),_r=new WeakMap,$r=new WeakMap;function xr(t){return $r.get(t)??[]}function Sr(t,e){$r.set(t,e)}const Ir=new WeakMap;function Pr(t){return Ir.get(t)??[]}function kr(t,e){Ir.set(t,e)}function Nr(t,e){const n=Pr(t);for(const t of n)xe(t,e)}const Ar=new WeakMap;function Er(t){return Ar.get(t)??[]}function Cr(t,e){Ar.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});const Mr=new WeakMap,Tr=new WeakSet;function Or(t,e){if(null===e)Mr.delete(t);else{Mr.set(t,e);const{stateElement:n,pathInfo:o}=t.absolutePathInfo;if(o.wildcardCount>0){for(let t=o.parentPathInfo;null!==t&&t.wildcardCount===o.wildcardCount&&!Tr.has(t);t=t.parentPathInfo)Tr.add(t);n.setPathInfo(o.lastWildcardPath,"prop","internal")}}}function Lr(t){const e=Mr.get(t);e&&(e.dirty=!0),null!==t.listIndex&&Tr.has(t.absolutePathInfo.pathInfo)&&t.listIndex.cacheStamp++}const Rr=Symbol.for("wcstack.transition-runner");function jr(t){const e=globalThis[Rr];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}function Wr(t,e,n){const o=jr(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const Dr=[],zr=[];let Br=-1,Fr=0,Hr=!1;function qr(t){zr.includes(t)||zr.push(t)}function Ur(t,e=0){const n=Dr.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Dr.push(o):Dr.splice(n,0,o)}function Vr(t){queueMicrotask(()=>{throw t})}const Gr=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){for(let e=0;e<zr.length;e++)zr[e](t);Br>Fr&&(Fr=Br),Br<0&&(Hr=!0);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(t){const e=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(t),e&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){On(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],qe++,this._applyChange(t,e)})}hasQueuedPath(t,e){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===t&&n.absoluteAddress.absolutePathInfo.pathInfo.path===e)}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t,n=[]){let o=Hr?0:Fr;Fr=0,Hr=!1;const s=new Map,r=new Set;for(let e=0;e<t.length;e++){const n=t[e],o=s.get(n.absoluteAddress);null!==Se&&null!=o&&null!==n.context&&o.transactionId!==n.context.transactionId&&Se({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:o.transactionId,winnerTransactionId:n.context.transactionId}),s.set(n.absoluteAddress,n.context),r.add(n.absoluteAddress)}for(let t=0;t<n.length;t++){const e=n[t];s.has(e)||s.set(e,null)}const i=[],a=new Map;s.forEach((t,e)=>{if(null!==t&&t.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,transactionId:t.transactionId,hop:t.hop,maxHops:32}),void(null!==Se&&Se({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop}));const n=yo(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(i.push(e),null!==t&&a.set(e,t));else!1!==n.replaceNode.isConnected&&(i.push(n),null!==t&&a.set(n,t))});try{const t=()=>{Br=o+1;try{a.size>0?hl(i,a):hl(i)}finally{Br=-1}};if(o>100&&i.length>0){if(101===o++){const t=[...new Set(Array.from(r,t=>t.absolutePathInfo.pathInfo.path))];console.error("[@wcstack/state] render chain depth limit exceeded; bindings for this batch were not applied.",{maxDepth:100,paths:t}),null!==Se&&Se({type:"state:render-chain-limit",maxDepth:100,paths:t})}}else if(e()||0===i.length)t();else{const e=Wr("state",t);void 0!==e&&e.catch(Vr)}}finally{Ln(),Br=o,function(t){for(const e of Dr.slice())e.listener(t)}(r),Br=-1}}};function Kr(){return Gr}const Jr=new WeakMap,Qr=new WeakMap,Xr=new WeakMap,Yr=new WeakMap;let Zr=!1;const ti=new WeakMap;function ei(t){const e=t.absolutePathInfo.stateElement;let n=ti.get(e);void 0===n&&ti.set(e,n=new Set),n.add(t)}function ni(t){const e=ti.get(t);return void 0===e?null:(ti.delete(t),e)}const oi=new WeakMap,si=new WeakMap,ri=new WeakMap,ii=new WeakMap,ai=new WeakMap,li=[];function ci(t,e){const n=ui(t);if(n.recorded.has(e))return;n.recorded.add(e);const o=ot(e).cumulativePaths;if(o.length<2)return;let s=ai.get(t);void 0===s&&ai.set(t,s=new Map);for(let t=0;t<o.length-1;t++){let n=s.get(o[t]);void 0===n&&s.set(o[t],n=new Set),n.add(e)}}function ui(t){let e=Jr.get(t);return void 0===e&&Jr.set(t,e={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),e}function di(t,e,n){let o=t.get(e);void 0===o&&t.set(e,o=new Set),o.add(n)}function hi(t,e,n){const o=t.get(e);o.delete(n),0===o.size&&t.delete(e)}function fi(t,e,n,o){const s=function(t,e){let n=t.byPath.get(e);return void 0===n&&t.byPath.set(e,n=new Map),n}(t,e);let r=Qr.get(o);if(void 0===r&&Qr.set(o,r=new Map),r.has(e)){const t=r.get(e);return Object.is(t,n)||(hi(s,t,o),r.set(e,n),di(s,n,o)),!1}return r.set(e,n),di(s,n,o),!0}function pi(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):(o.push(n),!1)}function mi(t,e,n,o,s,r){t.lastValue.set(e,n),s&&(null!==o.listIndex&&pi(Xr,o.listIndex,r)&&function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){let n=ri.get(e);void 0===n&&ri.set(e,n=new Set),n.add(t)}}(o.listIndex),null!==r.levelListIndex&&pi(Yr,r.levelListIndex,r))}function gi(t,e,n,o,s){Zr=!0;const r=ui(t);ci(t,e),mi(r,e,s,o,fi(r,e,n,o),{stateElement:t,path:e,absAddress:o,levelListIndex:null})}function yi(t,e){ui(t).tracked.add(e)}function bi(t,e){return!0===Jr.get(t)?.byPath.has(e)||!0===oi.get(t)?.has(e)}function wi(t,e,n){if("number"!=typeof e)return;const o=t.indexes[e];if(void 0!==o)for(const e of t.getters)n.push(Xn(t.stateElement,$o(e,o)))}function vi(t,e){if(!Zr||t===e)return;const n=si.get(t);if(void 0===n)return;si.delete(t);const o=si.get(e);si.set(e,void 0===o?n:o.concat(n)),hn(e);for(const o of n){o.indexes=e;const n=ui(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=t[n],r=e[n];if(s!==r)for(const t of[s,r])if(void 0!==t&&!Je(t))for(const e of o.getters){const n=Xn(o.stateElement,$o(e,t));Lr(n),Kr().enqueueAbsoluteAddress(n,null),ei(n)}}}function _i(t,e){if(void 0!==t)for(const n of t)e.push(n)}function $i(t,e,n,o,s){const r=Jr.get(t),i=r?.byPath.get(e),a=oi.get(t)?.get(e);if(void 0===r||void 0===i&&void 0===a)return li;const l=r.lastValue.has(e),c=r.lastValue.get(e);r.lastValue.set(e,s);const u=[],d=!n||!Object.is(o,s),h=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&_i(i.get(o),u),h&&_i(i.get(c),u),d&&_i(i.get(s),u)),void 0!==a)for(const t of a)n&&wi(t,o,u),h&&wi(t,c,u),d&&wi(t,s,u);return u}function xi(t,e){return!0===ai.get(t)?.has(e)}function Si(t,e){let n=t;for(const t of e){if("object"!=typeof n||null===n)return;n=n[t]}return n}function Ii(t,e,n,o,s=!0){const r=ot(e).segments.length,i=[];for(const a of ai.get(t).get(e)){const e=ot(a).segments.slice(r);if(e.includes(c)){Pi(t,a,i);continue}const l=s?Si(n,e):void 0;for(const n of $i(t,a,s,l,Si(o,e)))i.push(n)}return i}function Pi(t,e,n){const o=Jr.get(t).byPath.get(e);if(void 0!==o)for(const t of o.values())_i(t,n);const s=oi.get(t)?.get(e);if(void 0!==s)for(const t of s)for(let e=0;e<t.indexes.length;e++)wi(t,e,n)}function ki(t){const e=Yr.get(t.levelListIndex),n=e.indexOf(t);e.splice(n,1)}function Ni(t){const e=Xr.get(t);if(void 0!==e){Xr.delete(t),function(t){for(let e=t.parentListIndex;null!==e;e=e.parentListIndex){const n=ri.get(e);void 0!==n&&(n.delete(t),0===n.size&&ri.delete(e))}}(t);for(const t of e){const{stateElement:e,path:n,absAddress:o}=t,s=Qr.get(o),r=s.get(n);s.delete(n),hi(Jr.get(e).byPath.get(n),r,o),null!==t.levelListIndex&&ki(t)}}}function Ai(t){const e=ii.get(t);if(void 0!==e){ii.delete(t);for(const t of e){const e=oi.get(t.stateElement),n=e.get(t.path);n.delete(t),0===n.size&&e.delete(t.path);const o=si.get(t.indexes);o.splice(o.indexOf(t),1),0===o.length&&si.delete(t.indexes)}}}function Ei(t){if(!Zr)return;Ni(t),Ai(t);const e=ri.get(t);if(void 0!==e){ri.delete(t);for(const t of e)Ni(t),Ai(t),ri.delete(t)}}function Ci(t,e,n){if(!Zr)return;const o=Yr.get(t);if(void 0!==o)for(const{stateElement:t,path:s,absAddress:r}of o){const o=Jr.get(t),i=o.byPath.get(s);hi(i,e,r),di(i,n,r),Qr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,e)||Object.is(a,n))&&(Lr(r),Kr().enqueueAbsoluteAddress(r,null),ei(r))}}const Mi=new WeakMap,Ti=Object.freeze([]),Oi=new Set,Li=new WeakMap,Ri=new WeakMap;function ji(t,e){Ri.set(t,new WeakRef(Object(e)))}function Wi(t){return Ri.get(t)?.deref()}function Di(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function zi(t){!function(t){for(const e of t)ze.add(e)}(t);for(const e of t)Ei(e)}function Bi(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:Ti,s=Array.isArray(n)&&n.length>0?n:Ti,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:Ti,o=Array.isArray(e)&&e.length>0?e:Ti;let s=Mi.get(n);return s&&s.get(o)||null}(o,s);if(r&&r.newIndexes===un(s,t))return r;const i=un(o,t)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Oi,deleteIndexSet:new Set(i),addIndexSet:Oi};let e=un(s,t);if(null===e&&null!==t&&function(t,e){const n=rn.get(t);for(const o of n??[])if(tn(t,o))n.delete(o);else if(o!==e)return!0;return!1}(o,t)&&ji(s,o),0===o.length||null===e&&Wi(s)===o){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=Ce(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:Oi,deleteIndexSet:new Set(i),addIndexSet:new Set(e)}}if(Di(o,s)&&(e??i)===i)return o!==s&&Fi(o,i,t),a={oldIndexes:i,newIndexes:i,changeIndexSet:Oi,deleteIndexSet:Oi,addIndexSet:Oi};if(null!==e)return Hi(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,l=new Set;let c=!1;for(let o=0;o<s.length;o++){const a=s[o],u=n.get(a),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=Ce(t,o);e.push(n),l.add(n)}else{const t=i[d];c=!0,d!==o&&r.add(t),e.push(t)}}return c&&Fi(o,e,t),a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(function(t,e,n){let o=Mi.get(t);o||(o=new WeakMap,Mi.set(t,o)),o.set(e,n)}(o,s,a),hn(i),fn(s,a.newIndexes))}}(t,e,n);return function(t,e){const n=t.newIndexes;let o;for(let t=0;t<n.length;t++){if(n[t].index!==t){const e=n[t].index;n[t].index=t,Ci(n[t],e,t)}Re(n[t],e[t])&&(o??=[]).push(n[t])}const s=Li.get(e);s?.[0]===qe&&(o=o?s[1].concat(o):s[1]),o&&Li.set(e,[qe,o]),t.valueChangeIndexes=o}(o,Array.isArray(n)&&n.length>0?n:Ti),function(t){for(const e of t)ze.delete(e)}(o.newIndexes),Wi(n)!==e&&(zi(o.deleteIndexSet),vi(o.oldIndexes,o.newIndexes)),o}function Fi(t,e,n){var o;if(o=t,ln.add(o),null!==n)for(const t of e)Oe(t,n)}function Hi(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}const qi=new WeakMap;function Ui(t){return qi.get(t)??null}function Vi(t,e){qi.set(t,e)}const Gi=new WeakMap,Ki=new WeakMap;function Ji(t,e){for(let n=0;n<t.length;n++)if(e.has(t[n]))return!0;return!1}function Qi(t,e,n){Nr(t,e);const o=xr(t),s=Ui(t);if(null!==s&&(s.activate(o,n.rootNode),null!==e&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(t){return Gi.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=Ki.get(t);void 0===o&&Ki.set(t,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=e.map((e,o)=>{const s=t.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=e.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const t of a){if("*"===t)return null;c+="."+t,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(t,e,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let t=0;t<e.length;t++){const u=e[t];if(!n.shouldApplyState(u))continue;const d=r[t];if(null===d||Ji(d.prefixes,i)){ul(u,s);continue}if(s.appliedBindingSet.has(u))continue;c||(l=s.state[Wn](o),c=!0);const h=d.tail;let f=l,p=!1;for(let t=0;t<h.length;t++){if(null==f){f=void 0;break}if(a&&!(h[t]in Object(f))){p=!0;break}f=f[h[t]]}p?ul(u,s):(s.appliedBindingSet.add(u),cl(u,s,f))}}(r,o,s,e,n)}for(const t of o)null===s&&po(uo(t),t),(null===s||s.shouldApplyState(t))&&ul(t,n);t.spreads&&fl(t.spreads,e,s,o,Er(t))}function Xi(t){if(!t.mounted)return;const e=xr(t),n=Ui(t);for(let t=0;t<e.length;t++){const o=e[t];null!==n?n.disposeBinding(o):mo(uo(o),o)}!function(t){const e=Pr(t);for(let t=0;t<e.length;t++)xe(e[t],null)}(t)}const Yi=new WeakMap,Zi=Object.freeze(new Set);function ta(t,e){const n=Yi.get(t);n?n.add(e):Yi.set(t,new Set([e]))}function ea(t){const e=Yi.get(t);return void 0!==e?e:Zi}function na(t,e){const n=Yi.get(t);n&&(n.delete(e),0===n.size&&Yi.delete(t))}const oa=new Set(["if","elseif","else","for"]);class sa{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e;const n=[];for(let e=t.firstChild;null!==e;e=e.nextSibling)n.push(e);this._childNodeArray=n,this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(t){const e=this._childNodeArray;for(let n=0;n<e.length;n++){const o=e[n];Es(o),t.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){Es(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=Ui(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRow(xr(this));const e=this._childNodeArray;for(let t=0;t<e.length;t++){const n=e[t];null!==n.parentNode&&(Is(n),n.parentNode.removeChild(n))}const n=xr(this);for(let t=0;t<n.length;t++){const e=n[t];oa.has(e.bindingType)&&ea(e.node).forEach(t=>{t.tryDestroy()||t.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const t=Ui(this);null!==t&&(t.isRowSession?t.disposeBindings(xr(this)):t.dispose())}this._teardownBindings()}_teardownBindings(){const t=xr(this);for(let e=0;e<t.length;e++){const n=t[e];oa.has(n.bindingType)&&ea(n.node).forEach(t=>{t.unmount()}),Io(n),ho(n)}}unmount(){{const t=Ui(this);null!==t&&(t.isRowSession?t.disposeBindings(xr(this)):t.dispose())}for(const t of this._childNodeArray)null!==t.parentNode&&(Is(t),t.parentNode.removeChild(t));const t=xr(this);for(let e=0;e<t.length;e++){const n=t[e];oa.has(n.bindingType)&&ea(n.node).forEach(t=>{t.unmount()}),Io(n),ho(n)}this._mounted=!1}}function ra(t){return 1<<Math.min(t,31)}function ia(t){let e=t.indexBits;if(void 0===e){e=0;for(const n of t.nodeInfos)for(const t of n.parseBindTextResults)t.statePathName in A&&(e|=ra(A[t.statePathName])),"string"==typeof t.uuid&&(e|=ia(Tl(t.uuid)));t.indexBits=e}return e}function aa(t){return ia(Tl(t.uuid))}function la(t,e){return t.statePathName in A||oa.has(t.bindingType)&&0!==(aa(t)&e)}function ca(t,e){const n=document.createDocumentFragment(),o=new sa(n,e);return o._childNodeArray=t,o._firstNode=t.length>0?t[0]:null,o._lastNode=t.length>0?t[t.length-1]:null,o._mounted=!0,o}function ua(t){void 0!==t.uuid&&null!==t.uuid||tt("BindingInfo.uuid is null.");const n=Tl(t.uuid);n||tt(`Fragment with UUID "${t.uuid}" not found.`);const o=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${s.commentForPrefix}|${s.commentIfPrefix}|${s.commentElseIfPrefix}|${s.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==s.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=s.enableDirectionalInitialSync,n=[],o=t.nodeInfos;for(let e=0;e<o.length;e++){const s=o[e],r=re(t.fragment,s.nodePath);if(null===r)return null;for(const t of s.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===S||s===$)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Gt(r))return null;if("prop"===o&&Zo(r,t.propName))return null;const i=ae(t);let a;try{a=qs({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:e,template:i,isEvent:"event"===o,isIndexBinding:t.statePathName in A,policy:a,authority:a.authority})}}return 0===n.length?null:{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=re(o,s[t].nodePath);null===e&&tt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),be(e),Ut(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e,n){let o=ml.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new mr,ml.set(n,o)),o.initializeRow(t,e),o}(n,a,t.node),u=new sa(o);return Vi(u,c),Sr(u,a),function(t,e){Gi.set(t,e)}(u,n),Cr(u,l),kr(u,r),ta(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o,s]=function(t,e){const n=[],o=[],s=[];for(const r of e){const e=re(t,r.nodePath);if(null===e&&tt(`Node not found by path [${r.nodePath.join(", ")}] in fragment.`),pe.has(e))continue;const i=me(e,r.parseBindTextResults,{allowDeferred:!0});null!==i.deferred&&(s.push(i.deferred),pe.add(e)),o.push(...i.bindings),n.push(e)}return[n,o,s]}(t,e),r=new mr;return{nodes:n,bindingInfos:r.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:r,spreads:s}}(i,n.nodeInfos);o&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new sa(i,o);a.spreads.length>0&&(l.spreads=a.spreads),Vi(l,a.bindingSession),Sr(l,a.bindingInfos);const c="for"===t.bindingType?(u=t.statePathInfo.wildcardCount+1,2**Math.min(u,32)-1):-1;var u;const d=[];for(const t of a.bindingInfos)la(t,c)&&d.push(t);return Cr(l,d),kr(l,a.nodes),ta(t.node,l),l}const da=new WeakSet,ha=Symbol.for("wcstack.state.view-transition-naming");function fa(){const t=jr("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function pa(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||da.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[ha]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(da.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const ma=new WeakMap,ga=new WeakMap,ya=new WeakMap,ba=new WeakMap,wa=new WeakMap,va=new WeakMap;function _a(t,e,n,o){let s=va.get(t);void 0===s&&(s=[document.createComment(""),document.createComment("")],va.set(t,s));const[r,i]=s;r.data=`@@wcs-for-start:${o}`,i.data=`@@wcs-for-end:${o}`,t.mounted||(r.remove(),i.remove());const a=null===n?null:n.nextSibling;if(null===r.parentNode)e.insertBefore(r,a),e.insertBefore(i,a),t.mountAfter(r);else if(a!==r){let t=r;for(;t!==i;){const n=t.nextSibling;e.insertBefore(t,a),t=n}e.insertBefore(i,a)}return i}function $a(t,e,n){!function(t,e,n){let o=ga.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,ga.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function xa(t,e){ma.set(t,e)}function Sa(t){return t.nodeType===Node.ELEMENT_NODE||(t.nodeType===Node.TEXT_NODE?""!==(t.textContent?.trim()??""):t.nodeType===Node.COMMENT_NODE&&t.data.startsWith("@@wcs-"))}function Ia(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const Pa=new Set(["if","elseif","else","for"]);function ka(t,e){for(const n of xr(t))if(e.appliedBindingSet.delete(n),Pa.has(n.bindingType))for(const t of ea(n.node))ka(t,e)}function Na(t,e,n){for(const o of Er(t))if(Pa.has(o.bindingType)){if(o.statePathName in A&&ul(o,e),0!==(aa(o)&n))for(const t of ea(o.node))t.mounted&&Na(t,e,n)}else ul(o,e)}function Aa(t){for(const e of xr(t)){if(!Pa.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of ea(e.node))Aa(n),t&&n.mounted&&(Xi(n),n.unmount(),na(e.node,n),wa.delete(e.node),ga.delete(e.node))}}function Ea(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function Ca(t,o,r){const i=Boolean(r);let a;const l=ea(t.node);a=0===l.size?ua(t):l.values().next().value;const c=e(),u=t.uuid??"",d=t.bindingType;if(i||(s.debug&&console.log(`unmount if content : ${Ea(t)}`),c&&a.mounted&&(n.seen=!0),Xi(a),a.unmount()),i){s.debug&&console.log(`mount if content : ${Ea(t)}`);const e=$e(t.node);if(Nr(a,e),c){if(!a.mounted){const e=document.createComment(`@@wcs-${d}-start:${u}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),a.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${u}:${t.statePathName}`),o=a.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}}else a.mountAfter(t.node);Qi(a,e,o);const n=fa();null!==n&&pa(a,"branch",n)}}const Ma=new WeakMap;function Ta(t){return Ma.get(t)??[]}const Oa=new Set;function La(){Oa.clear()}const Ra=Symbol.for("wcstack.trustedTypes.policy");function ja(){const t=globalThis[Ra];return null===t||"object"!=typeof t?null:t}let Wa,Da=!1;const za={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}};function Ba(t,n,o){if(1===t.propSegments.length){const e=t.propSegments[0];"textContent"===e||"innerText"===e?o=null==o?"":String(o):void 0===o&&"innerHTML"===e&&(o="")}if(void 0===o)return void(s.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0],u=r[c];if(u!==o){null!==br&&null!==u&&"object"==typeof u&&null!==o&&"object"==typeof o&&null!==Gt(r)&&br.rememberOverwrittenObject(r,c,u);const e="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let t=!1;try{r[c]=e?function(t){if("string"!=typeof t)return t;const e=ja(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(o):o,t=!0}catch(t){e&&function(t,e){if(Da)return;if(!function(){if(void 0!==Wa)return Wa;if(!("trustedTypes"in globalThis))return Wa=!1,Wa;try{document.createElement("div").innerHTML="<i></i>",Wa=!1}catch{Wa=!0}return Wa}())return;Da=!0;const n="function"==typeof ja()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${e}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:t,property:e})}(r,c),s.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:o,error:t})}if(t){const t=function(t,e){const n=Gt(t);if(null===n)return null;const o=Jt(t)?.get(n);if(void 0===o)return null;const s=Xt(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,o)}catch(e){s.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:o,error:e})}}};if(s.enablePropagationContext&&Zo(r,c)){const e=ss(r,c,t.statePathName),s=rs(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??us()??as(e);if(a.visitedEdges.has(s))null!==Se&&Se({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:s,node:r,member:c});else{const t=ls(a,s);ds(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:ns++,writtenValue:n};hs.push({receipt:i,node:t});try{return r()}finally{hs.pop()}}(r,c,o,e,t.transactionId,i))}}else i()}if(e()){const t=za[c];t?t(r,o):(function(t,e,n){let o=Ma.get(t);o||(o=[],Ma.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,o),a=r,Oa.add(a))}return}var a,l;const c=i[0];let u=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==u)return;u=u[e]}const d=i[i.length-1],h=u[d];if(h!==o){if(Object.isFrozen(u))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:o}));null!==br&&2===i.length&&"object"==typeof u&&null!==u&&null!==Gt(r)&&(d in u?br.rememberOverwrittenValue(r,c,d,u[d]):br.recordInjectedKey(r,c,d));try{u[d]=o}catch(t){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:o,error:t})}}}const Fa=new WeakSet;function Ha(t,e,n){}function qa(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}const Ua=new WeakMap;function Va(t,e,n,o){const s=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),r=e.length>0?e+l:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(l)&&!Ua.has(qa(o,t)?.get)&&s.push(e)}return s}const Ga={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Ka={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Ja(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${at}`}function Qa(t,e){return`[wcs/recursion-anchor] "${t}" does not match the declared recursion anchor "${e}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function Xa(t,e){return`$setAll("${t}") ${e}`}function Ya(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${at}`}const Za=new WeakSet;function tl(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const el=Object.freeze({[I]:function(t,e,n){const o=t.node,s=t.propSegments[1];null!=n?("boolean"!=typeof n&&tt(`Invalid value for class application: expected boolean, got ${typeof n}. Write "|truthy" if you mean to coerce.`),o.classList.toggle(s,n)):o.classList.toggle(s,!1)},[P]:function(t,e,n){const o=t.node,s=t.propSegments[1];if(null==n)return void(o.hasAttribute(s)&&o.removeAttribute(s));const r=String(n);o.getAttribute(s)!==r&&o.setAttribute(s,r)},[k]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[S]:function(t,e,n){zo(n)||tt("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=_r.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||tt('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Gt(t);if(null===e)return null;const n=Jt(t)?.get(e);return void 0===n&&tt(`Custom element <${e}> is not defined for command binding.`),Xt(t)}(r);null===a&&tt(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||tt(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${it(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),_r.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void _r.delete(t);const o=n[i];return"function"!=typeof o&&tt(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),_r.set(t,{token:o,unsubscribe:c,elementRef:l})}}),nl={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Fa.has(t.replaceNode)){Fa.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,o,s){const r=t.statePathInfo,i=ao(t),a=uo(t),l=xn(a),u=wa.get(t.node);let d,h;const f=void 0!==u&&function(t,e){const n=_n.get(t);return void 0!==n&&(n===e||cn(e)===cn(n))}(a,s),p=f||void 0===u||u.value===l?null:Bi(i,l,s);f?(d=u.value,h=Hi(cn(d),cn(s))):null!==p&&p.newIndexes.every(t=>t.parentListIndex===i||Je(t.parentListIndex)||!Ze(s,t.parentListIndex))?(d=u.value,h=Hi(cn(d)??[],p.newIndexes)):(d=l.length>0&&!ga.has(t.node)?[]:l,h=Bi(i,d,s));const m=Array.isArray(s)?s:[];o.newListValueByAbsAddress.set(a,m),wa.set(t.node,mn(m));let g=ga.get(t.node);const y=void 0!==g?function(t,e,n){if(!Ge(e))return null;let o=null;for(let e=0;e<n.newIndexes.length;e++){const s=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(s)&&n.deleteIndexSet.has(r)?t.get(r):void 0;void 0!==i&&(o??={byAddedIndex:new Map,reused:new Set},o.byAddedIndex.set(s,i),o.reused.add(i))}return o}(g,d,h):null,b=Array.isArray(d)&&d.length===h.deleteIndexSet.size&&h.deleteIndexSet.size>0;if(b&&null===y&&null!==t.node.parentNode){let e=ba.get(t.node);if(void 0===e){const n=ma.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(Sa(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Sa(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n.parentNode===t.node.parentNode?n:t.node),ba.set(t.node,e)}if(e){const e=t.node.parentNode;!function(t,e){ks.set(t,(ks.get(t)??0)+e)}(e,e.childNodes.length),e.textContent="",e.appendChild(t.node)}}let w=b?1e3-function(t){return ya.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;const v=e();if(void 0!==g){const e=g;h.deleteIndexSet.forEach(o=>{const s=e.get(o);void 0!==s&&(v&&(va.get(s)?.forEach(t=>t.remove()),n.seen=!0),null!==y&&y.reused.has(s)?(Xi(s),Aa(s),s.unmountInPlace()):w<=0&&s.tryDestroy()?na(t.node,s):(Xi(s),s.unmount(),function(t,e){let n=ya.get(t.node);void 0===n&&(n=[],ya.set(t.node,n)),n.length<1e3?n.push(e):na(t.node,e)}(t,s),w-=1),b||e.delete(o))}),b&&(ga.delete(t.node),g=void 0)}let _=t.node;const $=ot(r.path+"."+c),x=o.stateElement.loopContextStack,S=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const t of i)a.add(n[t]);return a}(h);let I=null;h.newIndexes.length==h.addIndexSet.size&&h.newIndexes.length>0&&_.isConnected&&null===y&&(I=document.createDocumentFragment(),to(I,o.rootNode));const P=v?`${t.uuid}:${r.path}:`:"",k=fa(),N=ya.get(t.node);for(const e of h.newIndexes){let n;if(h.addIndexSet.has(e)){const s=$o($,e);if(x.createLoopContext(s,s=>{n=y?.byAddedIndex.get(e)??(void 0!==N?N.pop():void 0),void 0===n?n=ua(t):(ka(n,o),Nr(n,s)),v?_=null!==I?_a(n,I,null,P+e.index):_a(n,_.parentNode,_,P+e.index):null!==I?n.appendTo(I):_.nextSibling!==n.firstNode&&n.mountAfter(_),Qi(n,s,o),null!==k&&pa(n,"row",k)}),void 0===n&&tt(`Content not found for ListIndex: ${e.index} at path "${r.path}"`),null!==y&&y.reused.has(n)){const t=o.stateElement.addressHooks;if(t){const e=t.rowReused;for(let t=0;t<e.length;t++)e[t](o.stateElement,n)}}}else{n=void 0!==g?g.get(e)??null:null,h.changeIndexSet.has(e)&&Na(n,o,ra(r.wildcardCount)),null===n&&tt(`Content not found for ListIndex: ${e.index} at path "${r.path}"`);const t=!n.mounted;if(v?_=_a(n,_.parentNode,_,P+e.index):null!==S&&S.has(e)&&Ia(_,n.firstNode)||_.nextSibling===n.firstNode||n.mountAfter(_),t){const t=n,s=$o($,e);x.createLoopContext(s,e=>{Qi(t,e,o)})}}v||(_=n.lastNode||_),void 0===g&&(g=new WeakMap,ga.set(t.node,g)),g.set(e,n)}ma.set(t.node,_),null!==I&&(t.node.parentNode.insertBefore(I,t.node.nextSibling),to(I,null))},if:Ca,else:Ca,elseif:Ca,radio:function(t,e,n){const o=t.node,s=wr(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=wr(o.value,t.inFilters),r=Array.isArray(n)?n:vr;o.checked=r.includes(s)}},ol=new WeakMap,sl=new WeakMap,rl=new WeakMap;function il(){}function al(t){const e=br;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return Ha;if(e.isDeclared(n,o))return il}return Ba}function ll(t,e){cl(t,e,function(t,e){const n=So(e);if(n.pathInfo.path in A){const t=$e(e.node);return null===t&&tt(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&tt("ListIndex not found for loopContext:");const n=A[e];void 0===n&&tt(`Invalid index name: ${e}`);const o=so(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&tt(Ya(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Wn](n)}(e.state,t))}function cl(t,e,n){const o=wr(n,t.outFilters);if(!0===sl.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=ol.get(t);if(void 0===s){if(ol.has(t))return s=al(t),s===Ha&&ol.set(t,s),void s(t,e,o);if(s=nl[t.bindingType],void 0===s){const e=t.propSegments[0];s=el[e],ol.set(t,s),void 0===s&&(Gt(t.replaceNode)?(s=al(t),s===Ha&&ol.set(t,s)):(s=Ba,ol.set(t,s)))}if(s===Ba&&"SELECT"===t.node.tagName){const n=t.propSegments[0];if("value"===n||"selectedIndex"===n)return e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement}),void sl.set(t,!0)}s(t,e,o)}else s(t,e,o)}function ul(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=uo(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=yr(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==rl.get(t)){const e=Gt(t.replaceNode);if(e&&(void 0===Jt(t.replaceNode)?.get(e)||function(t){return"waiting-definition"===Ys.get(t)?.phase}(t)))return void function(t,e){if(Za.has(t))return;Za.add(t);const n=()=>{Za.delete(t);const e=yr(t);(null===e||e.shouldApplyState(t))&&hl([t])},o=n=>{Za.delete(t),tl(e,n)},s=yr(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Za.delete(t),r()})||(Za.delete(t),r()))}const r=Jt(t.replaceNode);if(null===r)return Za.delete(t),void tl(e,new Error("CustomElementRegistry is unavailable."));js(r).wait(e,()=>{t.replaceNode.isConnected?n():Za.delete(t)},o)}(t,e);rl.set(t,!0)}if(!0===e.sameRootVerified)return void ll(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=eo(o),null===o&&tt("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Pl(o);null===n&&tt("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};ll(t,r)})}else ll(t,e)}function dl(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==Se&&Se({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function hl(t,e,n){let o=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;o<t.length;){let n=t[o];if(!1===n.replaceNode.isConnected){s.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),o++;continue}let u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=eo(u),null===u&&tt("Root node for fragment not found for binding."));const d=Pl(u);null===d&&tt("No state tree found on this root for binding."),d.createState("readonly",s=>{const h={rootNode:u,stateElement:d,state:s,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{ul(n,h)}catch(t){dl(n,t,d,c)}o++;const e=t[o];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{Ba(t,{propagationContextByBinding:e},n)}catch(e){dl(t,e,o??null,c)}for(const[t,e]of i.entries())Sn(t,e),Tn(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[Fn](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[Hn](n,o)}catch(t){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:t,original:n,node:o.node})}})}function fl(t,e,n,o,s){for(const r of t)r.cancel?.(),r.cancel=n.deferUntilDefined(r.node,r.tagName,()=>{const i=we(r);o&&(t.splice(t.indexOf(r),1),o.push(...i),s.push(...i.filter(t=>t.statePathName in A))),0!==i.length&&(xe(r.node,e),hl(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1})))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,t)})}function pl(t,e,n){const[o,s,r]=ge(t,n),i=gr(t);for(const t of o)xe(t,e);hl(i.initialize(s)),fl(r,e,i)}const ml=new WeakMap;async function gl(t){const e=t.querySelectorAll(s.tagNames.state),n=[],o=Jt(t);null===o&&tt(`CustomElementRegistry is unavailable for <${s.tagNames.state}>.`),await o.whenDefined(s.tagNames.state);for(const t of e){if(ue(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function yl(t){if(t===document)await gl(document),Y(document),Yl(document,document),pl(document.body,null);else{const e=t;e.host.hasAttribute(s.bindAttributeName)&&await qt(e.host),await gl(e),Y(e),Yl(e,e),pl(e,null)}}const bl={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function wl(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${bl[t]??t}" before the state is defined.`}let vl=null;function _l(t){return null===vl&&tt(wl("ssr",t)),vl}const $l=new WeakMap,xl=new WeakMap,Sl=new Set,Il=[];function Pl(t){return $l.get(t)??null}function kl(t){return xl.get(t)??Promise.resolve()}const Nl=new WeakSet;function Al(t){Nl.add(t)}function El(t,n){const o=$l.get(t);if(null===n){if(void 0===o)return;$l.delete(t),Sl.delete(o),null!==Se&&Se({type:"state:element-unregistered",rootNode:t,element:o}),s.debug&&console.debug("State element unregistered")}else{if(o===n)return;if(void 0===o){const o=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{o&&await _l('the "enable-ssr" attribute').hydrate(t)||await yl(t),Al(t),sc(),e()}catch(t){n(t)}})});xl.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await yl(t),Al(t),sc(),e()}catch(t){n(t)}})});xl.set(t,e)}}void 0!==o&&tt('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),$l.set(t,n),Sl.add(n);for(let e=0;e<Il.length;e++)Il[e](t,n);null!==Se&&Se({type:"state:element-registered",rootNode:t,element:n}),s.debug&&console.debug("State element registered",n)}}const Cl=new Map;function Ml(t,e,n){if(null===n)Cl.delete(t);else{Cl.set(t,n);const o=Pl(e);null===o&&tt("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function Tl(t){return Cl.get(t)||null}function Ol(t){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=Lt(e.getAttribute(s.bindAttributeName)||"");if(e.localName===s.tagNames.state){if(e.hasAttribute("mount"))return n.filter(t=>t.propSegments[0]!==x);const t=n.find(t=>t.propSegments[0]===x);if(void 0!==t){const e=`on a volume element — a <${s.tagNames.state}> with a "mount" attribute`;tt(1===t.propSegments.length?`[wcs/mount-path-invalid] "${t.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${x}.<key>: <path>") ${e}.`:`[wcs/mount-path-invalid] "${t.propName}: ${t.statePathName}" is a volume injection declaration, and it can only be written ${e}. Add mount="<path>", or bind an element property instead.`)}}return n}if(t.nodeType===Node.COMMENT_NODE){const e=Dt(t);null===e&&tt("Comment node binding text not found.");const n=Tl(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=zt(e),s=null):s=e,[{...o,uuid:s}]}return[]}let Ll;function Rl(){return Ll??={filterName:"not",args:[]}}const jl=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Wl(t,e){const n=e+l+c,o=Pt(t,"|");let s,r;if(-1!==o?(s=t.slice(0,o).trim(),r=t.slice(o)):(s=t.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return t;s=n+l+s.slice(1)}return r.length>0?s+r:s}function Dl(t,e){const n=jl.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+Wl(s,e)+r}function zl(t,e){const n=kt(t,";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=Pt(n,":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Wl(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function Bl(t,e){return zl(t,e)}function Fl(t,e){const n=s.bindAttributeName,o=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const t=o.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=Dl(n.data,e);continue}const s=t;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const t=zl(r,e);t!==r&&s.setAttribute(n,t)}}}function Hl(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}const ql=new WeakMap;function Ul(t){return ql.get(t)??null}function Vl(t){const e=[],n=fe(t);for(const t of n){const n=Ol(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");ql.set(e,t.data),t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:Hl(o),parseBindTextResults:n})}return e}function Gl(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const Kl=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),Jl=Rl();function Ql(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Jl],bindingType:t}}function Xl(t,e,n,o,s,r=!0){Gl(e),"string"==typeof o&&Fl(e,o),Yl(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Vl(e)};return void 0!==s&&function(t,e,n){for(const o of t)for(let t=0;t<o.parseBindTextResults.length;t++){const s=o.parseBindTextResults[t];null==s.uuid&&(o.parseBindTextResults[t]=e(s,n))}}(i.nodeInfos,s,o),i}function Yl(t,e,n,o){const r=s.commentElsePrefix,i=de(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(s.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],u=[];for(;a.nextNode();){const t=a.currentNode;u.push(t)}for(const e of u){let i=e.getAttribute(s.bindAttributeName)||"";"string"==typeof n&&(i=Bl(i,n));let a=Lt(i)[0];const u=Kl.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=Pe();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&tt("'else' binding found without preceding 'if' or 'elseif' binding."),a=Ql("else",l.parseBindTextResult),p=Xl(t,h,a,m,o,!1),Ml(f,t,p);const n=c.at(-1),s=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:Hl(s),parseBindTextResults:Ol(s)})):e.replaceWith(s)}else if("elseif"===d){null===l&&tt("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Xl(t,h,a,m,o),Ml(f,t,p);const n=document.createComment(`@@${u}:${f}`),s=Pe(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Ql("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Hl(n),parseBindTextResults:Ol(n)}),Ml(s,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${s}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:Hl(g),parseBindTextResults:Ol(g)})):e.replaceWith(g)}else{p=Xl(t,h,a,m,o),Ml(f,t,p);const n=document.createComment(`@@${u}:${f}`);e.replaceWith(n)}"if"===d?(c.length=0,l=p):"elseif"===d?l=p:"else"===d&&(l=null,c.length=0)}}const Zl=()=>`[${s.bindAttributeName}]`;function tc(t){if(or(t))return!0;if(!ec(t))return!1;if(t.hasAttribute(s.bindAttributeName))return!1;const e=t.querySelector(Zl());return null!==e&&or(e)}function ec(t){return 1===t.nodeType}function nc(t){if(tc(t))return;Y(t),Yl(t.getRootNode(),t);const e=t.hasAttribute(s.bindAttributeName),n=t.parentNode,o=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);pl(e&&o?n:t,null)}const oc=[];function sc(){const t=oc.splice(0,oc.length);for(const e of t)nc(e);!function(){const t=function(){const t=globalThis[r];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[i];return void 0===e&&(e=[],t[i]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[a];return void 0===e&&(e=new WeakSet,t[a]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const rc={protocol:"wcs-binder",version:1,bind:function(t){var e;ec(t)&&!tc(t)&&(e=t.getRootNode(),Nl.has(e)?nc(t):oc.push(t))}},ic="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let ac=0;async function lc(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++ac}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw await new Promise(t=>setTimeout(t)),new Error(`[@wcstack/state] ${function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src="./state.js") needs neither. See ${ic}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${ic}`}(e,t,s)}`,{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function cc(t){const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}class uc{_loopContextStack=Array(d).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&tt("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=d&&tt("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&tt("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&tt("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&tt(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const dc={$updatedCallback:M,$streams:B},hc=new WeakSet;function fc(t,e){let n=t;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,e);)n=Object.getPrototypeOf(n);return n}function pc(t){if((null===t||"object"!=typeof t&&"function"!=typeof t)&&tt(`The state must be an object, got ${null===t?"null":typeof t}. Check the source of the state element (json / src / the inline <script>).`),!hc.has(t)){dt?.state(t);for(const e of Object.keys(dc)){if(!(e in t))continue;const n=dc[e];n in t&&tt(`[wcs/declaration-alias] The state declares both "${e}" and "${n}". "${e}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${at}`),Object.isExtensible(t)||tt(`[wcs/declaration-alias] The state is not extensible, so the old name "${e}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${at}`);const o=fc(t,e),s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,n,{...s,configurable:!0}),o===t&&delete t[e]}hc.add(t)}}const mc=new WeakMap;function gc(t,e){let n=mc.get(t);void 0===n&&(n=new Map,mc.set(t,n));let o=n.get(e);return void 0===o&&(o=new Do(e,t),n.set(e,o)),o}const yc=new WeakMap;function bc(t){const e=yc.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return gc(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:gc(t,n)}},set(){tt("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){tt("$command namespace is read-only; deleting from it is not allowed.")}});return yc.set(t,n),n}const wc=Symbol("wcs.notHandled"),vc=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],_c=new Map;function $c(t,e){_c.set(t,e)}const xc=new Map;let Sc=[],Ic=[];function Pc(t,e){xc.set(t,e),Sc=Array.from(xc.values()).sort((t,e)=>t.order-e.order),Ic=Sc.slice().reverse()}function kc(t){return xc.has(t)}function Nc(t,e){for(let n=0;n<Sc.length;n++)Sc[n].activate?.(t,e)}const Ac=new Map;class Ec{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=ot(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Cc(t){let e;return Ac.get(t)??(Ac.set(t,e=new Ec(t)),e)}function Mc(t){"readonly"===t.mutability&&tt("This state is readonly.")}function Tc(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:so(n.listIndex,o,n.pathInfo.wildcardCount)}function Oc(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=oo(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?so(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?so(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}function Lc(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Rc(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](t,e,n,o,s);if(a!==wc)return a}}return wc}function jc(t,e,n,o,s){if(e.pathInfo.segments[0]===W)return function(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}(bc(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){if(null===e.parentAddress){const r=Rc(s,e,null,n,o);if(r!==wc)return r;tt(function(t,e,n){return`[${Ga.binding}] Path "${t}" does not exist on the state tree.${it(t,Va(e,"",n,e))}${at}`}(e.pathInfo.path,t,s.getterPaths))}const r=zc(t,e.parentAddress,n,o);if(null==r)return;const i=e.pathInfo.segments[e.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==c&&!(i in Object(r))){const t=Rc(s,e,Object(r),n,o);if(t!==wc)return t}if(i===c){const t=e.listIndex?.index??tt(Ya(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(r,t)}return Reflect.get(r,i)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}const Wc=new WeakSet;function Dc(t){return Wc.has(t)}function zc(t,e,n,o){Oc(o,e),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,e.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const t=r.read;for(let r=0;r<t.length;r++){const i=t[r](s,e,n,o);if(i!==wc)return i}}return Lc(s,e)?function(t,e,n,o,s){const r=Xn(s,e),i=function(t){return Mr.get(t)??null}(r),a=s.stateGeneration,l=e.pathInfo.lastSegment===c?void 0:Le(e.listIndex);if(null!==i&&!1===i.dirty&&i.generation===a&&i.rowStamp===l)return i.value;const u=jc(t,e,n,o,s);"function"!=typeof u&&Or(r,{value:u,dirty:!1,generation:a,rowStamp:l});const d=i?.value;return Array.isArray(u)&&u!==d&&s.getterPaths.has(e.pathInfo.path)&&function(t,e,n,o,s,r){const{path:i,wildcardCount:a}=e.pathInfo;r.beginUntrack();try{for(const[l,c]of r.stateElement.dynamicDependency){const u=ot(l);if(!c.includes(i)||u.wildcardCount>a)continue;const d=zc(t,$o(u,so(e.listIndex,u.wildcardCount-1,a)),s,r);d===n?Wc.add(e.pathInfo):d===o&&ji(n,o)}}finally{r.endUntrack()}}(t,e,u,d,n,o),u}(t,e,n,o,s):jc(t,e,n,o,s)}function Bc(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,u,d)=>{const h=o[s]??null;if(null===h)return void d.push(u);const f=$o(h,r),p=Xn(n.stateElement,f),m=Mn(p),g=zc(t,f,e,n),y=Bi(r,m,g).newIndexes,b=l[c]??null;if(i.set(p,g),null===b)for(let t=0;t<y.length;t++){const e=y[t];a(o,s+1,e,l,c+1,u.concat(e.index),d)}else{const t=y[b]??tt(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,u.concat(t.index),d):d.push(u.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Tn(t,Array.isArray(e)?e:[]);return l}function Fc(t,e,n){const o=un(n,e.listIndex);if(null!==o)return o;const s=Xn(t.stateElement,e),r=Bi(e.listIndex,Mn(s),n);return Tn(s,Array.isArray(n)?n:[]),r.newIndexes}function Hc(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=$o(a,r),c=Fc(n,l,zc(t,l,e,n)),u=s[i];r=c[u]??tt(`ListIndex not found at index ${u} of ${a.path}`)}return r}function qc(t,e,n,o){"object"==typeof t&&null!==t||tt(`${V} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&tt(`${V} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Uc(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&tt(`${V} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Vc(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];qc(a,n,o,i);const l=Uc(a,e,n,o,i);r.has(l)&&tt(`${V} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Gc(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function Kc(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const r=zc(t,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=e.pathInfo.lastSegment;if(i===c){const t=e.listIndex?.index;return"number"==typeof t&&t in r}return i in r}const Jc=new WeakMap;function Qc(t){return Jc.get(t)??null}function Xc(t,e){null===e?Jc.delete(t):(hn(e.listIndexes),Jc.set(t,e))}function Yc(t,e,n){const o=$o(ot(t.wildcardParentPaths[e]),n),r=Xn(t.stateElement,o),i=Mn(r),a=t.stateProxy[Wn](o),l=Bi(o.listIndex,i,a);t.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return s.debug&&console.log(`Invalid search type: ${e}`),[]}}(l,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)Yc(t,e+1,n)}function Zc(t,e,n,o){n?t.result.has(e)||t.quiet.add(e):t.quiet.delete(e),t.result.add(e),o.push(e)}const tu=[];function eu(t,e,n){return"full"!==t.listExpansion&&t.listPathSet.has(e)?t.stateElement.crossRowListPaths?.has(e)?{fullRows:n.newIndexes,movedRows:null}:0===n.addIndexSet.size&&0===n.changeIndexSet.size?0===n.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:tu,movedRows:null}:{fullRows:n.newIndexes,movedRows:null}:{fullRows:tu,movedRows:null}:{fullRows:n.addIndexSet,movedRows:n.changeIndexSet}:{fullRows:n.newIndexes,movedRows:null}}const nu=[];function ou(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return nu;let s=null;const r=e+l;for(const t of o){if(t!==e&&!t.startsWith(r))continue;const o=ot(t);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??nu}function su(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),t.quiet.has(a)?Lr(Xn(t.stateElement,a)):n(a),i.length=0,ru(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}function ru(t,e,n){const o=e.pathInfo.path,s=t.quiet.has(e),r=t.staticMap.get(o);if(r)for(const i of r){const r=ot(i);if(r.lastSegment===c){const a=t.stateProxy[Wn](e),l=Array.isArray(a)?a:[],c=Xn(t.stateElement,e),u=Mn(c),d=t.listPathSet.has(o);if(!d&&"diff"===t.listExpansion&&(t.keyedMergePath===o||cn(l)?.length!==l.length&&!Di(u,l)))continue;const h=Bi(e.listIndex,u,l);t.observedListValueByAbsAddress.set(c,l);const f=eu(t,o,h);for(const e of f.fullRows)Zc(t,$o(r,e),s||!d,n);for(const e of h.valueChangeIndexes??tu)Zc(t,$o(r,e),s||!d,n);if(null!==f.movedRows){const e=ou(t,i,r);if(null===e)for(const e of f.movedRows)Zc(t,$o(r,e),s,n);else if(e.length>0)for(const o of f.movedRows)for(const r of e)Zc(t,$o(r,o),s,n)}}else Zc(t,$o(r,e.listIndex),s,n)}const i=t.dynamicMap.get(o);if(i)for(const o of i){const r=ot(o),i=[];if(r.wildcardCount>0){const n=oo(e.pathInfo,r);if(r.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&tt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=so(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const s={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:r.wildcardPaths,wildcardParentPaths:r.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Yc(s,n,o),i.push(...s.targetListIndexes)}else{null===e.listIndex&&tt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=so(e.listIndex,n-1,e.pathInfo.wildcardCount);i.push(t)}}else i.push(null);for(const e of i)Zc(t,$o(r,e),s,n)}}function iu(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&tt(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),d={ranks:u,stateElement:t,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null,quiet:new Set};su(d,e,a),function(t,e){for(let n=0;n<1e3;n++){const n=ni(t.stateElement);if(null===n)return;n.forEach(n=>{su(t,$o(n.absolutePathInfo.pathInfo,n.listIndex),e)})}}(d,a);for(const[t,e]of d.observedListValueByAbsAddress)Tn(t,e);return Array.from(d.result)}function au(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](t,e,n,o,s)}}function lu(t,e,n){const o=t.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function cu(t,e,n){const o=t.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function uu(t,e,n,o,s,r){const i=bi(t,e),a=xi(t,e);if(!i&&!a)return null;const l=[],c=hu(l);return i&&$i(t,e,n,o,s).forEach(c),a&&Ii(t,e,n?o:r(),s).forEach(c),l}function du(){return s.enablePropagationContext?us()??null:null}function hu(t){const e=Kr(),n=du();return o=>{Lr(o),e.enqueueAbsoluteAddress(o,n),t.push(o)}}function fu(t,e,n){if(null===t||0===t.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=Kr(),a=du();for(let n=0;n<t.length;n++){const l=t[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const u=$o(l.pathInfo,t[n].listIndex);iu(o,u,s,r,o.listPaths,e,"new",t=>{if(t===u)return;const e=Xn(o,t);Lr(e),i.enqueueAbsoluteAddress(e,a)},{listExpansion:"diff"})}}function pu(t,e,n,o,r,i,a="diff"){const u=s.enablePropagationContext?us()??as(-1):null,d=Kr(),h=o.stateElement;d.enqueueAbsoluteAddress(e,u),i&&Lr(e);const f=e=>iu(h,e,h.staticDependency,h.dynamicDependency,h.listPaths,n,"new",e=>{if(e===t)return;const n=Xn(h,e);Lr(n),d.enqueueAbsoluteAddress(n,u)},{listExpansion:a,keyedMergePath:r});if(f(t),t.pathInfo.lastSegment!==c&&null!==t.listIndex&&null!==t.listIndex.parentListIndex){const e=t.listIndex,o=t.pathInfo.wildcardParentPathInfos[e.position],s=$o(o,e.parentListIndex),r=()=>n[Wn](s),i=t=>{Lr(t),d.enqueueRenderOnlyAddress(t)};for(const n of function(t,e){const n=(o=t,De(je.get(o.value),o));var o;if(0===n.length)return n;const s=new Set(Ke.get(e()));return n.filter(e=>e.position===t.position&&!s.has(e)&&!Be(e))}(e,r))i(Xn(h,$o(t.pathInfo,n)));const a=t.pathInfo.path.slice(t.pathInfo.wildcardPaths[e.position].length);for(const t of Pn(Xn(h,s),r())){const n=t.absolutePathInfo.pathInfo;n!==o&&n.wildcardCount===o.wildcardCount&&i(Yn(h,ot(n.path+l+c+a),e))}}const{path:p,lastSegment:m,wildcardCount:g,wildcardParentPaths:y,wildcardParentPathInfos:b}=t.pathInfo,w=t.listIndex;for(let t=0;w&&t<g;t++){const e=so(w,t-1,g);for(const o of h.dynamicDependency.get(y[t])??[]){const s=ot(o);if(h.listPaths.has(o)&&s.wildcardCount===t&&Dc(s)&&n[Wn]($o(s,e))===n[Wn]($o(b[t],e))){const e=$o(ot(o+p.slice(y[t].length)),w);f(e),m===c&&d.enqueueRenderOnlyAddress(Xn(h,e.parentAddress))}}}}function mu(t,e,n,o,s){s&&(t.getterPaths.has(e)?Lr(n):Or(n,{value:o,dirty:!1,generation:t.stateGeneration,rowStamp:n.absolutePathInfo.pathInfo.lastSegment===c?void 0:Le(n.listIndex)}))}function gu(t,e,n,o,s,r,i,a,l=!0){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const i=zc(t,n,s,r),a=e.pathInfo.segments[e.pathInfo.segments.length-1];if(a===c){const t=e.listIndex?.index??tt(Ya(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(i,t,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);r.pushAddress(e),r.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{l&&pu(e,n,s,r,i,a)}}function yu(t,e,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(e.pathInfo.path);if(void 0!==i){const r=zc(t,e,o,s),a=function(t,e,n,o){const s=Vc(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Vc(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,i,r,n);if(null!==a)return function(t,e,n,o,s,r){const i=e.pathInfo.path,a=e.listIndex;null===cn(o)&&Bi(a,null,o);const u=Bi(a,o,n.list),d=bu(t,e,n.list,s,r,i),h=ot(i+l+c);for(const e of n.matched){const n=Gc(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const i of n)void 0!==o?yu(t,$o(ot(h.path+l+i.field),o),i.value,s,r):e.oldRow[i.field]=i.value}return d}(t,e,a,r,o,s)}}return bu(t,e,n,o,s,null)}function bu(t,e,n,o,r,i){const a=r.stateElement,u=e.pathInfo.path,d=a.addressHooks;if(d){const t=d.write;for(let s=0;s<t.length;s++){const i=t[s](a,e,n,o,r);if(i!==wc)return i}}const h=function(){const t=fs;return fs=0,t}(),f=h>1;if(!(u in t)&&null!==e.parentAddress&&!a.elementPaths.has(u)){const l=zc(t,e.parentAddress,o,r);if("object"==typeof l&&null!==l){const t=e.pathInfo.lastSegment,h=t===c?e.listIndex?.index:t;let p,m=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==h&&h in l,e=void 0!==h?l[h]:void 0;if(t&&Object.is(e,n))return!0;p=e,m=!0}t===c&&(e=function(t,e,n,o,s){const r=e.listIndex,i=cn(n);if(i?.[o]!==r||n[o]===s)return e;const a=Ce(r.parentListIndex,o,Te(r));if(function(t){return pn.has(t)}(n)){const t=Qc(n)??{value:n.slice(),listIndexes:i};fn(t.value,t.listIndexes),gn(n,t.value)}const l=function(t){return dn.has(t)}(i)?i:i.slice();l[o]=a,fn(n,l,!0),vi(i,l),zi([r]);const c=$o(e.pathInfo,a);return cu(t,Xn(t,c),Xn(t,e)),c}(a,e,l,h,n));const g=uu(a,u,m,p,n,()=>l[h]),y=Lc(a,e),b=Xn(a,e);null!==Se&&Se({type:"state:write",absoluteAddress:b,value:n,oldValue:p,hasOldValue:m}),au(a,u,b,p,m);let w=!1;try{if(void 0===h&&tt(Ya(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),d&&0!==d.writeMissing.length&&t!==c&&!(h in l)){const t=d.writeMissing;for(let s=0;s<t.length;s++){w=!0;const i=t[s](a,e,l,h,n,o,r);if(i!==wc)return i;w=!1}}if(t!==c&&null!==e.listIndex){const o=l[h];o!==n&&(function(t,e,n,o){if(!Ke.has(t))return!1;let s=!1;for(const e in n)s||=e!==o&&n[e]===t;if(!s){let n=Qe.get(e);void 0===n&&(n=new WeakSet,Qe.set(e,n)),n.add(t)}const r=Ke.get(t),i=Ye.get(t);if(r[0]?.parentListIndex===e&&(!s||i?.[0]!==e||i[1]!==qe))for(const n of rn.get(t)??[])if(n!==e&&n.position===e.position&&sn(t,n)&&Object(Fe(n))[o]===t){r.forEach(t=>Me(t,n)),Xe.set(t,[e,qe]);break}return s}(o,e.listIndex,l,t)&&Array.isArray(n)&&ji(n,o),function(t,e){Qe.get(e)?.delete(t);const n=Ke.get(t);if(void 0!==n){Ye.set(t,[e,qe]);const o=Xe.get(t);o?.[0]===e&&o[1]===qe&&n.forEach(t=>Me(t,e))}}(n,e.listIndex))}return Reflect.set(l,h,n)}finally{pu(e,b,o,r,i,y),fu(g,o,r),w?Lr(b):mu(a,u,b,n,y),lu(a,e.pathInfo,{value:n})}}}let p,m=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=zc(t,e,o,r);if(Kc(t,e,o,r)&&Object.is(s,n))return!0;p=s,m=!0}const g=uu(a,u,m,p,n,()=>zc(t,e,o,r)),y=a.elementPaths.has(e.pathInfo.path),b=Lc(a,e),w=Xn(a,e);null!==Se&&Se({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:m}),au(a,u,w,p,m);try{return y?function(t,e,n,o,s,r,i,a,u){const d=e.parentAddress??tt(`address.parentAddress is undefined path: ${e.pathInfo.path}`),h=zc(t,d,s,r)??[],f=Qc(h);if(u)return f&&(f.value[e.listIndex.index]=o),Re(e.listIndex,o),gu(t,e,n,o,s,r,i,a);const p=e.listIndex,m=f??{value:[...h],listIndexes:cn(h)??[],written:new Map};try{return gu(t,e,n,o,s,r,i,a,!1)}finally{const t=function(t,e,n){const{value:o,listIndexes:s}=t,r=new Map;s.forEach((t,n)=>{if(e[n]!==o[n]){const e=r.get(o[n]);e?e.push(t):r.set(o[n],[t])}});let i,a=0;const l=[];for(let t=0;t<s.length;t++){const n=e[t]===o[t]?s[t]:r.get(e[t])?.shift();if(!n&&(a++?(i??=new Set(o)).has(e[t]):o.includes(e[t])))return null;l.push(n)}return l.map((t,e)=>t??Ce(n,e))}(m,h,d.listIndex);if(null===t)Xc(h,m),Re(p,o),m.written.set(p,qe),function(t){en.set(t,qe)}(p),pu(e,n,s,r,i,a);else{Xc(h,null);const e=[p.index];nn(p),m.written.forEach((t,n)=>{nn(n),Re(n,m.value[n.index]),t===qe&&e.push(n.index)}),m.written.delete(p),t.forEach((t,e)=>{t.index=e}),fn(h,t),vi(m.listIndexes,t),function(t,e,n,o,s,r,i){const a=r.stateElement,u=Kr(),d=Xn(a,t);fn(e.value,e.listIndexes),Ve(e.value),gn(n,e.value),xn(d)===n&&Sn(d,e.value),u.enqueueRenderOnlyAddress(d);for(const t of Pn(d,n))kn(t,n)&&u.enqueueRenderOnlyAddress(t);const h=new Map;e.listIndexes.forEach((t,e)=>h.set(t,e));const f=ot(t.pathInfo.path+l+c);for(let t=0;t<o.length;t++){const n=o[t],i=h.get(n);if(i===t)continue;const l=$o(f,n),c=Xn(a,l);if(void 0===i){const n=Yn(a,f,e.listIndexes[t]);cu(a,c,n),pu(l,c,s,r,null,Lc(a,l),"full");continue}iu(a,l,a.staticDependency,a.dynamicDependency,a.listPaths,s,"new",t=>{const e=Xn(a,t);Lr(e),u.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}for(const t of i){const n=o[t];if(h.has(n)&&e.written.get(n)!==qe){const o=$o(f,n),i=Xn(a,o);cu(a,i,Yn(a,f,e.listIndexes[t])),pu(o,i,s,r,null,Lc(a,o))}}}(d,m,h,t,s,r,e)}}}(t,e,w,n,o,r,i,b,h):gu(t,e,w,n,o,r,i,b)}finally{fu(g,o,r),y||mu(a,u,w,n,b),lu(a,e.pathInfo,{value:n})}}function wu(t,e,n,o){return(e,s,...r)=>{Array.isArray(s)||tt(`$resolve("${e}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&tt(`$resolve("${e}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=ot(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&tt(Ja("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=$o(i,Hc(t,n,o,i,s));if(0===r.length)return zc(t,a,n,o);Mc(o),yu(t,a,r[0],n,o)}}function vu(t,e,n,o){const s=wu(t,0,n,o);return(e,r)=>{const i=ot(e);if(void 0===r||Array.isArray(r)||tt(`$getAll("${e}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&tt(Ja("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Tc(o,i.wildcardPaths[t]);if(e){r=ro(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&tt(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(e,t.pathInfo.path)),r=[]}}const a=Bc(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}function _u(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Tc(o,s.wildcardPaths.at(-1)??tt(`lastWildcardPath is null: ${e.pathInfo.path}`))??tt(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??tt(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=$o(i,s),l=Fc(o,a,zc(t,a,n,o)),c=e.wildcardIndexes[r]??tt(`wildcardIndex is null: ${e.pathInfo.path}`);s=l[c]??tt(`ListIndex not found at index ${c} of ${i.path}`)}return s}case"partial":tt(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function $u(t,e,n,o){return(e,s,r,i)=>{Mc(o);const a=ot(e);Array.isArray(s)||tt(Xa(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&tt(Ja("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,u="function"==typeof r;l&&u&&tt(Xa(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&tt(Xa(e,"requires an array as the value when { spread: true } is set."));const d=Bc(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&tt(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,d.length,r.length));const h=[];for(let e=0;e<d.length;e++){const s=Hc(t,n,o,a,d[e]);h.push($o(a,s))}const f=a.lastSegment===c;let p=0;for(let e=0;e<h.length;e++){const s=f?$o(a,Hc(t,n,o,a,d[e])):h[e];let i;i=u?r(zc(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(yu(t,s,i,n,o),p++)}return p}}function xu(t,e){if("all"===Cc(e).wildcardType)return!0;const n=t.getterPaths;if(0===n.size)return!1;for(const t of ot(e).cumulativePaths)if(n.has(t))return!0;return!1}const Su=/^\$\d+$/,Iu=`${G}${l}`,Pu=`${K}${l}`,ku=new WeakMap;function Nu(t,e,n,o){const s=A[e];if(void 0===s&&"string"==typeof e&&36===e.charCodeAt(0)&&Su.test(e)&&tt(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&tt(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&tt(`ListIndex not found: ${e.toString()}`);let i=s;const a=t.pathInfo,l=o.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let n=0;n<e.length;n++)i+=e[n](o,t)}const c=so(r,i,a.wildcardCount);return c?.index??tt(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,e,n,t);if(i!==wc)return i}}if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>vu(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>$u(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=Cc(e),i=_u(t,r,n,o),a=$o(r.pathInfo,i),l=Xn(s,a),c=Kr();c.enqueueAbsoluteAddress(l),function(t,e,n,o,s){const r=bi(t,e),i=xi(t,e);if(!r&&!i)return;const a=n(),l=[],c=hu(l);r&&$i(t,e,!1,void 0,a).forEach(c),i&&Ii(t,e,void 0,a,!1).forEach(c),fu(l,o,s)}(s,r.pathInfo.path,()=>zc(t,a,n,o),n,o),iu(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Xn(s,t);Lr(e),c.enqueueAbsoluteAddress(e)});const u=s.addressHooks;if(u){const t=u.written;for(let e=0;e<t.length;e++)t[e](s,a.pathInfo)}}}(t,0,n,o)(e);case"$resolve":return(e,s,...r)=>wu(t,0,n,o)(e,s,...r);case"$trackDependency":dt?.renamed(e,"$dependOn");case"$dependOn":return t=>function(t,e,n,o){return t=>{-1!==t.indexOf(U)&&tt(`[wcs/recursion-unsupported] ${String(e)}("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&tt(`No active state reference to track dependency for path "${t}".`);const n=o.lastAddressStack?.pathInfo??tt("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==t&&s.addDynamicDependency(t,n.path)}}(0,e,0,o)(t);case"$eq":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(xu(o.stateElement,t))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&yi(o.stateElement,t),Object.is(n[t],e);let r;o.beginUntrack();try{r=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&gi(o.stateElement,t,e,Xn(o.stateElement,s),r),Object.is(r,e)};case"$eqPath":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=xu(o.stateElement,t);let i,a=r?n[t]:void 0;o.beginUntrack();try{r||(a=n[t]),i=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?yi(o.stateElement,t):gi(o.stateElement,t,i,Xn(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(t,e=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||tt(`$eqIndex("${t}") needs a list row scope.`);const r=so(s.listIndex,e-1,s.pathInfo.wildcardCount);if(null===r&&tt(`$eqIndex("${t}", ${e}): no list index at that level.`),xu(o.stateElement,t))return o.stateElement.getterPaths.has(s.pathInfo.path)&&(yi(o.stateElement,t),o.stateElement.addIndexDependentGetterPath?.(s.pathInfo.path)),Object.is(n[t],r.index);const i=e===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[t],i&&(l=n[s.pathInfo.wildcardParentPaths[e-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const e=i?cn(l):null;null!==e?function(t,e,n,o,s){Zr=!0,ui(t).lastValue.set(e,s),ci(t,e);let r=oi.get(t);void 0===r&&oi.set(t,r=new Map);let i=r.get(e);void 0===i&&r.set(e,i=new Set);let a,l=si.get(o);if(void 0===l?(si.set(o,l=[]),hn(o)):a=l.find(n=>n.stateElement===t&&n.path===e),void 0===a){a={stateElement:t,path:e,indexes:o,getters:new Set},l.push(a),i.add(a);const n=o[0]?.parentListIndex??null;if(null!==n){let t=ii.get(n);void 0===t&&ii.set(n,t=new Set),t.add(a)}}a.getters.add(n)}(o.stateElement,t,s.pathInfo,e,a):function(t,e,n,o,s){Zr=!0;const r=ui(t);ci(t,e),mi(r,e,s,o,fi(r,e,n.index,o),{stateElement:t,path:e,absAddress:o,levelListIndex:n})}(o.stateElement,t,r,Xn(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":dt?.renamed(e,"$untracked");case"$untracked":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case W:return bc(o.stateElement)}if(!e.startsWith(Iu)&&!e.startsWith(Pu))return}const r=Cc(e),i=_u(t,r,n,o),a=$o(r.pathInfo,i);return zc(t,a,n,o)}if("symbol"==typeof e){const s=function(t){let e=ku.get(t);return void 0===e&&(e=new Map,ku.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case jn:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&tt("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case Wn:i=e=>zc(t,e,n,o);break;case Dn:i=e=>Kc(t,e,n,o);break;case zn:i=()=>async function(t,e,n){const o=Reflect.get(t,E);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Bn:i=()=>function(t,e,n){const o=Reflect.get(t,C);"function"==typeof o&&o.call(n)}(t,0,n);break;case Fn:i=e=>function(t,e,n,o){const s=Reflect.get(t,M);let r;if("function"==typeof s){const t=new Set,i={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,s=e.path;if(-1===s.indexOf("#")&&(t.add(s),e.wildcardCount>0)){const t=ro(n.listIndex,e.wildcardCount),o=i[s];void 0===o?i[s]=[t]:o.push(t)}}(t.size>0||0===e.length)&&(r=s.call(n,Array.from(t),i))}const i=o.stateElement?.addressHooks;if(i){const t=i.updated;for(let s=0;s<t.length;s++)t[s](o.stateElement,e,n)}return r}(t,e,n,o);break;case Hn:i=(e,o)=>function(t,e,n,o){const s=Reflect.get(t,T);"function"==typeof s&&s.call(o,e,n)}(t,e,o,n);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}class Au{_stateElement;_addressStack=Array(d).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Pl(t);null===n&&tt("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&tt("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=d&&(this._hasRepeatedAddress()&&tt(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),tt(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const n=this._addressStack[e];if(n){if(t.has(n))return!0;t.add(n)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&tt(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return Nu(t,e,n,this)}set(t,e,n,o){return Mc(this),function(t,e,n,o,s){if("string"==typeof e){const r=Cc(e),i=_u(t,r,o,s);return yu(t,$o(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}deleteProperty(t,e){return Mc(this),Reflect.deleteProperty(t,e)}defineProperty(t,e,n){return Mc(this),Reflect.defineProperty(t,e,n)}}const Eu=Promise.resolve(),Cu=new Map;let Mu=[];function Tu(t,e){Cu.set(t,e),Mu=Array.from(Cu.values()).sort((t,e)=>t.order-e.order)}function Ou(t,e){return tt(wl(t,e))}const Lu="undefined"==typeof HTMLElement?class{}:HTMLElement;function Ru(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}let ju=null;const Wu=new Set(["for","if","elseif","else"]);const Du=[[F,"watch"],[H,"scan"],[B,"streams"],[q,"recursion"]];class zu extends Lu{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return kl(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new uc}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&tt(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){pc(t),function(t){for(let e=0;e<Du.length;e++){const[n,o]=Du[e];n in t&&!kc(o)&&tt(wl(o,`"${n}"`))}}(t);const e=this.__state,n=function(){const t=new Map;return{get:e=>t.get(e),set(e,n){t.set(e,n)}}}();n.set("previousState",e),function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].validateEarly?.(t,e,n)}(this,t,n);const o=function(t){const e=new Set,n=t[j];if(void 0===n)return e;Array.isArray(n)||tt(`${j} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||tt(`${j} entries must be non-empty strings.`),t===W&&tt(`${j} entry "${t}" conflicts with the reserved namespace name "${W}".`),e.has(t)&&tt(`${j} entry "${t}" is duplicated.`),e.add(t);return e}(t),s=function(t){const e=new Set,n=t[D];if(void 0===n)return e;Array.isArray(n)||tt(`${D} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||tt(`${D} entries must be non-empty strings.`),e.has(t)&&tt(`${D} entry "${t}" is duplicated.`),e.add(t);return e}(t),r=function(t){const e=t[V];if(void 0===e)return null;"object"==typeof e&&null!==e||tt(`${V} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&tt(`${V} entry path must be a non-empty string.`);const e=t.split(l);e.some(t=>0===t.length)&&tt(`${V} entry "${t}" must not contain empty path segments.`),e[e.length-1]===c&&tt(`${V} entry "${t}" must be the list path itself, not the element path (drop the trailing "${l}${c}").`),-1!==t.indexOf(U)&&tt(`[wcs/recursion-unsupported] ${V} entry "${t}" uses "${U}", which ${V} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${l}${c}${l}children").`),"function"!=typeof o?("string"!=typeof o&&tt(`${V} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&tt(`${V} entry "${t}" key field name must be a non-empty string.`),(o.includes(l)||o.includes(c))&&tt(`${V} entry "${t}" key field name "${o}" must be a flat property name ("${l}" / "${c}" are not allowed).`),o in Object.prototype&&tt(`${V} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t);n.set("eventTokenNames",s),function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].validate?.(t,e,n)}(this,t,n),function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].preCommit?.(t,e,n)}(this,t,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=t,void 0!==e&&ju?.reset(this),this._hasUpdatedCallback=M in t,this._hasErrorCallback=T in t,Ro.delete(this),function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].applyEarly?.(t,e,n)}(this,t,n),function(t,e,n){const o=e[z];if(void 0!==o){"object"==typeof o&&null!==o||tt(`${z} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||tt(`${z} entry "${e}" is not declared in $eventTokens.${it(e,n)}`),"function"!=typeof s&&tt(`${z} entry "${e}" must be a function.`),jo(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const i=function(t){const e=new Set,n=new Set,o=Ru(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of i.getterPaths)this._getterPaths.add(t);for(const t of i.setterPaths)this._setterPaths.add(t);!function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].apply?.(t,e,n)}(this,t,n),this._listKeys=r,this._rebuildPathInfo(),function(t,e,n){for(let o=0;o<Sc.length;o++)Sc[o].register?.(t,e,n)}(this,t,n),Nc(this,null),this._resolveLoading?.()}attributeChangedCallback(t,e,n){this._initialized&&e!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===e?"absent":`"${e}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${s.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?_l('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);return e&&"application/json"===e.type?JSON.parse(e.textContent||"{}"):(console.warn(`[@wcstack/state] state="${t}": no <script type="application/json" id="${t}"> in the document (3.x does not look inside shadow roots), so the state starts empty.`),{})}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await lc(t,s.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){let e;try{const n=await fetch(t);if(n.ok)return await n.json();e=`HTTP ${n.status} ${n.statusText}`}catch(t){e=t}return console.error(`[@wcstack/state] Failed to load JSON file "${t}", so the state starts empty (4.0 rejects instead):`,e),{}}(t);if(t&&t.endsWith(".js"))return await cc(t);tt(`Unsupported src file type: ${t}`)}}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}return await this._loadingPromise,null!==this._rootNode&&(El(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),tt(t)}_failInitializeLoudly(t,e=!0){if(this._initializationLanded)throw t;this._initializeFailed=!0;const n=["state","src"].find(t=>this.hasAttribute(t));throw console.error(`[@wcstack/state] <${s.tagNames.state}${n?` ${n}="${this.getAttribute(n)}"`:""}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),e&&null!==this._rootNode&&null===Pl(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),xl.set(t,n)}(this._rootNode,t),function(t,e,n){for(let o=0;o<Mu.length;o++)Mu[o].initializeFailed?.(t,e,n)}(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{E in t&&await t[zn]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{C in t&&t[Bn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(t){for(let e=0;e<Mu.length;e++)if(!0===Mu[e].reconnecting?.(t))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Pl(this._rootNode)===this||El(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const e=function(t){for(let e=0;e<Mu.length;e++){const n=Mu[e].connecting?.(t);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{Ou("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}const n=this.parentNode;if(n instanceof ShadowRoot&&n.host.hasAttribute(J))try{Ou("dcc",`a <${s.tagNames.state}> inside a [${J}] host`)}catch(t){this._failInitializeLoudly(t)}let o=!1;try{const t=function(t){for(let e=0;e<Mu.length;e++){const n=Mu[e].preparing?.(t);if(null!=n)return n}return null}(this);null===t&&this.hasAttribute("bind-component")&&Ou("scopes",'the "bind-component" attribute'),o=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(o)return;let r=!1;try{r=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!r)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!e()||t!==this._connectGeneration||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await _l('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Nc(this,t),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!function(t){for(let e=0;e<Mu.length;e++)if(!0===Mu[e].disconnecting?.(t))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(t,e){for(let n=0;n<Mu.length;n++)Mu[n].initializeFailureCleared?.(t,e)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{El(this.rootNode,null),yc.delete(this),function(t){for(let e=0;e<Ic.length;e++)Ic[e].deactivate?.(t)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(t=>(dt?.volumeLoaded(t),pc(t),t))}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e,this.attachAddressHooks("watch",F)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&tt(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return qa(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&tt("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const n=function(t,e){const n=_c.get(t);return void 0===n&&tt(wl(t,`"${e}"`)),n}(t,e);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(t,e){for(let n=0;n<vc.length;n++){const o=vc[n],s=e[o];if(void 0===s)continue;const r=t[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",L)}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){if(!this._addDependency(this._dynamicDependency,t,e))return!1;const n=ot(t);for(let t=n.parentPathInfo;null!==t&&t.wildcardCount>0&&t.wildcardCount===n.wildcardCount;t=t.parentPathInfo)this._addDependency(this._dynamicDependency,t.path,e);return!0}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(t);void 0===o?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:o.bound||"binding"===n})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+c)),!this._pathSet.has(t)){const e=ot(t);this._pathSet.add(t);const o=function(t,e){const n=Cc(e);return"all"===n.wildcardType&&1===n.wildcardIndexes.length&&isNaN(+n.segments[0])&&!e.includes("#")&&Object.isExtensible(t)&&!(e in t)}(this.__state,t);if(ju?.check(this,this.__state,t,n,o),o&&function(t,e){const{segments:n,cumulativePaths:o}=ot(e),s=n.length-1,r=(t,r,i)=>{let a,l=!1;for(let c=0;c<=s;c++){const u=n[c];if(l||=!(isNaN(+u)||Array.isArray(a)&&+u in a),r&&c===s)return l?a[u]=i:t[e]=i;a=l?a?.[u]:t[o[c]]}return a},i=function(){return r(this)};Ua.set(i,Cc(e).pathInfo.path),t.defineTreeAccessor(e,{get:i,set(t){r(this,!0,t)},configurable:!0})}(this,t),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=ot(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,n){try{const o=function(t,e,n){const o=new Au(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&tt(`<${s.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);!function(t){for(let e=0;e<Mu.length;e++)Mu[e].replacingState?.(t)}(this),(this._hasGraftedVolumes||this._hasMounts)&&tt("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const e=this.__state;this._state=t;const n=function(t){const e=new Set;for(const n of t)if(void 0!==n)for(const[t,o]of Object.entries(Ru(n)))t.startsWith("$")||t.includes(c)||"function"==typeof o.value||e.add(t);return e}([e,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){!function(t,n,o){const s=new Map;for(const t of o){const e=ot(t);if(null===e.lastWildcardPath)continue;const n=s.get(e.lastWildcardPath);void 0===n?s.set(e.lastWildcardPath,[e]):n.push(e)}const r=[],i=new Set,a=e=>{const n=Xn(t,e);if(i.has(n))return;i.add(n);const o=yo(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==e.listIndex){const t=s.get(e.pathInfo.path);if(void 0!==t)for(const n of t)a($o(n,e.listIndex))}};On();try{if(t.createState("readonly",e=>{for(const o of n){const n=$o(ot(o),null);a(n);try{iu(t,n,t.staticDependency,t.dynamicDependency,t.listPaths,e,"new",a)}catch{}}}),0===r.length)return;const o=function(t){const e=[],n=[];for(const o of t)Wu.has(o.bindingType)?e.push(o):n.push(o);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(n)}(r),s=()=>{hl(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=Wr("state",s);void 0!==i&&i.catch(Vr)}finally{Ln()}}(this,t,this._pathRegistrations.keys())}}const Bu=[],Fu=[];function Hu(){const t=[];let e=0;for(let n=0;n<Fu.length;n++){const o=Fu[n].deref();void 0!==o&&(t.push(o),Fu[e++]=Fu[n])}return Fu.length=e,t}function qu(t,e){const n=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(t);var i;n&&((i=n).tagNames&&Object.assign(o.tagNames,i.tagNames),"string"==typeof i.bindAttributeName&&(o.bindAttributeName=i.bindAttributeName),"string"==typeof i.commentTextPrefix&&(o.commentTextPrefix=i.commentTextPrefix),"string"==typeof i.commentForPrefix&&(o.commentForPrefix=i.commentForPrefix),"string"==typeof i.commentIfPrefix&&(o.commentIfPrefix=i.commentIfPrefix),"string"==typeof i.commentElseIfPrefix&&(o.commentElseIfPrefix=i.commentElseIfPrefix),"string"==typeof i.commentElsePrefix&&(o.commentElsePrefix=i.commentElsePrefix),"string"==typeof i.locale&&(o.locale=i.locale),"boolean"==typeof i.debug&&(o.debug=i.debug),"boolean"==typeof i.enableMustache&&(o.enableMustache=i.enableMustache),"boolean"==typeof i.enableDirectionalInitialSync&&(o.enableDirectionalInitialSync=i.enableDirectionalInitialSync),"boolean"==typeof i.enablePropagationContext&&(o.enablePropagationContext=i.enablePropagationContext),"boolean"==typeof i.enableContractAnalyzer&&(o.enableContractAnalyzer=i.enableContractAnalyzer),"boolean"==typeof i.sameValueGuard&&(o.sameValueGuard=i.sameValueGuard)),function(t=customElements){Hu().includes(t)||Fu.push(new WeakRef(t));for(let e=0;e<Bu.length;e++)Bu[e](t);t.get(s.tagNames.state)||t.define(s.tagNames.state,zu)}(e),function(){const t=globalThis;void 0===t[r]&&(t[r]=rc)}()}let Uu=null;function Vu(t){return Uu??tt(wl("watch",`"$watch" in <wcs-state mount="${t}">`))}let Gu=null;const Ku=Object.freeze([]),Ju="3.5.0",Qu=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Xu(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const Yu="__WCSTACK_DEVTOOLS_HOOK__";const Zu=t=>{null!==Se&&Se({type:"state:update-batch",addresses:t})};function td(t){const e=null!==Se;!function(t){Se=t}(t);const n=null!==t;n&&!e?Ur(Zu,0):!n&&e&&function(t){const e=Dr.findIndex(e=>e.listener===t);-1!==e&&Dr.splice(e,1)}(Zu)}function ed(t){return{rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function nd(t){return Pl(t)??tt("devtools: no state tree on this root")}let od=null;function sd(){if(e())return;if(null!==od)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Ju,getStateElements(){const t=[];for(const e of Sl)t.push(ed(e));return t},overlays(t){return e=nd(t),null===Gu?Ku:Gu(e);var e},keyedSubscriptions:t=>function(t){const e=function(t){const e=Jr.get(t);return void 0===e?null:{byPath:e.byPath,lastValue:e.lastValue,tracked:e.tracked,watchers:oi.get(t)}}(t);if(null===e)return[];const n=new Set([...e.byPath.keys(),...e.tracked]);if(void 0!==e.watchers)for(const t of e.watchers.keys())n.add(t);const o=[];for(const t of[...n].sort()){const n=e.byPath.get(t);let s=0;if(void 0!==n)for(const t of n.values())s+=t.size;o.push({path:t,tracked:e.tracked.has(t),rows:s,keys:n?.size??0,lists:e.watchers?.get(t)?.size??0,lastValue:e.lastValue.get(t)})}return o}(nd(t)),keys(t){const e=nd(t),n=[];return e.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}n.push(e)}}),n},read(t,e,n){let o;return nd(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){nd(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,o=new Set,r=t=>{const o=function(t){const e=`${ut(t.inFilters)}\0${ut(t.outFilters)}`;return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(o.has(t))return;o.add(t);const e=Tl(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Xu(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(s.bindAttributeName);if(null===n||0===n.length)continue;try{const t=se(e,Lt(n));for(const o of t)r(Xu(e,o,"attribute",n))}catch{}continue}const e=Qu.exec(t.data.trim());if(null===e)continue;const n=e[1]||s.commentTextPrefix,o=e[2],a=Tl(o);if(null===a){if(n===s.commentTextPrefix)try{r(Xu(t,zt(o),"comment",o))}catch{}}else r(Xu(t,a.parseBindTextResult,"comment",o)),i(o)}return e}(t),_setSink:td};od=t,function(){const t=globalThis,e=t[Yu];if(void 0!==e)return 2!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 2. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:2,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[Yu]=n,n}().register(t)}const rd={name:"devtools",install(){sd()}},id=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),ad=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])}),ld=new WeakMap,cd=new WeakMap,ud=new WeakSet,dd=new WeakMap;function hd(t,e,n,o){console.warn(`[@wcstack/state] [${Ga[n]}] ${Ka[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${it(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${at}`),null!==Se&&Se({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const fd={check:function(t,e,n,o,s){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const r=t.addressHooks;if(r){const e=r.suppressPathDiagnostic;for(let o=0;o<e.length;o++)if(e[o](t,n))return}const i=ot(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=ld.get(t);return void 0===n&&(n=new Set,ld.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const a=function(t,e,n,o){if(void 0!==qa(t,e))return ad;const s=ot(e).segments;let r=t,i="";for(let e=0;e<s.length;e++){const a=o&&Array.isArray(r)&&+s[e]>=0?c:s[e],u=i;i=0===e?a:i+l+a;const d=e>0&&qa(t,i),h=d&&Ua.get(d.get);if(d&&(!h||qa(t,h)))return e<s.length-1?id:ad;if(Object(r)!==r)return id;if(a===c){if(!Array.isArray(r)||0===r.length)return id;r=r[0];continue}const f=qa(r,a);if(void 0===f)return{existence:"missing",missingSegment:a,candidates:Va(r,u,n,t)};if("function"==typeof f.get)return e===s.length-1?ad:id;r=f.value}return ad}(e,n,t.getterPaths,s);"missing"===a.existence&&(function(t,e){return!0===dd.get(t)?.has(e)}(t,n)||("binding"!==o?hd(0,n,o,a):function(t,e,n){let o=cd.get(t);void 0===o&&(o=new Map,cd.set(t,o)),o.set(e,n),ud.has(t)||(ud.add(t),setTimeout(()=>function(t){ud.delete(t);const e=cd.get(t);if(void 0!==e){cd.delete(t);for(const[t,n]of e)hd(0,t,"binding",n)}}(t),0))}(t,n,a)))},reset:function(t){ld.delete(t),cd.delete(t)},markExported:function(t,e){let n=dd.get(t);void 0===n&&(n=new Set,dd.set(t,n)),n.add(e),cd.get(t)?.delete(e)}};let pd=!1;const md={name:"diagnostics",install(){pd||(pd=!0,ju=fd)}};function gd(t){tt(`filter ${t} requires at least one option`)}function yd(t){tt(`filter ${t} requires a number as option`)}function bd(t){tt(`filter ${t} requires a number value`)}function wd(t){tt(`filter ${t} requires a date value`)}const vd={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function _d(t){return!(!t||isNaN(Number(t)))}function $d(t,e){return _d(t)||yd(e),Number(t)}function xd(t,e,n){return $d(t?.[e]??gd(n),n)}const Sd=t=>e=>{const n=t(e);return t=>null==t?t:n(t)},Id={eq:(t,e)=>{const n=t?.[0]??gd("eq"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t===o:(_d(n)||yd("eq"),t===Number(n)):"string"==typeof t?t===n:t===o},ne:(t,e)=>{const n=t?.[0]??gd("ne"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?"string"!=typeof o?t!==o:(_d(n)||yd("ne"),t!==Number(n)):"string"==typeof t?t!==n:t!==o},not:t=>t=>!t,lt:t=>{const e=xd(t,0,"lt");return t=>("number"!=typeof t&&bd("lt"),t<e)},le:t=>{const e=xd(t,0,"le");return t=>("number"!=typeof t&&bd("le"),t<=e)},gt:t=>{const e=xd(t,0,"gt");return t=>("number"!=typeof t&&bd("gt"),t>e)},ge:t=>{const e=xd(t,0,"ge");return t=>("number"!=typeof t&&bd("ge"),t>=e)},add:t=>{const e=xd(t,0,"add");return t=>("number"!=typeof t&&bd("add"),t+e)},sub:t=>{const e=xd(t,0,"sub");return t=>("number"!=typeof t&&bd("sub"),t-e)},mul:t=>{const e=xd(t,0,"mul");return t=>("number"!=typeof t&&bd("mul"),t*e)},div:t=>{const e=xd(t,0,"div");return t=>("number"!=typeof t&&bd("div"),t/e)},mod:t=>{const e=xd(t,0,"mod");return t=>("number"!=typeof t&&bd("mod"),t%e)},abs:t=>t=>("number"!=typeof t&&bd("abs"),Math.abs(t)),clamp:t=>{const e=xd(t,0,"clamp"),n=xd(t,1,"clamp");return t=>("number"!=typeof t&&bd("clamp"),Math.min(Math.max(t,e),n))},toFixed:t=>{const e=$d(t?.[0]??"0","toFixed");return t=>("number"!=typeof t&&bd("toFixed"),t.toFixed(e))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&bd("locale"),t.toLocaleString(e??s.locale))},upper:Sd(t=>t=>String(t).toUpperCase()),lower:Sd(t=>t=>String(t).toLowerCase()),capitalize:Sd(t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)}),trim:Sd(t=>t=>String(t).trim()),slice:Sd(t=>{const e=[xd(t,0,"slice")],n=t?.[1];return void 0!==n&&e.push($d(n,"slice")),t=>String(t).slice(...e)}),substr:Sd(t=>{dt?.removed("substr");const e=xd(t,0,"substr"),n=xd(t,1,"substr");return t=>String(t).substr(e,n)}),padStart:Sd(t=>{const e=xd(t,0,"padStart"),n=t?.[1]??"0";return t=>String(t).padStart(e,n)}),padEnd:Sd(t=>{const e=xd(t,0,"padEnd"),n=t?.[1]??" ";return t=>String(t).padEnd(e,n)}),repeat:Sd(t=>{const e=xd(t,0,"repeat");return t=>String(t).repeat(e)}),reverse:Sd(t=>t=>String(t).split("").reverse().join("")),truncate:Sd(t=>{const e=xd(t,0,"truncate"),n=t?.[1]??"…";return t=>{const o=String(t);return o.length<=e?o:o.slice(0,e)+n}}),join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||tt("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=Math.pow(10,$d(t?.[0]??"0","round"));return t=>("number"!=typeof t&&bd("round"),Math.round(t*e)/e)},floor:t=>{const e=Math.pow(10,$d(t?.[0]??"0","floor"));return t=>("number"!=typeof t&&bd("floor"),Math.floor(t*e)/e)},ceil:t=>{const e=Math.pow(10,$d(t?.[0]??"0","ceil"));return t=>("number"!=typeof t&&bd("ceil"),Math.ceil(t*e)/e)},percent:t=>{const e=$d(t?.[0]??"0","percent");return t=>("number"!=typeof t&&bd("percent"),`${(100*t).toFixed(e)}%`)},unit:Sd(t=>{const e=t?.[0]??gd("unit");return t=>String(t)+e}),date:t=>{const e=t?.[0];return t=>(t instanceof Date||wd("date"),t.toLocaleDateString(e??s.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||wd("time"),t.toLocaleTimeString(e??s.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||wd("datetime"),t.toLocaleString(e??s.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||wd("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||wd("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!t,truthy:t=>t=>!!t,defaults:(t,e)=>{const n=t?.[0]??gd("defaults"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t||o},coalesce:(t,e)=>{const n=t?.[0]??gd("coalesce"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t??o},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),nullIfEmpty:t=>t=>""===t?null:t},Pd={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[2,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,1],time:[0,1],datetime:[0,1],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},kd=Id,Nd=Id;let Ad=!1;const Ed={name:"formats",install(){Ad||(Ad=!0,bt("input",Nd,Pd,vd),bt("output",kd,Pd,vd))}};function Cd(t){return-1!==t.indexOf(U)}function Md(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+l;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(Cd(o))return null;const s=o.slice(1).split(l);return s[0]===c||s.some(t=>0===t.length)?null:o}function Td(t){return 0===t.length?t:l+Rd(t.slice(1))}function Od(t,e,n){const o=l+t.repeat,s=e.length<=n.length?e:n,r=e.length<=n.length?n:e;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let t=0;t<i.length;t+=o.length)if(!i.startsWith(o,t))return!1;return!0}function Ld(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(l,o-1))if(Od(t,e,n.slice(0,o)))return!0;return!1}function Rd(t){const e=t.split(l);for(let t=0;t<e.length;t++)e[t]===c||Number.isNaN(Number(e[t]))||(e[t]=c);return e.join(l)}function jd(t,e){const n=t.repeat.split(l),o=l+t.repeat;let s=e;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===l+t.repeatList+l+"length")return!0;for(let t=1;t<n.length;t++)if(s===l+n.slice(0,t).join(l))return!0;return!1}function Wd(t,e,n){n<0&&tt(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=l+t.repeat;const s=o+e;let r=0;for(const t of s.split(l))t===c&&r++;return r>u&&tt(`[wcs/recursion-depth-exceeded] Recursion on "${t.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function Dd(t,e){return Wd(t,"",e)}function zd(t,e,n){if(!n.startsWith(t.anchor))return null;if(e.length>0&&!n.endsWith(e))return null;if(n.length<t.anchor.length+e.length)return null;const o=n.slice(t.anchor.length,n.length-e.length);if(0===o.length)return 0;const s=l+t.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function Bd(t,e,n){const o=t.recursionRegistry,s=Md(o.spec,n);null===s&&tt(Qa(n,o.spec.recursiveAnchor));const r=function(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=e.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(t,e){const n=t.spec;if(!e.startsWith(n.anchor))return null;const o=l+n.repeat;let s=0,r=n.anchor.length;for(;e.startsWith(o,r);)r+=o.length,s++;return r!==e.length&&46!==e.charCodeAt(r)?null:s}(e,n.pathInfo.path)}(e,o);return null===r&&tt(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function Fd(t,e,n,o,s){const r=o.spec,i=[],a=new Map,c=[],u=r.repeatList,d=r.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void i.push($o(t,n));const s=m(o[e],n,null).rows;for(let n=0;n<s.length;n++)p(t,e+1,s[n])};function m(o,s,i){const l=$o(o,s),c=Xn(n.stateElement,l),d=zc(t,l,e,n),f=null===i?null:((t,e,n)=>{if(!Array.isArray(e)||0===e.length)return null;const o=e;return h.has(o)&&tt(`[wcs/recursion-cycle] "${t}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&tt(`[wcs/recursion-shared-list] "${t}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${u}" array.`),o})(o.path,d,i),p=Bi(s,Mn(c),d);return a.set(c,Array.isArray(d)?d:[]),null!==f&&null!==i&&i.add(f),{rows:p.newIndexes,tracked:f}}const g=(t,e,n)=>{const{rows:r,tracked:a}=m(e,n,f);if(0===r.length)return;const d=(t=>{const e=c[t];if(void 0!==e)return e;const n=o.concretePathAt(s,t),r=0===s.length?n:o.concretePathAt("",t),i={nodePath:r,concretePathInfo:ot(n),childListPathInfo:ot(r+l+u)};return c[t]=i,i})(t),y=a;h.add(y);const b=d.concretePathInfo.wildcardCount===t+1;for(let e=0;e<r.length;e++){const n=r[e];b?i.push($o(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,ot(d),null);for(const[t,e]of a)Tn(t,e);return i}const Hd={write(t,e){if(!0!==t.hasRecursion)return wc;const n=t.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);return null!==n&&tt(`[wcs/recursion-readonly] "${e.pathInfo.path}" writes into the recursive getter "${n}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),wc},get(t,e,n,o){if(!0!==t.stateElement.hasRecursion)return wc;if("$getAll"===e)return(e,s)=>{if(Cd(e)){if(void 0!==s)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=Md(r.spec,o);null===i&&tt(Qa(o,r.spec.recursiveAnchor)),Array.isArray(s)||tt(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&tt(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=Fd(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(zc(t,a[o],e,n));return l}(o,n,t,e,s);e=Bd(t.stateElement,t,e)}return vu(o,0,n,t)(e,s)};if("$setAll"===e)return(e,s,r,i)=>Cd(e)?function(t,e,n,o,s,r,i){Mc(n);const a=n.stateElement.recursionRegistry,l=Md(a.spec,o);null===l&&tt(Qa(o,a.spec.recursiveAnchor));const c=Td(l);Array.isArray(s)||tt(Xa(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&tt(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&tt(Xa(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&tt(Xa(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(t,e,n){jd(t,n)&&tt(`[wcs/recursion-structural-write] "${e}" writes the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const u=a.conflictingRecursiveGetter(c);null!==u&&tt(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${u}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const d=Fd(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(yu(t,d[o],r,e,n),h++);return h}(o,n,t,e,s,r,i):$u(o,0,n,t)(e,s,r,i);if(36!==e.charCodeAt(0)&&Cd(e)){const s=Cc(Bd(t.stateElement,t,e)),r=_u(o,s,n,t);return zc(o,$o(s.pathInfo,r),n,t)}return wc}};let qd=!1;function Ud(t,e){"string"==typeof e&&0!==e.length||tt(`[wcs/recursion-declaration-invalid] ${q} ${t} must be a non-empty string.`);const n=e.split(l);n.some(t=>0===t.length)&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain empty path segments.`),n.length<2&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must name a list element: a property path ending with "${l}${c}" (for example "nodes${l}${c}").`),n[n.length-1]!==c&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must end with "${l}${c}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===c&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must have exactly one "${c}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===U&&tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain "${U}" — the declaration is what gives "${U}" its meaning.`),isNaN(Number(n[o]))||tt(`[wcs/recursion-declaration-invalid] ${q} ${t} "${e}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const Vd=new WeakSet;function Gd(t){return"function"==typeof t.get&&Vd.has(t.get)}const Kd="[wcs/recursion-declaration-invalid]";class Jd{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(t,e){this.spec=t;const n=Ru(e);for(const[e,o]of Object.entries(n)){if(!Cd(e))continue;"function"==typeof o.set&&tt(`${Kd} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&tt(`${Kd} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Md(t,e);null===n&&tt(Qa(e,t.recursiveAnchor)),0===n.length&&tt(`${Kd} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${l}total"), not the node.`),jd(t,Td(n))&&tt(`${Kd} "${e}" names the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${t.recursiveAnchor}${l}total").`),this._definitions.set(e,{recursivePath:e,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(t){for(const[e,n]of Object.entries(t)){if(Cd(e)||Gd(n))continue;const t=this._matchExpansion(e);null!==t&&tt(`${Kd} "${e}" is already defined on the state, so the recursive getter "${t}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const t=Array.from(this._definitions.values());for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)Od(this.spec,t[e].suffix,t[n].suffix)&&tt(`${Kd} "${t[e].recursivePath}" and "${t[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(t){for(const e of this._definitions.values())if(Ld(this.spec,e.suffix,t))return e.recursivePath;return null}recursiveGetterOwningPath(t){const e=this._ownerByPathInfo.get(t);if(void 0!==e)return e;const n=this.recursiveGetterOwning(t.path);return this._ownerByPathInfo.set(t,n),n}recursiveGetterOwning(t){const e=this._accessors.get(t);if(void 0!==e)return e.recursivePath;const n=Rd(t),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let t=n.lastIndexOf(l);null===s&&t>this.spec.anchor.length;t=n.lastIndexOf(l,t-1))s=this._matchExpansion(n.slice(0,t))}return this._ownerByPath.set(n,s),s}_matchExpansion(t){for(const e of this._definitions.values())if(null!==zd(this.spec,e.suffix,t))return e.recursivePath;return null}materializeForPathInfo(t,e){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(e);if(void 0!==n)return n;const o=this.materializeFor(t,e.path);return this._accessorByPathInfo.set(e,o),o}materializeFor(t,e){const n=this._accessors.get(e);if(void 0!==n)return n;if(!e.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const t of this._definitions.values()){const n=zd(this.spec,t.suffix,e);null!==n&&(null!==o&&tt(`"${e}" matches both "${o.recursivePath}" and "${t.recursivePath}".`),o=t,s=n)}return null===o?null:this._define(t,o,s,e)}_define(t,e,n,o){const s=t.findStateDescriptor(o);void 0===s||Gd(s)||tt(`"${o}" is already defined on the state, so the recursive getter "${e.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:e.recursivePath,depth:n}),i=e.get,a=function(){return i.call(this)};var l;return l=a,Vd.add(l),t.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(t,n),this._accessors.set(o,r),r}_registerListPaths(t,e){for(const n of function(t,e){const n=[];n.push(t.anchorList);for(let o=0;o<e;o++)n.push(Dd(t,o)+l+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){const n=new Set(this._accessors.keys());return function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&Gd(n)&&delete e[t]}for(const e of[t.staticDependency,t.dynamicDependency]){for(const t of n)e.delete(t);for(const[t,o]of e){let s=null;for(let t=0;t<o.length;t++)n.has(o[t])?s??=o.slice(0,t):s?.push(o[t]);null!==s&&(0===s.length?e.delete(t):e.set(t,s))}}}}(t,e,n),n}concretePathAt(t,e){let n=this._concreteBySuffix.get(t);void 0===n&&(n=[],this._concreteBySuffix.set(t,n));let o=n[e];return void 0===o&&(o=Wd(this.spec,t,e),n[e]=o),o}accessorFor(t){return this._accessors.get(t)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const Qd="recursionSpec",Xd="recursionRegistry",Yd={order:5,validateEarly(t,e,n){const o=function(t){const e=t[q];if(void 0===e)return null;"object"==typeof e&&null!==e||tt(`[wcs/recursion-declaration-invalid] ${q} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(e);0===n.length&&tt(`[wcs/recursion-declaration-invalid] ${q} must declare exactly one anchor; it is empty.`),n.length>1&&tt(`[wcs/recursion-declaration-invalid] ${q} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Ud("anchor",o),"string"!=typeof s&&tt(`[wcs/recursion-declaration-invalid] ${q} entry "${o}" must map to the repeating sub-path as a string (for example "children${l}${c}").`),Ud("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(l)),i=s.slice(0,s.lastIndexOf(l)),a=r+l+U;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(e);n.set(Qd,o),n.set(Xd,null===o?null:new Jd(o,e))},preCommit(t,e,n){const o=t.recursionRegistry;if(null!==o)for(const e of o.forgetGenerated(t,n.get("previousState")))t.addGeneratedPath?.(e);const s=n.get(Xd)??null;t.setRecursionRegistry?.(s),null!==s&&t.attachAddressHooks?.("recursion",q)},apply(t,e,n){const o=n.get(Qd)??null;null!==o&&t.addListPath(o.anchorList)}};let Zd=!1;const th={name:"recursion",install(){Zd||(Zd=!0,qd||(qd=!0,$c("recursion",Hd)),Pc("recursion",Yd))}},eh={written:function(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1&&-1===e.path.indexOf("#")?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let nh=!1;function oh(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function sh(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function rh(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function ih(t){return t.startsWith("$")}function ah(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function lh(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||tt(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||tt(`${e} entries must be non-empty strings.`),t.startsWith("$")&&tt(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&tt(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function ch(t,e,n){const o=t.tagName.toLowerCase();o.includes("-")||tt(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const r=Jt(t);null!==r&&"function"==typeof r.define||tt(`DCC: CustomElementRegistry is unavailable for "${o}".`),r.get(o)&&tt(`DCC: "${o}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const t of Array.from(e.childNodes))i.content.appendChild(a.importNode(t,!0));const l=e.mode,{bindables:c,commands:u,streamBackedBindables:d}=function(t){pc(t);const e=lh(t,L)??[],n=lh(t,R)??[],o=Ru(t),s=function(t){const e=t[B];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}tt(`${L} entry "${t}" is not declared on the state.${it(t,ah(o,"value"))}`)}"function"==typeof e.value&&tt(`${L} entry "${t}" is a method. Declare it in ${R} instead.`)}for(const t of n){const e=o[t];void 0===e&&tt(`${R} entry "${t}" is not declared on the state.${it(t,ah(o,"method"))}`),"function"!=typeof e.value&&tt(`${R} entry "${t}" is not a method. Declare it in ${L} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||u.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(o,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(o,c):{},p=s.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(J))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=Jt(this._shadow);return null!==t&&Qt(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(m.bindableEventMap).length>0){const e=t.querySelector(p);e?(nh||(nh=!0,$c("dcc",eh)),e.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${L} but its template has no <${s.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=Ru(n);for(const[t,e]of Object.entries(g)){if(ih(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=rh(t,o)}else n.get=oh(t),n.set=sh(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:oh(t),set:sh(t)});r.define(o,m)}const uh={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(J)?async function(t,e,n){const o=t;try{o.hasAttribute("bind-component")&&tt(`"bind-component" cannot be used inside a [${J}] host. DCC state comes from the template, not from a component property.`);const s=await async function(t,e){if(t.hasAttribute("src")){const e=t.getAttribute("src");if(e.endsWith(".js"))return await cc(e);tt(`DCC: Unsupported src type: ${e}`)}const n=t.querySelector('script[type="module"]');if(n)return await lc(n,e.tagName.toLowerCase());tt(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}(o,e);ch(e,n,s),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}(t,e.host,e):null}};let dh=!1;function hh(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function fh(t,e){for(const n of t)if(hh(e,n.innerSegments))return n;return null}function ph(t,e){const n=e.slice(t.innerSegments.length);return 0===n.length?t.outerPathInfo.path:t.outerPathInfo.path+l+n.join(l)}const mh=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function gh(t,e,n){const o=mh.get(t);return void 0===o?null:(...t)=>{const s=t.slice();for(let t=0;t<o.length;t++){const n=o[t];"string"==typeof s[n]&&(s[n]=e(s[n]))}return n(s)}}const yh=new WeakMap;function bh(t,e,n){let o=yh.get(t);void 0===o&&(o=new Map,yh.set(t,o));null!=o.get(e)&&tt(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function wh(t,e){if(null===t)return!1;const n=yh.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+l)||t.startsWith(e+l))return!0;return!1}const vh=new WeakMap,_h=[];function $h(t,e,n,o){if(e.length>0){const s=n.split(l),r=fh(e,s);if(null!==r)return o&&r.readonly&&tt(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${x}.${r.innerSegments.join(l)}#${g}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${g} from the injection.`),ph(r,s)}return t+l+n}function xh(t,e,n){let o=-1,s=null;for(const t of e){const e=t.outerPathInfo.path;e.length<=o||(n===e?(o=e.length,s=t.innerSegments.join(l)):n.startsWith(e+l)&&(o=e.length,s=t.innerSegments.join(l)+n.slice(e.length)))}if(t.length>o){if(n===t)return"";if(n.startsWith(t+l))return n.slice(t.length+1)}return s}function Sh(t,e,n=_h){return new Proxy({},{get(o,s){if("string"==typeof s&&"then"!==s){if("$"===s[0]){if("$postUpdate"===s||"$getAll"===s){const o=s;return(s,...r)=>e[o]($h(t,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>e.$setAll($h(t,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>e.$resolve($h(t,n,o,s.length>1),...s);const o=gh(s,e=>$h(t,n,e,!1),t=>e[s](...t));return null!==o?o:e[s]}return e[$h(t,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(e[s]=r,!0):(e[$h(t,n,s,!0)]=r,!0)),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Ih=new WeakMap,Ph=[],kh=new WeakMap,Nh=new WeakSet;function Ah(t){console.error(`[@wcstack/state] volume "${t.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),t.onGrafted(null)}let Eh=null,Ch=0;const Mh=["$watch",B,"$scan","$listKeys",M,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Th=new Set;function Oh(t,e,n){const o=t.stateObject[e];if("function"==typeof o)try{const s=o.call(n());s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function Lh(t){const e=t.indexOf(l);return-1===e?t:t.slice(0,e)}function Rh(t,e){const n=fh(t.entries,e);return null===n?null:ph(n,e)}function jh(t,e){return t.markerBasePath+l+e}function Wh(t,e,n,o){let s=t.accessorBySuffixByMarkerParent.get(e);void 0===s&&(s=new Map,t.accessorBySuffixByMarkerParent.set(e,s));const r=e+l+n;s.set(n,{accessorName:o,indexShift:ot(r).wildcardCount-ot(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(r),t.addedGetterPaths.add(r))}function Dh(t,e){return!t.injectedKeys.has(e)&&(!t.getterKeys.has(e)&&"function"==typeof t.stateObject[e]||!t.mappedKeys.has(e)&&Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function zh(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(l)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${Lh(e)}: path") or declare the key on the component state.`}const Bh=/^\$(\d+)$/;function Fh(t,e){if(!t.hasReadonlyEntries)return null;const n=e[0];if("$"===n||"#"===n)return null;if(t.getterKeys.has(e)||t.setterKeys.has(e))return null;const o=Lh(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||Dh(t,o))return null;const s=function(t,e){return fh(t.entries,e)}(t,e.split(l));return null!==s&&s.readonly?s:null}function Hh(t,e){const n=Fh(t,e);if(null!==n){const o=0===n.innerSegments.length?"":l+n.innerSegments.join(l);tt(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${g}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${g} from the mount.`)}return qh(t,e)}function qh(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(l);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===c){o=t;break}if(-1===o)return Wh(t,t.markerBasePath,e,e),jh(t,e);if(Dh(t,n[0]))return Wh(t,t.markerBasePath,e,e),jh(t,e);const s=n.slice(0,o+1),r=n.slice(o+1),i=Rh(t,s);null===i&&tt(zh(t,e)),0===r.length&&tt(`Wildcard-terminal accessor "${e}" on mounted <${t.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const a=i+l+t.marker;return Wh(t,a,r.join(l),e),a+l+r.join(l)}(t,e);const o=Lh(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return jh(t,e);if(Dh(t,o))return jh(t,e);const s=Rh(t,e.split(l));if(null!==s)return s;tt(zh(t,e))}const Uh=new Set(["prop","radio","checkbox"]);function Vh(t,e,n,o,s){if(void 0===o)return;const r=ot(n).wildcardCount-ot(e).wildcardCount;return 0===r?o:(s.length<r&&tt(`Cannot resolve "${e}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}function Gh(t,e,n){if(-1!==t.indexOf(c))return e;const o=e.split(l);let s=0;for(let t=0;t<o.length&&s<n.length;t++)o[t]===c&&(o[t]=String(n[s++]));return o.join(l)}const Kh=new WeakMap,Jh=new WeakMap,Qh=new WeakMap,Xh=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)}),Yh=new WeakMap;function Zh(t){return Yh.get(t)??null}let tf=!1;function ef(t){return Kh.get(t)??null}function nf(t){return of(t).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join(l),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]}))}function of(t){const e=Qh.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}function sf(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=Qh.get(t);if(void 0===o)return null;const s=e.indexOf(l,n),r=-1===s?e.slice(n):e.slice(n,s),i=o.get(r);if(void 0===i)return null;const a=i.deref();return void 0===a?(o.delete(r),null):a}const rf=new WeakMap,af=new Set;function lf(t,e,n,o){let s=rf.get(t);if(void 0===s){if(!o)return null;s=new Map,rf.set(t,s)}let r=s.get(e);if(void 0===r){if(!o)return null;r=new Map,s.set(e,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function cf(t,e){if(!t.component.isConnected)return!1;const n=$e(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function uf(t,e,n,o){const s=lf(t,e,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&cf(n,e)?n:null}(r,o);if(null!==t)return{record:t,entry:r.entry}}let i=null,a=null;for(const t of s.holders){const r=t.ref.deref();void 0!==r?cf(r,o)&&(null!==a&&tt(`[wcs/mount-export-ambiguous] "${e}${l}${n}" is exported by two mounted components on the same instance: <${a.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=t,a=r):s.holders.delete(t)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function df(t){const e=t.parentStateElement,n=$e(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[jn](n,()=>{t.$postUpdate(o.exportedPath)})})}const hf=new WeakMap,ff=new WeakMap,pf=new WeakMap,mf=new WeakMap;function gf(t,e){ff.set(t,e);const n=[];for(let t=e?.listIndex.parentListIndex??null;null!==t;t=t.parentListIndex)n.push(t);mf.set(t,n)}function yf(t){return $e(t.component)??ff.get(t)??null}function bf(t){return yf(t)?.listIndex??null}function wf(t){tt(`The host row of <${t.component.tagName.toLowerCase()}> was removed.`)}function vf(t){for(;null!==t;t=t.parentListIndex)if(Je(t))return!0;return!1}function _f(t,e){return!t.component.isConnected&&(vf(e)||!0===mf.get(t)?.some(t=>Je(t)))}class $f{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(t,e,n,o,s,r,i,a=!1){this.record=t,this.markerParentPath=e,this.listIndex=n,this.hostRow=o,this.isBase=s,this.receiver=r,this.handler=i,this.authorFacing=a}authorThis(t,e){return this.authorFacing?e:new Proxy(t,new $f(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return $o(ot(this.markerParentPath+l+t),this.listIndex)}hostIndexes(){const t=this.listIndex??bf(this.record),e=this.hostRow??t;return(null===this.listIndex?e!==t||_f(this.record,e):vf(e))&&wf(this.record),e?.indexes??[]}resolveTreePath(t,e){return-1===e.indexOf(c)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==Cc(e).wildcardType&&!_f(this.record,this.listIndex)?e:Gh(t,e,this.hostIndexes())}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(this.resolveTreePath(t,qh(this.record,t)))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.hostIndexes(),o=this.receiver,s=this.handler,r=this.listIndex;if("$resolve"===e)return(e,s,...r)=>{const i=r.length>0?Hh(t,e):qh(t,e),a=Vh(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const i=e;return(e,a,...l)=>{const c="$setAll"===i?Hh(t,e):qh(t,e),u=Vh(0,e,c,void 0===a&&"$getAll"===i&&null===r&&null===Tc(s,ot(c).wildcardPaths[0])?[]:a,n);return o[i](c,u,...l)}}const t=this.record,n=this.receiver,o=gh(e,e=>this.resolveTreePath(e,qh(t,e)),t=>n[e](...t));return null!==o?o:this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return Oc(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(this.authorThis(t,n))}return this.receiver[this.resolveTreePath(e,qh(this.record,e))]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||tt(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,this.authorThis(t,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(t,e)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress($o(ot(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+l+e]=n}finally{this.handler.popAddress()}return!0}return t[e]=n,!0}return this.receiver[this.resolveTreePath(e,Hh(this.record,e))]=n,!0}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return qh(this.record,e),!0}catch{return!1}}}function xf(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=hf.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},hf.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(i,new $f(t,s,e.listIndex,e.listIndex??bf(t),r,n,o))}function Sf(t){if(null===bf(t))return t.component[t.stateProp];let e=pf.get(t);if(void 0===e){const n={row:null};pf.set(t,e=[If(t,n),n])}return e[0]}function If(t,e){const n=()=>{const n=yf(t);return void 0!==e&&pf.get(t)?.[0]!==i&&n.listIndex!==e.row&&wf(t),n},o=()=>{const e=n();return _f(t,e?.listIndex??null)&&wf(t),e?.listIndex.indexes??[]},s=(e,n)=>-1===n.indexOf(c)?n:"partial"===Cc(n).wildcardType?Gh(e,n,o()):-1===n.indexOf("#")&&_f(t,bf(t))?wf(t):n,r=(e,o)=>{let s;const r=n();return t.parentStateElement.createState(e,t=>{s=t[jn](r,()=>o(t))}),s},i=new Proxy({},{get(e,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(t,e,n,o,s){return"$postUpdate"===e?e=>n("readonly",n=>n.$postUpdate(s(e,qh(t,e)))):(s,r,...i)=>{const a="$setAll"===e||"$resolve"===e&&i.length>0,l=a?Hh(t,s):qh(t,s),c=Vh(0,s,l,"$resolve"===e?r??[]:r,o());return n(a?"writable":"readonly",t=>t[e](l,c,...i))}}(t,n,r,o,s);const i=gh(n,e=>s(e,qh(t,e)),t=>r("readonly",e=>e[n](...t)));if(null!==i)return i;const a=e=>e["$"===n[0]?n:s(n,qh(t,n))],l=r("readonly",a);return"$"===n[0]||t.getterKeys.has(n)||"function"!=typeof t.stateObject[n]?l:function(...t){return r("writable",e=>a(e).apply(this,t))}},set:(e,n,o)=>("string"==typeof n&&r("writable",e=>{e["$"===n[0]?n:s(n,Hh(t,n))]=o}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return qh(t,n),!0}catch{return!1}}});return i}function Pf(t,e){const n=ef(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&tt(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&gr(e).dispose(),function(t,e){tf||(tf=!0,_e=t=>Kh.has(t)?t.host:null),Kh.set(t,e),Yh.set(e,t);let n=Qh.get(e.parentStateElement);void 0===n&&(n=new Map,Qh.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=Jh.get(e.component);void 0===o&&(o=new Map,Jh.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&Xh.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}(e,t),e instanceof ShadowRoot&&function(t,e){const n=$l.get(t);if(void 0!==n){if(n===e)return;tt("A state tree is already registered on this root.")}$l.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const s=Bh.exec(e.statePathName);if(null!==s){const r=function(t,e){return void 0===e?t.delta:ot(qh(t,e)).wildcardCount-ot(e).wildcardCount}(t,n);o=0===r?e.statePathName:`$${Number(s[1])+r}`}else if(o=qh(t,e.statePathName),"for"===e.bindingType){const n=ot(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+l+c,n)}const r=e.propModifiers,i=null===s&&Array.isArray(r)&&Uh.has(e.bindingType??"")&&!r.includes(g)&&null!==Fh(t,e.statePathName);return o!==e.statePathName||i?{...e,statePathName:o,statePathInfo:ot(o),...i?{propModifiers:[...r,g]}:{}}:e}(t,e,n);Y(e);const o=$e(t.component);gf(t,o),Yl(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),pl(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=qh(t,n)}catch{continue}const o=e.indexOf(l+t.marker);if(-1===o)continue;const s=e.slice(0,o+1+t.marker.length),r=e.slice(s.length+1),i=e.slice(0,o)+l+r,a=ot(i);if(a.wildcardCount!==t.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:e,exportedPath:i};t.exports.set(i,c),lf(t.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,i),ju?.markExported(t.parentStateElement,i)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=$e(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const s=`${n}|${o.exportedPath}`;if(af.has(s))continue;const r=ot(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[jn](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(af.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(t),df(t),o=e,s=Promise.resolve(),xl.set(o,s),s.then(()=>Al(o),()=>{})}function kf(t,e){hl(Nf(t,e).rebindAddresses()),df(t)}function Nf(t,e){const n=gr(e),o=$e(t.component);return gf(t,o),n.forEachActiveBindingNode(t=>xe(t,o)),n}function Af(t){for(let e=t.parentNode;null!==e;e=e.parentNode){const t=ef(e);if(null!==t)return Af(t.component),void Nf(t,e)}}function Ef(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const Cf={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const s=sf(t,e.pathInfo.path);if(null!==s)return xf(s,e,n,o)}return wc},readMissing(t,e,n,o,s){if(null===n){if(wh(t.rootNode??null,e.pathInfo.path))return;return wc}if(!0===t.hasMounts){const n=uf(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s){const r=xf(t,$o(ot(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(n.record,n.entry,e.listIndex,o,s)}return wc},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=vh.get(t);if(void 0===n||0===n.size)return null;const o=e+l;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&tt(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return wc},writeMissing(t,e,n,o,s,r,i){if(!0===t.hasMounts){const n=uf(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s,r){const i=xf(t,$o(ot(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(n.record,n.entry,e.listIndex,s,r,i)}return wc},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=sf(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(l,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const s=-1===o?e:e.slice(0,o),r=-1===o?"":e.slice(o+1),i=t.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:t.delta}(t,o)}return 0},handlerScope(t,e,n,o,s){if(!0!==t.hasMounts)return s;const r=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=Kh.get(n);if(void 0!==t)return t;n=n.parentNode}return Kh.get(e)??null}(e,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(t,e,n){const o=function(t){return Ih.get(t)??Ph}(t);for(const s of o){const o=new Set,r={};for(const n of e){if(n.absolutePathInfo.stateElement!==t)continue;const e=n.absolutePathInfo.pathInfo.path;if(-1!==e.indexOf("#"))continue;const i=xh(s.mountPath,s.injections,e);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const t=ro(n.listIndex,a);(r[i]??=[]).push(t)}}if(o.size>0)try{s.callback.call(Sh(s.mountPath,n,s.injections),Array.from(o),r)}catch(t){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>wh(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(function(t){const e=Qh.get(t);return void 0!==e&&e.size>0}(e))for(const n of of(e)){if(!Ef(n.component,t))continue;const e=Zh(n);null!==e&&kf(n,e)}}(e,t)}};let Mf=!1;const Tf=new WeakMap;function Of(t){let e=Tf.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Tf.set(t,e)),e}function Lf(t,e){null!==e.slotRootNode&&(function(t,e,n){const o=yh.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function Rf(t,e,n){if(e.slotRootNode===n)return!0;const o=e.mountPath;try{bh(n,o,t)}catch{return console.error(`[@wcstack/state] <${s.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return Pl(n)?.markHasVolume?.(),e.slotRootNode=n,!0}const jf={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=Of(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{bh(n,e.mountPath,t),Pl(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,Eu}return async function(t,e){const n=t,o=t.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(t){0===t.length&&tt('"mount" requires a non-empty tree path.');const e=ot(t);for(const n of e.segments)0===n.length&&tt(`"mount" path "${t}" has an empty segment.`),n===c&&tt(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&tt(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),i=function(t,e){const n=[],o=new Set;let r;try{r=Lt(t)}catch(t){tt(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${e}"> has an invalid ${s.bindAttributeName}: ${t instanceof Error?t.message:String(t)}`)}for(const t of r){if(t.propSegments[0]!==x)continue;const r=t.propSegments.slice(1),i=t.statePathInfo,a=n=>tt(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${e}"> "${t.propName}: ${t.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==c&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${x}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(t.inFilters.length>0||t.outFilters.length>0)&&a("an injection takes no filters."),t.propModifiers.some(t=>t!==g)&&a(`an injection accepts only #${g}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:t.propModifiers.includes(g)})}return n.sort((t,e)=>e.innerSegments.length-t.innerSegments.length),n}(n.getAttribute(s.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&tt('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${s.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),bh(o,r,t),Pl(o)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=o}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===Pl(o)&&function(t,e){const n=()=>{if(null!==Pl(t))return;const n=t.querySelectorAll(s.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${s.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${s.tagNames.state}> to this root node (an empty <${s.tagNames.state}></${s.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=t.ownerDocument??t;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&Lf(t,e),t.settleInitialization()};let l;try{await Promise.resolve(),l=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void a(null)}const u=t.connectedRootNode??null;null!==u&&Rf(t,e,u)?function(t,e,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};null===e?(cp(),function(t,e){if(Nh.has(t))return void Ah(e);let n=kh.get(t);void 0===n&&(n=[],kh.set(t,n)),n.push(e)}(t,a)):ap(e,a)}(u,Pl(u),r,l,a,()=>Rf(t,e,u),i):a(null)}(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=Of(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&Pl(n)===e.graftInfo.rootStateElement&&rp(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==Tf.get(t)?.initializing)return;const e=t.getAttribute("mount");tt(`Cannot replace the state of <${s.tagNames.state} mount="${e}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){Nh.add(t);const e=kh.get(t);if(void 0!==e){kh.delete(t);for(const t of e)Ah(t)}}(e)},initializeFailureCleared(t,e){!function(t){Nh.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=Of(t);return null!==e.graftInfo&&rp(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,Lf(t,e)),t.clearConnectedRootNode(),!0}};let Wf=!1;const Df=new WeakMap;function zf(t,e){let n=Df.get(t);n||(n=new Set,Df.set(t,n)),n.add(e)}const Bf=new WeakMap,Ff=new WeakMap,Hf=new WeakMap,qf=new WeakMap,Uf={isComplete:function(t,e){return!0===Df.get(t)?.has(e)},isDeclared:function(t,e){return!0===Bf.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=Ff.get(t);o||(o=new Map,Ff.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=Hf.get(t);o||(o=new Map,Hf.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)},rememberOverwrittenValue:function(t,e,n,o){let s=qf.get(t);s||(s=new Map,qf.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}};const Vf=new WeakMap;class Gf{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=Vf.get(t);return n?n.get(e)??null:null}(t,e)??tt("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const Kf=t=>()=>t;function Jf(t,e,n,o){!function(t,e,n){let o=Vf.get(t);o||(o=new Map,Vf.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(function(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}(o));const s=function(t,e){const n=new Gf(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:Kf(s),enumerable:!0,configurable:!0}),zf(e,n),Qf(e,n)}function Qf(t,e){if(O in t){const n=t[O];"function"==typeof n?n.call(t,e).catch(t=>{tt(`Error in ${O}: ${t instanceof Error?t.message:String(t)}`)}):tt(`${O} is not a function.`)}}const Xf=new Set;function Yf(t,e){Xf.has(t)||(Xf.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Zf(t){const e=t.rootEntry,n=$e(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[jn](n,()=>{o=t[e.outerPathInfo.path]})}),o}const tp=new WeakMap;function ep(t,e){t.landInitialization(),tt(e)}async function np(t,e){const n=t;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,c=a?Gt(a):null;null!==a&&null!==c||tt(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(s.bindAttributeName)||ep(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const u=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&u.push('<script type="module">'),u.length>0&&tt(`"bind-component" cannot be combined with ${u.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(t,e){let n=Bf.get(t);n||(n=new Set,Bf.set(t,n)),n.add(e)}(a,d);const h=Jt(a);null===h&&tt(`CustomElementRegistry is unavailable for <${c}>.`),await h.whenDefined(c.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await qt(a),d in a||tt(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||tt(`Component property "${d}" is not an object for state binding.`);const p=function(t,e){const n=Ff.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,d);if(void 0!==p&&function(t,e){if(!t.hasAttribute(s.bindAttributeName))return!1;const n=ce(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,d)&&(a[d]=p,f=p),e.boundComponent=a,e.boundComponentStateProp=d,t.setBoundComponent(a,d),i instanceof ShadowRoot||(ce(a)??[]).some(t=>t.propSegments[0]===d)||ep(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(s.bindAttributeName)){const s=(ce(a)??[]).filter(t=>t.propSegments[0]===d);if(s.length>0){const u=Pl(a.getRootNode())??ep(t,`No state tree found on this root for mount host <${c}>.`);let h=(o=a,r=d,Jh.get(o)?.get(r)??null);const p=null!==h;if(null===h&&(function(t,e,n){const o=qf.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;qf.get(t).delete(e)}}(a,d,f),h=function(t,e,n,o,s,r=new Set){0===n.length&&tt(`Cannot build a mount record without host bindings for "${e}".`),pc(s);const i=[],a=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(l);a.has(n)&&tt("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(g)};i.push(o),0===e.length&&(c=o)}i.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++Ch,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Ru(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(s),p=new Set;for(const t of i)1===t.innerSegments.length&&p.add(t.innerSegments[0]);const m={};for(const t of Object.keys(s))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof s[t]&&(r.has(t)||p.has(t)||(m[t]=s[t]));return{id:u,marker:d,component:t,stateProp:e,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?d:c.outerPathInfo.path+l+d,stateObject:s,getterKeys:h,setterKeys:f,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(t=>t.readonly),privateSnapshot:m,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(a,d,s,u,f,function(t,e){return Hf.get(t)?.get(e)}(a,d)),function(t){!function(t){const e=t.component.tagName.toLowerCase(),n=t.stateProp;let o=null;for(const s of t.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=Ru(t.stateObject);const i=o[r];let a;if(t.getterKeys.has(r)||t.setterKeys.has(r)||"function"==typeof i?.get||"function"==typeof i?.set)a="an accessor";else if("function"==typeof i?.value)a="a method";else{if(t.mappedKeys.has(r)||t.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(t.stateObject,r))continue;a="an own data key"}const c=s.innerSegments.join(l);Yf(`${e}|${n}|${c}|entry`,`<${e}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${c}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(t);const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp;let s,r=!1;for(const i of e){if(null===t.rootEntry)continue;if(r||(s=Zf(t),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const e=t.rootEntry.outerPathInfo.path;Yf(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${e}.${i}" (${o}: ${e}). Remove the default to read the tree, or rename it to keep it private.`)}}(h)),e.mountRecord=h,n.parentNode!==i)return;try{Pf(h,i instanceof ShadowRoot?i:a)}catch(e){throw t.landInitialization(),e}if(!p){const t=If(h);Object.defineProperty(a,d,{get:()=>t,enumerable:!0,configurable:!0}),zf(a,d)}return Qf(a,d),function(t){const e=Mh.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(U)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Th.has(n)||(Th.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(h),void Oh(h,"$connectedCallback",()=>Sf(h))}}Jf(t,e.boundComponent,e.boundComponentStateProp,f)}var o,r}const op={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=tp.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},tp.set(t,e)),e}(t);return np(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=tp.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&kf(n,o)}),t.isConnected&&(Af(n.component),Nf(n,o)),Oh(n,"$connectedCallback",()=>Sf(n)),!0},disconnecting(t){const e=tp.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord;return Oh(n,"$disconnectedCallback",()=>Sf(n)),function(t){const e=pf.get(t);void 0!==e&&(e[1].row=bf(t),pf.delete(t))}(n),df(e.mountRecord),t.clearConnectedRootNode(),!0}};let sp=!1;function rp(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(Sh(t.mountPath,o,t.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function ip(t,e,n,o=[]){pc(n),function(t,e,n,o){const s=0===o.length?null:Ru(n);for(const t of o){const n=t.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||tt(`[wcs/mount-path-invalid] Volume "${e}" declares "${n}" as an accessor or a method and also injects it ("${x}.${n}: ${t.outerPathInfo.path}"). Rename one of them.`)}const r=n[F];if(void 0!==r){"object"==typeof r&&null!==r||tt(`${F} must be an object mapping state paths to handler functions.`);const t=Vu(e);for(const[e,n]of Object.entries(r))"function"!=typeof n&&tt(`${F} entry "${e}" must be a function.`),t.assertValidPath(e)}const i=n[V];if(void 0!==i){"object"==typeof i&&null!==i||tt(`${V} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(i)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&tt(`${V} entry "${n}" must map a list path to a field name or a key function.`);const r=$h(e,o,n,!1);t.listKeys?.has(r)&&tt(`${V} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[B]&&tt(`Volume "${e}" declares ${B}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&tt(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[q]&&tt(`Volume "${e}" declares ${q}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys(Ru(n)))-1!==t.indexOf(U)&&tt(`Volume "${e}" declares "${t}", which uses "${U}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n,o);const{data:s,accessors:r}=function(t,e){const n={},o=new Map;for(const[s,r]of Object.entries(Ru(t)))s.startsWith("$")||e.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(t=>t.innerSegments[0]))),i=ot(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;tt(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],s=""===n?o in t:void 0!==t[n+l+o];n=""===n?o:n+l+o,s||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(a)return;tt(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=s}),function(t,e){let n=vh.get(t);void 0===n&&(n=new Set,vh.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,s]of r){const r=e+l+n,i=s.get,a=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(Sh(e,this,o))}),"function"==typeof a&&(c.set=function(t){a.call(Sh(e,this,o),t)}),t.defineTreeAccessor(r,c)}!function(t,e,n,o){const s=n[F];if(void 0!==s){const n=Vu(e),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=$h(e,o,n,!1),c=function(t,n,...s){l.call(Sh(e,this,o),t,n,...s)};r.push({path:s,pathInfo:ot(s),handler:c,order:1e6+a++}),i.add(s),t.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(t,r),t.addVolumeWatchPaths?.(i),n.start(t))}const r=n[V];if(void 0!==r){const n=new Map;for(const[t,s]of Object.entries(r))n.set($h(e,o,t,!1),s);t.mergeVolumeListKeys?.(n)}const i=n[M];"function"==typeof i&&(function(t,e){let n=Ih.get(t);void 0===n&&(n=[],Ih.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,injections:o,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`);dt?.volume(e,n,o.length)}(t,e,n,o);const c=n.$connectedCallback;return"function"==typeof c&&t.createState("writable",t=>{let n;try{n=c.call(Sh(e,t,o))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n,injections:o}}function ap(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=ip(t,e.mountPath,e.volumeState,e.injections)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}let lp=!1;function cp(){var t;lp||(lp=!0,Mf||(Mf=!0,$c("scopes",Cf),Gu=nf),Wf||(Wf=!0,Tu("scopes",jf)),sp||(sp=!0,Tu("bindComponent",op),br=Uf),Eh=ap,t=up,Il.includes(t)||Il.push(t))}function up(t,e){(function(t){const e=yh.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){Nh.delete(t);const n=kh.get(t);if(void 0===n||0===n.length||null===Eh)return;kh.delete(t);const o=Eh;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const dp={name:"scopes",install(){cp(),dh||(dh=!0,Tu("dcc",uh))}},hp=/^@@wcs-(?:for|if|elseif|else):[^-]/,fp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,pp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,mp=/^@@wcs-text-start:(.+)$/;function gp(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function yp(t,e){const n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const t=n.currentNode;e(t.data)&&o.push(t)}return o}const bp=t=>hp.test(t),wp=t=>fp.test(t),vp=t=>fp.test(t)||pp.test(t);function _p(t){if("else"===t.bindingType)return"else:";let e=`${t.bindingType}: ${t.statePathName}`;for(const n of t.outFilters){const t=n.literals??n.args;e+=`|${n.filterName}`,n.args.length>0&&(e+=`(${n.args.map((e,n)=>"string"==typeof t[n]?`'${e.split("'").join("'\"'\"'")}'`:e).join(",")})`)}return e}function $p(t){const e=t.fragment.cloneNode(!0);for(const n of t.nodeInfos){const o=Ul(re(t.fragment,n.nodePath));if(null===o)continue;const s=re(e,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return e}class xp extends Lu{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=Ju.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=s.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(e,t);if(void 0!==o&&"function"==typeof o.get)continue;const s=e[t];"function"!=typeof s&&(n[t]=s)}return n}static buildContent(t,e,o){const r=o??t.ownerDocument;n.seen&&function(t){const e=new Map;for(const n of yp(t,wp)){if(null===n.parentNode)continue;const[,t,o]=fp.exec(n.data),s=o.split(":")[0],r=n.previousSibling?.data,i=`@@wcs-${t}-end:${o}`;if(r!==`@@wcs-${t}:${s}`&&e.get(r)!==s)for(let t=n;null!==t;){const e=t.nextSibling;t.remove(),t=t.data===i?null:e}else"for"===t&&e.set(i,s)}}(r);const i=document.createElement("script");i.setAttribute("type","application/json"),i.textContent=gp(JSON.stringify(e)),t.appendChild(i);for(const[e,n]of function(t){const e=new Map,n=[t];for(;n.length>0;)for(const t of yp(n.shift(),bp)){const o=t.data,s=o.slice(o.indexOf(":")+1);if(e.has(s))continue;const r=Tl(s);null!==r&&(e.set(s,r),n.push(r.fragment))}return e}(r)){const o=document.createElement("template");o.setAttribute("id",e),o.setAttribute(s.bindAttributeName,_p(n.parseBindTextResult)),o.content.appendChild($p(n)),t.appendChild(o)}const a=t.ownerDocument,l=Array.from(Oa);if(l.length>0){const e={};for(let t=0;t<l.length;t++){const n=l[t];if(!n.isConnected||n.ownerDocument!==a)continue;const o=Ta(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const t of o)r[t.propName]=t.value;e[s]=r}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=gp(JSON.stringify(e)),t.appendChild(n)}}La()}static removeBlockBoundaryComments(t){for(const e of yp(t,vp))e.remove()}static removeStructuralComments(t){for(const e of yp(t,bp))e.remove()}static restoreTextBindings(t){for(const e of yp(t,t=>mp.test(t))){const t=mp.exec(e.data)[1],n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(s.tagNames.ssr),o=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&o.set(e,t)}}for(const t of yp(e,wp)){const e=fp.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}xp.restoreTextBindings(e);const r=t=>{for(const e of yp(t,bp)){const t=o.get(e.data.split(":")[1]);if(t){const n=document.createElement("template"),o=t.getAttribute(s.bindAttributeName);o&&n.setAttribute(s.bindAttributeName,o);const i=document.importNode(t.content,!0);if(i.childNodes.length>0)n.content.appendChild(i);else for(const e of Array.from(t.childNodes))n.content.appendChild(document.importNode(e,!0));r(n.content),e.parentNode.replaceChild(n,e)}}};r(e);const i=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of i)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const Sp={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=s.tagNames.state,n=s.tagNames.ssr,o=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of o){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Ju),xp.buildContent(o,xp.extractStateData(t),t.getRootNode()),t.parentNode?.insertBefore(o,t)}La()},reset:function(){Cl.clear(),La(),n.seen=!1}},Ip=new Set(["for","if","elseif","else"]);function Pp(t){const[,e,n]=fp.exec(t),[o,...s]=n.split(":");return"for"===e?{type:e,uuid:o,path:s[0],index:parseInt(s[1],10),nodes:[]}:{type:e,uuid:o,path:s.join(":"),index:null,nodes:[]}}function kp(t){const e=[];for(const n of t)if(n.nodeType===Node.ELEMENT_NODE){const t=n;t.hasAttribute(s.bindAttributeName)&&e.push(t),Array.from(t.children).some(t=>t.localName===s.tagNames.state&&ue(t))||e.push(...fe(t))}else null!==Dt(n)&&e.push(n);return e}function Np(t){const[e,n,o]=ye(t),s=new mr;return{bindingInfos:s.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:e,bindingSession:s,deferredSpreads:o}}const Ap=/^\s*@@\s*(?:wcs-text)?\s*:/;function Ep(t,e){for(const n of e)"event"===n.bindingType||Ip.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&Ap.test(n.node.data))&&t.push(n)}function Cp(t,e){const n=[];for(let o=0;o<t.nodes.length;o++){const s=e.get(t.nodes[o]);s?o+=s.nodes.length+1:n.push(t.nodes[o])}return n}function Mp(t,e,n,o,s,r){e.length>0&&(t.spreads=e);for(const t of e)be(t.node);fl(e,n,o,s,r)}function Tp(t,e){const n=Tl(e),o=Pl(t.getRootNode());let s=null;if(n&&o){const{statePathName:t,outFilters:e}=n.parseBindTextResult;o.createState("readonly",n=>{const o=wr(n[t],ie(e,"output"));Array.isArray(o)&&(s=o)})}return s}function Op(t,e){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[t]}:${e}`}function Lp(t,e,n){const o=Op(e,n);return yp(t,t=>t===o)[0]??null}function Rp(t,e){const n=t,o=e.templates,r=new Map;for(const[t,e]of o)for(const n of yp(e.content,bp))r.set(n.data.slice(n.data.indexOf(":")+1),t);const i=new Set(de(t));if(i.size>0)for(const t of yp(n,bp)){const e=t.data.slice(t.data.indexOf(":")+1);let n=t.parentNode;for(;null!==n&&!i.has(n);)n=n.parentNode;null===n||r.has(e)||r.set(e,n)}const a=new Map,l=[];for(const[t,e]of o){let n=Lt(e.getAttribute(s.bindAttributeName)||"")[0];const o=n.bindingType,i=r.get(t),c=a.get(i);"else"===o&&c&&(n={...c,outFilters:[...c.outFilters,Rl()],bindingType:"else"}),"if"===o||"elseif"===o?a.set(i,n):"else"===o&&a.set(i,null),l.push([t,e,n])}for(const[t,e,o]of l.reverse()){const s=document.importNode(e.content,!0),r="for"===o.bindingType?o.statePathName:void 0;Gl(s),"string"==typeof r&&Fl(s,r),Yl(n,s,r),Ml(t,n,{fragment:s,parseBindTextResult:o,nodeInfos:Vl(s)})}}const jp={hydrate:async function(t){await gl(t);const e=t.querySelectorAll(s.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${Ju}". Falling back to full render.`),xp.cleanupDom(t),!1}const n=function(t){const e=[];for(const n of yp(t,vp)){if(!wp(n.data)){e.pop();continue}const t=Pp(n.data),o=e.at(-1);if("for"===t.type&&o&&o.uuid!==t.uuid)return[t,o];e.push(t)}return null}(document.body);if(null!==n){const[e,o]=n;return console.warn(`[@wcstack/state] SSR: "for: ${e.path}" in "${o.type}: ${o.path}" (known limitation). Falling back to full render.`),xp.cleanupDom(t),!1}for(const n of e)Rp(t,n);xp.restoreTextBindings(document.body);const o=function(t){const e=[];for(const n of yp(t,wp)){const t=Pp(n.data);t.start=n;const o=n.data.replace("-start:","-end:");let s=n.nextSibling;for(;s&&(s.nodeType!==Node.COMMENT_NODE||s.data!==o);)t.nodes.push(s),s=s.nextSibling;e.push(t)}return e}(document.body),r=new Map,i=function(t,e,n=new Map){const o=new Map,s=[],r=new Map(e.map(t=>[t.start,t])),i=new Set;for(let t=e.length-1;t>=0;t--){const n=kp(e[t].nodes).filter(t=>!i.has(t));for(const t of n)i.add(t);e[t].subscribers=n}for(const i of e){const e=Cp(i,r);if(0===e.length)continue;const a=e.some(t=>bp(t.data));if(a){const t=document.createComment(`wcs-row-end:${i.uuid}`);i.nodes[i.nodes.length-1].after(t),e.push(t)}const{bindingInfos:l,subscriberNodes:u,bindingSession:d,deferredSpreads:h}=Np(i.subscribers);for(const t of l)if(t.node!==t.replaceNode){const n=e.indexOf(t.node);n>=0&&(e[n]=t.replaceNode)}const f=ca(e,a);Vi(f,d),Sr(f,l),kr(f,u);const p=l.filter(t=>la(t,-1));if(Cr(f,p),"for"===i.type&&null!==i.index){const e=Lp(t,"for",i.uuid);if(e){let t=n.get(i.uuid);if(!t){const s=Tp(e,i.uuid)??i.path;t=o.get(s),t||o.set(s,t=[]),n.set(i.uuid,t)}const r=t[i.index]??=Ce(null,i.index);$a(e,r,f),xa(e,f.lastNode),ta(e,f);const a=$o(ot(i.path+"."+c),r);Nr(f,a),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ep(s,l),Mp(f,h,a,d,l,p)}}else{const e=i.start.previousSibling,n=e?.data===Op(i.type,i.uuid)?e:Lp(t,i.type,i.uuid);if(n){ta(n,f);const t=$e(n);Nr(f,t),d.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ep(s,l),Mp(f,h,t,d,l,p)}}}return s}(document.body,o,r);xp.removeBlockBoundaryComments(document.body);const a=[];for(const t of e)t.parentNode&&(a.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());const[,l,u]=ge(document.body),d=[],h=[],f=gr(document.body),p=f.initialize(l);fl(u,null,f);for(const t of p)if("event"!==t.bindingType)if(Ip.has(t.bindingType))h.push(t);else{if(t.statePathName.includes(c))continue;d.push(t)}for(const t of h)if("for"===t.bindingType){const e=uo(t),n=Pl(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=wr(n[t.statePathName],t.outFilters);if(Array.isArray(o)){const n=r.get(t.uuid);n&&fn(o,n),Sn(e,o),s=t.node,i=o,wa.set(s,mn(i)),Tn(e,o)}var s,i})}hl([...d,...i]);for(const{el:t,parent:e,next:n}of a)e.insertBefore(t,n);const m=new Map;for(const e of t.querySelectorAll("[data-wcs-ssr-id]"))m.set(e.getAttribute("data-wcs-ssr-id"),e);for(const e of t.querySelectorAll(s.tagNames.ssr))for(const[t,n]of Object.entries(e.hydrateProps)){const e=m.get(t);if(e)for(const[t,o]of Object.entries(n))br?.isDeclared(e,t)||(e[t]=o)}for(const e of t.querySelectorAll("[data-wcs-ssr-id]"))e.removeAttribute("data-wcs-ssr-id");return!0},loadState(t){const e=t.parentNode;if(!e)return null;const n=xp.find(e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(t){await kl(t.rootNode);const e=xp.extractStateData(t),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",Ju),xp.buildContent(n,e,t.rootNode),t.parentNode?.insertBefore(n,t)}};let Wp=!1;const Dp={name:"ssr",install(){Wp||(Wp=!0,vl=jp,function(t){if(!Bu.includes(t)){Bu.push(t);for(const e of Hu())t(e)}}(t=>{t.get(s.tagNames.ssr)||t.define(s.tagNames.ssr,xp)}),function(){const e=globalThis;void 0===e[t]&&(e[t]=Sp)}())}},zp=new WeakMap,Bp=new Set,Fp=new Set;function Hp(t){return t.byFromPath.size>0||t.byResetPath.size>0}function qp(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function Up(t){return zp.get(t)}function Vp(t){Gp(t),zp.delete(t)}function Gp(t){Bp.delete(t),Fp.delete(t)}const Kp=new WeakSet;let Jp=0;function Qp(t){return Up(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function Xp(t){if(0===Fp.size)return;if(e=t.absolutePathInfo.stateElement,!Fp.has(e))return;var e;const n=Qp(t);if(void 0!==n)for(const t of n)Yp(t)}function Yp(t){Kp.has(t)||(Kp.add(t),Jp++)}function Zp(t){return!!Kp.delete(t)&&(Jp--,!0)}const tm=/^(?:0|[1-9]\d*)$/;function em(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function nm(t){if("object"!=typeof t||null===t||Object.isFrozen(t))return null;const e=Object.getPrototypeOf(t);return Array.isArray(t)?e===Array.prototype&&Reflect.ownKeys(t).every(e=>"length"===e||"string"==typeof e&&tm.test(e)&&em(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&em(t,e))?null:"object"}function om(t,e){const n=nm(t);if(null===n)return t;const o=t,s=e.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(t.length):null===Object.getPrototypeOf(t)?Object.create(null):{},e.set(o,r);for(const t of Object.keys(o))r[t]=om(o[t],e);return r}function sm(t){return om(t,new Map)}function rm(t,e,n){if(Object.is(t,e))return!0;const o=nm(e);if(null===o||"object"!=typeof t||null===t)return!1;const s=t,r=e;if("array"===o){if(!Array.isArray(t)||t.length!==e.length)return!1}else if(Array.isArray(t)||Object.keys(s).length!==Object.keys(r).length)return!1;if(nm(t)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let e=0;e<t.length;e++)if(!rm(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&rm(s[t],r[t],n))}function im(t,e){return rm(t,e,new Map)}const am=new WeakMap;function lm(t,e){if("function"!=typeof e)return;const n=am.get(e);void 0===n?am.set(e,new Set([t])):n.add(t)}function cm(t,e){return"function"==typeof e&&!0===am.get(e)?.has(t)}const um={"read-source":t=>`${H} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-rows":t=>`${H} could not read the rows of "from" for "${t}". Nothing was folded or written.`,"read-output":t=>`${H} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${H} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${H} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${H} could not write the output "${t}".`},dm={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function hm(t,e,n){null!==Se&&Se({type:"state:watch-error",phase:e,path:`${H}.${t}`,error:n})}function fm(t,e,n){console.error(`[@wcstack/state] ${um[n](t)}`,e),hm(t,dm[n],e)}function pm(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function mm(t,e){e.then(void 0,()=>{}),fm(t,new TypeError(`${H} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const gm=new WeakSet,ym="[wcs/scan-declaration-invalid]",bm=Object.freeze([]);function wm(t){return`${H} entry "${t}"`}function vm(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function _m(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${c}${c}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${at}`}function $m(t,e,n){0===n.length&&tt(`${ym} ${t} "${e}" must be a non-empty state path.${at}`),n.startsWith("$")&&tt(`${ym} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${at}`),n.includes("@")&&tt(`${ym} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${at}`),n in Object.prototype&&tt(`${ym} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${at}`);const o=ot(n);for(const s of o.segments)0===s.length&&tt(`${ym} ${t} ${e} "${n}" has an empty path segment.${at}`);return o.wildcardCount>u&&tt(`${ym} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function xm(t,e,n,o){const s=wm(t);0===t.length&&tt(`${ym} ${H} entry name must be a non-empty string.${at}`),(t.includes(l)||t.includes(c))&&tt(`${ym} ${s} must be a flat property name ("${l}" and "${c}" are not allowed). The output is a property the runtime owns.${at}`),t.startsWith("$")&&tt(`${ym} ${s} must not start with "$" (reserved namespace).${at}`),t in Object.prototype&&tt(`${ym} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${at}`),e.has(t)&&tt(`${ym} ${s} conflicts with a getter declared on the state.${at}`),n.has(t)&&tt(`${ym} ${s} conflicts with a setter declared on the state.${at}`),o.has(t)&&tt(`${ym} ${s} conflicts with the ${B} entry of the same name — each output has exactly one owner.${at}`)}function Sm(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!cm(t,o)&&tt(`${ym} ${wm(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${at}`)}function Im(t,e,n,o,s,r){const i=wm(t),a=void 0!==e.from,c=void 0!==e.on;if(a===c&&tt(`${ym} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${at}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||tt(`${ym} ${i} "on" must be a non-empty event-token name.${at}`),n.has(t)||tt(`${ym} ${i} on "${t}" is not declared in ${D}.${it(t,n)}${at}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&tt(`${ym} ${i} "from" must be a state path string.${at}`);const d=$m(i,"from",u),h=vm(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&tt(_m(i,"from",u,h));const f=vm(d,s);return null!==f&&tt(function(t,e,n){return`${ym} ${t} from "${e}" ${n===e?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${at}`}(i,u,f)),(u===t||u.startsWith(t+l))&&tt(`${ym} ${i} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${at}`),{kind:"path",path:u,pathInfo:d}}function Pm(t,e,n,o){if(void 0===e)return bm;const s=wm(t);Array.isArray(e)||tt(`${ym} ${s} "resetOn" must be an array of state paths.${at}`);const r=[];for(const t of e){"string"!=typeof t&&tt(`${ym} ${s} "resetOn" must contain only state path strings.${at}`);const e=$m(s,"resetOn",t);e.wildcardCount>0&&tt(`${ym} ${s} resetOn "${t}" must not contain "${c}" — a reset returns the whole output to "initial".${at}`);const i=vm(e,o);null!==i&&tt(_m(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&tt(`${ym} ${s} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${at}`),"path"===n.kind&&t.startsWith(n.path+l)&&tt(`${ym} ${s} resetOn "${t}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${at}`),r.push(t)}return r}function km(t){const e=t.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[t.name];i="threw";const a=function(t){return Kp.has(t)}(t),l=a&&!im(n,t.initial)?sm(t.initial):n,c=e(l,o,...s);if(pm(c))return void mm(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,lm(t.name,c)),a&&Zp(t)}catch(e){fm(t.name,e,i)}}}const Nm="scanEntries",Am={order:8,validate(t,e,n){const o=function(t,e,n=null){const o=t[H];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&tt(`${ym} ${H} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${at}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(Ru(t)))"function"==typeof n.get?s.add(e):"function"==typeof n.set&&i.add(e),"function"==typeof n.set&&r.add(e),"function"==typeof n.value&&a.set(e,n.value);const l=function(t){pc(t);const e=t[B];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];let u=0;for(const[t,d]of Object.entries(o)){xm(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&tt(`${ym} ${wm(t)} must be an object ({ from | on, initial, fold, resetOn? }).${at}`);const o=d;Sm(t,a,o);const h=Im(t,o,e,s,i,n);"initial"in o||tt(`${ym} ${wm(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${at}`),"function"!=typeof o.fold&&tt(`${ym} ${wm(t)} fold must be a function.${at}`);const f=Pm(t,o.resetOn,h,s);c.push({name:t,source:h,fold:o.fold,initial:o.initial,resetOn:f,order:u++})}return function(t){const e=new Set(t.map(t=>t.name)),n=new Map;for(const o of t){for(const t of o.resetOn){const n=ot(t).segments[0];e.has(n)&&tt(`${ym} ${wm(o.name)} resetOn "${t}" reads the ${H} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${at}`)}if("path"===o.source.kind){const t=o.source.pathInfo.segments[0];e.has(t)&&n.set(o.name,t)}}for(const t of n.keys()){const o=[t];let s=n.get(t);for(;void 0!==s&&o.length<=e.size;)s===t&&tt(`${ym} ${H} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${at}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}(e,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Nm,o)},applyEarly(t,e,n){const o=n.get(Nm)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=sm(n.initial);t[n.name]=e,lm(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&jo(t,n.source.tokenName).subscribe(km(n))}(t,o))},register(t,e,n){const o=n.get(Nm)??null,s=function(t){const e=new Map,n=Up(t);if(void 0!==n)for(const t of n.entries)Zp(t)&&e.set(t.name,t.resetOn);return Vp(t),e}(t);t.setScanPaths?.(null===o?null:function(t,e,n){const o=function(t,e){Vp(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&qp(n,t.source.path,t);for(const e of t.resetOn)qp(o,e,t),"event"===t.source.kind&&qp(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return zp.set(t,r),r}(t,e);for(const o of e){const e=n.get(o.name);"event"===o.source.kind&&void 0!==e&&o.resetOn.some(n=>e.includes(n)&&Kr().hasQueuedPath(t,n))&&Yp(o)}const s=new Set;for(const e of o.byFromPath.keys())s.add(e),t.setPathInfo(e,"prop","scan");for(const e of o.byResetPath.keys())t.setPathInfo(e,"prop","scan");return s.size>0?s:null}(t,o,s))}};let Em=!1;const Cm=Object.freeze([]),Mm=Object.freeze([]);function Tm(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Cm,i=t.dynamicDependency.get(n)??Cm,a=e.byFromPath.get(n)??Mm;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const Om=Symbol("wcs-stream-last-notified-uncertain"),Lm=new WeakMap;function Rm(t,e){const n=Lm.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function jm(t,e){const n=Lm.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Om,error:Object.is(o.error,null)?null:Om})}const Wm=new Set;function Dm(t){Wm.delete(t)}const zm=new WeakMap;function Bm(t){return zm.get(t)??new Map}function Fm(t){Dm(t);const e=zm.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,jm(t,n.name)}const Hm=(t,e)=>e,qm=new Set;const Um=new WeakMap,Vm=new WeakMap;function Gm(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=Bm(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&Bm(t).has(n),ownKeys:()=>Array.from(Bm(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=Bm(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){tt(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){tt(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Km(t){const e=Um.get(t);if(void 0!==e)return e;const n=Gm(t,G,t=>t.status);return Um.set(t,n),n}function Jm(t){const e=Vm.get(t);if(void 0!==e)return e;const n=Gm(t,K,t=>t.error);return Vm.set(t,n),n}function Qm(t){Um.delete(t),Vm.delete(t)}let Xm=null;function Ym(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}const Zm={read(t,e){!function(t,e){null!==Xm&&Xm.add(Xn(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===G?Ym(Km(t),e.pathInfo.segments):n===K?Ym(Jm(t),e.pathInfo.segments):wc},get:(t,e)=>e===G?Km(t.stateElement):e===K?Jm(t.stateElement):wc};let tg=0,eg=null,ng=0;const og=new WeakMap;function sg(t){tg=t+1}function rg(){tg=0}function ig(t){if(tg>0){const e=eg??=new Map;tg>(e.get(t)??0)&&e.set(t,tg),ng=Math.max(ng,tg)}}function ag(t,e){return og.get(t)?.get(e)??0}function lg(t){mg();const e=Bm(t);if(0!==e.size){!function(t){Wm.add(t)}(t);for(const n of e.values())cg(t,n)}}function cg(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=Xm,s=new Set;let r;Xm=s;try{t.createState("readonly",t=>{r=n(t)})}finally{Xm=o}r instanceof Promise&&tt(`${B} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${G}${l}${e.name}`,a=`${K}${l}${e.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==i&&o.path!==a||tt(`${B} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&tt(`${B} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=s,r}(t,e);!function(t,e){const n=Up(t);if(void 0!==n&&0!==e.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==e.name)continue;const s=Tm(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&tt(`[wcs/scan-feedback-loop] ${B} entry "${e.name}" args read "${n}", which is derived from the ${H} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,e),t.createState("writable",t=>{t[e.name]=e.definition.initial}),lm(e.name,e.definition.initial),ug(t,e,"active",null);const s=e.definition,r={fold(n){t.createState("writable",t=>{const o=s.fold(t[e.name],n);t[e.name]=o,lm(e.name,o)})},done(){ug(t,e,"done",null)},fail(o){ug(t,e,"error",o),n.abort()}};!async function(t,e,n,o){let s=null;const r=()=>{if(null!==s)try{s.return?.()?.then?.(void 0,()=>{})}catch{}};n.addEventListener("abort",r,{once:!0});try{const i=await t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError(`[@wcstack/state] ${B}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",r)}}(s.source,o,n.signal,r)}function ug(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return Lm.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(function(t,e,n,o){let s=Lm.get(t);void 0===s&&(s=new Map,Lm.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${G}${l}${e.name}`),i&&t.$postUpdate(`${K}${l}${e.name}`)}))}function dg(t){const e=Wm;if(0===e.size)return;const n=[];for(const o of e)for(const e of Bm(o).values()){let s=-1;for(const n of e.depAddresses)t.has(n)&&(s=Math.max(s,ag(t,n)));s>=0&&s<=32&&n.push({stateElement:o,entry:e,depth:s})}try{for(const{stateElement:t,entry:o,depth:s}of n)if(e.has(t)&&Bm(t).get(o.name)===o){sg(s);try{cg(t,o)}catch(n){o.controller?.abort(),e.has(t)&&Bm(t).get(o.name)===o&&ug(t,o,"error",n)}}}finally{rg()}}let hg=!1;const fg=new WeakMap,pg={order:20,apply(t,e){var n;Qm(t),Fm(n=t),Dm(n),zm.delete(n),function(t,e){pc(e);const n=e[B];if(void 0===n)return void Rm(t,qm);"object"==typeof n&&null!==n||tt(`${B} must be an object mapping stream names to stream definitions.`);const o=new Map,s=Ru(e);for(const[r,i]of Object.entries(n)){0===r.length&&tt(`${B} entry name must be a non-empty string.`),r.includes(l)&&tt(`${B} entry "${r}" must be a flat property name ("${l}" is not allowed).`),r.includes(c)&&tt(`${B} entry "${r}" must be a flat property name ("${c}" is not allowed).`),r.startsWith("$")&&tt(`${B} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&tt(`${B} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(r)&&tt(`${B} entry "${r}" conflicts with a getter declared on the state.`),t.setterPaths.has(r)&&tt(`${B} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||tt(`${B} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||cm(r,a)||tt(`${B} entry "${r}" conflicts with a method (a function-valued property) declared on the state. The value is a property the runtime owns.`),"function"!=typeof n.source&&tt(`${B} entry "${r}" source must be a function.`);const u=void 0!==n.fold;u&&"function"!=typeof n.fold&&tt(`${B} entry "${r}" fold must be a function.`),u&&!("initial"in n)&&tt(`${B} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&tt(`${B} entry "${r}" args must be a function.`);const d={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??Hm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in e||(e[r]=d.definition.initial,lm(r,d.definition.initial)),o.set(r,d)}!function(t,e){zm.set(t,e)}(t,o),Rm(t,new Set(o.keys()))}(t,e),void 0!==e[B]&&t.attachAddressHooks?.("streams",B)},activate(t,n){if(!e()&&null!=t.connectedRootNode){if(null===n){if(!0!==t.initialized)return;return lg(t),void fg.set(t,t.connectGeneration??0)}n===t.connectGeneration&&fg.get(t)!==n&&lg(t)}},deactivate(t){Fm(t),Qm(t)}};function mg(){hg||(hg=!0,$c("streams",Zm),Pc("streams",pg),Ur(dg,20))}const gg=new WeakMap;function yg(t,e,n){let o=gg.get(t);void 0===o&&(o=new Map,gg.set(t,o)),o.set(e,n)}const bg=new Map;function wg(t,e){bg.has(t)||bg.set(t,e)}function vg(t){return bg.get(t)}const _g=new WeakMap,$g=new WeakMap,xg=new Set,Sg=new Map;function Ig(t){return _g.get(t)??Sg}function Pg(t,e){let n=$g.get(t);void 0===n&&(n=new Map,$g.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}const kg=new Map;function Ng(t){return $g.get(t)??kg}function Ag(t){0===t.length&&tt(`[wcs/watch-declaration-invalid] ${F} entry name must be a non-empty state path.`),t.startsWith("$")&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not start with "$" (reserved namespace).${at}`),t.includes("@")&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${at}`),t in Object.prototype&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=ot(t);for(const n of e.segments)0===n.length&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" has an empty path segment.${at}`);return e.wildcardCount>u&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const Eg={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||wg(n,o)},swapped(t,e,n){var o;o=n,bg.has(o)&&wg(e,vg(n))}};function Cg(t){for(let e=t;null!==e;e=e.parentListIndex)if(Je(e))return!0;return!1}function Mg(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[Wn]($o(e.wildcardParentPathInfos[i],r)),l=cn(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=so(o,i,e.wildcardCount);if(l!==c&&!He(l,c)){if(Je(c))return"gone";s="replaced"}r=l}return s}function Tg(t,e,n){const o=new Map;for(const s of n){const n=Mg(t,e,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),t=>t.row)}const Og=Object.freeze([]);function Lg(t,e,n,o){let s=t.get(n);return void 0===s&&(s={stateElement:e,entry:n,rows:[],reset:!1,depth:o},t.set(n,s)),s.depth=Math.max(s.depth,o),s}function Rg(t,e){let n=0;for(;n<t.indexes.length-1&&t.indexes[n]===e.indexes[n];)n++;return t.indexes[n]-e.indexes[n]}function jg(t,e){return e.has(t.stateElement)&&!0===Up(t.stateElement)?.entries.has(t.entry)}function Wg(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Dg(n,t))||Zp(e)}function Dg(t,e){return Kr().hasQueuedPath(t,e)}function zg(t,e){!function(t,e,n){if(0!==Jp)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=Qp(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||Zp(e)}}(t,e,Dg)}function Bg(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function Fg(t,e,n){if(!jg(t,n))return Wg(t),null;const{stateElement:o,entry:s}=t;if(t.reset)return{group:t,next:s.initial};const r=s.source;if(function(t,e){for(const n of e.pathInfo.cumulativePaths)if(t.getterPaths.has(n))return!0;return!1}(o,r))return function(t,e,n){if(gm.has(t))return;gm.add(t);const o=`[wcs/scan-source-computed] ${H} entry "${e}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),hm(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=Bm(t).get(e);if(void 0===o)return!1;for(const t of o.depAddresses)if(n.has(t))return!0;return!1}(o,r.pathInfo.segments[0],e))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",e=>{const n=e[s.name];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?t.rows:Tg(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(Rg)){let n;try{n=Bg(e,r,t)}catch(t){fm(s.name,t,"read-source");continue}const o=a(l,n,vg(t.absAddress),...t.indexes);if(pm(o))return void mm(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){fm(s.name,t,i.failure)}return i.plan}function Hg(t,e){const{group:n}=t;if(!jg(n,e))return void Wg(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Zp(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!im(o,s.initial):!Object.is(o,t.next)){const o=n.reset?sm(s.initial):t.next;e[s.name]=o,lm(s.name,o)}})}catch(t){fm(s.name,t,"write")}}function qg(t){Zg(),(0!==Ig(t).size||0!==Ng(t).size||function(t){const e=zp.get(t);return void 0!==e&&Hp(e)}(t))&&(function(t){xg.add(t),function(t){const e=zp.get(t);void 0!==e&&(Hp(e)&&Bp.add(t),function(t){return t.eventResetByPath.size>0}(e)&&Fp.add(t))}(t)}(t),function(t){const e=[];for(const n of Ig(t).values())Ug(t,n)&&e.push(n);for(const n of Ng(t).values())for(const o of n)Ug(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{yg(t,Yn(t,o.pathInfo,null),n[o.path])}catch(e){Gg(t,o.path,"prime",e)}})}(t))}function Ug(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Vg={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Gg(t,e,n,o){console.error(`[@wcstack/state] $watch ${Vg[n]} "${e}" threw.`,o),null!==Se&&Se({type:"state:watch-error",phase:n,path:e,error:o})}function Kg(t){const e=xg,n=function(t){const e=ng;return e>0&&(og.set(t,eg),eg=null,ng=0),e}(t);try{if(n>32){zg(t,null);const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==Se&&Se({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}if(0===e.size)return void zg(t,e);!function(t,e){if(0!==t.length)try{for(const n of t)sg(n.group.depth),Hg(n,e)}finally{rg()}}(function(t,e){if(zg(t,e),0===Bp.size)return Og;const n=new Map;for(const o of t){const s=o.absolutePathInfo.stateElement;if(!e.has(s))continue;const r=Up(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=ag(t,o),l=r.byFromPath.get(i.path);if(void 0!==l){let t=[];if(i.wildcardCount>0){if(null===o.listIndex)continue;t=ro(o.listIndex,i.wildcardCount)}for(const e of l)Lg(n,s,e,a).rows.push({absAddress:o,indexes:t})}const c=r.byResetPath.get(i.path);if(void 0!==c)for(const t of c)Lg(n,s,t,a).reset=!0}if(0===n.size)return Og;const o=Array.from(n.values()).sort((t,e)=>t.entry.order-e.entry.order),s=[];try{for(const n of o){sg(n.depth);const o=Fg(n,t,e);null!==o&&s.push(o)}}finally{rg()}return s}(t,e),e),function(t,e){const n=[],o=new Set;for(const s of t){const t=s.absolutePathInfo.stateElement;if(!e.has(t))continue;const r=s.absolutePathInfo.pathInfo.path;o.add(r);const i=Ig(t).get(r),a=Ng(t).get(r);if(void 0===i&&void 0===a)continue;const l=void 0===i?[]:[i];void 0!==a&&l.push(...a);for(const e of l){let o=[];if(e.pathInfo.wildcardCount>0){if(null===s.listIndex)continue;o=ro(s.listIndex,e.pathInfo.wildcardCount)}n.push({stateElement:t,entry:e,absAddress:s,indexes:o})}}if(0===n.length)return;n.sort(Qg);const s=function(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(0===s.entry.pathInfo.wildcardCount)continue;const r=t[o-1];(Cg(s.absAddress.listIndex)||r?.entry===s.entry&&Jg(r.indexes,s.indexes)||s.entry.pathInfo.wildcardParentPaths.some(t=>e.has(t)))&&(n??=new Set).add(s.entry)}if(null===n)return t;const o=new Set;for(const e of n){const n=t.filter(t=>t.entry===e),s=n[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(Tg(t,e.pathInfo,n));for(const t of n)s.has(t)||o.add(t)})}catch(t){Gg(0,e.path,"evaluate",t);for(const t of n)o.add(t)}}return t.filter(t=>!o.has(t))}(n,o);try{for(const n of s){if(!e.has(n.stateElement))continue;const o=Ig(n.stateElement).get(n.entry.path)===n.entry,s=!0===Ng(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(sg(ag(t,n.absAddress)),Xg(n))}}finally{rg()}}(t,e)}finally{bg.clear()}}function Jg(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Qg(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function Xg(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Ug(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void Gg(0,n.path,"evaluate",t)}const a=r?function(t,e){return gg.get(t)?.get(e)}(e,o):vg(o);r&&yg(e,o,i),null!==Se&&Se({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){Gg(0,n.path,"handler",t)}}let Yg=!1;function Zg(){Yg||(Yg=!0,$c("watch",Eg),Pc("watch",ty),Ur(Kg,10),qr(ig),Uu={assertValidPath:Ag,addEntries:Pg,start:qg})}const ty={order:10,register(t,e){var n;n=t,xg.delete(n),Gp(n),_g.delete(n),function(t){gg.delete(t)}(t);const o=function(t,e){const n=e[F];if(void 0===n)return null;"object"==typeof n&&null!==n||tt(`[wcs/watch-declaration-invalid] ${F} must be an object mapping state paths to handler functions.${at}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&tt(`[wcs/watch-declaration-invalid] ${F} entry "${e}" must be a function.${at}`);const n=Ag(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){_g.set(t,e)}(t,o),s.size>0?s:null}(t,e);t.setWatchPaths?.(o),null===o&&null==t.scanPaths||t.attachAddressHooks?.("watch",null!==o?F:H)},activate(t,n){e()||null==t.connectedRootNode||(null===n?!0===t.initialized:n===t.connectGeneration)&&qg(t)},deactivate(t){var e;e=t,xg.delete(e),Gp(e)}},ey={name:"temporal",install(){Zg(),Em||(Em=!0,Pc("scan",Am),qr(Xp)),mg()}},ny=new Set,oy=new Set;function sy(t){ny.has(t)||(ny.add(t),console.warn(`[@wcstack/state] [wcs/v4-migration] ${t} See "Preparing for 4.0" in the @wcstack/state README.`))}const ry=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],iy=["formats","diagnostics","temporal","list-keys","scopes","recursion","ssr","devtools"],ay=(t,e,n)=>sy(`${t}: "${e}" is not one of its options, or not ${n}. 4.0 throws on it.`);function ly(t,e){oy.has(t)||(oy.add(t),sy(`${"$"===t[0]?"":"filter "}"${t}" is removed in 4.0: write "${e}" (its name since 3.2).`))}const cy={substr:'filter "substr" is removed in 4.0: write slice(start, start + length) — slice takes the end index, not a length.'},uy={$watch:"Move it to the root state, where its paths are absolute.",$listKeys:"Move it to the root state, where its paths are absolute.",$renderedCallback:"Move it to the root state, where it receives absolute paths.",$behavior:"Declare it on the root state.",$features:"Declare it on the root state."},dy=new WeakSet,hy={state(t){const e=t;for(const t of Object.keys(dc))void 0!==e[t]&&ly(t,dc[t]);var n;void 0!==e[H]&&sy(`"${H}" is removed in 4.0: rewrite it with $watch (state paths) or $on (event tokens).`),dy.has(t)||(function(t){if(null==t)return;if("object"!=typeof t)return void ay("state","$behavior","an object");const e=t;for(const t in e){const n=e[t];ry.includes(t)&&"boolean"==typeof n?n!==s[t]&&sy(`$behavior takes effect in 4.0; 3.x does not read it and runs this state with ${t}: ${!n}. Until you upgrade, pass bootstrapState({ ${t}: ${n} }).`):ay("$behavior",t,"a boolean")}}(e.$behavior),void 0!==(n=e.$features)&&(Array.isArray(n)&&!n.some(t=>!iy.includes(t))||sy(`$features is not an array of add-on names (${iy.join(", ")}). 4.0 throws on it.`)))},volumeLoaded(t){dy.add(t)},renamed:ly,removed(t){sy(cy[t])},volume(t,e,n){n>0&&sy(`volume "${t}" injects root paths (data-wcs="state.<key>: …"): 4.0 does not graft a volume with injections. Read the root path in a root getter instead.`);for(const n of Object.keys(uy))void 0!==e[n]&&sy(`volume "${t}" declares ${n}: 4.0 does not graft a volume that declares it. ${uy[n]}`)}};const fy=[Ed,ey,th,dp,Dp,rd,md];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(fy),dt=hy,void qu(void 0,void 0));const py={tagNames:{route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},enableShadowRoot:!1,basenameFileExtensions:[".html"]};function my(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function gy(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let yy=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const by={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function wy(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function vy(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}const _y={static:2,param:1,"catch-all":0};let $y=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&gy(`${py.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&gy(`${py.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=_y[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(by).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||gy(`${py.tagNames.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath,o=await this._guardHandler(e,n,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:wy(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new yy("Navigation cancelled by guard.",o);if(!o)throw new yy("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new yy("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const xy="data-wcs-ssr",Sy="data-wcs-ssr-link",Iy="@@wcs-route-ph:",Py="@@wcs-route-start:",ky="@@wcs-route-end:";let Ny=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=my();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new $y(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||gy(`${py.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${ky}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t,e){for(this._childNodeArray=[...t],e&&(this._endMarker=e);this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):gy(`${py.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&gy(`${py.tagNames.route} with fallback attribute must be a direct child of ${py.tagNames.router}.`),t.fallbackRoute&&gy(`${py.tagNames.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const Ay=Symbol.for("wcstack.trustedTypes.policy"),Ey=Symbol.for("wcstack.trustedTypes.internal"),Cy="wcstack";function My(){const t=globalThis[Ay];return null===t||"object"!=typeof t?null:t}let Ty=!1;function Oy(t){const e=function(){const t=globalThis,e=t[Ey];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Cy,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof My()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Cy}". Allow it in the CSP (\`trusted-types ${Cy};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[Ey]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=My(),s=o?.createHTML;return"function"==typeof s?(Ty||(Ty=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Cy}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Cy};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Ly=new Map;class Ry extends HTMLElement{_uuid=my();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||gy(`${py.tagNames.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Ly.set(t,n),n}catch(e){gy(`${py.tagNames.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${py.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Ly.has(t)?n.innerHTML=Oy(Ly.get(t)||""):n.innerHTML=Oy(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Oy(t):console.warn(`${py.tagNames.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&py.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class jy extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||gy(`${py.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&py.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const Wy=new Set(["props","states","attr",""]);function Dy(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function zy(t,e){t.hasAttribute("data-bind")||gy(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Wy.has(n)||gy(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&Dy(t,e,o)}).catch(()=>{gy(`Failed to define custom element: ${s}`)}):Dy(t,e,o)}const By=Symbol.for("wcstack.binder");function Fy(){const t=globalThis[By];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const Hy=Symbol.for("wcstack.binder.pending"),qy=Symbol.for("wcstack.binder.taken");function Uy(){const t=globalThis;let e=t[qy];return void 0===e&&(e=new WeakSet,t[qy]=e),e}function Vy(t,e){const n=Fy();return null===n?(function(){const t=globalThis;let e=t[Hy];return void 0===e&&(e=[],t[Hy]=e),e}().push(t),!1):(Uy().add(t),n.bind(t,e),!0)}const Gy={range:!0};function Ky(t,e){for(const n of t.routeChildNodes)e.add(n.placeHolder).add(n.endMarker),Ky(n,e);return e}function Jy(t){const e=t.placeHolder,n=t.endMarker,o=null!==n.parentNode&&n.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(n)),s=o?null:Ky(t,new Set),r=[];let i=0;for(let a=e.nextSibling;null!==a&&a!==n&&(null===s||8!==a.nodeType||!/^@@(route:|wcs-route-)/.test(a.data)||s.has(a));a=a.nextSibling)r.push(a),(o||t.childNodeArray.includes(a))&&(i=r.length);return r.length=i,r}let Qy=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||gy(`${py.tagNames.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${py.tagNames.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}!function(t){if(null!==Fy())for(const e of t)1===e.nodeType&&Vy(e,Gy)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{zy(e,t)}),e.hasAttribute("data-bind")&&zy(e,t))}};function Xy(){return document.createElement(py.tagNames.layoutOutlet)}const Yy="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Zy(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){await new Promise(t=>setTimeout(t)),gy(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${Yy}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${Yy}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function tb(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function eb(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===py.tagNames.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),tb(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===py.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Zy(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===py.tagNames.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=Xy();o.layout=n,i=o,a=e}}const c=await eb(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function nb(t){const e=new Map;return await eb(t,t.template.content,[],e)}function ob(t){return!1!==t.checkVisibility?.()}function sb(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",n=by[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)sb(s,e,n,o)}function rb(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)sb(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let ib=null,ab=null;function lb(){const t=py.basenameFileExtensions;return 0===t.length?null:(ib===t&&ab||(ib=t,ab=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),ab)}function cb(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=lb();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function ub(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function db(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=lb();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function hb(t){if(null!==t.held)return;const e=Jy(t),n=new Set(e),o=[...e,...t.childNodeArray];let s=null;for(const r of t.childNodeArray)n.has(r)?s=r:null===r.parentNode||o.some(t=>t!==r&&t.contains(r))||(e.splice(null===s?0:e.indexOf(s)+1,0,r),n.add(r),s=r);const r=document.createDocumentFragment();!function(t,e){const n=e.map(t=>t.parentNode);for(let o=0;o<e.length;o++)e[o].parentNode===n[o]&&t.appendChild(e[o])}(r,e),r.appendChild(t.endMarker),t.held=r}function fb(t){t.clearParams(),hb(t)}function pb(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{zy(e,t.typedParams)}),n.hasAttribute("data-bind")&&zy(n,t.typedParams),n.querySelectorAll(py.tagNames.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===py.tagNames.layoutOutlet&&n.assignParams(t.typedParams)}}const mb=new WeakSet;function gb(t){const e=t.placeHolder;null!==e.parentNode&&(mb.has(t)||null!==t.endMarker.parentNode?(hb(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),mb.add(t))}const yb=Symbol.for("wcstack.transition-runner");const bb=new WeakSet,wb="data-wcs";function vb(t,e,n){!bb.has(t)&&function(t){return t.hasAttribute(wb)||null!==t.querySelector(`[${wb}]`)}(t)&&(bb.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==Fy()||(o=t,Uy().has(o))||console.warn(`[@wcstack/router] ${e} contains ${wb} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function _b(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(Vy(e,Gy))continue}else if(null!==Fy())continue;vb(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.')}}async function $b(t,e){try{let t=null;for(const n of e.routes){const o=await n.guardCheck(e);o&&(t=null===t?o:Object.assign({},t,o))}e.data=t}catch(e){if(e instanceof yy)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function xb(t,e,n,o,s=""){const r=ub(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:s,path:r}),!0;let i=rb(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:gy(`${py.tagNames.router} No route matched for path: ${r}`)),i.lastPath=o,i.search=s;const a=e.lastRoutes,l=await async function(t,e,n){if(!await $b(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||fb(t);const t=[];for(const n of e.routes)(t.length>0||!s.has(n)||n.shouldChange(e.params))&&(t.push(n),pb(n,e));let r=!1;for(const e of t){const t=s.has(e);t&&r||gb(e),r||=t,n.length>0&&!t&&_b(e)}};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[yb];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",data:i.data??null,search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(ob(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(ob(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(t,i),!0)}function Sb(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Ib(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function Pb(t){return"?"===t?"":t}function kb(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function Nb(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Ab=Object.freeze({});class Eb extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Ab;_typedParams=Ab;_searchParams=Ab;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return cb(t)}_normalizeBasename(t){return db(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(py.tagNames.outlet))return t;const e=document.createElement(py.tagNames.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||gy(`${py.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||gy(`${py.tagNames.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=wy(t.search),s=t.data??null,r=this._data!==s,i=!vy(this._params,e),a=this._routeName!==t.routeName,l=!vy(this._searchParams,o),c=this._path!==t.path;r&&(this._data=s),i&&(this._params=e,this._typedParams=n),a&&(this._routeName=t.routeName),l&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,r&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${py.tagNames.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${py.tagNames.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=Ib(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Pb(n.search)+n.hash,r=Sb();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(ub(t,this._basename));await xb(this,this.outlet,t,this._path,Pb(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(ub(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await xb(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${py.tagNames.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await xb(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=Nb();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||gy(`${py.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||gy(`${py.tagNames.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await nb(this),r=!t&&this._outlet.hasAttribute(xy);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&gy(`${py.tagNames.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(xy);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await xb(this,this.outlet,i,this._path,window.location.search||""),(r||null!==Fy())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(py.tagNames.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(Iy)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Py)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith(ky)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=ub(t,this._basename);let d=rb(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of d.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(Py)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===py.tagNames.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o,n)}for(const{comment:t}of r.values())t.remove();this.outlet.removeAttribute(xy);for(const t of d.routes)pb(t,d);return this.outlet.lastRoutes=d.routes,!await $b(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(t){const e=ub(t,this._basename),n=rb(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&gy(`${py.tagNames.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await xb(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${Iy}${t.absolutePath}`}),this.outlet.setAttribute(xy,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${Py}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&Vy(e,Gy)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!kb(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),Nb()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Sb();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Sb()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Cb=["title","rel","target","download","hreflang","lang","dir"];class Mb extends HTMLElement{static get observedAttributes(){return["to",...Cb]}_childNodeArray=[];_uuid=my();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(py.tagNames.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(py.tagNames.router);if(n)return this._router=n;gy(`${py.tagNames.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return cb(t)}_joinInternalPath(t,e){const n=db(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=Ib(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+Pb(o)+s}else try{t.href=new URL(e).toString()}catch{gy(`[${py.tagNames.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){Nb()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Sy)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(Sy),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||Cb.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,Nb())return this._updateActiveState(),void n.setAttribute(Sy,"");Sb()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Sb()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Sb()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Cb.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=Ib(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Tb=[],Ob=new Map;let Lb=!1;const Rb=new WeakMap;class jb extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Lb||(this._captureInitialHead(),Lb=!0),Tb.push(this),this._reapplyHead()}disconnectedCallback(){const t=Tb.indexOf(this);-1!==t&&Tb.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||gy("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Rb.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Rb.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Ob.has(t)||Ob.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Tb)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Ob.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=Tb.length-1;e>=0;e--){const o=Tb[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Ob.has(n)&&(t=Ob.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),Vy(t)||vb(t,`<${t.tagName.toLowerCase()}> inside <${py.tagNames.head}>`,`<${py.tagNames.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(py.tagNames.layout)||t.define(py.tagNames.layout,Ry),t.get(py.tagNames.layoutOutlet)||t.define(py.tagNames.layoutOutlet,Qy),t.get(py.tagNames.outlet)||t.define(py.tagNames.outlet,jy),t.get(py.tagNames.route)||t.define(py.tagNames.route,Ny),t.get(py.tagNames.router)||t.define(py.tagNames.router,Eb),t.get(py.tagNames.link)||t.define(py.tagNames.link,Mb),t.get(py.tagNames.head)||t.define(py.tagNames.head,jb)}(void 0);const Wb={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};let Db=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function zb(t,e){return e.every(e=>"available"===t.availability.get(e))}const Bb=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Fb=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new Db("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return zb(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),u=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",d=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:u,userActivation:d},epoch:e.epoch??0,lastError:e.lastError}}(Bb,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!zb(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:u="auto",timeout:d=0}=e;let h=null;d>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},d));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===u)s=await n.blob();else if("arrayBuffer"===u)s=await n.arrayBuffer();else if("text"===u)s=await n.text();else if("json"===u)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,d)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},Hb=!1;function qb(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Wb.triggerAttribute}]`);if(!n)return;const o=n.getAttribute(Wb.triggerAttribute);if(!o)return;const s=customElements.get(Wb.tagNames.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function Ub(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}const Vb=Symbol.for("wcstack.trustedTypes.policy");function Gb(){const t=globalThis[Vb];return null===t||"object"!=typeof t?null:t}let Kb,Jb=!1;let Qb=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Fb.wcBindable,properties:[...Fb.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new Fb(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(Wb.tagNames.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(Wb.tagNames.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&function(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=Gb(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Kb)return Kb;if(!("trustedTypes"in globalThis))return Kb=!1,Kb;try{document.createElement("div").innerHTML="<i></i>",Kb=!1}catch{Kb=!0}return Kb}())return void function(){if(Jb)return;Jb=!0;const t="function"==typeof Gb()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}(t,s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Ub(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Hb||(Hb=!0,document.addEventListener("click",qb)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Xb extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}let Yb=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}};class Zb extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof Qb&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}!function(t=customElements){t.get(Wb.tagNames.fetch)||t.define(Wb.tagNames.fetch,Qb),t.get(Wb.tagNames.fetchHeader)||t.define(Wb.tagNames.fetchHeader,Xb),t.get(Wb.tagNames.fetchBody)||t.define(Wb.tagNames.fetchBody,Yb),t.get(Wb.tagNames.infiniteScroll)||t.define(Wb.tagNames.infiniteScroll,Zb)}(void 0);const tw={triggerAttribute:"data-storagetarget",tagNames:{storage:"wcs-storage"}},ew="wcs-storage:value-changed",nw="wcs-storage:loading-changed",ow="wcs-storage:error",sw="wcs-storage:error-info-changed",rw="wcs-storage:trigger-changed";let iw=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:ew,semantics:"state",getter:t=>t.detail},{name:"loading",event:nw,semantics:"state"},{name:"error",event:ow,semantics:"state"},{name:"errorInfo",event:sw,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(nw,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(ow,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(sw,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(ew,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},aw=!1;function lw(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${tw.triggerAttribute}]`);if(!n)return;const o=n.getAttribute(tw.triggerAttribute);if(!o)return;const s=customElements.get(tw.tagNames.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function cw(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let uw=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...iw.wcBindable,properties:[...iw.wcBindable.properties,{name:"trigger",event:rw,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new iw(this),this._internals=this._initInternals(),this._wireStates({[nw]:t=>({loading:!0===t}),[ow]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(rw,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!cw(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",aw||(aw=!0,document.addEventListener("click",lw)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(tw.tagNames.storage)||t.define(tw.tagNames.storage,uw)}(void 0);const dw="*",hw="vanilla",fw={scanImportmap:!0,loaders:{[hw]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[dw]:hw},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function pw(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function mw(t,e,n){let o;if(null===e||e===dw||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===dw)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[dw],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const gw=new Set,yw=new Map;let bw=new WeakMap;function ww(t){if(t===globalThis.customElements)return yw;let e=bw.get(t);return void 0===e&&(e=new Map,bw.set(t,e)),e}const vw=new Map;async function _w(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of vw)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){gw.has(e)||(console.error(`Failed to eager load component '${e}':`,t),gw.add(e))}}function $w(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function xw(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&vw.set(t,e)});const Sw=new WeakSet,Iw=new WeakSet;async function Pw(t,e,n){t.shadowRoot&&(Sw.has(t)||await async function(t,e,n){Sw.add(t),await Ew(t.shadowRoot,e,n)}(t,e,n))}async function kw(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=ww(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=mw("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),gw.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Nw(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=xw(t);void 0===o.get(s.name)?(Iw.has(t)||(Iw.add(t),o.whenDefined(s.name).then(async()=>{await Pw(t,e,n)})),a.has(s.name)||gw.has(s.name)||(a.add(s.name),i.push(s))):await Pw(t,e,n)}let l=0;for(const t of i)await kw(t,e,n,o),l++;return l}async function Aw(t,e,n,o){for(;await Nw(t,e,n,o)>0;);}async function Ew(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return $w(e)}return $w(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Aw(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await Aw(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Cw extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Cw._instance)throw new Error(`${fw.tagNames.autoloader} can only be instantiated once.`);Cw._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=pw(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=mw(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(_w(s,o,r))}await Promise.all(n)}(n,fw.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await Ew(document,fw,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Cw._instance===this&&(Cw._instance=null)}}!function(t=customElements){t.get(fw.tagNames.autoloader)||t.define(fw.tagNames.autoloader,Cw)}(void 0);
2
2
  //# sourceMappingURL=auto.min.js.map