@wcstack/state 3.5.2 → 3.5.4

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 e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.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;const r=Symbol.for("wcstack.binder");const i=Symbol.for("wcstack.binder.pending"),a=Symbol.for("wcstack.binder.taken");function l(){const e=function(){const e=globalThis[r];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;const t=function(){const e=globalThis;let t=e[i];return void 0===t&&(t=[],e[i]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[a];return void 0===t&&(t=new WeakSet,e[a]=t),t}();for(const t of n)o.add(t),e.bind(t)}const c=".",d="*",u=128,f=128,h=100,p="#",g="|",m="prevent",y="stop",w="ro",b="init",v="sync",$="else",x="...",S="on",I="eventToken",P="state",k="command",N="class",A="attr",_="style",C={};for(let e=0;e<u;e++)C[`$${e+1}`]=e;const E=Object.freeze(C),M="$connectedCallback",O="$disconnectedCallback",T="$renderedCallback",R="$errorCallback",j="$stateReadyCallback",L="$bindables",W="$commands",D="$commandTokens",B="$command",z="$eventTokens",F="$on",q="$stream",V="$watch",H="$scan",U="$recursion",G="**",K="$listKeys",J="$streamStatus",X="$streamError",Q="data-wc-definition",Y=/\{\{\s*(.+?)\s*\}\}/g,Z=new Set(["SCRIPT","STYLE"]);function ee(e,t){if(!s.enableMustache)return;!function(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o)e.parentElement&&Z.has(e.parentElement.tagName)||te(e,t)}(e,t);const n=Array.from(e.querySelectorAll("template"));for(const e of n)if("http://www.w3.org/2000/svg"===e.namespaceURI){const t=document.createElement("template"),n=Array.from(e.childNodes);for(let e=0;e<n.length;e++){const o=n[e];t.content.appendChild(o)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),ee(t.content)}else ee(e.content)}function te(e,t){const n=e.data;if(Y.lastIndex=0,!Y.test(n)||t?.(e))return;Y.lastIndex=0;const o=document.createDocumentFragment();let s,r=0;for(;null!==(s=Y.exec(n));){s.index>r&&o.appendChild(document.createTextNode(n.slice(r,s.index)));const e=s[1];o.appendChild(document.createComment(`@@: ${e}`)),r=s.index+s[0].length}r<n.length&&o.appendChild(document.createTextNode(n.slice(r))),e.parentNode.replaceChild(o,e)}function ne(e){throw new Error(`[@wcstack/state] ${e}`)}const oe=new Map;let se=0;function re(e){let t=oe.get(e);if(void 0!==t)return t;-1!==e.indexOf(G)&&ne(`[wcs/recursion-unsupported] "${e}" uses "${G}", 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(e){let t=1;for(let n=0;n<e.length;n++)e[n]===c&&t++;return t}(e);return n>512&&ne(`[wcs/binding-syntax] "${e}" 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.`),t=Object.freeze(new ie(e)),oe.set(e,t),t}class ie{id=++se;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(e){const t=t=>e===t?this:re(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===d&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),c.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=o.length>1?o[o.length-2]:null;this.path=e,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=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=u,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function ae(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;const o=new Array(t.length+1),s=new Array(t.length+1);for(let e=0;e<=t.length;e++)o[e]=e;for(let n=1;n<=e.length;n++){s[0]=n;for(let r=1;r<=t.length;r++){const i=e[n-1]===t[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let e=0;e<=t.length;e++)o[e]=s[e]}return o[t.length]}function le(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ae(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ce=" Validate statically: npx @wcstack/lint <file>.",de=new Set(["if","elseif","else","for"]);function ue(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}function fe(e){if(0===e.length)return"";let t="";for(let n=0;n<e.length;n++){const o=e[n];n>0&&(t+="|"),t+=`${o.filterName}(${ue(o.args,o.literals??o.args)})`}return t}let he=null;const pe=new Map([["not",()=>e=>!e]]),ge=new Map([["not",[0,0]]]),me={input:new Map,output:new Map},ye={input:new Map,output:new Map},we={input:new Map,output:new Map},be=new Map;function ve(e,t,n,o){const s=me[e],r=ye[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}const i=o??{},a=we[e];for(const[e,n]of[...a])Object.prototype.hasOwnProperty.call(t,n)&&i[e]!==n&&a.delete(e);for(const e of Object.keys(i))a.set(e,i[e]);be.clear()}function $e(e,t,n,o=t){const s=we[n].get(e);void 0!==s&&he?.renamed(e,s);const r=s??e,i=`${r}${ue(t,o)}:${n}`,a=be.get(i);if(void 0!==a)return a;const l=me[n].get(r)??pe.get(r);if(void 0===l){const t=0===me[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";ne(`[wcs/filter-unknown] filter not found: ${e}.${le(e,function(e){return[...new Set([...pe.keys(),...me[e].keys()])]}(n))}${t}${ce}`)}const c=ye[n].get(r)??ge.get(r);void 0!==c&&(t.length<c[0]||t.length>c[1])&&ne(t.length<c[0]?`[wcs/filter-arity] filter "${e}" requires at least ${c[0]} argument(s) (${t.length} given).${ce}`:`[wcs/filter-arity] filter "${e}" accepts at most ${c[1]} argument(s) (${t.length} given).${ce}`);const d=l(t,o);return be.set(i,d),d}function xe(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const Se=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function Ie(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:Se.test(e)?Number(e):e)}function Pe(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=xe(o,i,a);t.push(e),n.push(Ie(e,r)),o="",r=!1,i=-1,a=-1};for(let t=0;t<e.length;t++){const n=e[t];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&&ne(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ce}`);const c=xe(o,i,a);return(c||r)&&(t.push(c),n.push(Ie(c,r))),{args:t,literals:n}}const ke=e=>e.trim(),Ne=e=>"'"===e||'"'===e;function Ae(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if(Ne(s))n=s;else if(s===t)return o}return-1}function _e(e,t){const n=[];let o=null,s=0;for(let r=0;r<e.length;r++){const i=e[r];null!==o?i===o&&(o=null):Ne(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}function Ce(e,t,n){const o=n??e.join("|");return e.map(e=>{const n=Ae(e,"(");let s=function(e,t){let n=null,o=-1;for(let s=0;s<e.length;s++){const r=e[s];null!==n?r===n&&(n=null):Ne(r)?n=r:r===t&&(o=s)}return o}(e,")");if(-1===s&&(s=e.lastIndexOf(")")),-1!==n&&-1===s&&ne(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${e}".${ce}`),-1!==s&&-1===n&&ne(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${e}".${ce}`),-1!==s&&s<n&&ne(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${e}".${ce}`),-1!==s&&e.slice(s+1).trim().length>0){const t=e.slice(s+1).trim();ne(`[wcs/binding-syntax] "${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,s+1)}|${t}").${ce}`)}const r=(-1===n?e:e.substring(0,n)).trim();if(0===r.length&&ne(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${ce}`),r.includes(p)){const[e,n]=r.split(p);ne("input"===t?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${p}${n}" comes before the input filters, not inside one — write "<property>${p}${n}|${e}".${ce}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${p}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${e}" here.${ce}`)}if(-1===n)return{filterName:r,args:[],literals:[]};return{filterName:r,...Pe(e.substring(n+1,s))}})}const Ee=new Map;function Me(e){const t=Ae(e,g);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ee.has(s)?r=Ee.get(s):(o=_e(s,g).map(ke),r=Ce(o,"input",e),Ee.set(s,r))):n=e.trim();const i=n.split(p).map(ke);i.length>2&&ne(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${p}" — write "${i[0]}${p}${i.slice(1).join(",")}".${ce}`);const[a,l]=i,d=a.split(c).map(ke);d.length>1&&""===d[0]||0!==a.length&&!d.some(e=>0===e.length)||ne(`[wcs/binding-syntax] "${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${ce}`);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(ke):[],inFilters:r}}const Oe=new Map;function Te(e){const t=Ae(e,g);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Oe.has(s)?r=Oe.get(s):(o=_e(s,g).map(ke),r=Ce(o,"output",e),Oe.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&ne(`"${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(c),l=a?i.slice(1):i;(l.length>0&&l.split(c).some(e=>0===e.length)||!a&&0===l.length)&&ne(`[wcs/binding-syntax] "${e}": 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).${ce}`);return{statePathName:i,statePathInfo:re(i),outFilters:r}}const Re=new Set([$,"if","elseif","for",x]),je=new Set([N,A,_,k,I,P]);function Le(e){const[...t]=function(e){return _e(e,";")}(e).map(ke).filter(e=>e.length>0),n=t.map(e=>{const t=Ae(e,":");-1===t&&ne(`[wcs/binding-syntax] Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.${ce}`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(p)[0].split(g)[0].trim();if(s!==n&&Re.has(s)&&ne(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ce}`),n===$){o.length>0&&ne(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ce}`);const t=re("#else");return{propName:$,propSegments:[$],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===x){0===o.length&&ne(`[wcs/binding-syntax] Invalid spread binding "${e}": spread target path is required.${ce}`);const t=Te(o);return t.outFilters.length>0&&ne(`[wcs/binding-syntax] Invalid spread binding "${e}": filters are not allowed on spread targets.${ce}`),{propName:x,propSegments:[x],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Te(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Te(o);return{...Me(n),...e,bindingType:s}}{const e=Te(o),t=Me(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||je.has(o[0]))&&ne(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...je].join(", ")}).${ce}`),{...t,propName:o.join(c),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===I||t.propSegments[0].startsWith(S)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>de.has(e.bindingType))&&ne(`[wcs/template-syntax] Invalid bindText: "${e}". '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">).${ce}`)}return n}const We=new WeakMap,De=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),Be=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function ze(e){const t=We.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),o=Be.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return De.has(r)?(We.set(e,o[2]),o[2]):null}function Fe(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Te(e),bindingType:"text"}}const qe=new WeakMap,Ve=new WeakSet;let He=0;async function Ue(e){const t=function(e){let t,n=qe.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++He,promise:o,resolve:t},qe.set(e,n),Ve.has(e)&&n.resolve(),n}(e);await t.promise}function Ge(e){const t=qe.get(e);void 0===t?Ve.add(e):t.resolve()}const Ke=new WeakMap;function Je(e){const t=Ke.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{Ke.set(e,n)}}function Xe(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Qe(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Xe(t);if(void 0!==n)return Xe(n)}return Xe(globalThis.customElements)}function Ye(e,t){e.upgrade?.(t)}function Ze(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.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=ot(s.properties,et);if(null===r)return null;const i=void 0===s.inputs?new Map:ot(s.inputs,tt);if(null===i)return null;const a=void 0===s.commands?new Map:ot(s.commands,nt);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function et(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function tt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function nt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function ot(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function st(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:re(n),inFilters:[],outFilters:[],bindingType:"prop"}}function rt(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function it(e,t,n={}){const o=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&ne("Spread binding requires an element node.");const t=e,s=Je(t);null===s&&ne(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Qe(t);null===a&&ne(`CustomElementRegistry is unavailable for <${s}>.`);if(void 0===a.get(s)){o||ne(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Ye(a,t);const l=Ze(t);null===l&&ne(`Spread binding "${n.statePathName}" requires <${s}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=st(e,c);i.add(t),r.push(t)}for(const e of l.declaredInputs.keys()){if(d.has(e))continue;d.add(e);const t=st(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=rt(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=rt(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(s.debug&&i.has(r[t])){const o=r[a.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[t])}return l}function at(e,t){let n=e;for(let e=0;e<t.length;e++){let o=t[e];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function lt(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:$e(s.filterName,s.args,t,r)})}return n}function ct(e){return{...e,inFilters:lt(e.inFilters,"input"),outFilters:lt(e.outFilters,"output")}}const dt=new WeakMap;function ut(e){return dt.get(e)||null}function ft(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(s.bindAttributeName)}function ht(e){const t=[],n=e.querySelectorAll(`${s.tagNames.state}[bind-component]`);for(const o of n){if(!ft(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function pt(e,t){for(let n=0;n<t.length;n++){const o=t[n];if(o!==e&&o.contains(e))return!0}return!1}function gt(e){const t=[],n=ht(e),o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==ze(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();){const e=o.currentNode;n.length>0&&pt(e,n)||t.push(e)}return t}const mt=new WeakSet;function yt(e,t,n,o){const s=it(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Je(e):null;return null===n&&ne("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}mt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=lt(o.inFilters,"input"),s=lt(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:e});else{const r=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:r})}}return n}(e,function(e,t){return void 0===t?e:e.map(e=>null!=e.uuid?e:t(e))}(s,o));return function(e,t){dt.set(e,t)}(e,r),Ge(e),{bindings:r,deferred:null}}function wt(e,t){const n=[],o=[];for(const s of e){if(mt.has(s))continue;const e=yt(s,Yl(s),{allowDeferred:!0},t);null===e.deferred?n.push(...e.bindings):o.push(e.deferred)}return[e,n,o]}function bt(e){mt.add(e)}function vt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){mt.delete(e)}(t);return yt(t,n,{allowDeferred:!1},o).bindings}const $t=new WeakMap;let xt=null;function St(e){let t=e;for(;t;){const e=$t.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==xt&&t instanceof ShadowRoot&&(n=xt(t)),t=n}return null}function It(e,t){null!==t?$t.set(e,t):$t.delete(e)}let Pt=null;let kt=0;function Nt(){return`u${(kt++).toString(36)}`}let At=0,_t=0;const Ct=Symbol("wcs.listIndex.noValue");class Et{uuid=Nt();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;cacheStamp=0;ref;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ct,this._index=t,this._version=At,this._chainGeneration=_t}get index(){return this._index}set index(e){this._index=e,this._version=++At,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}set homeParentListIndex(e){this._homeParentListIndex=e}get value(){return this._value}set value(e){this._value=e}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=At),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===_t||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=_t),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++At,_t++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Mt(e,t,n=e){return new Et(e,t,n)}function Ot(e,t){e.reparent(t)}function Tt(e){return e.homeParentListIndex}function Rt(e,t){e.homeParentListIndex=t}function jt(e){return e?.cacheStamp}function Lt(e,t){const n=e,o=n.value,s=o!==Ct&&!Object.is(o,t);return o!==t&&(Wt.get(o)?.delete(n.ref),function(e,t){if("object"!=typeof e||null===e||null===t.parentListIndex)return;let n=Wt.get(e);void 0===n?(n=new Set,Wt.set(e,n)):n.size>=(Dt.get(n)??8)&&(Bt(n,t,!0),Dt.set(n,2*n.size+8));n.add(t.ref??=new WeakRef(t))}(t,n)),n.value=t,s}const Wt=new WeakMap,Dt=new WeakMap;function Bt(e,t,n=!1){const o=[];return e?.forEach(s=>{const r=s.deref();void 0===r||n&&Ft(r)?e.delete(s):r!==t&&o.push(r)}),o}const zt=new WeakSet;function Ft(e){for(let t=e;null!==t;t=t.parentListIndex)if(zt.has(t))return!0;return!1}function qt(e){return e.value}function Vt(e,t){const n=e.value;return n!==Ct&&n===t.value}let Ht=0;const Ut=new WeakSet;function Gt(e){Ut.add(e)}function Kt(e){return Ut.has(e)}const Jt=new WeakMap;function Xt(e){return zt.has(e)}const Qt=new WeakMap;const Yt=new WeakMap,Zt=new WeakMap;function en(e,t){return!0===Qt.get(t)?.has(e)}function tn(e,t){return en(e,t)||Ft(t)}const nn=new WeakMap;function on(e){nn.delete(e)}function sn(e,t,n){const o=Object(qt(t)),s=qt(n);for(const t in s)if(s[t]===e&&o[t]!==e)return!1;return!0}function rn(e,t){return!tn(e,t)&&nn.get(t)!==Ht}const an=new WeakMap,ln=new WeakMap;const cn=new WeakSet;function dn(e,t){const n=(o=e,Bt(Wt.get(o.value),o));var o;if(0===n.length)return n;const s=new Set(Jt.get(t()));return n.filter(t=>t.position===e.position&&!s.has(t)&&!Ft(t))}function un(e,t,n){const o=Tt(t),s=t.parentListIndex;return null!==o&&o!==s&&!tn(e,o)&&sn(e,o,s)?o:function(e,t,n,o){return null!==t&&null!==o&&o!==n&&!!zt.has(t)&&!(!rn(e,o)||o.position!==t.position)&&!en(e,t)&&Vt(o,t)}(e,o,s,n)||function(e,t,n){return t!==n&&null!==t&&null!==n&&t.position===n.position&&tn(e,t)&&rn(e,n)}(e,s,n)?n:null}function fn(e){const t=Jt.get(e);return void 0===t?null:t}function hn(e,t){const n=Jt.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o&&!Kt(e)){const s=null!==t&&o.parentListIndex!==t&&nn.get(t)!==Ht,r=un(e,o,t);if(null!==r&&cn.has(e)){cn.delete(e);const t=[...e];Gt(t),Jt.set(t,n),bn(e,t);const o=n.map((t,n)=>{const o=Mt(r,n);return Lt(o,e[n]),o});return Jt.set(e,o),o}if(null!==r)for(const e of n)Ot(e,r);else if(s){!function(e,t){let n=an.get(e);void 0===n?(n=new Set,an.set(e,n)):n.size>=(ln.get(e)??8)&&(n.forEach(t=>{tn(e,t)&&n.delete(t)}),ln.set(e,2*n.size+8));for(const e of t)n.add(e)}(e,[o.parentListIndex,t]);const s=o.parentListIndex;if(null!==s&&s.position===t.position&&!sn(e,s,t)&&sn(e,t,s))for(const e of n)Ot(e,t)}}return n}const pn=new WeakSet;function gn(e){pn.delete(e)}function mn(e,t,n=!1){null!==t?(n?pn.add(t):gn(t),Jt.set(e,t)):Jt.delete(e)}const yn=new WeakMap;function wn(e){let t=yn.get(e);return void 0===t&&(t={value:e},yn.set(e,t)),t}function bn(e,t){const n=yn.get(e);void 0!==n&&(n.value=t,yn.delete(e))}const vn=new WeakMap,$n=new WeakMap,xn=new Set,Sn=new WeakMap,In=new WeakMap;function Pn(e){const t=e.absolutePathInfo.stateElement;let n=$n.get(t);return void 0===n&&(n=new WeakMap,$n.set(t,n)),n}function kn(e){return vn.get(e)??[]}function Nn(e,t){const n=vn.get(e);vn.set(e,t),In.delete(e);const o=Pn(e);n!==t&&void 0!==n&&o.get(n).delete(e);const s=o.get(t);void 0===s?o.set(t,new Set([e])):s.has(e)||(s.size>=(Sn.get(s)??8)&&(s.forEach(e=>{An(e.listIndex)&&s.delete(e)}),Sn.set(s,Math.max(8,2*s.size))),s.add(e))}function An(e){for(let t=e;null!==t;t=t.parentListIndex)if(Xt(t))return!0;return!1}function _n(e,t){const n=Pn(e).get(t);return void 0===n?xn:(n.forEach(e=>{An(e.listIndex)&&n.delete(e)}),n)}function Cn(e,t){return!In.has(e)&&(In.set(e,t),!0)}function En(e){return vn.has(e)}const Mn=new WeakMap;let On=null,Tn=0;function Rn(e){return Mn.get(e)??[]}function jn(e,t){null===On?Mn.set(e,t):On.set(e,t)}function Ln(){Tn++,null===On&&(On=new Map)}function Wn(){if(0!==Tn&&(Tn--,!(Tn>0||null===On))){for(const[e,t]of On)Mn.set(e,t);On=null}}function Dn(e){return(On?.has(e)??!1)||Mn.has(e)}const Bn=Symbol("$$setLoopContext"),zn=Symbol("$$getByAddress"),Fn=Symbol("$$hasByAddress"),qn=Symbol("$$connectedCallback"),Vn=Symbol("$$disconnectedCallback"),Hn=Symbol("$$updatedCallback"),Un=Symbol("$$errorCallback"),Gn=new WeakMap,Kn=new WeakMap;class Jn{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Xn(e,t){if(null===t){let t=Kn.get(e);return void 0!==t||(t=new Jn(e,null),Kn.set(e,t)),t}{let n=Gn.get(t);void 0===n&&(n=new WeakMap,Gn.set(t,n));let o=n.get(e);return void 0!==o||(o=new Jn(e,t),n.set(e,o)),o}}const Qn=new WeakMap;function Yn(e,t){let n=Qn.get(e);void 0===n&&(n=new Map,Qn.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Zn(e,t)),n.set(t,o)),o}class Zn{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function eo(e,t){return Xn(Yn(e,t.pathInfo),t.listIndex)}function to(e,t,n){return Xn(Yn(e,t),n)}const no=new WeakMap;function oo(e,t){null===t?no.delete(e):no.set(e,t)}function so(e){return no.get(e)||null}const ro=new Map;function io(e,t){let n,o;if(0===e.wildcardCount||0===t.wildcardCount)return 0;if(1===e.wildcardCount&&t.wildcardCount>0&&t.wildcardPathSet.has(e.path))return 1;e.id<t.id?(n=e,o=t):(n=t,o=e);const s=`${n.path}\t${o.path}`;let r=ro.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,ro.set(s,r),r}function ao(e,t,n){return t<0||t>=n?null:e.at(t-n)}function lo(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const co=new WeakMap;function uo(e){const t=St(e.node);if(null===t)return null;let n=co.get(t);if(void 0===n)n=new WeakMap,co.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=io(t.pathInfo,e.statePathInfo);return n>0&&(o=ao(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const fo=new WeakMap;function ho(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=so(n);null===t?ne(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function po(e,t){let n=null;if(n=fo.get(e)||null,null!==n)return n;const o=ho(e,t),s=uo(e),r=Vl(o);return null===r&&ne("No state tree found on this root for binding."),n=to(r,e.statePathInfo,s),fo.set(e,n),n}function go(e){fo.delete(e)}const mo=new WeakMap;function yo(e,t){const n=mo.get(e);void 0===n?mo.set(e,t):n instanceof Set?n.add(t):n!==t&&mo.set(e,new Set([n,t])),null!==Pt&&Pt({type:"state:binding-added",absoluteAddress:e,binding:t})}function wo(e,t){const n=mo.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&mo.delete(e),null!==Pt&&Pt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const bo=new WeakMap;function vo(e){const t=mo.get(e);return void 0!==t?t:null!==e.listIndex?bo.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const $o=new WeakMap,xo=new WeakMap;class So{pathInfo;listIndex;_parentAddress;_rowAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t,this._rowAddress=null!==t&&e.lastSegment===d}get parentAddress(){const e=this._parentAddress;if(void 0!==e&&(!this._rowAddress||e.listIndex===this.listIndex.parentListIndex))return e;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let n=null;n=this.pathInfo.segments[this.pathInfo.segments.length-1]===d?this.listIndex?.parentListIndex??null:this.listIndex;const o=Po(t,n);return void 0!==e&&!Io(o,this.listIndex)&&Io(e,this.listIndex)?e:this._parentAddress=o}}function Io(e,t){const n=e.pathInfo;let o=qt(e.listIndex);for(const e of n.segments.slice(n.wildcardPositions[n.wildcardCount-1]+1))o=Object(o)[e];return fn(o)?.[t.index]===t}function Po(e,t){if(null===t){let t=xo.get(e);return void 0!==t||(t=new So(e,null),xo.set(e,t)),t}{let n=$o.get(t);void 0===n&&(n=new WeakMap,$o.set(t,n));let o=n.get(e);return void 0!==o||(o=new So(e,t),n.set(e,o)),o}}const ko=new WeakMap;function No(e){let t=null;if(t=ko.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=uo(e);null===n&&ne(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=Po(e.statePathInfo,n)}else t=Po(e.statePathInfo,null);return ko.set(e,t),t}function Ao(e){ko.delete(e)}function _o(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const Co=new Map,Eo=_o();function Mo(e,t){const n=fe(e.inFilters);return`${e.statePathName}::${t}::${n}`}function Oo(e){let t="input";for(const n of e.propModifiers)n.startsWith(S)&&(t=n.slice(2));return t}function To(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(w)){const o=Oo(e),s=Mo(e,o);let r=Co.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.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 e of n)r=e.filterFn(r);const i=Vl(o.getRootNode());null===i&&ne("No state tree found on this root for two-way binding.");const a=St(o);i.createState("writable",e=>{e[Bn](a,()=>{let n=e[t];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(e[t]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(e[t]=n.toSpliced(o,1))}else e[t]=s?[r]:[]})})},Co.set(s,r)),e.node.addEventListener(o,r),Eo.add(s,e),!0}var t,n;return!1}function Ro(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function jo(e,t){console.error(`[wcstack/state] ${t} rejected.`,e)}function Lo(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Ro(e)&&Promise.resolve(e).catch(e=>jo(e,t))}class Wo{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,e)}return t}}class Do extends Wo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Pt&&Pt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Bo=new WeakMap;function zo(e,t){let n=Bo.get(e);void 0===n&&(n=new Map,Bo.set(e,n));let o=n.get(t);return void 0===o&&(o=new Do(t,e),n.set(t,o)),o}const Fo=new WeakMap;function qo(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Je(t),o=Qe(t);if(null!==n&&void 0===o?.get(n))return null===o&&ne(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Fo.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||ne('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Je(e)?null:Ze(e)}(t);null===r&&ne(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&ne(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${le(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(m)&&e.preventDefault(),c.includes(y)&&e.stopPropagation();const n=Vl(t.getRootNode());null===n&&ne("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||ne(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${le(l,n.eventTokenNames)}${ce}`);const o=St(t);n.createStateAsync("writable",async t=>{Lo(t[Bn](o,()=>{const s=null!==o?lo(o.listIndex,o.pathInfo.wildcardCount):[];return zo(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Fo.set(e,{eventName:a,handler:d}),!0}class Vo extends Wo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Pt&&Pt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Ho(e){return e instanceof Vo}const Uo=new Map,Go=_o();function Ko(e){const t=e.propModifiers.filter(e=>e===m||e===y).sort().join(",");return`${e.statePathName}::${t}`}const Jo=(e,t,n)=>o=>{t.includes(m)&&o.preventDefault(),t.includes(y)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Vl(r);null===i&&ne("No state tree found on this root for event handler.");const a=St(s),l=e.startsWith(B+".");i.createStateAsync("writable",async t=>{const c=t[Bn](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const e=i.addressHooks;if(e){const t=e.handlerScope;for(let e=0;e<t.length;e++)c=t[e](i,s,r,a,c)}}const d=null!==a?lo(a.listIndex,c):[];if(l){const s=t[zn](Po(n,null));return Ho(s)||ne(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...d)}const u=t[e];return"function"!=typeof u&&ne(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Lo(c,`"${e}"`)}).catch(t=>jo(t,`"${e}"`))};function Xo(e){return"event"===e.bindingType&&e.propName.startsWith(S)}function Qo(e){if(!Xo(e))return!1;const t=Ko(e);let n=Uo.get(t);void 0===n&&(n=Jo(e.statePathName,e.propModifiers,e.statePathInfo),Uo.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Go.add(t,e),!0}function Yo(e){if(!Xo(e))return!1;const t=Ko(e),n=Uo.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Go.countOf(t)&&(Go.remove(t,e)&&Uo.delete(t),!0)}const Zo=new Map,es=_o();function ts(e,t){const n=fe(e.inFilters);return`${e.statePathName}::${t}::${n}`}function ns(e){let t="input";for(const n of e.propModifiers)n.startsWith(S)&&(t=n.slice(2));return t}function os(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(w)){const o=ns(e),s=ts(e,o);let r=Zo.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.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 e of n)s=e.filterFn(s);const r=Vl(o.getRootNode());null===r&&ne("No state tree found on this root for two-way binding.");const i=St(o);r.createState("writable",e=>{e[Bn](i,()=>{e[t]=s})})},Zo.set(s,r)),e.node.addEventListener(o,r),es.add(s,e),!0}var t,n;return!1}const ss=new Set(["radio","checkbox"]),rs=new Set(["value","valueAsNumber","valueAsDate"]);function is(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(ss.has(e)&&"checked"===t)return!0;if(rs.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Je(n);if(null!==s){const e=Qe(n)?.get(s);void 0===e&&ne(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ze(n);if(o?.knownProperties.has(t))return!0}return!1}let as=1,ls=1,cs=1;const ds=new WeakMap;function us(e,t,n){let o=ds.get(e);void 0===o&&(o=new Map,ds.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=as++,o.set(s,r)),r}function fs(e,t){return"to-element"===t?2*e:2*e+1}const hs=new Set;function ps(e){return{transactionId:ls++,originBindingId:e,visitedEdges:hs,hop:0}}function gs(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let ms=null;function ys(){return ms}function ws(e,t){const n=ms;ms=e;try{return t()}finally{ms=n}}const bs=[];let vs=0;function $s(e,t,n,o,s=!1){vs=s?2:1;try{e.createState("writable",e=>{e[Bn](t,()=>{e[n]=o})})}finally{vs=0}}const xs=new Map,Ss=_o(),Is=new WeakMap,Ps=e=>e.detail,ks=new WeakMap;const Ns=new WeakMap;let As=0;const _s=new WeakMap;function Cs(e,t,n,o){const s=fe(e.inFilters);return`${e.propName}::${e.statePathName}::${t}::${s}::${function(e){if(null===e)return"n";let t=Ns.get(e);return void 0===t&&Ns.set(e,t=++As),`g${t}`}(n)}::${o?"o":"s"}`}const Es=(e,t,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!==Ps||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=ks.get(e);void 0===r&&(r=new Set,ks.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=Is.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(s.enablePropagationContext){const n=us(a,e,t),o=function(e,t){for(let n=bs.length-1;n>=0;n--){const o=bs[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==o&&Object.is(o.writtenValue,l))return s.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:o.transactionId,coveredBySameValueGuard:s.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==Pt&&Pt({type:"propagation:suppressed",reason:"confirmation",transactionId:o.transactionId,edgeId:fs(n,"to-state"),node:a,member:e}));const r=fs(n,"to-state"),i=ys();if(null!==i&&i.visitedEdges.has(r))return void(null!==Pt&&Pt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=gs(i??ps(n),r)}const f=Vl(a.getRootNode());null===f&&ne("No state tree found on this root for two-way binding.");const h=St(a),p=()=>$s(f,h,t,c,r);null!==u?ws(u,p):p()};function Ms(e){const t=Je(e.node);if(null!==t){const n=Qe(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&ne(`CustomElementRegistry is unavailable for <${t}>.`))}if(is(e.node,e.propName)&&-1===e.propModifiers.indexOf(w)){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Je(e.node);if(null!==n){const o=Qe(e.node)?.get(n);void 0===o&&ne(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ze(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(S)&&(t=n.slice(2));return t}(e),n=function(e){if(null!==Je(e.node)){const t=Ze(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??Ps}return null}(e),o=function(e){if(null===Je(e.node))return!1;const t=Ze(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}(e),s=Cs(e,t,n,o);_s.set(e,{key:s,eventName:t});let r=xs.get(s);void 0===r&&(r=Es(e.propName,e.statePathName,e.inFilters,n,o),xs.set(s,r)),e.node.addEventListener(t,r),Ss.add(s,e)}}const Os=new WeakSet;function Ts(e){Os.add(e)}function Rs(e){return!!Os.has(e)&&(Os.delete(e),!0)}const js=new WeakMap;function Ls(e,t){const n=js.get(e);return!(void 0===n||n<t)&&(n===t?js.delete(e):js.set(e,n-t),!0)}const Ws=new WeakSet;function Ds(e){Ws.add(e)}function Bs(e){return!!Ws.has(e)&&(Ws.delete(e),!0)}let zs=0;function Fs(){zs--}function qs(){return zs>0}class Vs{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.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),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const Hs=new WeakMap;function Us(e){let t=Hs.get(e);return void 0===t&&(t=new Vs(e),Hs.set(e,t)),t}const Gs=new Set([N,A,_,k]);function Ks(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==b&&s!==v&&ne(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&ne(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Js(e){return e.propModifiers.some(e=>e.includes("="))}const Xs=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Qs=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Ys(e,t){return"state"===e&&"call"===t?Xs:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Zs(e){if(!s.enableDirectionalInitialSync)return Js(e)&&ne("init=/sync= modifiers require enableDirectionalInitialSync."),Xs;const t=null===(n=Ks(e,b))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:ne(`Invalid init modifier value "${n}".`);var n;const o=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":ne(`Invalid sync modifier value "${e}".`)}(Ks(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&ne("Event bindings only allow init=none."),"call"===o?Qs:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(Gs.has(e.propSegments[0]))return Ys("state",o);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&ne(`Binding type "${e.bindingType}" does not support init=${t}.`),Ys(t??"state",o);const r=Ze(e.node);if(null===r)return Ys(t??"state",o);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||ne(`Property "${e.propName}" is not declared by wcBindable.`);const l=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||ne(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==o||i||ne(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:o,observable:i,outputOnly:i&&!a}}function er(e){let t=e.getRootNode();return t instanceof DocumentFragment&&!(t instanceof ShadowRoot)&&(t=so(t)),null===t?null:Vl(t)}function tr(e,t){return"auto"!==t?t:function(e){const t=er(e.replaceNode);null===t&&ne("No state tree found on this root for binding.");const n=No(e);let o=!1;return t.createState("readonly",e=>{o=e[Fn](n)}),o}(e)?"state":"element"}let nr=0,or=null,sr=0;const rr=["active","disposed","failed"],ir=new WeakMap,ar=new WeakMap,lr=new WeakMap,cr=new WeakMap,dr=new WeakMap,ur=new WeakMap;function fr(e,t){const n=ur.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):ur.set(e,new Set([n,t]))):ur.set(e,t)}function hr(e){return ur.has(e)}function pr(e,t){const n=ur.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function gr(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))gr(n,t)}function mr(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class yr{root;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}handleMutations(e){const t=[],n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.removedNodes;if(0===r.length||!Ls(s.target,r.length))for(let e=0;e<r.length;e++)t.push(r[e]);const i=s.addedNodes;for(let e=0;e<i.length;e++)n.push(i[e])}const o=[];for(const e of t)Rs(e)||gr(e,e=>{pr(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Bs(e)&&!qs()||gr(e,e=>{pr(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&Cl(o)}}const wr=new WeakMap;function br(e){let t=wr.get(e);return void 0===t&&(t=new yr(e),wr.set(e,t)),t}function vr(e){const t=fe(e.inFilters),n=fe(e.outFilters);return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function $r(e,t,n){const o=Vl(ho(e,n));null===o&&ne("No state tree found on this root for binding.");const s=Yn(o,e.statePathInfo);return function(e,t,n){let o=bo.get(e);void 0===o&&(o=new WeakMap,bo.set(e,o));const s=o.get(t);void 0===s?o.set(t,n):s instanceof Set?s.add(n):s!==n&&o.set(t,new Set([s,n])),null!==Pt&&Pt({type:"state:binding-added",absoluteAddress:Xn(e,t),binding:n})}(s,t,e),s}function xr(e,t){const n=po(e,t);return yo(n,e),n}function Sr(e,t,n,o){null!==t?wo(t,e):function(e,t,n){const o=bo.get(e);if(void 0===o)return;const s=o.get(t);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(t),null!==Pt&&Pt({type:"state:binding-removed",absoluteAddress:Xn(e,t),binding:n}))}(n,o,e),Ao(e),go(e)}function Ir(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class Pr{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;disposedAt=0;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=this.rowOf(e),i=null===o?-1:o.bindings.indexOf(e);if(null!==o&&0===o.phases[i]){const t=o;this.observe(e.replaceNode),s.registerAddress&&null===t.addresses[i]&&null===t.patternPathInfos[i]&&(t.registered=!0,this.registerRowSlot(t,i));continue}const a=lr.get(e);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(e,s,n),r.push(e)):(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(e=>this.shouldApplyState(e))}activate(e,t){if(mr(t)&&br(t),null===this.rowPlan)for(const n of e){const e=lr.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!s.enableDirectionalInitialSync)return Js(e)&&Zs(e),!0;const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0){if(!t.registered)return!0;if(2===t.phases[n])return!1;const e=t.plan.slots[n];return 1&t.flags[n]?"state"===e.authority||!e.policy.outputOnly:(t.flags[n]|=1,"state"===e.authority)}}const n=lr.get(e);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(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0){let o=ar.get(t);void 0===o&&ar.set(t,o=[]);return{id:o[n]??(o[n]=++nr),info:e,generation:t.generation,phase:rr[t.phases[n]],teardowns:null}}const o=lr.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=lr.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(Ir(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=this.deferredByNode.get(e)??new Set,r=()=>s.delete(a)&&this.deferred.delete(a),i=()=>{const s=Qe(e);null===s&&ne(`CustomElementRegistry is unavailable for <${t}>.`),a.cancel=Us(s).wait(t,()=>{if(r())try{Ye(s,e),n()}catch(e){o(e)}},e=>{r()&&o(e)})},a={node:e,born:++sr,cancel:null,arm:()=>{if(null===a.cancel&&this.deferred.has(a))try{i()}catch(e){r(),o(e)}}},l=e.getRootNode();if(null!==or||11===l.nodeType&&!mr(l)){if(null===or){const e=or=[];queueMicrotask(()=>{or=null;for(let t=0;t<e.length;t++)e[t].arm()})}or.push(a)}else i();return mr(l)&&br(l),fr(e,this),this.deferredByNode.set(e,s.add(a)),this.deferred.add(a),()=>{r(),a.cancel?.()}}disposeBinding(e){const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0)return void this.disposeRowSlot(t,n)}const n=lr.get(e);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(e){for(let t=0;t<e.length;t++)this.disposeBinding(e[t]);if(!(this.rows.size>0))for(const e of Array.from(this.deferred))e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}destroyRow(e){const t=e.length>0?this.rowOf(e[0]):null;null!==t?(this.destroyRowRecord(t),this.rows.delete(t)):this.destroyRecords()}destroyRowRecord(e){for(let t=0;t<e.bindings.length;t++){const n=e.addresses[t];null!==n&&(wo(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){this.disposedAt=sr;for(const e of Array.from(this.rows))for(let t=0;t<e.bindings.length;t++)this.disposeRowSlot(e,t);for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){this.disposedAt=sr;for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(wo(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.rows)for(let n=0;n<t.bindings.length;n++)0===t.phases[n]&&e(t.bindings[n].node);for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.rows)for(let n=0;n<t.bindings.length;n++){if(0!==t.phases[n])continue;if(null===t.addresses[n]&&null===t.patternPathInfos[n])continue;const o=t.bindings[n];this.unregisterRowSlot(t,n),this.registerRowSlot(t,n),this.shouldApplyState(o)&&e.push(o)}for(const t of this.records){if("active"!==t.phase)continue;const n=t.info;if(null===t.address&&null===t.patternListIndex)continue;const o="for"===n.bindingType?po(n):null;if(Sr(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=po(n);e!==o&&En(o)&&Nn(e,kn(o)),e!==o&&Dn(o)&&jn(e,Rn(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return mr(t)?t:null}(e);null!==t&&br(t)}handleMutations(e,t,n){for(const n of t)gr(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)gr(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&Cl(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);this.deferredByNode.get(e)?.forEach(e=>{e.cancel?.(),e.cancel=null,this.deferred.delete(e)})}handleAddedNode(e,t,n){this.deferredByNode.get(e)?.forEach(e=>{e.born<=this.disposedAt||(this.deferred.add(e),e.arm())});const o=this.knownBindingsByNode.get(e);if(void 0===o)return;const s=o instanceof Map?o.values():[o];for(const e of s){const o=lr.get(e);if("active"===o?.phase){this.settleConnectedSnapshot(o);continue}if("disposed"!==o?.phase)continue;const s=this.optionsByBinding.get(e);if(void 0!==s)try{this.start(e,s),(s.applyOnReconnect||o.pendingDefinitions>0&&o.generation>this.disposedAt)&&this.shouldApplyState(e)&&t.push(e)}catch(e){n?.(e)}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=dr.get(t);void 0===e&&(e=vr(t),dr.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;fr(n,this);const o=this.knownMapFor(n);let s=dr.get(e);void 0===s&&(s=vr(e),dr.set(e,s));const r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}initializeRow(e,t){this.rowPlan=e;const n=e.slots,o=t.length,s={id:++nr,session:this,generation:++sr,plan:e,bindings:t,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 e=0;e<o;e++){const o=t[e],r=o.replaceNode;if(fr(r,this),this.addKnownRowBinding(r,o,e),ir.set(o,s),n[e].isEvent){let t=!1;try{t=Qo(o)}catch(t){throw s.phases[e]=2,t}t&&(s.flags[e]|=2)}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++sr,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){let n=!1;try{n=Qo(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}n&&(o.flags[e]|=2)}this.registerRowSlot(o,e,n)}}rowOf(e){const t=ir.get(e);return void 0!==t&&t.session===this?t:null}registerRowSlot(e,t,n){if(null!==e.addresses[t]||null!==e.patternPathInfos[t])return;const o=e.bindings[t],s=uo(o);null!==s?(e.patternPathInfos[t]=$r(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=xr(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(Sr(e.bindings[t],n,o,e.patternListIndexes[t]),e.addresses[t]=null,e.patternPathInfos[t]=null,e.patternListIndexes[t]=null)}disposeRowSlot(e,t){if(1!==e.phases[t]){e.phases[t]=1,this.runRowSlotTeardowns(e,t);for(let t=0;t<e.phases.length;t++)if(0===e.phases[t])return;this.rows.delete(e)}}runRowSlotTeardowns(e,t){try{this.unregisterRowSlot(e,t)}catch{}if(2&e.flags[t]){e.flags[t]&=-3;try{Yo(e.bindings[t])}catch{}}}addKnownRowBinding(e,t,n){const o=this.knownBindingsByNode.get(e);if(void 0===o)return void this.knownBindingsByNode.set(e,t);if(o instanceof Map)return void o.set("@plan:"+n,t);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,t),this.knownBindingsByNode.set(e,s)}start(e,t,n){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const o=this.optionsByBinding.get(e)??{...t},s={id:++nr,info:e,generation:++sr,phase:"discovered",teardowns:null,session:this,anchor:e.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};lr.set(e,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(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;Qo(t)?e.eventAttached=!0:t.propSegments[0]!==I?(os(t)&&Ir(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(w)){const t=ns(e),n=ts(e,t),o=Zo.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==es.countOf(n)&&(es.remove(n,e)&&Zo.delete(n),!0))}return!1}(t)),To(t)&&Ir(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(w)){const t=Oo(e),n=Mo(e,t),o=Co.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Eo.countOf(n)&&(Eo.remove(n,e)&&Co.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(s.enableDirectionalInitialSync&&is(t.node,t.propName)&&-1===t.propModifiers.indexOf(w)){const n=function(e,t,n){let o=Is.get(e);void 0===o&&(o=new Map,Is.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&Is.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});Ir(e,n)}Ms(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{qo(t)&&Ir(e,()=>function(e){if(e.propSegments[0]!==I)return!1;const t=Fo.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Fo.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Je(e.info.node);if(null===n)return void t();const o=Qe(e.info.node);if(null===o&&ne(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation;Ir(e,this.deferUntilDefined(e.info.node,n,()=>{this.isAlive(e,s)&&(t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e)))},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))}))}settleInitialRecord(e){if(s.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Zs(e.info),n=tr(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void zs++;this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending&&(e.observationPending=!1,Fs()),t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=er(e.node);null===o&&ne("No state tree found on this root for initial binding sync."),$s(o,St(e.node),e.statePathName,n)}(e.info,r))}settleConnectedSnapshot(e){if(s.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=uo(n);if(null!==o?(e.patternPathInfo=$r(n,o,t),e.patternListIndex=o):e.address=xr(n,t),!e.options.registerPathInfo)return;const s=Vl(n.replaceNode.getRootNode());null===s&&ne("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&lr.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,Fs());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{Sr(t,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=_s.get(e);if(void 0===t)return;_s.delete(e);const n=xs.get(t.key);void 0!==n&&(e.node.removeEventListener(t.eventName,n),Ss.remove(t.key,e)&&xs.delete(t.key))}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{Yo(t)}catch{}}}}function kr(e){let t=cr.get(e);return void 0===t&&(t=new Pr(e),cr.set(e,t)),t}function Nr(e){return lr.get(e)?.session??ir.get(e)?.session??null}let Ar=null;function _r(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const Cr=Object.freeze([]);const Er=new WeakMap;const Mr=new WeakMap;function Or(e){return Mr.get(e)??[]}function Tr(e,t){Mr.set(e,t)}const Rr=new WeakMap;function jr(e){return Rr.get(e)??[]}function Lr(e,t){Rr.set(e,t)}function Wr(e,t){const n=jr(e);for(const e of n)It(e,t)}const Dr=new WeakMap;function Br(e){return Dr.get(e)??[]}function zr(e,t){Dr.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});const Fr=new WeakMap,qr=new WeakSet;function Vr(e,t){if(null===t)Fr.delete(e);else{Fr.set(e,t);const{stateElement:n,pathInfo:o}=e.absolutePathInfo;if(o.wildcardCount>0){for(let e=o.parentPathInfo;null!==e&&e.wildcardCount===o.wildcardCount&&!qr.has(e);e=e.parentPathInfo)qr.add(e);n.setPathInfo(o.lastWildcardPath,"prop","internal")}}}function Hr(e){const t=Fr.get(e);t&&(t.dirty=!0),null!==e.listIndex&&qr.has(e.absolutePathInfo.pathInfo)&&e.listIndex.cacheStamp++}const Ur=Symbol.for("wcstack.transition-runner");function Gr(e){const t=globalThis[Ur];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}function Kr(e,t,n){const o=Gr(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Jr=[],Xr=[];let Qr=-1,Yr=0,Zr=!1;function ei(e){Xr.includes(e)||Xr.push(e)}function ti(e,t=0){const n=Jr.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Jr.push(o):Jr.splice(n,0,o)}function ni(e){queueMicrotask(()=>{throw e})}class oi{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Xr.length;t++)Xr[t](e);Qr>Yr&&(Yr=Qr),Qr<0&&(Zr=!0);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Ln(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],Ht++,this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){let o=Zr?0:Yr;Yr=0,Zr=!1;const s=new Map,r=new Set;for(let t=0;t<e.length;t++){const n=e[t],o=s.get(n.absoluteAddress);null!==Pt&&null!=o&&null!==n.context&&o.transactionId!==n.context.transactionId&&Pt({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 e=0;e<n.length;e++){const t=n[e];s.has(t)||s.set(t,null)}const i=[],a=new Map;s.forEach((e,t)=>{if(null!==e&&e.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),void(null!==Pt&&Pt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=vo(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(i.push(t),null!==e&&a.set(t,e));else!1!==n.replaceNode.isConnected&&(i.push(n),null!==e&&a.set(n,e))});try{const e=()=>{Qr=o+1;try{a.size>0?Cl(i,a):Cl(i)}finally{Qr=-1}};if(o>h&&i.length>0){if(101===o++){const e=[...new Set(Array.from(r,e=>e.absolutePathInfo.pathInfo.path))];console.error("[@wcstack/state] render chain depth limit exceeded; bindings for this batch were not applied.",{maxDepth:h,paths:e}),null!==Pt&&Pt({type:"state:render-chain-limit",maxDepth:h,paths:e})}}else if(t()||0===i.length)e();else{const t=Kr("state",e);void 0!==t&&t.catch(ni)}}finally{Wn(),Qr=o,function(e){for(const t of Jr.slice())t.listener(e)}(r),Qr=-1}}}const si=new oi;function ri(){return si}const ii=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap;let di=!1;const ui=new WeakMap;function fi(e){const t=e.absolutePathInfo.stateElement;let n=ui.get(t);void 0===n&&ui.set(t,n=new Set),n.add(e)}function hi(e){const t=ui.get(e);return void 0===t?null:(ui.delete(e),t)}const pi=new WeakMap,gi=new WeakMap,mi=new WeakMap,yi=new WeakMap,wi=new WeakMap,bi=[];function vi(e,t){const n=$i(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=re(t).cumulativePaths;if(o.length<2)return;let s=wi.get(e);void 0===s&&wi.set(e,s=new Map);for(let e=0;e<o.length-1;e++){let n=s.get(o[e]);void 0===n&&s.set(o[e],n=new Set),n.add(t)}}function $i(e){let t=ii.get(e);return void 0===t&&ii.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function xi(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function Si(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function Ii(e,t,n,o){const s=function(e,t){let n=e.byPath.get(t);return void 0===n&&e.byPath.set(t,n=new Map),n}(e,t);let r=ai.get(o);if(void 0===r&&ai.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(Si(s,e,o),r.set(t,n),xi(s,n,o)),!1}return r.set(t,n),xi(s,n,o),!0}function Pi(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):(o.push(n),!1)}function ki(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&Pi(li,o.listIndex,r)&&function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){let n=mi.get(t);void 0===n&&mi.set(t,n=new Set),n.add(e)}}(o.listIndex),null!==r.levelListIndex&&Pi(ci,r.levelListIndex,r))}function Ni(e,t,n,o,s){di=!0;const r=$i(e);vi(e,t);ki(r,t,s,o,Ii(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function Ai(e,t){$i(e).tracked.add(t)}function _i(e,t){return!0===ii.get(e)?.byPath.has(t)||!0===pi.get(e)?.has(t)}function Ci(e,t,n){if("number"!=typeof t)return;const o=e.indexes[t];if(void 0!==o)for(const t of e.getters)n.push(eo(e.stateElement,Po(t,o)))}function Ei(e,t){if(!di||e===t)return;const n=gi.get(e);if(void 0===n)return;gi.delete(e);const o=gi.get(t);gi.set(t,void 0===o?n:o.concat(n)),gn(t);for(const o of n){o.indexes=t;const n=$i(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=e[n],r=t[n];if(s!==r)for(const e of[s,r])if(void 0!==e&&!Xt(e))for(const t of o.getters){const n=eo(o.stateElement,Po(t,e));Hr(n),ri().enqueueAbsoluteAddress(n,null),fi(n)}}}function Mi(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Oi(e,t,n,o,s){const r=ii.get(e),i=r?.byPath.get(t),a=pi.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return bi;const l=r.lastValue.has(t),c=r.lastValue.get(t);r.lastValue.set(t,s);const d=[],u=!n||!Object.is(o,s),f=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&Mi(i.get(o),d),f&&Mi(i.get(c),d),u&&Mi(i.get(s),d)),void 0!==a)for(const e of a)n&&Ci(e,o,d),f&&Ci(e,c,d),u&&Ci(e,s,d);return d}function Ti(e,t){return!0===wi.get(e)?.has(t)}function Ri(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function ji(e,t,n,o,s=!0){const r=re(t).segments.length,i=[];for(const a of wi.get(e).get(t)){const t=re(a).segments.slice(r);if(t.includes(d)){Li(e,a,i);continue}const l=s?Ri(n,t):void 0;for(const n of Oi(e,a,s,l,Ri(o,t)))i.push(n)}return i}function Li(e,t,n){const o=ii.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())Mi(e,n);const s=pi.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)Ci(e,t,n)}function Wi(e){const t=ci.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Di(e){const t=li.get(e);if(void 0!==t){li.delete(e),function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){const n=mi.get(t);void 0!==n&&(n.delete(e),0===n.size&&mi.delete(t))}}(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=ai.get(o),r=s.get(n);s.delete(n),Si(ii.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Wi(e)}}}function Bi(e){const t=yi.get(e);if(void 0!==t){yi.delete(e);for(const e of t){const t=pi.get(e.stateElement),n=t.get(e.path);n.delete(e),0===n.size&&t.delete(e.path);const o=gi.get(e.indexes);o.splice(o.indexOf(e),1),0===o.length&&gi.delete(e.indexes)}}}function zi(e){if(!di)return;Di(e),Bi(e);const t=mi.get(e);if(void 0!==t){mi.delete(e);for(const e of t)Di(e),Bi(e),mi.delete(e)}}function Fi(e,t,n){if(!di)return;const o=ci.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=ii.get(e),i=o.byPath.get(s);Si(i,t,r),xi(i,n,r),ai.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Hr(r),ri().enqueueAbsoluteAddress(r,null),fi(r))}}const qi=new WeakMap,Vi=Object.freeze([]),Hi=new Set,Ui=new WeakMap,Gi=new WeakMap;function Ki(e,t){Gi.set(e,new WeakRef(Object(t)))}function Ji(e){return Gi.get(e)?.deref()}function Xi(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Qi(e){!function(e){for(const t of e)zt.add(t)}(e);for(const t of e)zi(t)}function Yi(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Vi,s=Array.isArray(n)&&n.length>0?n:Vi,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Vi,o=Array.isArray(t)&&t.length>0?t:Vi;let s=qi.get(n);return s&&s.get(o)||null}(o,s);if(r&&r.newIndexes===hn(s,e))return r;const i=hn(o,e)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Hi,deleteIndexSet:new Set(i),addIndexSet:Hi};let t=hn(s,e);if(null===t&&null!==e&&function(e,t){const n=an.get(e);for(const o of n??[])if(tn(e,o))n.delete(o);else if(o!==t)return!0;return!1}(o,e)&&Ki(s,o),0===o.length||null===t&&Ji(s)===o){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Mt(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:Hi,deleteIndexSet:new Set(i),addIndexSet:new Set(t)}}if(Xi(o,s)&&(t??i)===i)return o!==s&&Zi(o,i,e),a={oldIndexes:i,newIndexes:i,changeIndexSet:Hi,deleteIndexSet:Hi,addIndexSet:Hi};if(null!==t)return ea(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,l=new Set;let c=!1;for(let o=0;o<s.length;o++){const a=s[o],d=n.get(a),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=Mt(e,o);t.push(n),l.add(n)}else{const e=i[u];c=!0,u!==o&&r.add(e),t.push(e)}}c&&Zi(o,t,e);return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:l}}finally{void 0!==a&&(!function(e,t,n){let o=qi.get(e);o||(o=new WeakMap,qi.set(e,o)),o.set(t,n)}(o,s,a),gn(i),mn(s,a.newIndexes))}}(e,t,n);return function(e,t){const n=e.newIndexes;let o;for(let e=0;e<n.length;e++){if(n[e].index!==e){const t=n[e].index;n[e].index=e,Fi(n[e],t,e)}Lt(n[e],t[e])&&(o??=[]).push(n[e])}const s=Ui.get(t);s?.[0]===Ht&&(o=o?s[1].concat(o):s[1]),o&&Ui.set(t,[Ht,o]),e.valueChangeIndexes=o}(o,Array.isArray(n)&&n.length>0?n:Vi),function(e){for(const t of e)zt.delete(t)}(o.newIndexes),Ji(n)!==t&&(Qi(o.deleteIndexSet),Ei(o.oldIndexes,o.newIndexes)),o}function Zi(e,t,n){var o;if(o=e,cn.add(o),null!==n)for(const e of t)Rt(e,n)}function ea(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}function ta(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.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(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?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 e of i)a.add(n[e]);return a}const na=new WeakMap;function oa(e){return na.get(e)??null}function sa(e,t){na.set(e,t)}const ra=new WeakMap;const ia=new WeakMap;function aa(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function la(e,t,n,o,s){const r=function(e,t,n){let o=ia.get(e);void 0===o&&ia.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let e=0;e<t.length;e++){const d=t[e];if(!n.shouldApplyState(d))continue;const u=r[e];if(null===u||aa(u.prefixes,i)){Al(d,s);continue}if(s.appliedBindingSet.has(d))continue;c||(l=s.state[zn](o),c=!0);const f=u.tail;let h=l,p=!1;for(let e=0;e<f.length;e++){if(null==h){h=void 0;break}if(a&&!(f[e]in Object(h))){p=!0;break}h=h[f[e]]}p?Al(d,s):(s.appliedBindingSet.add(d),Nl(d,s,h))}}function ca(e,t,n){Wr(e,t);const o=Or(e),s=oa(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return ra.get(e)??null}(e);if(null!==r)return void la(r,o,s,t,n)}for(const e of o){if(null===s){yo(po(e),e)}(null===s||s.shouldApplyState(e))&&Al(e,n)}e.spreads&&El(e.spreads,t,s,o,Br(e))}function da(e){if(!e.mounted)return;const t=Or(e),n=oa(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{wo(po(o),o)}}!function(e){const t=jr(e);for(let e=0;e<t.length;e++)It(t[e],null)}(e)}function ua(){return Object.freeze(new Set)}const fa=new WeakMap,ha=ua();function pa(e,t){const n=fa.get(e);n?n.add(t):fa.set(e,new Set([t]))}function ga(e){const t=fa.get(e);return void 0!==t?t:ha}function ma(e,t){const n=fa.get(e);n&&(n.delete(t),0===n.size&&fa.delete(e))}const ya=new Set(["if","elseif","else","for"]);class wa{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t;const n=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)n.push(t);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(e){const t=this._childNodeArray;for(let n=0;n<t.length;n++){const o=t[n];Ds(o),e.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const e=this._firstNode,t=this._lastNode;if(null===e||null===t||null===e.parentNode)return this._childNodeArray;const n=[];for(let o=e;null!==o;o=o.nextSibling)if(n.push(o),o===t)return n;return this._childNodeArray}mountAfter(e){const t=e.parentNode;if(t){let n=e;for(const e of this._movableNodes()){if(n.nextSibling!==e){Ds(e);const o=t;e.parentNode===t&&"function"==typeof o.moveBefore?o.moveBefore(e,n.nextSibling):t.insertBefore(e,n.nextSibling)}n=e}}this._mounted=!0}tryDestroy(){const e=oa(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(Or(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Ts(n),n.parentNode.removeChild(n))}const n=Or(this);for(let e=0;e<n.length;e++){const t=n[e];ya.has(t.bindingType)&&ga(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=oa(this);null!==e&&(e.isRowSession?e.disposeBindings(Or(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=Or(this);for(let t=0;t<e.length;t++){const n=e[t];ya.has(n.bindingType)&&ga(n.node).forEach(e=>{e.unmount()}),Ao(n),go(n)}}unmount(){{const e=oa(this);null!==e&&(e.isRowSession?e.disposeBindings(Or(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Ts(e),e.parentNode.removeChild(e));const e=Or(this);for(let t=0;t<e.length;t++){const n=e[t];ya.has(n.bindingType)&&ga(n.node).forEach(e=>{e.unmount()}),Ao(n),go(n)}this._mounted=!1}}function ba(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${s.commentForPrefix}|${s.commentIfPrefix}|${s.commentElseIfPrefix}|${s.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function va(e){return 1<<Math.min(e,31)}function $a(e){let t=e.indexBits;if(void 0===t){t=0;for(const n of e.nodeInfos)for(const e of n.parseBindTextResults)e.statePathName in E&&(t|=va(E[e.statePathName])),"string"==typeof e.uuid&&(t|=$a(Ql(e.uuid)));e.indexBits=t}return t}function xa(e){return $a(Ql(e.uuid))}function Sa(e,t){return e.statePathName in E||ya.has(e.bindingType)&&0!==(xa(e)&t)}function Ia(e,t){const n=document.createDocumentFragment(),o=new wa(n,t);return o._childNodeArray=e,o._firstNode=e.length>0?e[0]:null,o._lastNode=e.length>0?e[e.length-1]:null,o._mounted=!0,o}function Pa(e,t,n){const o=document.importNode(t.fragment,!0),s=t.nodeInfos,r=new Array(s.length);for(let e=0;e<s.length;e++){const t=at(o,s[e].nodePath);null===t&&ne(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),bt(t),Ge(t),r[e]=t}const i=n.slots,a=new Array(i.length),l=[];for(let e=0;e<i.length;e++){const t=i[e],n=r[t.nodeIndex],o={...t.template,node:n,replaceNode:n};a[e]=o,t.isIndexBinding&&l.push(o)}const c=function(e,t,n){let o=Ol.get(n);void 0!==o&&o.currentRowPlan===e||(o=new Pr,Ol.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new wa(o);return sa(d,c),Tr(d,a),function(e,t){ra.set(e,t)}(d,n),zr(d,l),Lr(d,r),pa(e.node,d),d}function ka(e){void 0!==e.uuid&&null!==e.uuid||ne("BindingInfo.uuid is null.");const n=Ql(e.uuid);n||ne(`Fragment with UUID "${e.uuid}" not found.`);const o=!t()&&ba(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==s.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=s.enableDirectionalInitialSync,n=[],o=e.nodeInfos;for(let t=0;t<o.length;t++){const s=o[t],r=at(e.fragment,s.nodePath);if(null===r)return null;for(const e of s.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===k||s===I)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Je(r))return null;if("prop"===o&&is(r,e.propName))return null;const i=ct(e);let a;try{a=Zs({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:t,template:i,isEvent:"event"===o,isIndexBinding:e.statePathName in E,policy:a,authority:a.authority})}}return 0===n.length?null:{directional:t,slots:n}}(n)),null!==r)return Pa(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o,s]=function(e,t){const n=[],o=[],s=[];for(const r of t){const t=at(e,r.nodePath);if(null===t&&ne(`Node not found by path [${r.nodePath.join(", ")}] in fragment.`),mt.has(t))continue;const i=yt(t,r.parseBindTextResults,{allowDeferred:!0});null!==i.deferred&&(s.push(i.deferred),mt.add(t)),o.push(...i.bindings),n.push(t)}return[n,o,s]}(e,t),r=new Pr,i=r.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:i,bindingSession:r,spreads:s}}(i,n.nodeInfos);o&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new wa(i,o);a.spreads.length>0&&(l.spreads=a.spreads),sa(l,a.bindingSession),Tr(l,a.bindingInfos);const c="for"===e.bindingType?(d=e.statePathInfo.wildcardCount+1,2**Math.min(d,32)-1):-1;var d;const u=[];for(const e of a.bindingInfos)Sa(e,c)&&u.push(e);return zr(l,u),Lr(l,a.nodes),pa(e.node,l),l}const Na=new WeakSet,Aa=Symbol.for("wcstack.state.view-transition-naming");function _a(){const e=Gr("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Ca(e,t,n){const o=function(e){const t=e.firstNode;if(null===t)return null;const n=e.lastNode;for(let e=t;null!==e;e=e.nextSibling){if(e.nodeType===Node.ELEMENT_NODE)return e;if(e===n)break}return null}(e);if(null===o||Na.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[Aa]??={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.`)):(Na.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${t}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${t}`))}const Ea=new WeakMap,Ma=new WeakMap,Oa=new WeakMap,Ta=new WeakMap,Ra=new WeakMap,ja=new WeakMap;function La(e,t,n,o){let s=ja.get(e);void 0===s&&(s=[document.createComment(""),document.createComment("")],ja.set(e,s));const[r,i]=s;r.data=`@@wcs-for-start:${o}`,i.data=`@@wcs-for-end:${o}`,e.mounted||(r.remove(),i.remove());const a=null===n?null:n.nextSibling;if(null===r.parentNode)t.insertBefore(r,a),t.insertBefore(i,a),e.mountAfter(r);else if(a!==r){let e=r;for(;e!==i;){const n=e.nextSibling;t.insertBefore(e,a),e=n}t.insertBefore(i,a)}return i}function Wa(e,t,n){!function(e,t,n){let o=Ma.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,Ma.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function Da(e,t){Ea.set(e,t)}function Ba(e){return e.nodeType===Node.ELEMENT_NODE||(e.nodeType===Node.TEXT_NODE?""!==(e.textContent?.trim()??""):e.nodeType===Node.COMMENT_NODE&&e.data.startsWith("@@wcs-"))}function za(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const Fa=new Set(["if","elseif","else","for"]);function qa(e,t){for(const n of Or(e))if(t.appliedBindingSet.delete(n),Fa.has(n.bindingType))for(const e of ga(n.node))qa(e,t)}function Va(e,t,n){for(const o of Br(e))if(Fa.has(o.bindingType)){if(o.statePathName in E&&Al(o,t),0!==(xa(o)&n))for(const e of ga(o.node))e.mounted&&Va(e,t,n)}else Al(o,t)}function Ha(e){for(const t of Or(e)){if(!Fa.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of ga(t.node))Ha(n),e&&n.mounted&&(da(n),n.unmount(),ma(t.node,n),Ra.delete(t.node),Ma.delete(t.node))}}function Ua(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ga(e,o,r){const i=Boolean(r);let a;const l=ga(e.node);a=0===l.size?ka(e):l.values().next().value;const c=t(),d=e.uuid??"",u=e.bindingType;if(i||(s.debug&&console.log(`unmount if content : ${Ua(e)}`),c&&a.mounted&&(n.seen=!0),da(a),a.unmount()),i){s.debug&&console.log(`mount if content : ${Ua(e)}`);const t=St(e.node);if(Wr(a,t),c){if(!a.mounted){const t=document.createComment(`@@wcs-${u}-start:${d}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),a.mountAfter(t);const n=document.createComment(`@@wcs-${u}-end:${d}:${e.statePathName}`),o=a.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}}else a.mountAfter(e.node);ca(a,t,o);const n=_a();null!==n&&Ca(a,"branch",n)}}const Ka=new WeakMap;function Ja(e){return Ka.get(e)??[]}const Xa=new Set;function Qa(){Xa.clear()}const Ya=Symbol.for("wcstack.trustedTypes.policy");function Za(){const e=globalThis[Ya];return null===e||"object"!=typeof e?null:e}let el;let tl=!1;function nl(e,t){if(tl)return;if(!function(){if(void 0!==el)return el;if(!("trustedTypes"in globalThis))return el=!1,el;try{document.createElement("div").innerHTML="<i></i>",el=!1}catch{el=!0}return el}())return;tl=!0;const n="function"==typeof Za()?.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 "${t}" 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:e,property:t})}const ol={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function sl(e,n,o){if(1===e.propSegments.length){const t=e.propSegments[0];"textContent"===t||"innerText"===t?o=null==o?"":String(o):void 0===o&&"innerHTML"===t&&(o="")}if(void 0===o)return void(s.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==o){null!==Ar&&null!==d&&"object"==typeof d&&null!==o&&"object"==typeof o&&null!==Je(r)&&Ar.rememberOverwrittenObject(r,c,d);const t="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let e=!1;try{r[c]=t?function(e){if("string"!=typeof e)return e;const t=Za(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(o):o,e=!0}catch(e){t&&nl(r,c),s.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:o,error:e})}if(e){const e=function(e,t){const n=Je(e);if(null===n)return null;const o=Qe(e)?.get(n);if(void 0===o)return null;const s=Ze(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,o)}catch(t){s.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:o,error:t})}}};if(s.enablePropagationContext&&is(r,c)){const t=us(r,c,e.statePathName),s=fs(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??ys()??ps(t);if(a.visitedEdges.has(s))null!==Pt&&Pt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:s,node:r,member:c});else{const e=gs(a,s);ws(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:cs++,writtenValue:n};bs.push({receipt:i,node:e});try{return r()}finally{bs.pop()}}(r,c,o,t,e.transactionId,i))}}else i()}if(t()){const e=ol[c];e?e(r,o):(!function(e,t,n){let o=Ka.get(e);o||(o=[],Ka.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,o),a=r,Xa.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==o){if(Object.isFrozen(d))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:o}));null!==Ar&&2===i.length&&"object"==typeof d&&null!==d&&null!==Je(r)&&(u in d?Ar.rememberOverwrittenValue(r,c,u,d[u]):Ar.recordInjectedKey(r,c,u));try{d[u]=o}catch(e){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:o,error:e})}}}const rl=new WeakSet;function il(e,t,n){}function al(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}const ll=new WeakMap;function cl(e,t,n,o){const s=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),r=t.length>0?t+c:"";for(const e of n){if(r.length>0&&!e.startsWith(r))continue;const t=e.slice(r.length);t.length>0&&-1===t.indexOf(c)&&!ll.has(al(o,e)?.get)&&s.push(t)}return s}const dl={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},ul={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function fl(e,t,n,o){return`[wcs/index-arity] ${e}("${t}") requires ${"$resolve"===e?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${ce}`}function hl(e,t){return`[wcs/recursion-anchor] "${e}" does not match the declared recursion anchor "${t}". 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 pl(e,t){return`$setAll("${e}") ${t}`}function gl(e,t,n){return`[wcs/wildcard-rank] ${e} needs ${t} 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.${ce}`}function ml(e,t){const n=No(t);if(n.pathInfo.path in E){const e=St(t.node);return null===e&&ne(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&ne("ListIndex not found for loopContext:");const n=E[t];void 0===n&&ne(`Invalid index name: ${t}`);const o=ao(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&ne(gl(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[zn](n)}const yl=new WeakSet;function wl(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const bl=Object.freeze({[N]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?("boolean"!=typeof n&&ne(`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)},[A]:function(e,t,n){const o=e.node,s=e.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)},[_]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[k]:function(e,t,n){Ho(n)||ne("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Er.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||ne('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Je(e);if(null===t)return null;const n=Qe(e)?.get(t);return void 0===n&&ne(`Custom element <${t}> is not defined for command binding.`),Ze(e)}(r);null===a&&ne(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||ne(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${le(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Er.delete(e));const l=new WeakRef(r);let c=null;c=o.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void Er.delete(e);const o=n[i];return"function"!=typeof o&&ne(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),Er.set(e,{token:o,unsubscribe:c,elementRef:l})}}),vl={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!rl.has(e.replaceNode)){rl.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,o,s){const r=e.statePathInfo,i=uo(e),a=po(e),l=kn(a),c=Ra.get(e.node);let u,f;const h=void 0!==c&&function(e,t){const n=In.get(e);return void 0!==n&&(n===t||fn(t)===fn(n))}(a,s),p=h||void 0===c||c.value===l?null:Yi(i,l,s);h?(u=c.value,f=ea(fn(u),fn(s))):null!==p&&p.newIndexes.every(e=>e.parentListIndex===i||Xt(e.parentListIndex)||!en(s,e.parentListIndex))?(u=c.value,f=ea(fn(u)??[],p.newIndexes)):(u=l.length>0&&!Ma.has(e.node)?[]:l,f=Yi(i,u,s));const g=Array.isArray(s)?s:[];o.newListValueByAbsAddress.set(a,g),Ra.set(e.node,wn(g));let m=Ma.get(e.node);const y=void 0!==m?function(e,t,n){if(!Kt(t))return null;let o=null;for(let t=0;t<n.newIndexes.length;t++){const s=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(s)&&n.deleteIndexSet.has(r)?e.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}(m,u,f):null,w=Array.isArray(u)&&u.length===f.deleteIndexSet.size&&f.deleteIndexSet.size>0;if(w&&null===y&&null!==e.node.parentNode){let t=Ta.get(e.node);if(void 0===t){const n=Ea.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Ba(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Ba(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n.parentNode===e.node.parentNode?n:e.node),Ta.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){js.set(e,(js.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let b=w?1e3-function(e){return Oa.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;const v=t();if(void 0!==m){const t=m;f.deleteIndexSet.forEach(o=>{const s=t.get(o);void 0!==s&&(v&&(ja.get(s)?.forEach(e=>e.remove()),n.seen=!0),null!==y&&y.reused.has(s)?(da(s),Ha(s),s.unmountInPlace()):b<=0&&s.tryDestroy()?ma(e.node,s):(da(s),s.unmount(),function(e,t){let n=Oa.get(e.node);void 0===n&&(n=[],Oa.set(e.node,n)),n.length<1e3?n.push(t):ma(e.node,t)}(e,s),b-=1),w||t.delete(o))}),w&&(Ma.delete(e.node),m=void 0)}let $=e.node;const x=re(r.path+"."+d),S=o.stateElement.loopContextStack,I=ta(f);let P=null;f.newIndexes.length==f.addIndexSet.size&&f.newIndexes.length>0&&$.isConnected&&null===y&&(P=document.createDocumentFragment(),oo(P,o.rootNode));const k=v?`${e.uuid}:${r.path}:`:"",N=_a(),A=Oa.get(e.node);for(const t of f.newIndexes){let n;if(f.addIndexSet.has(t)){const s=Po(x,t);if(S.createLoopContext(s,s=>{n=y?.byAddedIndex.get(t)??(void 0!==A?A.pop():void 0),void 0===n?n=ka(e):(qa(n,o),Wr(n,s)),v?$=null!==P?La(n,P,null,k+t.index):La(n,$.parentNode,$,k+t.index):null!==P?n.appendTo(P):$.nextSibling!==n.firstNode&&n.mountAfter($),ca(n,s,o),null!==N&&Ca(n,"row",N)}),void 0===n&&ne(`Content not found for ListIndex: ${t.index} at path "${r.path}"`),null!==y&&y.reused.has(n)){const e=o.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](o.stateElement,n)}}}else{n=void 0!==m?m.get(t)??null:null,f.changeIndexSet.has(t)&&Va(n,o,va(r.wildcardCount)),null===n&&ne(`Content not found for ListIndex: ${t.index} at path "${r.path}"`);const e=!n.mounted;if(v?$=La(n,$.parentNode,$,k+t.index):null!==I&&I.has(t)&&za($,n.firstNode)||$.nextSibling===n.firstNode||n.mountAfter($),e){const e=n,s=Po(x,t);S.createLoopContext(s,t=>{ca(e,t,o)})}}v||($=n.lastNode||$),void 0===m&&(m=new WeakMap,Ma.set(e.node,m)),m.set(t,n)}Ea.set(e.node,$),null!==P&&(e.node.parentNode.insertBefore(P,e.node.nextSibling),oo(P,null))},if:Ga,else:Ga,elseif:Ga,radio:function(e,t,n){const o=e.node,s=_r(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=_r(o.value,e.inFilters),r=Array.isArray(n)?n:Cr;o.checked=r.includes(s)}},$l=new WeakMap,xl=new WeakMap,Sl=new WeakMap;function Il(){}function Pl(e){const t=Ar;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return il;if(t.isDeclared(n,o))return Il}return sl}function kl(e,t){Nl(e,t,ml(t.state,e))}function Nl(e,t,n){const o=_r(n,e.outFilters);if(!0===xl.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=$l.get(e);if(void 0===s){if($l.has(e))return s=Pl(e),s===il&&$l.set(e,s),void s(e,t,o);if(s=vl[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=bl[t],$l.set(e,s),void 0===s){Je(e.replaceNode)?(s=Pl(e),s===il&&$l.set(e,s)):(s=sl,$l.set(e,s))}}if(s===sl){if("SELECT"===e.node.tagName){const n=e.propSegments[0];if("value"===n||"selectedIndex"===n)return t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement}),void xl.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function Al(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=po(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=Nr(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Sl.get(e)){const t=Je(e.replaceNode);if(t&&(void 0===Qe(e.replaceNode)?.get(t)||function(e){return"waiting-definition"===lr.get(e)?.phase}(e)))return void function(e,t){if(yl.has(e))return;yl.add(e);const n=()=>{yl.delete(e);const t=Nr(e);(null===t||t.shouldApplyState(e))&&Cl([e])},o=n=>{yl.delete(e),wl(t,n)},s=Nr(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{yl.delete(e),r()})||(yl.delete(e),r()))}const r=Qe(e.replaceNode);if(null===r)return yl.delete(e),void wl(t,new Error("CustomElementRegistry is unavailable."));Us(r).wait(t,()=>{e.replaceNode.isConnected?n():yl.delete(e)},o)}(e,t);Sl.set(e,!0)}if(!0===t.sameRootVerified)return void kl(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=so(o),null===o&&ne("Root node for fragment not found for binding.")),o!==t.rootNode){const n=Vl(o);null===n&&ne("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};kl(e,r)})}else kl(e,t)}function _l(e,t,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:e.statePathName,bindingType:e.bindingType,node:e.node},r=o.get(n);void 0===r?o.set(n,[{error:t,info:s}]):r.push({error:t,info:s})}else console.error(`[@wcstack/state] binding "${e.bindingType}: ${e.statePathName}" failed to apply; the rest of this batch continues.`,{node:e.node,error:t});null!==Pt&&Pt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function Cl(e,t,n){let o=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;o<e.length;){let n=e[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 d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=so(d),null===d&&ne("Root node for fragment not found for binding."));const u=Vl(d);null===u&&ne("No state tree found on this root for binding."),u.createState("readonly",s=>{const f={rootNode:d,stateElement:u,state:s,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{Al(n,f)}catch(e){_l(n,e,u,c)}o++;const t=e[o];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{sl(e,{propagationContextByBinding:t},n)}catch(t){_l(e,t,o??null,c)}for(const[e,t]of i.entries())Nn(e,t),jn(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Hn](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Un](n,o)}catch(e){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:e,original:n,node:o.node})}})}function El(e,t,n,o,s){for(const r of e)r.cancel?.(),r.cancel=n.deferUntilDefined(r.node,r.tagName,()=>{const i=vt(r);if(o&&(e.splice(e.indexOf(r),1),o.push(...i),s.push(...i.filter(e=>e.statePathName in E))),0===i.length)return;It(r.node,t);Cl(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1}))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,e)})}function Ml(e,t,n,o=gt(e),s=kr(e)){const[r,i,a]=wt(function(e){return e.filter(e=>!mt.has(e))}(o),n);for(const e of r)It(e,t);Cl(s.initialize(i)),El(a,t,s)}const Ol=new WeakMap;async function Tl(e){const t=e.querySelectorAll(s.tagNames.state),n=[],o=Qe(e);null===o&&ne(`CustomElementRegistry is unavailable for <${s.tagNames.state}>.`),await o.whenDefined(s.tagNames.state);for(const e of t){if(ft(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function Rl(e){if(e===document)await Tl(document),ee(document),mc(document,document),Ml(document.body,null);else{const t=e;t.host.hasAttribute(s.bindAttributeName)&&await Ue(t.host),await Tl(t),ee(t),mc(t,t),Ml(t,null)}}const jl={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function Ll(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${jl[e]??e}" before the state is defined.`}let Wl=null;function Dl(e){return null===Wl&&ne(Ll("ssr",e)),Wl}const Bl=new WeakMap,zl=new WeakMap,Fl=new Set,ql=[];function Vl(e){return Bl.get(e)??null}function Hl(e){return zl.get(e)??Promise.resolve()}const Ul=new WeakSet;function Gl(e){Ul.add(e)}function Kl(e,n){const o=Bl.get(e);if(null===n){if(void 0===o)return;Bl.delete(e),Fl.delete(o),null!==Pt&&Pt({type:"state:element-unregistered",rootNode:e,element:o}),s.debug&&console.debug("State element unregistered")}else{if(o===n)return;if(void 0===o){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await Dl('the "enable-ssr" attribute').hydrate(e)||await Rl(e)}else await Rl(e);Gl(e),xc(),t()}catch(e){n(e)}})});zl.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await Rl(e),Gl(e),xc(),t()}catch(e){n(e)}})});zl.set(e,t)}}void 0!==o&&ne('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="...">.'),Bl.set(e,n),Fl.add(n);for(let t=0;t<ql.length;t++)ql[t](e,n);null!==Pt&&Pt({type:"state:element-registered",rootNode:e,element:n}),s.debug&&console.debug("State element registered",n)}}const Jl=new Map;function Xl(e,t,n){if(null===n)Jl.delete(e);else{Jl.set(e,n);const o=Vl(t);null===o&&ne("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const t of e.parseBindTextResults)o.setPathInfo(t.statePathName,t.bindingType)}}function Ql(e){return Jl.get(e)||null}function Yl(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Le(t.getAttribute(s.bindAttributeName)||"");if(t.localName===s.tagNames.state){if(t.hasAttribute("mount"))return n.filter(e=>e.propSegments[0]!==P);const e=n.find(e=>e.propSegments[0]===P);if(void 0!==e){const t=`on a volume element — a <${s.tagNames.state}> with a "mount" attribute`;ne(1===e.propSegments.length?`[wcs/mount-path-invalid] "${e.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${P}.<key>: <path>") ${t}.`:`[wcs/mount-path-invalid] "${e.propName}: ${e.statePathName}" is a volume injection declaration, and it can only be written ${t}. Add mount="<path>", or bind an element property instead.`)}}return n}if(e.nodeType===Node.COMMENT_NODE){const t=ze(e);null===t&&ne("Comment node binding text not found.");const n=Ql(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Fe(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Zl;function ec(){return Zl??={filterName:"not",args:[]}}const tc=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function nc(e,t){const n=t+c+d,o=Ae(e,"|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+c+s.slice(1)}return r.length>0?s+r:s}function oc(e,t){const n=tc.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+nc(s,t)+r}function sc(e,t){const n=_e(e,";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=Ae(n,":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=nc(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function rc(e,t){return sc(e,t)}function ic(e,t){const n=s.bindAttributeName,o=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const e=o.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=oc(n.data,t);continue}const s=e;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const e=sc(r,t);e!==r&&s.setAttribute(n,e)}}}function ac(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}const lc=new WeakMap;function cc(e){return lc.get(e)??null}function dc(e){const t=[],n=gt(e);for(const e of n){const n=Yl(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");lc.set(t,e.data),e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:ac(o),parseBindTextResults:n})}return t}function uc(e){const t=Array.from(e.childNodes);for(const n of t)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&e.removeChild(n)}}const fc=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),hc=ec();function pc(e,t){const n=t.outFilters;return{...t,outFilters:[...n,hc],bindingType:e}}function gc(e,t,n,o,s,r=!0){uc(t),"string"==typeof o&&ic(t,o),mc(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:dc(t)};return void 0!==s&&function(e,t,n){for(const o of e)for(let e=0;e<o.parseBindTextResults.length;e++){const s=o.parseBindTextResults[e];null==s.uuid&&(o.parseBindTextResults[e]=t(s,n))}}(i.nodeInfos,s,o),i}function mc(e,t,n,o){const r=s.commentElsePrefix,i=ht(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(s.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(s.bindAttributeName)||"";"string"==typeof n&&(i=rc(i,n));let a=Le(i)[0];const d=fc.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Nt();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&ne("'else' binding found without preceding 'if' or 'elseif' binding."),a=pc("else",l.parseBindTextResult),p=gc(e,f,a,g,o,!1),Xl(h,e,p);const n=c.at(-1),s=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:ac(s),parseBindTextResults:Yl(s)})):t.replaceWith(s)}else if("elseif"===u){null===l&&ne("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=gc(e,f,a,g,o),Xl(h,e,p);const n=document.createComment(`@@${d}:${h}`),s=Nt(),i={fragment:document.createDocumentFragment(),parseBindTextResult:pc("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ac(n),parseBindTextResults:Yl(n)}),Xl(s,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${s}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:ac(m),parseBindTextResults:Yl(m)})):t.replaceWith(m)}else{p=gc(e,f,a,g,o),Xl(h,e,p);const n=document.createComment(`@@${d}:${h}`);t.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}const yc=()=>`[${s.bindAttributeName}]`;function wc(e){if(hr(e))return!0;if(!bc(e))return!1;if(e.hasAttribute(s.bindAttributeName))return!1;const t=e.querySelector(yc());return null!==t&&hr(t)}function bc(e){return 1===e.nodeType}function vc(e){if(!e.isConnected||wc(e))return;const t=e.hasAttribute(s.bindAttributeName)?[e]:[];Array.from(e.children).some(e=>e.localName===s.tagNames.state&&ft(e))||(ee(e),mc(e.getRootNode(),e),t.push(...gt(e))),Ml(e,null,void 0,t,new Pr)}const $c=[];function xc(){const e=$c.splice(0,$c.length);for(const t of e)vc(t);l()}const Sc={protocol:"wcs-binder",version:1,bind:function(e){var t;bc(e)&&e.isConnected&&!wc(e)&&(t=e.getRootNode(),Ul.has(t)?vc(e):$c.push(e))}};const Ic="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Pc=0;async function kc(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Pc}\n`;let s=!1;const r=e=>{e.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+o],{type:"application/javascript"}),s=URL.createObjectURL(t);try{n=await import(s)}finally{URL.revokeObjectURL(s)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+o)));n=await import(`data:application/javascript;base64,${t}`)}}catch(e){throw await new Promise(e=>setTimeout(e)),new Error(`[@wcstack/state] ${function(e,t,n){const o=t?.message??String(t);return n?`The inline <script> of state "${e}" 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 "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Ic}`}(t,e,s)}`,{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Nc(e){const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}class Ac{_loopContextStack=Array(f).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&ne("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=f&&ne("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&&ne("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const e=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==e&&ne("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&&ne(`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=t(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 _c={$updatedCallback:T,$streams:q},Cc=new WeakSet;function Ec(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function Mc(e){if((null===e||"object"!=typeof e&&"function"!=typeof e)&&ne(`The state must be an object, got ${null===e?"null":typeof e}. Check the source of the state element (json / src / the inline <script>).`),!Cc.has(e)){he?.state(e);for(const t of Object.keys(_c)){if(!(t in e))continue;const n=_c[t];n in e&&ne(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${ce}`),Object.isExtensible(e)||ne(`[wcs/declaration-alias] The state is not extensible, so the old name "${t}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${ce}`);const o=Ec(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}Cc.add(e)}}const Oc=new WeakMap;function Tc(e,t){let n=Oc.get(e);void 0===n&&(n=new Map,Oc.set(e,n));let o=n.get(t);return void 0===o&&(o=new Vo(t,e),n.set(t,o)),o}const Rc=new WeakMap;function jc(e){const t=Rc.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return Tc(e,n)},has:(t,n)=>"string"==typeof n&&e.commandTokenNames.has(n),ownKeys:()=>Array.from(e.commandTokenNames),getOwnPropertyDescriptor(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Tc(e,n)}},set(){ne("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){ne("$command namespace is read-only; deleting from it is not allowed.")}});return Rc.set(e,n),n}const Lc=Symbol("wcs.notHandled"),Wc=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Dc=new Map;function Bc(e,t){Dc.set(e,t)}const zc=new Map;let Fc=[],qc=[];function Vc(e,t){zc.set(e,t),Fc=Array.from(zc.values()).sort((e,t)=>e.order-t.order),qc=Fc.slice().reverse()}function Hc(e){return zc.has(e)}function Uc(e,t){for(let n=0;n<Fc.length;n++)Fc[n].activate?.(e,t)}const Gc=new Map;class Kc{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice();let o=0,s=0,r=0,i="none";const a=[];for(let e=0;e<t.length;e++){const i=t[e];if("*"===i)n[e]="*",a.push(null),o++,r++;else{const t=Number(i);Number.isNaN(t)||(n[e]="*",a.push(t),s++,r++)}}const l=re(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=e,this.segments=t,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Jc(e){let t;return Gc.get(e)??(Gc.set(e,t=new Kc(e)),t)}function Xc(e){"readonly"===e.mutability&&ne("This state is readonly.")}function Qc(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[t];return void 0===o||null===n.listIndex?null:ao(n.listIndex,o,n.pathInfo.wildcardCount)}function Yc(e,t){if(!e.untracking&&e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=io(t.pathInfo,o);if(e>0){let r=!1;const i=t.listIndex??null,a=n.listIndex??null;for(let n=0;n<e;n++){if((null!==i?ao(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?ao(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function Zc(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function ed(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](e,t,n,o,s);if(a!==Lc)return a}}return Lc}function td(e,t,n,o,s){if(t.pathInfo.segments[0]===B)return function(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}(jc(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=ed(s,t,null,n,o);if(r!==Lc)return r;ne(function(e,t,n){return`[${dl.binding}] Path "${e}" does not exist on the state tree.${le(e,cl(t,"",n,t))}${ce}`}(t.pathInfo.path,e,s.getterPaths))}const r=rd(e,t.parentAddress,n,o);if(null==r)return;const i=t.pathInfo.segments[t.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==d&&!(i in Object(r))){const e=ed(s,t,Object(r),n,o);if(e!==Lc)return e}if(i===d){const e=t.listIndex?.index??ne(gl(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(r,e)}return Reflect.get(r,i)}if(!s.getterPaths.has(t.pathInfo.path))return Reflect.get(e,t.pathInfo.path);o.pushAddress(t);try{return Reflect.get(e,t.pathInfo.path,n)}finally{o.popAddress()}}function nd(e,t,n,o,s){const r=eo(s,t),i=function(e){return Fr.get(e)??null}(r),a=s.stateGeneration,l=t.pathInfo.lastSegment===d?void 0:jt(t.listIndex);if(null!==i&&!1===i.dirty&&i.generation===a&&i.rowStamp===l)return i.value;const c=td(e,t,n,o,s);"function"!=typeof c&&Vr(r,{value:c,dirty:!1,generation:a,rowStamp:l});const u=i?.value;return Array.isArray(c)&&c!==u&&s.getterPaths.has(t.pathInfo.path)&&function(e,t,n,o,s,r){const{path:i,wildcardCount:a}=t.pathInfo;r.beginUntrack();try{for(const[l,c]of r.stateElement.dynamicDependency){const d=re(l);if(!c.includes(i)||d.wildcardCount>a)continue;const u=rd(e,Po(d,ao(t.listIndex,d.wildcardCount-1,a)),s,r);u===n?od.add(t.pathInfo):u===o&&Ki(n,o)}}finally{r.endUntrack()}}(e,t,c,u,n,o),c}const od=new WeakSet;function sd(e){return od.has(e)}function rd(e,t,n,o){Yc(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const e=r.read;for(let r=0;r<e.length;r++){const i=e[r](s,t,n,o);if(i!==Lc)return i}}return Zc(s,t)?nd(e,t,n,o,s):td(e,t,n,o,s)}function id(e,t,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=Po(f,r),p=eo(n.stateElement,h),g=Rn(p),m=rd(e,h,t,n),y=Yi(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??ne(`ListIndex not found at index ${w} of ${f.path}`);s+1<o.length?a(o,s+1,e,l,c+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[e,t]of i.entries())jn(e,Array.isArray(t)?t:[]);return l}function ad(e,t,n){const o=hn(n,t.listIndex);if(null!==o)return o;const s=eo(e.stateElement,t),r=Yi(t.listIndex,Rn(s),n);return jn(s,Array.isArray(n)?n:[]),r.newIndexes}function ld(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Po(a,r),c=ad(n,l,rd(e,l,t,n)),d=s[i];r=c[d]??ne(`ListIndex not found at index ${d} of ${a.path}`)}return r}function cd(e,t,n,o){"object"==typeof e&&null!==e||ne(`${K} list "${t}": ${n} row at index ${o} must be a plain object (got ${null===e?"null":typeof e}).`);const s=Object.getPrototypeOf(e);s!==Object.prototype&&null!==s&&ne(`${K} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function dd(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&ne(`${K} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function ud(e,t,n,o){const s=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){const a=e[i];cd(a,n,o,i);const l=dd(a,t,n,o,i);r.has(l)&&ne(`${K} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function fd(e,t){const n=[];for(const o of Object.keys(t))Object.is(e[o],t[o])||n.push({field:o,value:t[o]});for(const o of Object.keys(e))Object.hasOwn(t,o)||null==e[o]||n.push({field:o,value:null});return n}function hd(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=rd(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===d){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const pd=new WeakMap;function gd(e){return pd.get(e)??null}function md(e,t){null===t?pd.delete(e):(gn(t.listIndexes),pd.set(e,t))}function yd(e,t,n){const o=Po(re(e.wildcardParentPaths[t]),n),r=eo(e.stateElement,o),i=Rn(r),a=e.stateProxy[zn](o),l=Yi(o.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return s.debug&&console.log(`Invalid search type: ${t}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)yd(e,t+1,n)}function wd(e,t,n,o){n?e.result.has(t)||e.quiet.add(t):e.quiet.delete(t),e.result.add(t),o.push(t)}const bd=[];function vd(e,t,n){return"full"!==e.listExpansion&&e.listPathSet.has(t)?e.stateElement.crossRowListPaths?.has(t)?{fullRows:n.newIndexes,movedRows:null}:0===n.addIndexSet.size&&0===n.changeIndexSet.size?0===n.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:bd,movedRows:null}:{fullRows:n.newIndexes,movedRows:null}:{fullRows:bd,movedRows:null}:{fullRows:n.addIndexSet,movedRows:n.changeIndexSet}:{fullRows:n.newIndexes,movedRows:null}}const $d=[];function xd(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return $d;let s=null;const r=t+c;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=re(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??$d}function Sd(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),e.quiet.has(a)?Hr(eo(e.stateElement,a)):n(a),i.length=0,Id(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}function Id(e,t,n){const o=t.pathInfo.path,s=e.quiet.has(t),r=e.staticMap.get(o);if(r)for(const i of r){const r=re(i);if(r.lastSegment===d){const a=e.stateProxy[zn](t),l=Array.isArray(a)?a:[],c=eo(e.stateElement,t),d=Rn(c),u=e.listPathSet.has(o);if(!u&&"diff"===e.listExpansion&&(e.keyedMergePath===o||fn(l)?.length!==l.length&&!Xi(d,l)))continue;const f=Yi(t.listIndex,d,l);e.observedListValueByAbsAddress.set(c,l);const h=vd(e,o,f);for(const t of h.fullRows)wd(e,Po(r,t),s||!u,n);for(const t of f.valueChangeIndexes??bd)wd(e,Po(r,t),s||!u,n);if(null!==h.movedRows){const t=xd(e,i,r);if(null===t)for(const t of h.movedRows)wd(e,Po(r,t),s,n);else if(t.length>0)for(const o of h.movedRows)for(const r of t)wd(e,Po(r,o),s,n)}}else wd(e,Po(r,t.listIndex),s,n)}const i=e.dynamicMap.get(o);if(i)for(const o of i){const r=re(o),i=[];if(r.wildcardCount>0){const n=io(t.pathInfo,r);if(r.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&ne(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=ao(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const s={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:r.wildcardPaths,wildcardParentPaths:r.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};yd(s,n,o),i.push(...s.targetListIndexes)}else{null===t.listIndex&&ne(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=ao(t.listIndex,n-1,t.pathInfo.wildcardCount);i.push(e)}}else i.push(null);for(const t of i)wd(e,Po(r,t),s,n)}}function Pd(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&ne(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,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};Sd(u,t,a),function(e,t){for(let n=0;n<1e3;n++){const n=hi(e.stateElement);if(null===n)return;n.forEach(n=>{Sd(e,Po(n.absolutePathInfo.pathInfo,n.listIndex),t)})}}(u,a);for(const[e,t]of u.observedListValueByAbsAddress)jn(e,t);return Array.from(u.result)}function kd(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](e,t,n,o,s)}}function Nd(e,t,n){const o=e.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Ad(e,t,n){const o=e.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function _d(e,t,n,o,s,r){const i=_i(e,t),a=Ti(e,t);if(!i&&!a)return null;const l=[],c=Ed(l);return i&&Oi(e,t,n,o,s).forEach(c),a&&ji(e,t,n?o:r(),s).forEach(c),l}function Cd(){return s.enablePropagationContext?ys()??null:null}function Ed(e){const t=ri(),n=Cd();return o=>{Hr(o),t.enqueueAbsoluteAddress(o,n),e.push(o)}}function Md(e,t,n){if(null===e||0===e.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=ri(),a=Cd();for(let n=0;n<e.length;n++){const l=e[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const d=Po(l.pathInfo,e[n].listIndex);Pd(o,d,s,r,o.listPaths,t,"new",e=>{if(e===d)return;const t=eo(o,e);Hr(t),i.enqueueAbsoluteAddress(t,a)},{listExpansion:"diff"})}}function Od(e,t,n,o,r,i,a="diff"){const l=s.enablePropagationContext?ys()??ps(-1):null,u=ri(),f=o.stateElement;u.enqueueAbsoluteAddress(t,l),i&&Hr(t);const h=t=>Pd(f,t,f.staticDependency,f.dynamicDependency,f.listPaths,n,"new",t=>{if(t===e)return;const n=eo(f,t);Hr(n),u.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r});if(h(e),e.pathInfo.lastSegment!==d&&null!==e.listIndex&&null!==e.listIndex.parentListIndex){const t=e.listIndex,o=e.pathInfo.wildcardParentPathInfos[t.position],s=Po(o,t.parentListIndex),r=()=>n[zn](s),i=e=>{Hr(e),u.enqueueRenderOnlyAddress(e)};for(const n of dn(t,r))i(eo(f,Po(e.pathInfo,n)));const a=e.pathInfo.path.slice(e.pathInfo.wildcardPaths[t.position].length);for(const e of _n(eo(f,s),r())){const n=e.absolutePathInfo.pathInfo;n!==o&&n.wildcardCount===o.wildcardCount&&i(to(f,re(n.path+c+d+a),t))}}const{path:p,lastSegment:g,wildcardCount:m,wildcardParentPaths:y,wildcardParentPathInfos:w}=e.pathInfo,b=e.listIndex;for(let e=0;b&&e<m;e++){const t=ao(b,e-1,m);for(const o of f.dynamicDependency.get(y[e])??[]){const s=re(o);if(f.listPaths.has(o)&&s.wildcardCount===e&&sd(s)&&n[zn](Po(s,t))===n[zn](Po(w[e],t))){const t=Po(re(o+p.slice(y[e].length)),b);h(t),g===d&&u.enqueueRenderOnlyAddress(eo(f,t.parentAddress))}}}}function Td(e,t,n,o,s){s&&(e.getterPaths.has(t)?Hr(n):Vr(n,{value:o,dirty:!1,generation:e.stateGeneration,rowStamp:n.absolutePathInfo.pathInfo.lastSegment===d?void 0:jt(n.listIndex)}))}function Rd(e,t,n,o,s){const r=t.listIndex,i=fn(n);if(i?.[o]!==r||n[o]===s)return t;const a=Mt(r.parentListIndex,o,Tt(r));if(function(e){return yn.has(e)}(n)){const e=gd(n)??{value:n.slice(),listIndexes:i};mn(e.value,e.listIndexes),bn(n,e.value)}const l=function(e){return pn.has(e)}(i)?i:i.slice();l[o]=a,mn(n,l,!0),Ei(i,l),Qi([r]);const c=Po(t.pathInfo,a);return Ad(e,eo(e,c),eo(e,t)),c}function jd(e,t,n,o,s,r,i,a,l=!0){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=rd(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??ne(gl(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(i,e,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t),r.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{l&&Od(t,n,s,r,i,a)}}function Ld(e,t,n,o,s,r,i,a,l){const u=t.parentAddress??ne(`address.parentAddress is undefined path: ${t.pathInfo.path}`),f=rd(e,u,s,r)??[],h=gd(f);if(l)return h&&(h.value[t.listIndex.index]=o),Lt(t.listIndex,o),jd(e,t,n,o,s,r,i,a);const p=t.listIndex,g=h??{value:[...f],listIndexes:fn(f)??[],written:new Map};try{return jd(e,t,n,o,s,r,i,a,!1)}finally{const e=function(e,t,n){const{value:o,listIndexes:s}=e,r=new Map;s.forEach((e,n)=>{if(t[n]!==o[n]){const t=r.get(o[n]);t?t.push(e):r.set(o[n],[e])}});let i,a=0;const l=[];for(let e=0;e<s.length;e++){const n=t[e]===o[e]?s[e]:r.get(t[e])?.shift();if(!n&&(a++?(i??=new Set(o)).has(t[e]):o.includes(t[e])))return null;l.push(n)}return l.map((e,t)=>e??Mt(n,t))}(g,f,u.listIndex);if(null===e)md(f,g),Lt(p,o),g.written.set(p,Ht),function(e){nn.set(e,Ht)}(p),Od(t,n,s,r,i,a);else{md(f,null);const t=[p.index];on(p),g.written.forEach((e,n)=>{on(n),Lt(n,g.value[n.index]),e===Ht&&t.push(n.index)}),g.written.delete(p),e.forEach((e,t)=>{e.index=t}),mn(f,e),Ei(g.listIndexes,e),function(e,t,n,o,s,r,i){const a=r.stateElement,l=ri(),u=eo(a,e);mn(t.value,t.listIndexes),Gt(t.value),bn(n,t.value),kn(u)===n&&Nn(u,t.value);l.enqueueRenderOnlyAddress(u);for(const e of _n(u,n))Cn(e,n)&&l.enqueueRenderOnlyAddress(e);const f=new Map;t.listIndexes.forEach((e,t)=>f.set(e,t));const h=re(e.pathInfo.path+c+d);for(let e=0;e<o.length;e++){const n=o[e],i=f.get(n);if(i===e)continue;const c=Po(h,n),d=eo(a,c);if(void 0===i){const n=to(a,h,t.listIndexes[e]);Ad(a,d,n),Od(c,d,s,r,null,Zc(a,c),"full");continue}Pd(a,c,a.staticDependency,a.dynamicDependency,a.listPaths,s,"new",e=>{const t=eo(a,e);Hr(t),l.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}for(const e of i){const n=o[e];if(f.has(n)&&t.written.get(n)!==Ht){const o=Po(h,n),i=eo(a,o);Ad(a,i,to(a,h,t.listIndexes[e])),Od(o,i,s,r,null,Zc(a,o))}}}(u,g,f,e,s,r,t)}}}function Wd(e,t,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(t.pathInfo.path);if(void 0!==i){const r=rd(e,t,o,s),a=function(e,t,n,o){const s=ud(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=ud(r,t,e,"current"),a=new Map;for(let e=0;e<r.length;e++)a.set(i[e],r[e]);const l=new Array(o.length),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=a.get(s[e]);void 0!==n&&n!==t?(l[e]=n,c.push({position:e,oldRow:n,newRow:t})):l[e]=t}return c.length>0?{list:l,matched:c}:null}(t.pathInfo.path,i,r,n);if(null!==a)return function(e,t,n,o,s,r){const i=t.pathInfo.path,a=t.listIndex;null===fn(o)&&Yi(a,null,o);const l=Yi(a,o,n.list),u=Dd(e,t,n.list,s,r,i),f=re(i+c+d);for(const t of n.matched){const n=fd(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?Wd(e,Po(re(f.path+c+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return Dd(e,t,n,o,s,null)}function Dd(e,t,n,o,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let s=0;s<e.length;s++){const i=e[s](a,t,n,o,r);if(i!==Lc)return i}}const u=function(){const e=vs;return vs=0,e}(),f=u>1;if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const u=rd(e,t.parentAddress,o,r);if("object"==typeof u&&null!==u){const e=t.pathInfo.lastSegment,h=e===d?t.listIndex?.index:e;let p,g=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in u,t=void 0!==h?u[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}e===d&&(t=Rd(a,t,u,h,n));const m=_d(a,l,g,p,n,()=>u[h]),y=Zc(a,t),w=eo(a,t);null!==Pt&&Pt({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:g}),kd(a,l,w,p,g);let b=!1;try{if(void 0===h&&ne(gl(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==d&&!(h in u)){const e=c.writeMissing;for(let s=0;s<e.length;s++){b=!0;const i=e[s](a,t,u,h,n,o,r);if(i!==Lc)return i;b=!1}}if(e!==d&&null!==t.listIndex){const o=u[h];o!==n&&(function(e,t,n,o){if(!Jt.has(e))return!1;let s=!1;for(const t in n)s||=t!==o&&n[t]===e;if(!s){let n=Qt.get(t);void 0===n&&(n=new WeakSet,Qt.set(t,n)),n.add(e)}const r=Jt.get(e),i=Zt.get(e);if(r[0]?.parentListIndex===t&&(!s||i?.[0]!==t||i[1]!==Ht))for(const n of an.get(e)??[])if(n!==t&&n.position===t.position&&rn(e,n)&&Object(qt(n))[o]===e){r.forEach(e=>Ot(e,n)),Yt.set(e,[t,Ht]);break}return s}(o,t.listIndex,u,e)&&Array.isArray(n)&&Ki(n,o),function(e,t){Qt.get(t)?.delete(e);const n=Jt.get(e);if(void 0!==n){Zt.set(e,[t,Ht]);const o=Yt.get(e);o?.[0]===t&&o[1]===Ht&&n.forEach(e=>Ot(e,t))}}(n,t.listIndex))}return Reflect.set(u,h,n)}finally{Od(t,w,o,r,i,y),Md(m,o,r),b?Hr(w):Td(a,l,w,n,y),Nd(a,t.pathInfo,{value:n})}}}let h,p=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=rd(e,t,o,r);if(hd(e,t,o,r)&&Object.is(s,n))return!0;h=s,p=!0}const g=_d(a,l,p,h,n,()=>rd(e,t,o,r)),m=a.elementPaths.has(t.pathInfo.path),y=Zc(a,t),w=eo(a,t);null!==Pt&&Pt({type:"state:write",absoluteAddress:w,value:n,oldValue:h,hasOldValue:p}),kd(a,l,w,h,p);try{return m?Ld(e,t,w,n,o,r,i,y,u):jd(e,t,w,n,o,r,i,y)}finally{Md(g,o,r),m||Td(a,l,w,n,y),Nd(a,t.pathInfo,{value:n})}}function Bd(e,t,n,o){return(t,s,...r)=>{Array.isArray(s)||ne(`$resolve("${t}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&ne(`$resolve("${t}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=re(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}s.length!==i.wildcardParentPathInfos.length&&ne(fl("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=Po(i,ld(e,n,o,i,s));if(0===r.length)return rd(e,a,n,o);Xc(o),Wd(e,a,r[0],n,o)}}function zd(e,t,n,o){const s=Bd(e,0,n,o);return(t,r)=>{const i=re(t);if(void 0===r||Array.isArray(r)||ne(`$getAll("${t}") 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 e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&ne(fl("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=Qc(o,i.wildcardPaths[e]);if(t){r=lo(t,t.length);break}}if(void 0===r){const e=o.addressStackLength>0?o.lastAddressStack:null,n=e?.listIndex??null;i.wildcardCount>0&&null!==e&&null!==n&&n.length>0&&ne(function(e,t){return`$getAll("${e}") was called without indexes inside the loop context of "${t}", 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).`}(t,e.pathInfo.path)),r=[]}}const a=id(e,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let e=0;e<a.length;e++)l.push(s(i.path,a[e]));return l}}function Fd(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Qc(o,s.wildcardPaths.at(-1)??ne(`lastWildcardPath is null: ${t.pathInfo.path}`))??ne(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??ne(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Po(i,s),l=ad(o,a,rd(e,a,n,o)),c=t.wildcardIndexes[r]??ne(`wildcardIndex is null: ${t.pathInfo.path}`);s=l[c]??ne(`ListIndex not found at index ${c} of ${i.path}`)}return s}case"partial":ne(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function qd(e,t,n,o){const s=o.stateElement;return t=>{const r=Jc(t),i=Fd(e,r,n,o),a=Po(r.pathInfo,i),l=eo(s,a),c=ri();c.enqueueAbsoluteAddress(l),function(e,t,n,o,s){const r=_i(e,t),i=Ti(e,t);if(!r&&!i)return;const a=n(),l=[],c=Ed(l);r&&Oi(e,t,!1,void 0,a).forEach(c),i&&ji(e,t,void 0,a,!1).forEach(c),Md(l,o,s)}(s,r.pathInfo.path,()=>rd(e,a,n,o),n,o),Pd(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=eo(s,e);Hr(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}function Vd(e,t,n,o){return(t,s,r,i)=>{Xc(o);const a=re(t);Array.isArray(s)||ne(pl(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&ne(fl("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&ne(pl(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&ne(pl(t,"requires an array as the value when { spread: true } is set."));const u=id(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&ne(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,u.length,r.length));const f=[];for(let t=0;t<u.length;t++){const s=ld(e,n,o,a,u[t]);f.push(Po(a,s))}const h=a.lastSegment===d;let p=0;for(let t=0;t<f.length;t++){const s=h?Po(a,ld(e,n,o,a,u[t])):f[t];let i;if(c){i=r(rd(e,s,n,o),...u[t])}else i=l?r[t]:r;void 0!==i&&(Wd(e,s,i,n,o),p++)}return p}}function Hd(e,t){if("all"===Jc(t).wildcardType)return!0;const n=e.getterPaths;if(0===n.size)return!1;for(const e of re(t).cumulativePaths)if(n.has(e))return!0;return!1}const Ud=/^\$\d+$/,Gd=`${J}${c}`,Kd=`${X}${c}`,Jd=new WeakMap;function Xd(e,t,n,o){const s=E[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&Ud.test(t)&&ne(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&ne(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack,n=e?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=e?.listIndex;null==r&&ne(`ListIndex not found: ${t.toString()}`);let i=s;const a=e.pathInfo,l=o.stateElement?.addressHooks;if(l){const t=l.indexShift;for(let n=0;n<t.length;n++)i+=t[n](o,e)}const c=ao(r,i,a.wildcardCount);return c?.index??ne(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,t,n,e);if(i!==Lc)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>zd(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>Vd(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>qd(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Bd(e,0,n,o)(t,s,...r);case"$trackDependency":he?.renamed(t,"$dependOn");case"$dependOn":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(G)&&ne(`[wcs/recursion-unsupported] ${String(t)}("${e}") 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&&ne(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??ne("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==e&&s.addDynamicDependency(e,n.path)}}(0,t,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Hd(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ai(o.stateElement,e),Object.is(n[e],t);let r;o.beginUntrack();try{r=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ni(o.stateElement,e,t,eo(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Hd(o.stateElement,e);let i,a=r?n[e]:void 0;o.beginUntrack();try{r||(a=n[e]),i=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?Ai(o.stateElement,e):Ni(o.stateElement,e,i,eo(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||ne(`$eqIndex("${e}") needs a list row scope.`);const r=ao(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&ne(`$eqIndex("${e}", ${t}): no list index at that level.`),Hd(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&(Ai(o.stateElement,e),o.stateElement.addIndexDependentGetterPath?.(s.pathInfo.path)),Object.is(n[e],r.index);const i=t===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[e],i&&(l=n[s.pathInfo.wildcardParentPaths[t-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const t=i?fn(l):null;null!==t?function(e,t,n,o,s){di=!0,$i(e).lastValue.set(t,s),vi(e,t);let r=pi.get(e);void 0===r&&pi.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=gi.get(o);if(void 0===l?(gi.set(o,l=[]),gn(o)):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a){a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a);const n=o[0]?.parentListIndex??null;if(null!==n){let e=yi.get(n);void 0===e&&yi.set(n,e=new Set),e.add(a)}}a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){di=!0;const r=$i(e);vi(e,t),ki(r,t,s,o,Ii(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,eo(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":he?.renamed(t,"$untracked");case"$untracked":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case B:return jc(o.stateElement)}if(!t.startsWith(Gd)&&!t.startsWith(Kd))return}const r=Jc(t),i=Fd(e,r,n,o),a=Po(r.pathInfo,i);return rd(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=Jd.get(e);return void 0===t&&(t=new Map,Jd.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Bn:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&ne("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case zn:i=t=>rd(e,t,n,o);break;case Fn:i=t=>hd(e,t,n,o);break;case qn:i=()=>async function(e,t,n){const o=Reflect.get(e,M);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Vn:i=()=>function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&o.call(n)}(e,0,n);break;case Hn:i=t=>function(e,t,n,o){const s=Reflect.get(e,T);let r;if("function"==typeof s){const e=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,s=t.path;if(-1===s.indexOf("#")&&(e.add(s),t.wildcardCount>0)){const e=lo(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}(e.size>0||0===t.length)&&(r=s.call(n,Array.from(e),i))}const i=o.stateElement?.addressHooks;if(i){const e=i.updated;for(let s=0;s<e.length;s++)e[s](o.stateElement,t,n)}return r}(e,t,n,o);break;case Un:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,R);"function"==typeof s&&s.call(o,t,n)}(e,t,o,n);break;default:return Reflect.get(e,t,n)}return s.set(t,i),i}}class Qd{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=Vl(e);null===n&&ne("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&ne("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=f&&(this._hasRepeatedAddress()&&ne(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),ne(`[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]=e}_hasRepeatedAddress(){const e=new Set;for(let t=0;t<=this._addressStackIndex;t++){const n=this._addressStack[t];if(n){if(e.has(n))return!0;e.add(n)}}return!1}_tailAddressPaths(){const e=[];for(let t=this._addressStackIndex;t>=0&&e.length<8;t--){const n=this._addressStack[t];n&&e.push(n.pathInfo.path)}return e}_describeAddressCycle(){const e=this._tailAddressPaths();return`${Array.from(new Set(e)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&ne(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return Xd(e,t,n,this)}set(e,t,n,o){return Xc(this),function(e,t,n,o,s){if("string"==typeof t){const r=Jc(t),i=Fd(e,r,o,s);return Wd(e,Po(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}deleteProperty(e,t){return Xc(this),Reflect.deleteProperty(e,t)}defineProperty(e,t,n){return Xc(this),Reflect.defineProperty(e,t,n)}}const Yd=Promise.resolve(),Zd=new Map;let eu=[];function tu(e,t){Zd.set(e,t),eu=Array.from(Zd.values()).sort((e,t)=>e.order-t.order)}function nu(e,t){return ne(Ll(e,t))}const ou="undefined"==typeof HTMLElement?class{}:HTMLElement;function su(e){const t=[];let n=e;for(;n&&n!==Object.prototype;)t.push(n),n=Object.getPrototypeOf(n);const o={};for(let e=t.length-1;e>=0;e--)Object.assign(o,Object.getOwnPropertyDescriptors(t[e]));return o}let ru=null;const iu=new Set(["for","if","elseif","else"]);function au(e,n,o){const s=new Map;for(const e of o){const t=re(e);if(null===t.lastWildcardPath)continue;const n=s.get(t.lastWildcardPath);void 0===n?s.set(t.lastWildcardPath,[t]):n.push(t)}const r=[],i=new Set,a=t=>{const n=eo(e,t);if(i.has(n))return;i.add(n);const o=vo(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(Po(n,t.listIndex))}};Ln();try{if(e.createState("readonly",t=>{for(const o of n){const n=Po(re(o),null);a(n);try{Pd(e,n,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",a)}catch{}}}),0===r.length)return;const o=function(e){const t=[],n=[];for(const o of e)iu.has(o.bindingType)?t.push(o):n.push(o);return t.sort((e,t)=>0!==(e.replaceNode.compareDocumentPosition(t.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),t.concat(n)}(r),s=()=>{Cl(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Kr("state",s);void 0!==i&&i.catch(ni)}finally{Wn()}}const lu=[[V,"watch"],[H,"scan"],[q,"streams"],[U,"recursion"]];class cu extends ou{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Hl(e)}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 Ac}();_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(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&ne(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){Mc(e),function(e){for(let t=0;t<lu.length;t++){const[n,o]=lu[t];n in e&&!Hc(o)&&ne(Ll(o,`"${n}"`))}}(e);const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[D];if(void 0===n)return t;Array.isArray(n)||ne(`${D} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ne(`${D} entries must be non-empty strings.`),e===B&&ne(`${D} entry "${e}" conflicts with the reserved namespace name "${B}".`),t.has(e)&&ne(`${D} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[z];if(void 0===n)return t;Array.isArray(n)||ne(`${z} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ne(`${z} entries must be non-empty strings.`),t.has(e)&&ne(`${z} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[K];if(void 0===t)return null;"object"==typeof t&&null!==t||ne(`${K} must be an object mapping list paths to key specs.`);const n=new Map;for(const[e,o]of Object.entries(t)){0===e.length&&ne(`${K} entry path must be a non-empty string.`);const t=e.split(c);t.some(e=>0===e.length)&&ne(`${K} entry "${e}" must not contain empty path segments.`),t[t.length-1]===d&&ne(`${K} entry "${e}" must be the list path itself, not the element path (drop the trailing "${c}${d}").`),-1!==e.indexOf(G)&&ne(`[wcs/recursion-unsupported] ${K} entry "${e}" uses "${G}", which ${K} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${c}${d}${c}children").`),"function"!=typeof o?("string"!=typeof o&&ne(`${K} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&ne(`${K} entry "${e}" key field name must be a non-empty string.`),(o.includes(c)||o.includes(d))&&ne(`${K} entry "${e}" key field name "${o}" must be a flat property name ("${c}" / "${d}" are not allowed).`),o in Object.prototype&&ne(`${K} entry "${e}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(e,o)):n.set(e,o)}return n.size>0?n:null}(e);var i;n.set("eventTokenNames",s),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&ru?.reset(this),this._hasUpdatedCallback=T in e,this._hasErrorCallback=R in e,i=this,Bo.delete(i),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[F];if(void 0!==o){"object"==typeof o&&null!==o||ne(`${F} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||ne(`${F} entry "${t}" is not declared in $eventTokens.${le(t,n)}`),"function"!=typeof s&&ne(`${F} entry "${t}" must be a function.`),zo(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const a=function(e){const t=new Set,n=new Set,o=su(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterPaths:t,setterPaths:n}}(e);for(const e of a.getterPaths)this._getterPaths.add(e);for(const e of a.setterPaths)this._setterPaths.add(e);!function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].register?.(e,t,n)}(this,e,n),Uc(this,null),this._resolveLoading?.()}attributeChangedCallback(e,t,n){this._initialized&&t!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===t?"absent":`"${t}"`}, 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")?Dl('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);return t&&"application/json"===t.type?JSON.parse(t.textContent||"{}"):(console.warn(`[@wcstack/state] state="${e}": no <script type="application/json" id="${e}"> 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 e=this.getAttribute("json");return JSON.parse(e)}{const e=this.querySelector('script[type="module"]');if(e)return await kc(e,s.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){let t;try{const n=await fetch(e);if(n.ok)return await n.json();t=`HTTP ${n.status} ${n.statusText}`}catch(e){t=e}return console.error(`[@wcstack/state] Failed to load JSON file "${e}", so the state starts empty (4.0 rejects instead):`,t),{}}(e);if(e&&e.endsWith(".js"))return await Nc(e);ne(`Unsupported src file type: ${e}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,n]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=n}return await this._loadingPromise,null!==this._rootNode&&(Kl(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),ne(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;this._initializeFailed=!0;const n=["state","src"].find(e=>this.hasAttribute(e));throw console.error(`[@wcstack/state] <${s.tagNames.state}${n?` ${n}="${this.getAttribute(n)}"`:""}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===Vl(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),zl.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<eu.length;o++)eu[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{M in e&&await e[qn]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{O in e&&e[Vn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<eu.length;t++)if(!0===eu[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Vl(this._rootNode)===this||Kl(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(e){for(let t=0;t<eu.length;t++){const n=eu[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{nu("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(Q))try{nu("dcc",`a <${s.tagNames.state}> inside a [${Q}] host`)}catch(e){this._failInitializeLoudly(e)}let n=!1;try{const e=function(e){for(let t=0;t<eu.length;t++){const n=eu[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&nu("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let o=!1;try{o=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!o)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const e=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(e)}if(this.hasAttribute("enable-ssr")&&!t()||e!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await Dl('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}Uc(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<eu.length;t++)if(!0===eu[t].disconnecting?.(e))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(e,t){for(let n=0;n<eu.length;n++)eu[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Kl(this.rootNode,null),e=this,Rc.delete(e),function(e){for(let t=0;t<qc.length;t++)qc[t].deactivate?.(e)}(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(e=>(he?.volumeLoaded(e),Mc(e),e))}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}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(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t,this.attachAddressHooks("watch",V)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&ne(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),t.set(n,o);this._listKeys=t}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(e){this._listPaths.add(e)}findStateDescriptor(e){return al(this._state,e)}defineTreeAccessor(e,t){Object.defineProperty(this._state,e,t),"function"==typeof t.get&&this._getterPaths.add(e),"function"==typeof t.set&&this._setterPaths.add(e),this.setPathInfo(e,"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&&ne("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(e,t){const n=function(e,t){const n=Dc.get(e);return void 0===n&&ne(Ll(e,`"${t}"`)),n}(e,t);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(e,t){for(let n=0;n<Wc.length;n++){const o=Wc[n],s=t[o];if(void 0===s)continue;const r=e[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(e){this.attachAddressHooks("scopes",e)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e,this.attachAddressHooks("dcc",L)}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){if(!this._addDependency(this._dynamicDependency,e,t))return!1;const n=re(e);for(let e=n.parentPathInfo;null!==e&&e.wildcardCount>0&&e.wildcardCount===n.wildcardCount;e=e.parentPathInfo)this._addDependency(this._dynamicDependency,e.path,t);return!0}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+d)),!this._pathSet.has(e)){const t=re(e);this._pathSet.add(e);const o=function(e,t){const n=Jc(t);return"all"===n.wildcardType&&1===n.wildcardIndexes.length&&isNaN(+n.segments[0])&&!t.includes("#")&&Object.isExtensible(e)&&!(t in e)}(this.__state,e);if(ru?.check(this,this.__state,e,n,o),o&&function(e,t){const{segments:n,cumulativePaths:o}=re(t),s=n.length-1,r=(e,r,i)=>{let a,l=!1;for(let c=0;c<=s;c++){const d=n[c];if(l||=!(isNaN(+d)||Array.isArray(a)&&+d in a),r&&c===s)return l?a[d]=i:e[t]=i;a=l?a?.[d]:e[o[c]]}return a},i=function(){return r(this)};ll.set(i,Jc(t).pathInfo.path),e.defineTreeAccessor(t,{get:i,set(e){r(this,!0,e)},configurable:!0})}(this,e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=re(e.parentPath)}}}_rebuildPathInfo(){for(const[e,t]of Array.from(this._pathRegistrations))t.bound&&!this._generatedPaths.has(e)&&this.setPathInfo(e,t.bindingType)}_createState(e,t,n){try{const o=function(e,t,n){const o=new Qd(e,n);return new Proxy(t,o)}(e,this._state,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(e){this._indexDependentGetterPaths.add(e)}setInitialState(e){if(!this._initialized)return this._initializeFailed&&ne(`<${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?.(e);!function(e){for(let t=0;t<eu.length;t++)eu[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&ne("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 t=this.__state;this._state=e;const n=function(e){const t=new Set;for(const n of e)if(void 0!==n)for(const[e,o]of Object.entries(su(n)))e.startsWith("$")||e.includes(d)||"function"==typeof o.value||t.add(e);return t}([t,e]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(e){au(this,e,this._pathRegistrations.keys())}}const du=[],uu=[];function fu(){const e=[];let t=0;for(let n=0;n<uu.length;n++){const o=uu[n].deref();void 0!==o&&(e.push(o),uu[t++]=uu[n])}return uu.length=t,e}function hu(e=customElements){fu().includes(e)||uu.push(new WeakRef(e));for(let t=0;t<du.length;t++)du[t](e);e.get(s.tagNames.state)||e.define(s.tagNames.state,cu)}function pu(e){const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}function gu(e,t){const n=pu(e);var s;n&&((s=n).tagNames&&Object.assign(o.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(o.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(o.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(o.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(o.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(o.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(o.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(o.locale=s.locale),"boolean"==typeof s.debug&&(o.debug=s.debug),"boolean"==typeof s.enableMustache&&(o.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(o.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(o.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(o.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(o.sameValueGuard=s.sameValueGuard)),hu(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=Sc)}()}let mu=null;function yu(e){return mu??ne(Ll("watch",`"$watch" in <wcs-state mount="${e}">`))}let wu=null;const bu=Object.freeze([]);const vu="3.5.2",$u=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function xu(e,t,n,o){return{node:e,propName:t.propName,statePathName:t.statePathName,bindingType:t.bindingType,inFilters:t.inFilters,outFilters:t.outFilters,origin:n,raw:o}}function Su(e){const t=[],n=new Set,o=new Set,r=e=>{const o=function(e){const t=`${fe(e.inFilters)}\0${fe(e.outFilters)}`;return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(o.has(e))return;o.add(e);const t=Ql(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(xu(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(s.bindAttributeName);if(null===n||0===n.length)continue;try{const e=it(t,Le(n));for(const o of e)r(xu(t,o,"attribute",n))}catch{}continue}const t=$u.exec(e.data.trim());if(null===t)continue;const n=t[1]||s.commentTextPrefix,o=t[2],a=Ql(o);if(null===a){if(n===s.commentTextPrefix)try{r(xu(e,Fe(o),"comment",o))}catch{}}else r(xu(e,a.parseBindTextResult,"comment",o)),i(o)}return t}function Iu(e){const t=function(e){const t=ii.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:pi.get(e)}}(e);if(null===t)return[];const n=new Set([...t.byPath.keys(),...t.tracked]);if(void 0!==t.watchers)for(const e of t.watchers.keys())n.add(e);const o=[];for(const e of[...n].sort()){const n=t.byPath.get(e);let s=0;if(void 0!==n)for(const e of n.values())s+=e.size;o.push({path:e,tracked:t.tracked.has(e),rows:s,keys:n?.size??0,lists:t.watchers?.get(e)?.size??0,lastValue:t.lastValue.get(e)})}return o}const Pu="__WCSTACK_DEVTOOLS_HOOK__";function ku(){const e=globalThis,t=e[Pu];if(void 0!==t)return 2!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 2. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:2,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[Pu]=n,n}const Nu=e=>{null!==Pt&&Pt({type:"state:update-batch",addresses:e})};function Au(e){const t=null!==Pt;!function(e){Pt=e}(e);const n=null!==e;n&&!t?ti(Nu,0):!n&&t&&function(e){const t=Jr.findIndex(t=>t.listener===e);-1!==t&&Jr.splice(t,1)}(Nu)}function _u(e){return{rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency,watchPaths:e.watchPaths??null,keyedListPaths:void 0===e.listKeys||null===e.listKeys?null:new Set(e.listKeys.keys())}}function Cu(e){return Vl(e)??ne("devtools: no state tree on this root")}let Eu=null;function Mu(){if(t())return;if(null!==Eu)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:vu,getStateElements(){const e=[];for(const t of Fl)e.push(_u(t));return e},overlays(e){return t=Cu(e),null===wu?bu:wu(t);var t},keyedSubscriptions:e=>Iu(Cu(e)),keys(e){const t=Cu(e),n=[];return t.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}n.push(t)}}),n},read(e,t,n){let o;return Cu(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){Cu(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>Su(e),_setSink:Au};Eu=e,ku().register(e)}const Ou={name:"devtools",install(){Mu()}},Tu=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Ru=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const ju=new WeakMap;const Lu=new WeakMap,Wu=new WeakSet,Du=new WeakMap;function Bu(e,t,n,o){console.warn(`[@wcstack/state] [${dl[n]}] ${ul[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${le(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ce}`),null!==Pt&&Pt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const zu={check:function(e,t,n,o,s){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const r=e.addressHooks;if(r){const t=r.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const i=re(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=ju.get(e);return void 0===n&&(n=new Set,ju.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const a=function(e,t,n,o){if(void 0!==al(e,t))return Ru;const s=re(t).segments;let r=e,i="";for(let t=0;t<s.length;t++){const a=o&&Array.isArray(r)&&+s[t]>=0?d:s[t],l=i;i=0===t?a:i+c+a;const u=t>0&&al(e,i),f=u&&ll.get(u.get);if(u&&(!f||al(e,f)))return t<s.length-1?Tu:Ru;if(Object(r)!==r)return Tu;if(a===d){if(!Array.isArray(r)||0===r.length)return Tu;r=r[0];continue}const h=al(r,a);if(void 0===h)return{existence:"missing",missingSegment:a,candidates:cl(r,l,n,e)};if("function"==typeof h.get)return t===s.length-1?Ru:Tu;r=h.value}return Ru}(t,n,e.getterPaths,s);"missing"===a.existence&&(function(e,t){return!0===Du.get(e)?.has(t)}(e,n)||("binding"!==o?Bu(e,n,o,a):function(e,t,n){let o=Lu.get(e);void 0===o&&(o=new Map,Lu.set(e,o));if(o.set(t,n),Wu.has(e))return;Wu.add(e),setTimeout(()=>function(e){Wu.delete(e);const t=Lu.get(e);if(void 0===t)return;Lu.delete(e);for(const[n,o]of t)Bu(e,n,"binding",o)}(e),0)}(e,n,a)))},reset:function(e){ju.delete(e),Lu.delete(e)},markExported:function(e,t){let n=Du.get(e);void 0===n&&(n=new Set,Du.set(e,n)),n.add(t),Lu.get(e)?.delete(t)}};let Fu=!1;function qu(){Fu||(Fu=!0,function(e){ru=e}(zu))}const Vu={name:"diagnostics",install(){qu()}};function Hu(e){ne(`filter ${e} requires at least one option`)}function Uu(e){ne(`filter ${e} requires a number as option`)}function Gu(e){ne(`filter ${e} requires a number value`)}function Ku(e){ne(`filter ${e} requires a date value`)}const Ju={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function Xu(e){return!(!e||isNaN(Number(e)))}function Qu(e,t){return Xu(e)||Uu(t),Number(e)}function Yu(e,t,n){return Qu(e?.[t]??Hu(n),n)}const Zu=e=>t=>{const n=e(t);return e=>null==e?e:n(e)},ef={eq:(e,t)=>{const n=e?.[0]??Hu("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e===o:(Xu(n)||Uu("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Hu("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e!==o:(Xu(n)||Uu("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>!e,lt:e=>{const t=Yu(e,0,"lt");return e=>("number"!=typeof e&&Gu("lt"),e<t)},le:e=>{const t=Yu(e,0,"le");return e=>("number"!=typeof e&&Gu("le"),e<=t)},gt:e=>{const t=Yu(e,0,"gt");return e=>("number"!=typeof e&&Gu("gt"),e>t)},ge:e=>{const t=Yu(e,0,"ge");return e=>("number"!=typeof e&&Gu("ge"),e>=t)},add:e=>{const t=Yu(e,0,"add");return e=>("number"!=typeof e&&Gu("add"),e+t)},sub:e=>{const t=Yu(e,0,"sub");return e=>("number"!=typeof e&&Gu("sub"),e-t)},mul:e=>{const t=Yu(e,0,"mul");return e=>("number"!=typeof e&&Gu("mul"),e*t)},div:e=>{const t=Yu(e,0,"div");return e=>("number"!=typeof e&&Gu("div"),e/t)},mod:e=>{const t=Yu(e,0,"mod");return e=>("number"!=typeof e&&Gu("mod"),e%t)},abs:e=>e=>("number"!=typeof e&&Gu("abs"),Math.abs(e)),clamp:e=>{const t=Yu(e,0,"clamp"),n=Yu(e,1,"clamp");return e=>("number"!=typeof e&&Gu("clamp"),Math.min(Math.max(e,t),n))},toFixed:e=>{const t=Qu(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&Gu("toFixed"),e.toFixed(t))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Gu("locale"),e.toLocaleString(t??s.locale))},upper:Zu(e=>e=>String(e).toUpperCase()),lower:Zu(e=>e=>String(e).toLowerCase()),capitalize:Zu(e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),trim:Zu(e=>e=>String(e).trim()),slice:Zu(e=>{const t=[Yu(e,0,"slice")],n=e?.[1];return void 0!==n&&t.push(Qu(n,"slice")),e=>String(e).slice(...t)}),substr:Zu(e=>{he?.removed("substr");const t=Yu(e,0,"substr"),n=Yu(e,1,"substr");return e=>String(e).substr(t,n)}),padStart:Zu(e=>{const t=Yu(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),padEnd:Zu(e=>{const t=Yu(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),repeat:Zu(e=>{const t=Yu(e,0,"repeat");return e=>String(e).repeat(t)}),reverse:Zu(e=>e=>String(e).split("").reverse().join("")),truncate:Zu(e=>{const t=Yu(e,0,"truncate"),n=e?.[1]??"…";return e=>{const o=String(e);return o.length<=t?o:o.slice(0,t)+n}}),join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||ne(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=Math.pow(10,Qu(e?.[0]??"0","round"));return e=>("number"!=typeof e&&Gu("round"),Math.round(e*t)/t)},floor:e=>{const t=Math.pow(10,Qu(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&Gu("floor"),Math.floor(e*t)/t)},ceil:e=>{const t=Math.pow(10,Qu(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&Gu("ceil"),Math.ceil(e*t)/t)},percent:e=>{const t=Qu(e?.[0]??"0","percent");return e=>("number"!=typeof e&&Gu("percent"),`${(100*e).toFixed(t)}%`)},unit:Zu(e=>{const t=e?.[0]??Hu("unit");return e=>String(e)+t}),date:e=>{const t=e?.[0];return e=>(e instanceof Date||Ku("date"),e.toLocaleDateString(t??s.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Ku("time"),e.toLocaleTimeString(t??s.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Ku("datetime"),e.toLocaleString(t??s.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Ku("ymd");const n=e.getFullYear().toString(),o=(e.getMonth()+1).toString().padStart(2,"0"),s=e.getDate().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},hms:e=>{const t=e?.[0]??":";return e=>{e instanceof Date||Ku("hms");const n=e.getHours().toString().padStart(2,"0"),o=e.getMinutes().toString().padStart(2,"0"),s=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!e,truthy:e=>e=>!!e,defaults:(e,t)=>{const n=e?.[0]??Hu("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Hu("coalesce"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e??o},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),nullIfEmpty:e=>e=>""===e?null:e},tf={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]},nf=ef,of=ef;let sf=!1;const rf={name:"formats",install(){sf||(sf=!0,ve("input",of,tf,Ju),ve("output",nf,tf,Ju))}};function af(e){return-1!==e.indexOf(G)}function lf(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+c;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(af(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function cf(e){return 0===e.length?e:c+ff(e.slice(1))}function df(e,t,n){const o=c+e.repeat,s=t.length<=n.length?t:n,r=t.length<=n.length?n:t;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 e=0;e<i.length;e+=o.length)if(!i.startsWith(o,e))return!1;return!0}function uf(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(df(e,t,n.slice(0,o)))return!0;return!1}function ff(e){const t=e.split(c);for(let e=0;e<t.length;e++)t[e]===d||Number.isNaN(Number(t[e]))||(t[e]=d);return t.join(c)}function hf(e,t){const n=e.repeat.split(c),o=c+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===c+e.repeatList+c+"length")return!0;for(let e=1;e<n.length;e++)if(s===c+n.slice(0,e).join(c))return!0;return!1}function pf(e,t,n){n<0&&ne(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=c+e.repeat;const s=o+t;let r=0;for(const e of s.split(c))e===d&&r++;return r>u&&ne(`[wcs/recursion-depth-exceeded] Recursion on "${e.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 gf(e,t){return pf(e,"",t)}function mf(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const o=n.slice(e.anchor.length,n.length-t.length);if(0===o.length)return 0;const s=c+e.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function yf(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=t.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const o=c+n.repeat;let s=0,r=n.anchor.length;for(;t.startsWith(o,r);)r+=o.length,s++;return r!==t.length&&46!==t.charCodeAt(r)?null:s}(t,n.pathInfo.path)}function wf(e,t,n){const o=e.recursionRegistry,s=lf(o.spec,n);null===s&&ne(hl(n,o.spec.recursiveAnchor));const r=yf(t,o);return null===r&&ne(`[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 bf(e,t,n,o,s){const r=o.spec,i=[],a=new Map,l=[],d=r.repeatList,u=r.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void i.push(Po(e,n));const s=g(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function g(o,s,i){const l=Po(o,s),c=eo(n.stateElement,l),u=rd(e,l,t,n),h=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&ne(`[wcs/recursion-cycle] "${e}" 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)&&ne(`[wcs/recursion-shared-list] "${e}" 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 "${d}" array.`),o})(o.path,u,i),p=Yi(s,Rn(c),u);return a.set(c,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=l[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:re(n),childListPathInfo:re(r+c+d)};return l[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(Po(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,re(u),null);for(const[e,t]of a)jn(e,t);return i}function vf(e,t,n,o,s,r,i){Xc(n);const a=n.stateElement.recursionRegistry,l=lf(a.spec,o);null===l&&ne(hl(o,a.spec.recursiveAnchor));const c=cf(l);Array.isArray(s)||ne(pl(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&ne(`[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&&ne(pl(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&ne(pl(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(e,t,n){hf(e,n)&&ne(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.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 d=a.conflictingRecursiveGetter(c);null!==d&&ne(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${d}", 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 u=bf(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Wd(e,u[o],r,t,n),f++);return f}const $f={write(e,t){if(!0!==e.hasRecursion)return Lc;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&ne(`[wcs/recursion-readonly] "${t.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.`),Lc},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return Lc;if("$getAll"===t)return(t,s)=>{if(af(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=lf(r.spec,o);null===i&&ne(hl(o,r.spec.recursiveAnchor)),Array.isArray(s)||ne(`[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&&ne(`[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=bf(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(rd(e,a[o],t,n));return l}(o,n,e,t,s);t=wf(e.stateElement,e,t)}return zd(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>af(t)?vf(o,n,e,t,s,r,i):Vd(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&af(t)){const s=Jc(wf(e.stateElement,e,t)),r=Fd(o,s,n,e);return rd(o,Po(s.pathInfo,r),n,e)}return Lc}};let xf=!1;function Sf(e,t){"string"==typeof t&&0!==t.length||ne(`[wcs/recursion-declaration-invalid] ${U} ${e} must be a non-empty string.`);const n=t.split(c);n.some(e=>0===e.length)&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not contain empty path segments.`),n.length<2&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must name a list element: a property path ending with "${c}${d}" (for example "nodes${c}${d}").`),n[n.length-1]!==d&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must end with "${c}${d}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===d&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must have exactly one "${d}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===G&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not contain "${G}" — the declaration is what gives "${G}" its meaning.`),isNaN(Number(n[o]))||ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const If=new WeakSet;function Pf(e){return"function"==typeof e.get&&If.has(e.get)}const kf="[wcs/recursion-declaration-invalid]";class Nf{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(e,t){this.spec=e;const n=su(t);for(const[t,o]of Object.entries(n)){if(!af(t))continue;"function"==typeof o.set&&ne(`${kf} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&ne(`${kf} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=lf(e,t);null===n&&ne(hl(t,e.recursiveAnchor)),0===n.length&&ne(`${kf} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),hf(e,cf(n))&&ne(`${kf} "${t}" names the recursion structure itself (a node, its "${e.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 "${e.recursiveAnchor}${c}total").`),this._definitions.set(t,{recursivePath:t,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(af(t)||Pf(n))continue;const e=this._matchExpansion(t);null!==e&&ne(`${kf} "${t}" is already defined on the state, so the recursive getter "${e}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const e=Array.from(this._definitions.values());for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)df(this.spec,e[t].suffix,e[n].suffix)&&ne(`${kf} "${e[t].recursivePath}" and "${e[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(e){for(const t of this._definitions.values())if(uf(this.spec,t.suffix,e))return t.recursivePath;return null}recursiveGetterOwningPath(e){const t=this._ownerByPathInfo.get(e);if(void 0!==t)return t;const n=this.recursiveGetterOwning(e.path);return this._ownerByPathInfo.set(e,n),n}recursiveGetterOwning(e){const t=this._accessors.get(e);if(void 0!==t)return t.recursivePath;const n=ff(e),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 e=n.lastIndexOf(c);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(c,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==mf(this.spec,t.suffix,e))return t.recursivePath;return null}materializeForPathInfo(e,t){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(t);if(void 0!==n)return n;const o=this.materializeFor(e,t.path);return this._accessorByPathInfo.set(t,o),o}materializeFor(e,t){const n=this._accessors.get(t);if(void 0!==n)return n;if(!t.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const e of this._definitions.values()){const n=mf(this.spec,e.suffix,t);null!==n&&(null!==o&&ne(`"${t}" matches both "${o.recursivePath}" and "${e.recursivePath}".`),o=e,s=n)}return null===o?null:this._define(e,o,s,t)}_define(e,t,n,o){const s=e.findStateDescriptor(o);void 0===s||Pf(s)||ne(`"${o}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:t.recursivePath,depth:n}),i=t.get,a=function(){return i.call(this)};var l;return l=a,If.add(l),e.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(e,n),this._accessors.set(o,r),r}_registerListPaths(e,t){for(const n of function(e,t){const n=[];n.push(e.anchorList);for(let o=0;o<t;o++)n.push(gf(e,o)+c+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return function(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Pf(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}}}(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let o=n[t];return void 0===o&&(o=pf(this.spec,e,t),n[t]=o),o}accessorFor(e){return this._accessors.get(e)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const Af="recursionSpec",_f="recursionRegistry",Cf={order:5,validateEarly(e,t,n){const o=function(e){const t=e[U];if(void 0===t)return null;"object"==typeof t&&null!==t||ne(`[wcs/recursion-declaration-invalid] ${U} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&ne(`[wcs/recursion-declaration-invalid] ${U} must declare exactly one anchor; it is empty.`),n.length>1&&ne(`[wcs/recursion-declaration-invalid] ${U} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Sf("anchor",o),"string"!=typeof s&&ne(`[wcs/recursion-declaration-invalid] ${U} entry "${o}" must map to the repeating sub-path as a string (for example "children${c}${d}").`),Sf("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(c)),i=s.slice(0,s.lastIndexOf(c)),a=r+c+G;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(Af,o),n.set(_f,null===o?null:new Nf(o,t))},preCommit(e,t,n){const o=e.recursionRegistry;if(null!==o)for(const t of o.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(_f)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",U)},apply(e,t,n){const o=n.get(Af)??null;null!==o&&e.addListPath(o.anchorList)}};let Ef=!1;function Mf(){Ef||(Ef=!0,xf||(xf=!0,Bc("recursion",$f)),Vc("recursion",Cf))}const Of={name:"recursion",install(){Mf()}};const Tf={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1&&-1===t.path.indexOf("#")?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let Rf=!1;function jf(e){return function(){const t=this.stateElement;if(!t)return;if(!0!==t.initialized)return;let n;try{t.createState("readonly",t=>{n=t[e]})}catch(t){return void console.warn(`[@wcstack/state] DCC getter "${e}" failed:`,t)}return n}}function Lf(e){return function(t){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})}):n.createState("writable",n=>{n[e]=t}))}}function Wf(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[e](...t)}).then(()=>o)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[e](...t)}),o})}}function Df(e){return e.startsWith("$")}function Bf(e,t){return Object.keys(e).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof e[n].value;return"method"===t?o:!o})}function zf(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||ne(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||ne(`${t} entries must be non-empty strings.`),e.startsWith("$")&&ne(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&ne(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Ff(e){Mc(e);const t=zf(e,L)??[],n=zf(e,W)??[],o=su(e),s=function(e){const t=e[q];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),r=[];for(const e of t){const t=o[e];if(void 0===t){if(s.has(e)){r.push(e);continue}ne(`${L} entry "${e}" is not declared on the state.${le(e,Bf(o,"value"))}`)}"function"==typeof t.value&&ne(`${L} entry "${e}" is a method. Declare it in ${W} instead.`)}for(const e of n){const t=o[e];void 0===t&&ne(`${W} entry "${e}" is not declared on the state.${le(e,Bf(o,"method"))}`),"function"!=typeof t.value&&ne(`${W} entry "${e}" is not a method. Declare it in ${L} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function qf(e,t,n){const o=e.tagName.toLowerCase();o.includes("-")||ne(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const r=Qe(e);null!==r&&"function"==typeof r.define||ne(`DCC: CustomElementRegistry is unavailable for "${o}".`),r.get(o)&&ne(`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 e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=Ff(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(o,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(o,c):{},p=s.tagNames.state,g=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(Q))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=Qe(this._shadow);return null!==e&&Ye(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(Rf||(Rf=!0,Bc("dcc",Tf)),t.setBindableEventMap(g.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}},m=su(n);for(const[e,t]of Object.entries(m)){if(Df(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Wf(e,o)}else n.get=jf(e),n.set=Lf(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:jf(e),set:Lf(e)});r.define(o,g)}async function Vf(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&ne(`"bind-component" cannot be used inside a [${Q}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await Nc(t);ne(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await kc(n,t.tagName.toLowerCase());ne(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}(o,t);qf(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const Hf={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Q)?Vf(e,t.host,t):null}};let Uf=!1;function Gf(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function Kf(e,t){for(const n of e)if(Gf(t,n.innerSegments))return n;return null}function Jf(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+c+n.join(c)}const Xf=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function Qf(e,t,n){const o=Xf.get(e);return void 0===o?null:(...e)=>{const s=e.slice();for(let e=0;e<o.length;e++){const n=o[e];"string"==typeof s[n]&&(s[n]=t(s[n]))}return n(s)}}const Yf=new WeakMap;function Zf(e,t,n){let o=Yf.get(e);void 0===o&&(o=new Map,Yf.set(e,o));const s=o.get(t);null!=s&&ne(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function eh(e,t){if(null===e)return!1;const n=Yf.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+c)||e.startsWith(t+c))return!0;return!1}const th=new WeakMap;const nh=[];function oh(e,t,n,o){if(t.length>0){const s=n.split(c),r=Kf(t,s);if(null!==r)return o&&r.readonly&&ne(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${P}.${r.innerSegments.join(c)}#${w}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${w} from the injection.`),Jf(r,s)}return e+c+n}function sh(e,t,n){let o=-1,s=null;for(const e of t){const t=e.outerPathInfo.path;t.length<=o||(n===t?(o=t.length,s=e.innerSegments.join(c)):n.startsWith(t+c)&&(o=t.length,s=e.innerSegments.join(c)+n.slice(t.length)))}if(e.length>o){if(n===e)return"";if(n.startsWith(e+c))return n.slice(e.length+1)}return s}function rh(e,t,n=nh){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)=>t[o](oh(e,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>t.$setAll(oh(e,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>t.$resolve(oh(e,n,o,s.length>1),...s);const o=Qf(s,t=>oh(e,n,t,!1),e=>t[s](...e));return null!==o?o:t[s]}return t[oh(e,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(t[s]=r,!0):(t[oh(e,n,s,!0)]=r,!0)),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const ih=new WeakMap,ah=[];const lh=new WeakMap,ch=new WeakSet;function dh(e){console.error(`[@wcstack/state] volume "${e.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>.`),e.onGrafted(null)}let uh=null;let fh=0;const hh=["$watch",q,"$scan","$listKeys",T,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],ph=new Set;function gh(e,t,n){const o=e.stateObject[t];if("function"==typeof o)try{const s=o.call(n());s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function mh(e,t,n,o,s,r=new Set){0===n.length&&ne(`Cannot build a mount record without host bindings for "${t}".`),Mc(s);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(c);a.has(n)&&ne("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(w)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++fh,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=su(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)1===e.innerSegments.length&&p.add(e.innerSegments[0]);const g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?u:l.outerPathInfo.path+c+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(e=>e.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function yh(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function wh(e,t){const n=Kf(e.entries,t);return null===n?null:Jf(n,t)}function bh(e,t){return e.markerBasePath+c+t}function vh(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+c+n;s.set(n,{accessorName:o,indexShift:re(r).wildcardCount-re(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function $h(e,t){return!e.injectedKeys.has(t)&&(!e.getterKeys.has(t)&&"function"==typeof e.stateObject[t]||!e.mappedKeys.has(t)&&(Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t)))}function xh(e,t){return`Path "${t}" in <${e.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${e.entries.filter(e=>e.innerSegments.length>0).map(e=>e.innerSegments.join(c)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${yh(t)}: path") or declare the key on the component state.`}const Sh=/^\$(\d+)$/;function Ih(e,t){if(!e.hasReadonlyEntries)return null;const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=yh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||$h(e,o))return null;const s=function(e,t){return Kf(e.entries,t)}(e,t.split(c));return null!==s&&s.readonly?s:null}function Ph(e,t){const n=Ih(e,t);if(null!==n){const o=0===n.innerSegments.length?"":c+n.innerSegments.join(c);ne(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${w}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${w} from the mount.`)}return kh(e,t)}function kh(e,t){const n=t[0];if("$"===n||"#"===n)return t;if(e.getterKeys.has(t)||e.setterKeys.has(t))return function(e,t){const n=t.split(c);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===d){o=e;break}if(-1===o)return vh(e,e.markerBasePath,t,t),bh(e,t);if($h(e,n[0]))return vh(e,e.markerBasePath,t,t),bh(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=wh(e,s);null===i&&ne(xh(e,t)),0===r.length&&ne(`Wildcard-terminal accessor "${t}" on mounted <${e.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+c+e.marker;return vh(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=yh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return bh(e,t);if($h(e,o))return bh(e,t);const s=wh(e,t.split(c));if(null!==s)return s;ne(xh(e,t))}const Nh=new Set(["prop","radio","checkbox"]);function Ah(e,t,n){let o;const s=Sh.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:re(kh(e,t)).wildcardCount-re(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=kh(e,t.statePathName),"for"===t.bindingType){const n=re(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+c+d,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&Nh.has(t.bindingType??"")&&!r.includes(w)&&null!==Ih(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:re(o),...i?{propModifiers:[...r,w]}:{}}:t}function _h(e,t,n,o,s){if(void 0===o)return;const r=re(n).wildcardCount-re(t).wildcardCount;return 0===r?o:(s.length<r&&ne(`Cannot resolve "${t}" 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 Ch(e,t,n){if(-1!==e.indexOf(d))return t;const o=t.split(c);let s=0;for(let e=0;e<o.length&&s<n.length;e++)o[e]===d&&(o[e]=String(n[s++]));return o.join(c)}const Eh=new WeakMap,Mh=new WeakMap;const Oh=new WeakMap;const Th=new FinalizationRegistry(function(e){const t=e.byMarker.get(e.marker);if(void 0!==t&&void 0===t.deref()&&e.byMarker.delete(e.marker),void 0!==e.getterPaths)for(const t of e.addedGetterPaths)e.getterPaths.delete(t)}),Rh=new WeakMap;function jh(e){return Rh.get(e)??null}let Lh=!1;function Wh(){Lh||(Lh=!0,xt=e=>Eh.has(e)?e.host:null)}function Dh(e){return Eh.get(e)??null}function Bh(e){return zh(e).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join(c),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]}))}function zh(e){const t=Oh.get(e);if(void 0===t)return[];const n=[];for(const e of t.values()){const t=e.deref();void 0!==t&&n.push(t)}return n}function Fh(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Oh.get(e);if(void 0===o)return null;const s=t.indexOf(c,n),r=-1===s?t.slice(n):t.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 qh=new WeakMap,Vh=new Set;function Hh(e,t,n,o){let s=qh.get(e);if(void 0===s){if(!o)return null;s=new Map,qh.set(e,s)}let r=s.get(t);if(void 0===r){if(!o)return null;r=new Map,s.set(t,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 Uh(e,t){if(!e.component.isConnected)return!1;const n=St(e.component)?.listIndex??null;if(null===t)return null===n;let o=n;for(;null!==o;){if(o===t)return!0;o=o.parentListIndex}return!1}function Gh(e,t,n,o){const s=Hh(e,t,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&Uh(n,t)?n:null}(r,o);if(null!==e)return{record:e,entry:r.entry}}let i=null,a=null;for(const e of s.holders){const r=e.ref.deref();void 0!==r?Uh(r,o)&&(null!==a&&ne(`[wcs/mount-export-ambiguous] "${t}${c}${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=e,a=r):s.holders.delete(e)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function Kh(e){const t=e.parentStateElement,n=St(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Bn](n,()=>{e.$postUpdate(o.exportedPath)})})}const Jh=new WeakMap,Xh=new WeakMap,Qh=new WeakMap,Yh=new WeakMap;function Zh(e,t){Xh.set(e,t);const n=[];for(let e=t?.listIndex.parentListIndex??null;null!==e;e=e.parentListIndex)n.push(e);Yh.set(e,n)}function ep(e){return St(e.component)??Xh.get(e)??null}function tp(e){return ep(e)?.listIndex??null}function np(e){ne(`The host row of <${e.component.tagName.toLowerCase()}> was removed.`)}function op(e){for(;null!==e;e=e.parentListIndex)if(Xt(e))return!0;return!1}function sp(e,t){return!e.component.isConnected&&(op(t)||!0===Yh.get(e)?.some(e=>Xt(e)))}class rp{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(e,t,n,o,s,r,i,a=!1){this.record=e,this.markerParentPath=t,this.listIndex=n,this.hostRow=o,this.isBase=s,this.receiver=r,this.handler=i,this.authorFacing=a}authorThis(e,t){return this.authorFacing?t:new Proxy(e,new rp(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return Po(re(this.markerParentPath+c+e),this.listIndex)}hostIndexes(){const e=this.listIndex??tp(this.record),t=this.hostRow??e;return(null===this.listIndex?t!==e||sp(this.record,t):op(t))&&np(this.record),t?.indexes??[]}resolveTreePath(e,t){return-1===t.indexOf(d)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==Jc(t).wildcardType&&!sp(this.record,this.listIndex)?t:Ch(e,t,this.hostIndexes())}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(this.resolveTreePath(e,kh(this.record,e)))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.hostIndexes(),o=this.receiver,s=this.handler,r=this.listIndex;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Ph(e,t):kh(e,t),a=_h(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const i=t;return(t,a,...l)=>{const c="$setAll"===i?Ph(e,t):kh(e,t),d=_h(0,t,c,void 0===a&&"$getAll"===i&&null===r&&null===Qc(s,re(c).wildcardPaths[0])?[]:a,n);return o[i](c,d,...l)}}const e=this.record,n=this.receiver,o=Qf(t,t=>this.resolveTreePath(t,kh(e,t)),e=>n[t](...e));return null!==o?o:this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return Yc(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(this.authorThis(e,n))}return this.receiver[this.resolveTreePath(t,kh(this.record,t))]}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n);const s=this.accessorNameFor(t);if(void 0!==s){this.record.setterKeys.has(s)||ne(`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(t)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,this.authorThis(e,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(e,t)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress(Po(re(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+c+t]=n}finally{this.handler.popAddress()}return!0}return e[t]=n,!0}return this.receiver[this.resolveTreePath(t,Ph(this.record,t))]=n,!0}has(e,t){if("string"!=typeof t)return Reflect.has(e,t);if("$"===t[0]||"#"===t[0])return!1;if(void 0!==this.accessorNameFor(t))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return!0;if("function"==typeof this.record.stateObject[t])return!0}try{return kh(this.record,t),!0}catch{return!1}}}function ip(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Jh.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Jh.set(e,n)),null===t)return n.noIndex??={...e.privateSnapshot};let o=n.byListIndex.get(t);return void 0===o&&(o={...e.privateSnapshot},n.byListIndex.set(t,o)),o}(e,t.listIndex):{};return new Proxy(i,new rp(e,s,t.listIndex,t.listIndex??tp(e),r,n,o))}function ap(e){if(null===tp(e))return e.component[e.stateProp];let t=Qh.get(e);if(void 0===t){const n={row:null};Qh.set(e,t=[lp(e,n),n])}return t[0]}function lp(e,t){const n=()=>{const n=ep(e);return void 0!==t&&Qh.get(e)?.[0]!==i&&n.listIndex!==t.row&&np(e),n},o=()=>{const t=n();return sp(e,t?.listIndex??null)&&np(e),t?.listIndex.indexes??[]},s=(t,n)=>-1===n.indexOf(d)?n:"partial"===Jc(n).wildcardType?Ch(t,n,o()):-1===n.indexOf("#")&&sp(e,tp(e))?np(e):n,r=(t,o)=>{let s;const r=n();return e.parentStateElement.createState(t,e=>{s=e[Bn](r,()=>o(e))}),s},i=new Proxy({},{get(t,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(e,t,n,o,s){return"$postUpdate"===t?t=>n("readonly",n=>n.$postUpdate(s(t,kh(e,t)))):(s,r,...i)=>{const a="$setAll"===t||"$resolve"===t&&i.length>0,l=a?Ph(e,s):kh(e,s),c=_h(0,s,l,"$resolve"===t?r??[]:r,o());return n(a?"writable":"readonly",e=>e[t](l,c,...i))}}(e,n,r,o,s);const i=Qf(n,t=>s(t,kh(e,t)),e=>r("readonly",t=>t[n](...e)));if(null!==i)return i;const a=t=>t["$"===n[0]?n:s(n,kh(e,n))],l=r("readonly",a);return"$"===n[0]||e.getterKeys.has(n)||"function"!=typeof e.stateObject[n]?l:function(...e){return r("writable",t=>a(t).apply(this,e))}},set:(t,n,o)=>("string"==typeof n&&r("writable",t=>{t["$"===n[0]?n:s(n,Ph(e,n))]=o}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return kh(e,n),!0}catch{return!1}}});return i}function cp(e,t){const n=Dh(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&ne(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&function(e){const t=kr(e);t.dispose();const n=[],o=document.createTreeWalker(e);for(;o.nextNode();)t.handleAddedNode(o.currentNode,n,e=>{console.error("[@wcstack/state] a binding failed to start again on the mount scope's re-initialization.",e)});Cl(n)}(t),function(e,t){Wh(),Eh.set(e,t),Rh.set(t,e);let n=Oh.get(t.parentStateElement);void 0===n&&(n=new Map,Oh.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Mh.get(t.component);void 0===o&&(o=new Map,Mh.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Th.register(t,{byMarker:n,marker:t.marker,getterPaths:t.parentStateElement.getterPaths,addedGetterPaths:t.addedGetterPaths}),t.parentStateElement.markHasMounts?.()}(t,e),t instanceof ShadowRoot&&function(e,t){const n=Bl.get(e);if(void 0!==n){if(n===t)return;ne("A state tree is already registered on this root.")}Bl.set(e,t)}(t,e.parentStateElement),function(e,t,n){const o=(t,n)=>Ah(e,t,n);ee(t,n?e=>function(e,t){for(let n=e;n!==t;n=n.parentNode)if(hr(n))return!0;return!1}(e,t):void 0);const s=St(e.component);Zh(e,s);mc(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,o),Ml(t,s,o)}(e,t,null!==n),function(e){if(e.exports.size>0||null===e.rootEntry)return;const t=new Set([...e.getterKeys,...e.setterKeys]);for(const n of t){let t;try{t=kh(e,n)}catch{continue}const o=t.indexOf(c+e.marker);if(-1===o)continue;const s=t.slice(0,o+1+e.marker.length),r=t.slice(s.length+1),i=t.slice(0,o)+c+r,a=re(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Hh(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),ru?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=St(e.component);if(e.delta>0&&null===t)return;const n=e.component.tagName.toLowerCase();for(const o of e.exports.values()){const s=`${n}|${o.exportedPath}`;if(Vh.has(s))continue;const r=re(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Bn](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Vh.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${e.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.`))}}(e),Kh(e),o=t,s=Promise.resolve(),zl.set(o,s),s.then(()=>Gl(o),()=>{})}function dp(e,t){Cl(up(e,t).rebindAddresses()),Kh(e)}function up(e,t){const n=kr(t),o=St(e.component);return Zh(e,o),n.forEachActiveBindingNode(e=>It(e,o)),n}function fp(e){for(let t=e.parentNode;null!==t;t=t.parentNode){const e=Dh(t);if(null!==e)return fp(e.component),void up(e,t)}}function hp(e,t){if(function(e){const t=Oh.get(e);return void 0!==t&&t.size>0}(t))for(const n of zh(t)){if(!pp(n.component,e))continue;const t=jh(n);null!==t&&dp(n,t)}}function pp(e,t){for(let n=t.firstNode;null!==n;n=n.nextSibling){if(n===e||n.contains(e))return!0;if(n===t.lastNode)break}return!1}const gp={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Fh(e,t.pathInfo.path);if(null!==s)return ip(s,t,n,o)}return Lc},readMissing(e,t,n,o,s){if(null===n){if(eh(e.rootNode??null,t.pathInfo.path))return;return Lc}if(!0===e.hasMounts){const n=Gh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=ip(e,Po(re(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return Lc},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=th.get(e);if(void 0===n||0===n.size)return null;const o=t+c;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&ne(`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 Lc},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Gh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=ip(e,Po(re(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return Lc},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Fh(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(c,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const s=-1===o?t:t.slice(0,o),r=-1===o?"":t.slice(o+1),i=e.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:e.delta}(e,o)}return 0},handlerScope(e,t,n,o,s){if(!0!==e.hasMounts)return s;const r=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=Eh.get(n);if(void 0!==e)return e;n=n.parentNode}return Eh.get(t)??null}(t,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(e,t,n){const o=function(e){return ih.get(e)??ah}(e);for(const s of o){const o=new Set,r={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(-1!==t.indexOf("#"))continue;const i=sh(s.mountPath,s.injections,t);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const e=lo(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(rh(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>eh(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){hp(t,e)}};let mp=!1;function yp(){mp||(mp=!0,Bc("scopes",gp),wu=Bh)}const wp=new WeakMap;function bp(e){let t=wp.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},wp.set(e,t)),t}function vp(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Yf.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function $p(e,t,n){if(t.slotRootNode===n)return!0;const o=t.mountPath;try{Zf(n,o,e)}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 Vl(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function xp(e,t){const n=e,o=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&ne('"mount" requires a non-empty tree path.');const t=re(e);for(const n of t.segments)0===n.length&&ne(`"mount" path "${e}" has an empty segment.`),n===d&&ne(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&ne(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],o=new Set;let r;try{r=Le(e)}catch(e){ne(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> has an invalid ${s.bindAttributeName}: ${e instanceof Error?e.message:String(e)}`)}for(const e of r){if(e.propSegments[0]!==P)continue;const r=e.propSegments.slice(1),i=e.statePathInfo,a=n=>ne(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> "${e.propName}: ${e.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==d&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${P}.<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)."),(e.inFilters.length>0||e.outFilters.length>0)&&a("an injection takes no filters."),e.propModifiers.some(e=>e!==w)&&a(`an injection accepts only #${w}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:e.propModifiers.includes(w)})}return n.sort((e,t)=>t.innerSegments.length-e.innerSegments.length),n}(n.getAttribute(s.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&ne('"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).`),Zf(o,r,e),Vl(o)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=o}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===Vl(o)&&function(e,t){const n=()=>{if(null!==Vl(e))return;const n=e.querySelectorAll(s.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${s.tagNames.state} mount="${t}"> 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=e.ownerDocument??e;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&vp(e,t),e.settleInitialization()};let l;try{await Promise.resolve(),l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const c=e.connectedRootNode??null;null!==c&&$p(e,t,c)?function(e,t,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};if(null!==t)return void Qp(t,a);Zp(),function(e,t){if(ch.has(e))return void dh(t);let n=lh.get(e);void 0===n&&(n=[],lh.set(e,n)),n.push(t)}(e,a)}(c,Vl(c),r,l,a,()=>$p(e,t,c),i):a(null)}const Sp={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=bp(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{Zf(n,t.mountPath,e),Vl(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,Yd}return xp(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=bp(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&Vl(n)===t.graftInfo.rootStateElement&&Kp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==wp.get(e)?.initializing)return;const t=e.getAttribute("mount");ne(`Cannot replace the state of <${s.tagNames.state} mount="${t}"> 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 "${t}" on the root state instead.`)},initializeFailed(e,t){!function(e){ch.add(e);const t=lh.get(e);if(void 0!==t){lh.delete(e);for(const e of t)dh(e)}}(t)},initializeFailureCleared(e,t){!function(e){ch.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=bp(e);return null!==t.graftInfo&&Kp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,vp(e,t)),e.clearConnectedRootNode(),!0}};let Ip=!1;const Pp=new WeakMap;function kp(e,t){let n=Pp.get(e);n||(n=new Set,Pp.set(e,n)),n.add(t)}const Np=new WeakMap;const Ap=new WeakMap,_p=new WeakMap;const Cp=new WeakMap;const Ep={isComplete:function(e,t){return!0===Pp.get(e)?.has(t)},isDeclared:function(e,t){return!0===Np.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=Ap.get(e);o||(o=new Map,Ap.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=_p.get(e);o||(o=new Map,_p.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)},rememberOverwrittenValue:function(e,t,n,o){let s=Cp.get(e);s||(s=new Map,Cp.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function Mp(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),o=Object.getOwnPropertyDescriptors(e);for(const e in o){const t=o[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,o),n}(e)}const Op=new WeakMap;class Tp{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=Op.get(e);return n?n.get(t)??null:null}(e,t)??ne("State element not found for web component.")}get(e,t,n){if("string"==typeof t){let e;return this._innerStateElement.createState("readonly",n=>{e=n[t]}),e}return Reflect.get(e,t,n)}set(e,t,n,o){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,o)}}const Rp=e=>()=>e;function jp(e,t,n,o){!function(e,t,n){let o=Op.get(e);o||(o=new Map,Op.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(Mp(o));const s=function(e,t){const n=new Tp(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Rp(s),enumerable:!0,configurable:!0}),kp(t,n),Lp(t,n)}function Lp(e,t){if(j in e){const n=e[j];"function"==typeof n?n.call(e,t).catch(e=>{ne(`Error in ${j}: ${e instanceof Error?e.message:String(e)}`)}):ne(`${j} is not a function.`)}}const Wp=new Set;function Dp(e,t){Wp.has(e)||(Wp.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function Bp(e){!function(e){const t=e.component.tagName.toLowerCase(),n=e.stateProp;let o=null;for(const s of e.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=su(e.stateObject);const i=o[r];let a;if(e.getterKeys.has(r)||e.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(e.mappedKeys.has(r)||e.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(e.stateObject,r))continue;a="an own data key"}const l=s.innerSegments.join(c);Dp(`${t}|${n}|${l}|entry`,`<${t}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${l}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(e);const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=zp(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;Dp(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}function zp(e){const t=e.rootEntry,n=St(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Bn](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Fp=new WeakMap;function qp(e,t){e.landInitialization(),ne(t)}async function Vp(e,t){const n=e;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?Je(a):null;null!==a&&null!==l||ne(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(s.bindAttributeName)||qp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(e=>n.hasAttribute(e));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&ne(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(e,t){let n=Np.get(e);n||(n=new Set,Np.set(e,n)),n.add(t)}(a,d);const u=Qe(a);null===u&&ne(`CustomElementRegistry is unavailable for <${l}>.`);const f=e.connectGeneration;if(await u.whenDefined(l.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await Ue(a),e.connectGeneration!==f)return!0;d in a||ne(`Component does not have property "${d}" for state binding.`);let h=a[d];"object"==typeof h&&null!==h||ne(`Component property "${d}" is not an object for state binding.`);const p=function(e,t){const n=Ap.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==p&&function(e,t){if(!e.hasAttribute(s.bindAttributeName))return!1;const n=ut(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(a,d)&&(a[d]=p,h=p),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(ut(a)??[]).some(e=>e.propSegments[0]===d)||qp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(s.bindAttributeName)){const s=(ut(a)??[]).filter(e=>e.propSegments[0]===d);if(s.length>0){const c=Vl(a.getRootNode())??qp(e,`No state tree found on this root for mount host <${l}>.`);let u=(o=a,r=d,Mh.get(o)?.get(r)??null);const f=null!==u;if(null===u&&(!function(e,t,n){const o=Cp.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;Cp.get(e).delete(t)}}(a,d,h),u=mh(a,d,s,c,h,function(e,t){return _p.get(e)?.get(t)}(a,d)),Bp(u)),t.mountRecord=u,n.parentNode!==i)return!1;try{cp(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!f){const e=lp(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),kp(a,d)}return Lp(a,d),function(e){const t=hh.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(G)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;ph.has(n)||(ph.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${e.stateProp} declares ${t.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.`))}(u),gh(u,"$connectedCallback",()=>ap(u)),!1}}jp(e,t.boundComponent,t.boundComponentStateProp,h)}var o,r;return!1}const Hp={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=Fp.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Fp.set(e,t)),t}(e);return Vp(e,t).then(n=>!!n||null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Fp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&dp(n,o)}),e.isConnected&&(fp(n.component),up(n,o)),gh(n,"$connectedCallback",()=>ap(n)),!0},disconnecting(e){const t=Fp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord;return gh(n,"$disconnectedCallback",()=>ap(n)),function(e){const t=Qh.get(e);void 0!==t&&(t[1].row=tp(e),Qh.delete(e))}(n),Kh(t.mountRecord),e.clearConnectedRootNode(),!0}};let Up=!1;function Gp(){Up||(Up=!0,tu("bindComponent",Hp),Ar=Ep)}function Kp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(rh(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function Jp(e,t,n,o){const s=n[V];if(void 0!==s){const n=yu(t),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=oh(t,o,n,!1),c=function(e,n,...s){l.call(rh(t,this,o),e,n,...s)};r.push({path:s,pathInfo:re(s),handler:c,order:1e6+a++}),i.add(s),e.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(e,r),e.addVolumeWatchPaths?.(i),n.start(e))}const r=n[K];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(oh(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[T];"function"==typeof i&&(!function(e,t){let n=ih.get(e);void 0===n&&(n=[],ih.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,injections:o,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[e]&&console.warn(`[@wcstack/state] volume "${t}" declares ${e}, which volumes do not support. Declare it on the root state instead.`);he?.volume(t,n,o.length)}function Xp(e,t,n,o=[]){Mc(n),function(e,t,n,o){const s=0===o.length?null:su(n);for(const e of o){const n=e.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||ne(`[wcs/mount-path-invalid] Volume "${t}" declares "${n}" as an accessor or a method and also injects it ("${P}.${n}: ${e.outerPathInfo.path}"). Rename one of them.`)}const r=n[V];if(void 0!==r){"object"==typeof r&&null!==r||ne(`${V} must be an object mapping state paths to handler functions.`);const e=yu(t);for(const[t,n]of Object.entries(r))"function"!=typeof n&&ne(`${V} entry "${t}" must be a function.`),e.assertValidPath(t)}const i=n[K];if(void 0!==i){"object"==typeof i&&null!==i||ne(`${K} 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)&&ne(`${K} entry "${n}" must map a list path to a field name or a key function.`);const r=oh(t,o,n,!1);e.listKeys?.has(r)&&ne(`${K} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[q]&&ne(`Volume "${t}" declares ${q}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&ne(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[U]&&ne(`Volume "${t}" declares ${U}, 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 e of Object.keys(su(n)))-1!==e.indexOf(G)&&ne(`Volume "${t}" declares "${e}", which uses "${G}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n,o);const{data:s,accessors:r}=function(e,t){const n={},o=new Map;for(const[s,r]of Object.entries(su(e)))s.startsWith("$")||t.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(e=>e.innerSegments[0]))),i=re(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;ne(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let t=0;t<i.segments.length-1;t++){const o=i.segments[t],s=""===n?o in e:void 0!==e[n+c+o];n=""===n?o:n+c+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;ne(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=s}),function(e,t){let n=th.get(e);void 0===n&&(n=new Set,th.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+c+n,i=s.get,a=s.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(rh(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(rh(t,this,o),e)}),e.defineTreeAccessor(r,l)}Jp(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(rh(t,e,o))}catch(e){return void console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)}n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n,injections:o}}function Qp(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=Xp(e,t.mountPath,t.volumeState,t.injections)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let Yp=!1;function Zp(){var e;Yp||(Yp=!0,yp(),Ip||(Ip=!0,tu("scopes",Sp)),Gp(),uh=Qp,e=eg,ql.includes(e)||ql.push(e))}function eg(e,t){(function(e){const t=Yf.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){ch.delete(e);const n=lh.get(e);if(void 0===n||0===n.length||null===uh)return;lh.delete(e);const o=uh;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const tg={name:"scopes",install(){Zp(),Uf||(Uf=!0,tu("dcc",Hf))}},ng=/^@@wcs-(?:for|if|elseif|else):[^-]/,og=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,sg=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,rg=/^@@wcs-text-start:(.+)$/;function ig(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ag(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const e=n.currentNode;t(e.data)&&o.push(e)}return o}const lg=e=>ng.test(e),cg=e=>og.test(e),dg=e=>og.test(e)||sg.test(e);function ug(e){if("else"===e.bindingType)return"else:";let t=`${e.bindingType}: ${e.statePathName}`;for(const n of e.outFilters){const e=n.literals??n.args;t+=`|${n.filterName}`,n.args.length>0&&(t+=`(${n.args.map((t,n)=>"string"==typeof e[n]?`'${t.split("'").join("'\"'\"'")}'`:t).join(",")})`)}return t}function fg(e){const t=e.fragment.cloneNode(!0);for(const n of e.nodeInfos){const o=cc(at(e.fragment,n.nodePath));if(null===o)continue;const s=at(t,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return t}class hg extends ou{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=vu.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static find(e){const t=s.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t,o){const r=o??e.ownerDocument;n.seen&&function(e){const t=new Map;for(const n of ag(e,cg)){if(null===n.parentNode)continue;const[,e,o]=og.exec(n.data),s=o.split(":")[0],r=n.previousSibling?.data,i=`@@wcs-${e}-end:${o}`;if(r!==`@@wcs-${e}:${s}`&&t.get(r)!==s)for(let e=n;null!==e;){const t=e.nextSibling;e.remove(),e=e.data===i?null:t}else"for"===e&&t.set(i,s)}}(r);const i=document.createElement("script");i.setAttribute("type","application/json"),i.textContent=ig(JSON.stringify(t)),e.appendChild(i);for(const[t,n]of function(e){const t=new Map,n=[e];for(;n.length>0;)for(const e of ag(n.shift(),lg)){const o=e.data,s=o.slice(o.indexOf(":")+1);if(t.has(s))continue;const r=Ql(s);null!==r&&(t.set(s,r),n.push(r.fragment))}return t}(r)){const o=document.createElement("template");o.setAttribute("id",t),o.setAttribute(s.bindAttributeName,ug(n.parseBindTextResult)),o.content.appendChild(fg(n)),e.appendChild(o)}const a=e.ownerDocument,l=Array.from(Xa);if(l.length>0){const t={};for(let e=0;e<l.length;e++){const n=l[e];if(!n.isConnected||n.ownerDocument!==a)continue;const o=Ja(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const e of o)r[e.propName]=e.value;t[s]=r}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ig(JSON.stringify(t)),e.appendChild(n)}}Qa()}static removeBlockBoundaryComments(e){for(const t of ag(e,dg))t.remove()}static removeStructuralComments(e){for(const t of ag(e,lg))t.remove()}static restoreTextBindings(e){for(const t of ag(e,e=>rg.test(e))){const e=rg.exec(t.data)[1],n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(s.tagNames.ssr),o=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&o.set(t,e)}}for(const e of ag(t,cg)){const t=og.exec(e.data),n=`@@wcs-${t[1]}-end:${t[2]}`;let o=e.nextSibling;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=e}e.remove()}hg.restoreTextBindings(t);const r=e=>{for(const t of ag(e,lg)){const e=o.get(t.data.split(":")[1]);if(e){const n=document.createElement("template"),o=e.getAttribute(s.bindAttributeName);o&&n.setAttribute(s.bindAttributeName,o);const i=document.importNode(e.content,!0);if(i.childNodes.length>0)n.content.appendChild(i);else for(const t of Array.from(e.childNodes))n.content.appendChild(document.importNode(t,!0));r(n.content),t.parentNode.replaceChild(n,t)}}};r(t);const i=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of i)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const pg={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=s.tagNames.state,n=s.tagNames.ssr,o=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of o){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",vu),hg.buildContent(o,hg.extractStateData(e),e.getRootNode()),e.parentNode?.insertBefore(o,e)}Qa()},reset:function(){Jl.clear(),Qa(),n.seen=!1}};const gg=new Set(["for","if","elseif","else"]);function mg(e){const[,t,n]=og.exec(e),[o,...s]=n.split(":");return"for"===t?{type:t,uuid:o,path:s[0],index:parseInt(s[1],10),nodes:[]}:{type:t,uuid:o,path:s.join(":"),index:null,nodes:[]}}function yg(e){const t=[];for(const n of e)if(n.nodeType===Node.ELEMENT_NODE){const e=n;e.hasAttribute(s.bindAttributeName)&&t.push(e),Array.from(e.children).some(e=>e.localName===s.tagNames.state&&ft(e))||t.push(...gt(e))}else null!==ze(n)&&t.push(n);return t}function wg(e){const[t,n,o]=wt(e),s=new Pr;return{bindingInfos:s.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:t,bindingSession:s,deferredSpreads:o}}const bg=/^\s*@@\s*(?:wcs-text)?\s*:/;function vg(e,t){for(const n of t)"event"===n.bindingType||gg.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&bg.test(n.node.data))&&e.push(n)}function $g(e,t){const n=[];for(let o=0;o<e.nodes.length;o++){const s=t.get(e.nodes[o]);s?o+=s.nodes.length+1:n.push(e.nodes[o])}return n}function xg(e,t,n,o,s,r){t.length>0&&(e.spreads=t);for(const e of t)bt(e.node);El(t,n,o,s,r)}function Sg(e,t){const n=Ql(t),o=Vl(e.getRootNode());let s=null;if(n&&o){const{statePathName:e,outFilters:t}=n.parseBindTextResult;o.createState("readonly",n=>{const o=_r(n[e],lt(t,"output"));Array.isArray(o)&&(s=o)})}return s}function Ig(e,t){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[e]}:${t}`}function Pg(e,t,n){const o=Ig(t,n);return ag(e,e=>e===o)[0]??null}function kg(e,t){const n=e,o=t.templates,r=new Map;for(const[e,t]of o)for(const n of ag(t.content,lg))r.set(n.data.slice(n.data.indexOf(":")+1),e);const i=new Set(ht(e));if(i.size>0)for(const e of ag(n,lg)){const t=e.data.slice(e.data.indexOf(":")+1);let n=e.parentNode;for(;null!==n&&!i.has(n);)n=n.parentNode;null===n||r.has(t)||r.set(t,n)}const a=new Map,l=[];for(const[e,t]of o){let n=Le(t.getAttribute(s.bindAttributeName)||"")[0];const o=n.bindingType,i=r.get(e),c=a.get(i);"else"===o&&c&&(n={...c,outFilters:[...c.outFilters,ec()],bindingType:"else"}),"if"===o||"elseif"===o?a.set(i,n):"else"===o&&a.set(i,null),l.push([e,t,n])}for(const[e,t,o]of l.reverse()){const s=document.importNode(t.content,!0),r="for"===o.bindingType?o.statePathName:void 0;uc(s),"string"==typeof r&&ic(s,r),mc(n,s,r);Xl(e,n,{fragment:s,parseBindTextResult:o,nodeInfos:dc(s)})}}const Ng={hydrate:async function(e){await Tl(e);const t=e.querySelectorAll(s.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${vu}". Falling back to full render.`),hg.cleanupDom(e),!1}const n=function(e){const t=[];for(const n of ag(e,dg)){if(!cg(n.data)){t.pop();continue}const e=mg(n.data),o=t.at(-1);if("for"===e.type&&o&&o.uuid!==e.uuid)return[e,o];t.push(e)}return null}(document.body);if(null!==n){const[t,o]=n;return console.warn(`[@wcstack/state] SSR: "for: ${t.path}" in "${o.type}: ${o.path}" (known limitation). Falling back to full render.`),hg.cleanupDom(e),!1}for(const n of t)kg(e,n);hg.restoreTextBindings(document.body);const o=function(e){const t=[];for(const n of ag(e,cg)){const e=mg(n.data);e.start=n;const o=n.data.replace("-start:","-end:");let s=n.nextSibling;for(;s&&(s.nodeType!==Node.COMMENT_NODE||s.data!==o);)e.nodes.push(s),s=s.nextSibling;t.push(e)}return t}(document.body),r=new Map,i=function(e,t,n=new Map){const o=new Map,s=[],r=new Map(t.map(e=>[e.start,e])),i=new Set;for(let e=t.length-1;e>=0;e--){const n=yg(t[e].nodes).filter(e=>!i.has(e));for(const e of n)i.add(e);t[e].subscribers=n}for(const i of t){const t=$g(i,r);if(0===t.length)continue;const a=t.some(e=>lg(e.data));if(a){const e=document.createComment(`wcs-row-end:${i.uuid}`);i.nodes[i.nodes.length-1].after(e),t.push(e)}const{bindingInfos:l,subscriberNodes:c,bindingSession:u,deferredSpreads:f}=wg(i.subscribers);for(const e of l)if(e.node!==e.replaceNode){const n=t.indexOf(e.node);n>=0&&(t[n]=e.replaceNode)}const h=Ia(t,a);sa(h,u),Tr(h,l),Lr(h,c);const p=l.filter(e=>Sa(e,-1));if(zr(h,p),"for"===i.type&&null!==i.index){const t=Pg(e,"for",i.uuid);if(t){let e=n.get(i.uuid);if(!e){const s=Sg(t,i.uuid)??i.path;e=o.get(s),e||o.set(s,e=[]),n.set(i.uuid,e)}const r=e[i.index]??=Mt(null,i.index);Wa(t,r,h),Da(t,h.lastNode),pa(t,h);const a=Po(re(i.path+"."+d),r);Wr(h,a),u.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),vg(s,l),xg(h,f,a,u,l,p)}}else{const t=i.start.previousSibling,n=t?.data===Ig(i.type,i.uuid)?t:Pg(e,i.type,i.uuid);if(n){pa(n,h);const e=St(n);Wr(h,e),u.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),vg(s,l),xg(h,f,e,u,l,p)}}}return s}(document.body,o,r);hg.removeBlockBoundaryComments(document.body);const a=[];for(const e of t)e.parentNode&&(a.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());const[,l,c]=function(e,t){return wt(gt(e),t)}(document.body),u=[],f=[],h=kr(document.body),p=h.initialize(l);El(c,null,h);for(const e of p)if("event"!==e.bindingType)if(gg.has(e.bindingType))f.push(e);else{if(e.statePathName.includes(d))continue;u.push(e)}for(const e of f)if("for"===e.bindingType){const t=po(e),n=Vl(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=_r(n[e.statePathName],e.outFilters);if(Array.isArray(o)){const n=r.get(e.uuid);n&&mn(o,n),Nn(t,o),s=e.node,i=o,Ra.set(s,wn(i)),jn(t,o)}var s,i})}Cl([...u,...i]);for(const{el:e,parent:t,next:n}of a)t.insertBefore(e,n);const g=new Map;for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))g.set(t.getAttribute("data-wcs-ssr-id"),t);for(const t of e.querySelectorAll(s.tagNames.ssr))for(const[e,n]of Object.entries(t.hydrateProps)){const t=g.get(e);if(t)for(const[e,o]of Object.entries(n))Ar?.isDeclared(t,e)||(t[e]=o)}for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))t.removeAttribute("data-wcs-ssr-id");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=hg.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Hl(e.rootNode);const t=hg.extractStateData(e),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",vu),hg.buildContent(n,t,e.rootNode),e.parentNode?.insertBefore(n,e)}};let Ag=!1;function _g(){Ag||(Ag=!0,Wl=Ng,function(e){if(!du.includes(e)){du.push(e);for(const t of fu())e(t)}}(e=>{e.get(s.tagNames.ssr)||e.define(s.tagNames.ssr,hg)}),function(){const t=globalThis;void 0===t[e]&&(t[e]=pg)}())}const Cg={name:"ssr",install(){_g()}},Eg=new WeakMap,Mg=new Set,Og=new Set;function Tg(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Rg(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function jg(e){return Eg.get(e)}function Lg(e){Wg(e),Eg.delete(e)}function Wg(e){Mg.delete(e),Og.delete(e)}const Dg=new WeakSet;let Bg=0;function zg(e){return jg(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Fg(e){if(0===Og.size)return;if(t=e.absolutePathInfo.stateElement,!Og.has(t))return;var t;const n=zg(e);if(void 0!==n)for(const e of n)qg(e)}function qg(e){Dg.has(e)||(Dg.add(e),Bg++)}function Vg(e){return!!Dg.delete(e)&&(Bg--,!0)}const Hg=/^(?:0|[1-9]\d*)$/;function Ug(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Gg(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return null;const t=Object.getPrototypeOf(e);if(Array.isArray(e)){return t===Array.prototype&&Reflect.ownKeys(e).every(t=>"length"===t||"string"==typeof t&&Hg.test(t)&&Ug(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Ug(e,t))?"object":null}function Kg(e,t){const n=Gg(e);if(null===n)return e;const o=e,s=t.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(e.length):null===Object.getPrototypeOf(e)?Object.create(null):{},t.set(o,r);for(const e of Object.keys(o))r[e]=Kg(o[e],t);return r}function Jg(e){return Kg(e,new Map)}function Xg(e,t,n){if(Object.is(e,t))return!0;const o=Gg(t);if(null===o||"object"!=typeof e||null===e)return!1;const s=e,r=t;if("array"===o){if(!Array.isArray(e)||e.length!==t.length)return!1}else if(Array.isArray(e)||Object.keys(s).length!==Object.keys(r).length)return!1;if(Gg(e)!==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 t=0;t<e.length;t++)if(!Xg(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&Xg(s[e],r[e],n))}function Qg(e,t){return Xg(e,t,new Map)}const Yg=new WeakMap;function Zg(e,t){if("function"!=typeof t)return;const n=Yg.get(t);void 0===n?Yg.set(t,new Set([e])):n.add(e)}function em(e,t){return"function"==typeof t&&!0===Yg.get(t)?.has(e)}const tm={"read-source":e=>`${H} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-rows":e=>`${H} could not read the rows of "from" for "${e}". Nothing was folded or written.`,"read-output":e=>`${H} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${H} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${H} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${H} could not write the output "${e}".`},nm={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function om(e,t,n){null!==Pt&&Pt({type:"state:watch-error",phase:t,path:`${H}.${e}`,error:n})}function sm(e,t,n){console.error(`[@wcstack/state] ${tm[n](e)}`,t),om(e,nm[n],t)}function rm(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function im(e,t){t.then(void 0,()=>{}),sm(e,new TypeError(`${H} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const am=new WeakSet;const lm="[wcs/scan-declaration-invalid]",cm=Object.freeze([]);function dm(e){return`${H} entry "${e}"`}function um(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function fm(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${d}${d}`)?`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.${ce}`}function hm(e,t,n){0===n.length&&ne(`${lm} ${e} "${t}" must be a non-empty state path.${ce}`),n.startsWith("$")&&ne(`${lm} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ce}`),n.includes("@")&&ne(`${lm} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ce}`),n in Object.prototype&&ne(`${lm} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ce}`);const o=re(n);for(const s of o.segments)0===s.length&&ne(`${lm} ${e} ${t} "${n}" has an empty path segment.${ce}`);return o.wildcardCount>u&&ne(`${lm} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function pm(e,t,n,o){const s=dm(e);0===e.length&&ne(`${lm} ${H} entry name must be a non-empty string.${ce}`),(e.includes(c)||e.includes(d))&&ne(`${lm} ${s} must be a flat property name ("${c}" and "${d}" are not allowed). The output is a property the runtime owns.${ce}`),e.startsWith("$")&&ne(`${lm} ${s} must not start with "$" (reserved namespace).${ce}`),e in Object.prototype&&ne(`${lm} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ce}`),t.has(e)&&ne(`${lm} ${s} conflicts with a getter declared on the state.${ce}`),n.has(e)&&ne(`${lm} ${s} conflicts with a setter declared on the state.${ce}`),o.has(e)&&ne(`${lm} ${s} conflicts with the ${q} entry of the same name — each output has exactly one owner.${ce}`)}function gm(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!em(e,o)&&ne(`${lm} ${dm(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ce}`)}function mm(e,t,n,o,s,r){const i=dm(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&ne(`${lm} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ce}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||ne(`${lm} ${i} "on" must be a non-empty event-token name.${ce}`),n.has(e)||ne(`${lm} ${i} on "${e}" is not declared in ${z}.${le(e,n)}${ce}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&ne(`${lm} ${i} "from" must be a state path string.${ce}`);const u=hm(i,"from",d),f=um(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&ne(fm(i,"from",d,f));const h=um(u,s);return null!==h&&ne(function(e,t,n){return`${lm} ${e} from "${t}" ${n===t?"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.${ce}`}(i,d,h)),(d===e||d.startsWith(e+c))&&ne(`${lm} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ce}`),{kind:"path",path:d,pathInfo:u}}function ym(e,t,n,o){if(void 0===t)return cm;const s=dm(e);Array.isArray(t)||ne(`${lm} ${s} "resetOn" must be an array of state paths.${ce}`);const r=[];for(const e of t){"string"!=typeof e&&ne(`${lm} ${s} "resetOn" must contain only state path strings.${ce}`);const t=hm(s,"resetOn",e);t.wildcardCount>0&&ne(`${lm} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${ce}`);const i=um(t,o);null!==i&&ne(fm(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&ne(`${lm} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ce}`),"path"===n.kind&&e.startsWith(n.path+c)&&ne(`${lm} ${s} resetOn "${e}" 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.${ce}`),r.push(e)}return r}function wm(e,t,n=null){const o=e[H];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&ne(`${lm} ${H} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ce}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(su(e)))"function"==typeof n.get?s.add(t):"function"==typeof n.set&&i.add(t),"function"==typeof n.set&&r.add(t),"function"==typeof n.value&&a.set(t,n.value);const l=function(e){Mc(e);const t=e[q];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),c=[];let d=0;for(const[e,u]of Object.entries(o)){pm(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&ne(`${lm} ${dm(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ce}`);const o=u;gm(e,a,o);const f=mm(e,o,t,s,i,n);"initial"in o||ne(`${lm} ${dm(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ce}`),"function"!=typeof o.fold&&ne(`${lm} ${dm(e)} fold must be a function.${ce}`);const h=ym(e,o.resetOn,f,s);c.push({name:e,source:f,fold:o.fold,initial:o.initial,resetOn:h,order:d++})}return function(e){const t=new Set(e.map(e=>e.name)),n=new Map;for(const o of e){for(const e of o.resetOn){const n=re(e).segments[0];t.has(n)&&ne(`${lm} ${dm(o.name)} resetOn "${e}" reads the ${H} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ce}`)}if("path"===o.source.kind){const e=o.source.pathInfo.segments[0];t.has(e)&&n.set(o.name,e)}}for(const e of n.keys()){const o=[e];let s=n.get(e);for(;void 0!==s&&o.length<=t.size;)s===e&&ne(`${lm} ${H} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ce}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function bm(e){const t=e.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[e.name];i="threw";const a=function(e){return Dg.has(e)}(e),l=a&&!Qg(n,e.initial)?Jg(e.initial):n,c=t(l,o,...s);if(rm(c))return void im(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Zg(e.name,c)),a&&Vg(e)}catch(t){sm(e.name,t,i)}}}function vm(e,t,n){const o=function(e,t){Lg(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Rg(n,e.source.path,e);for(const t of e.resetOn)Rg(o,t,e),"event"===e.source.kind&&Rg(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Eg.set(e,r),r}(e,t);for(const o of t){const t=n.get(o.name);"event"===o.source.kind&&void 0!==t&&(o.resetOn.some(n=>t.includes(n)&&ri().hasQueuedPath(e,n))&&qg(o))}const s=new Set;for(const t of o.byFromPath.keys())s.add(t),e.setPathInfo(t,"prop","scan");for(const t of o.byResetPath.keys())e.setPathInfo(t,"prop","scan");return s.size>0?s:null}const $m="scanEntries",xm={order:8,validate(e,t,n){const o=wm(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set($m,o)},applyEarly(e,t,n){const o=n.get($m)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=Jg(n.initial);e[n.name]=t,Zg(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&zo(e,n.source.tokenName).subscribe(bm(n))}(e,o))},register(e,t,n){const o=n.get($m)??null,s=function(e){const t=new Map,n=jg(e);if(void 0!==n)for(const e of n.entries)Vg(e)&&t.set(e.name,e.resetOn);return Lg(e),t}(e);e.setScanPaths?.(null===o?null:vm(e,o,s))}};let Sm=!1;const Im=Object.freeze([]),Pm=Object.freeze([]);function km(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??Im,i=e.dynamicDependency.get(n)??Im,a=t.byFromPath.get(n)??Pm;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Nm=Symbol("wcs-stream-last-notified-uncertain"),Am=new WeakMap;function _m(e,t){const n=Am.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Cm(e,t){const n=Am.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:Nm,error:Object.is(o.error,null)?null:Nm})}const Em=new Set;function Mm(e){Em.delete(e)}const Om=new WeakMap;function Tm(e){return Om.get(e)??new Map}function Rm(e){Mm(e);const t=Om.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Cm(e,n.name)}const jm=(e,t)=>t,Lm=new Set;function Wm(e,t){Mc(t);const n=t[q];if(void 0===n)return void _m(e,Lm);"object"==typeof n&&null!==n||ne(`${q} must be an object mapping stream names to stream definitions.`);const o=new Map,s=su(t);for(const[r,i]of Object.entries(n)){0===r.length&&ne(`${q} entry name must be a non-empty string.`),r.includes(c)&&ne(`${q} entry "${r}" must be a flat property name ("${c}" is not allowed).`),r.includes(d)&&ne(`${q} entry "${r}" must be a flat property name ("${d}" is not allowed).`),r.startsWith("$")&&ne(`${q} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&ne(`${q} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(r)&&ne(`${q} entry "${r}" conflicts with a getter declared on the state.`),e.setterPaths.has(r)&&ne(`${q} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||ne(`${q} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||em(r,a)||ne(`${q} 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&&ne(`${q} entry "${r}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&ne(`${q} entry "${r}" fold must be a function.`),l&&!("initial"in n)&&ne(`${q} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&ne(`${q} entry "${r}" args must be a function.`);const u={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??jm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in t||(t[r]=u.definition.initial,Zg(r,u.definition.initial)),o.set(r,u)}!function(e,t){Om.set(e,t)}(e,o),_m(e,new Set(o.keys()))}const Dm=new WeakMap,Bm=new WeakMap;function zm(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=Tm(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&Tm(e).has(n),ownKeys:()=>Array.from(Tm(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=Tm(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){ne(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){ne(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Fm(e){const t=Dm.get(e);if(void 0!==t)return t;const n=zm(e,J,e=>e.status);return Dm.set(e,n),n}function qm(e){const t=Bm.get(e);if(void 0!==t)return t;const n=zm(e,X,e=>e.error);return Bm.set(e,n),n}function Vm(e){Dm.delete(e),Bm.delete(e)}let Hm=null;function Um(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}const Gm={read(e,t){!function(e,t){null!==Hm&&Hm.add(eo(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===J?Um(Fm(e),t.pathInfo.segments):n===X?Um(qm(e),t.pathInfo.segments):Lc},get:(e,t)=>t===J?Fm(e.stateElement):t===X?qm(e.stateElement):Lc};let Km=0,Jm=null,Xm=0;const Qm=new WeakMap;function Ym(e){Km=e+1}function Zm(){Km=0}function ey(e){if(Km>0){const t=Jm??=new Map;Km>(t.get(e)??0)&&t.set(e,Km),Xm=Math.max(Xm,Km)}}function ty(e,t){return Qm.get(e)?.get(t)??0}async function ny(e,t,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 e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError(`[@wcstack/state] ${q}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",r)}}function oy(e){dy();const t=Tm(e);if(0!==t.size){!function(e){Em.add(e)}(e);for(const n of t.values())sy(e,n)}}function sy(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=Hm,s=new Set;let r;Hm=s;try{e.createState("readonly",e=>{r=n(e)})}finally{Hm=o}r instanceof Promise&&ne(`${q} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${J}${c}${t.name}`,a=`${X}${c}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||ne(`${q} entry "${t.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&&ne(`${q} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);!function(e,t){const n=jg(e);if(void 0!==n&&0!==t.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==t.name)continue;const s=km(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&ne(`[wcs/scan-feedback-loop] ${q} entry "${t.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.`)}}}(e,t),e.createState("writable",e=>{e[t.name]=t.definition.initial}),Zg(t.name,t.definition.initial),ry(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{const o=s.fold(e[t.name],n);e[t.name]=o,Zg(t.name,o)})},done(){ry(e,t,"done",null)},fail(o){ry(e,t,"error",o),n.abort()}};ny(s.source,o,n.signal,r)}function ry(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return Am.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=Am.get(e);void 0===s&&(s=new Map,Am.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${J}${c}${t.name}`),i&&e.$postUpdate(`${X}${c}${t.name}`)}))}function iy(e){const t=Em;if(0===t.size)return;const n=[];for(const o of t)for(const t of Tm(o).values()){let s=-1;for(const n of t.depAddresses)e.has(n)&&(s=Math.max(s,ty(e,n)));s>=0&&s<=32&&n.push({stateElement:o,entry:t,depth:s})}try{for(const{stateElement:e,entry:o,depth:s}of n)if(t.has(e)&&Tm(e).get(o.name)===o){Ym(s);try{sy(e,o)}catch(n){o.controller?.abort(),t.has(e)&&Tm(e).get(o.name)===o&&ry(e,o,"error",n)}}}finally{Zm()}}let ay=!1;const ly=new WeakMap,cy={order:20,apply(e,t){var n;Vm(e),Rm(n=e),Mm(n),Om.delete(n),Wm(e,t),void 0!==t[q]&&e.attachAddressHooks?.("streams",q)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return oy(e),void ly.set(e,e.connectGeneration??0)}n===e.connectGeneration&&ly.get(e)!==n&&oy(e)}},deactivate(e){Rm(e),Vm(e)}};function dy(){ay||(ay=!0,Bc("streams",Gm),Vc("streams",cy),ti(iy,20))}const uy=new WeakMap;function fy(e,t,n){let o=uy.get(e);void 0===o&&(o=new Map,uy.set(e,o)),o.set(t,n)}const hy=new Map;function py(e,t){hy.has(e)||hy.set(e,t)}function gy(e){return hy.get(e)}const my=new WeakMap,yy=new WeakMap,wy=new Set,by=new Map;function vy(e){return my.get(e)??by}function $y(e){wy.add(e),function(e){const t=Eg.get(e);void 0!==t&&(Tg(t)&&Mg.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Og.add(e))}(e)}function xy(){return wy}function Sy(e,t){let n=yy.get(e);void 0===n&&(n=new Map,yy.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}const Iy=new Map;function Py(e){return yy.get(e)??Iy}function ky(e){0===e.length&&ne(`[wcs/watch-declaration-invalid] ${V} entry name must be a non-empty state path.`),e.startsWith("$")&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" must not start with "$" (reserved namespace).${ce}`),e.includes("@")&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ce}`),e in Object.prototype&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=re(e);for(const n of t.segments)0===n.length&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" has an empty path segment.${ce}`);return t.wildcardCount>u&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Ny(e,t){const n=t[V];if(void 0===n)return null;"object"==typeof n&&null!==n||ne(`[wcs/watch-declaration-invalid] ${V} must be an object mapping state paths to handler functions.${ce}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${t}" must be a function.${ce}`);const n=ky(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){my.set(e,t)}(e,o),s.size>0?s:null}const Ay={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||py(n,o)},swapped(e,t,n){var o;o=n,hy.has(o)&&py(t,gy(n))}};function _y(e){for(let t=e;null!==t;t=t.parentListIndex)if(Xt(t))return!0;return!1}function Cy(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[zn](Po(t.wildcardParentPathInfos[i],r)),l=fn(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=ao(o,i,t.wildcardCount);if(l!==c&&!Vt(l,c)){if(Xt(c))return"gone";s="replaced"}r=l}return s}function Ey(e,t,n){const o=new Map;for(const s of n){const n=Cy(e,t,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(),e=>e.row)}const My=Object.freeze([]);function Oy(e,t,n,o){let s=e.get(n);return void 0===s&&(s={stateElement:t,entry:n,rows:[],reset:!1,depth:o},e.set(n,s)),s.depth=Math.max(s.depth,o),s}function Ty(e,t){let n=0;for(;n<e.indexes.length-1&&e.indexes[n]===t.indexes[n];)n++;return e.indexes[n]-t.indexes[n]}function Ry(e,t){return t.has(e.stateElement)&&!0===jg(e.stateElement)?.entries.has(e.entry)}function jy(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Ly(n,e))||Vg(t)}function Ly(e,t){return ri().hasQueuedPath(e,t)}function Wy(e,t){!function(e,t,n){if(0!==Bg)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=zg(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||Vg(t)}}(e,t,Ly)}function Dy(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function By(e,t,n){if(!Ry(e,n))return jy(e),null;const{stateElement:o,entry:s}=e;if(e.reset)return{group:e,next:s.initial};const r=s.source;if(function(e,t){for(const n of t.pathInfo.cumulativePaths)if(e.getterPaths.has(n))return!0;return!1}(o,r))return function(e,t,n){if(am.has(e))return;am.add(e);const o=`[wcs/scan-source-computed] ${H} entry "${t}" 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}`),om(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=Tm(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?e.rows:Ey(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Ty)){let n;try{n=Dy(t,r,e)}catch(e){sm(s.name,e,"read-source");continue}const o=a(l,n,gy(e.absAddress),...e.indexes);if(rm(o))return void im(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){sm(s.name,e,i.failure)}return i.plan}function zy(e,t){const{group:n}=e;if(!Ry(n,t))return void jy(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Vg(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!Qg(o,s.initial):!Object.is(o,e.next)){const o=n.reset?Jg(s.initial):e.next;t[s.name]=o,Zg(s.name,o)}})}catch(e){sm(s.name,e,"write")}}function Fy(e,t){if(Wy(e,t),0===Mg.size)return My;const n=new Map;for(const o of e){const s=o.absolutePathInfo.stateElement;if(!t.has(s))continue;const r=jg(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=ty(e,o),l=r.byFromPath.get(i.path);if(void 0!==l){let e=[];if(i.wildcardCount>0){if(null===o.listIndex)continue;e=lo(o.listIndex,i.wildcardCount)}for(const t of l)Oy(n,s,t,a).rows.push({absAddress:o,indexes:e})}const c=r.byResetPath.get(i.path);if(void 0!==c)for(const e of c)Oy(n,s,e,a).reset=!0}if(0===n.size)return My;const o=Array.from(n.values()).sort((e,t)=>e.entry.order-t.entry.order),s=[];try{for(const n of o){Ym(n.depth);const o=By(n,e,t);null!==o&&s.push(o)}}finally{Zm()}return s}function qy(e){Yy(),(0!==vy(e).size||0!==Py(e).size||function(e){const t=Eg.get(e);return void 0!==t&&Tg(t)}(e))&&($y(e),function(e){const t=[];for(const n of vy(e).values())Vy(e,n)&&t.push(n);for(const n of Py(e).values())for(const o of n)Vy(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{fy(e,to(e,o.pathInfo,null),n[o.path])}catch(t){Uy(e,o.path,"prime",t)}})}(e))}function Vy(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Hy={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Uy(e,t,n,o){console.error(`[@wcstack/state] $watch ${Hy[n]} "${t}" threw.`,o),null!==Pt&&Pt({type:"state:watch-error",phase:n,path:t,error:o})}function Gy(e){const t=xy(),n=function(e){const t=Xm;return t>0&&(Qm.set(e,Jm),Jm=null,Xm=0),t}(e);try{if(n>32){Wy(e,null);const t=Array.from(e,e=>e.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:t}),void(null!==Pt&&Pt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}if(0===t.size)return void Wy(e,t);!function(e,t){if(0!==e.length)try{for(const n of e)Ym(n.group.depth),zy(n,t)}finally{Zm()}}(Fy(e,t),t),function(e,t){const n=[],o=new Set;for(const s of e){const e=s.absolutePathInfo.stateElement;if(!t.has(e))continue;const r=s.absolutePathInfo.pathInfo.path;o.add(r);const i=vy(e).get(r),a=Py(e).get(r);if(void 0===i&&void 0===a)continue;const l=void 0===i?[]:[i];void 0!==a&&l.push(...a);for(const t of l){let o=[];if(t.pathInfo.wildcardCount>0){if(null===s.listIndex)continue;o=lo(s.listIndex,t.pathInfo.wildcardCount)}n.push({stateElement:e,entry:t,absAddress:s,indexes:o})}}if(0===n.length)return;n.sort(Jy);const s=function(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(0===s.entry.pathInfo.wildcardCount)continue;const r=e[o-1];(_y(s.absAddress.listIndex)||r?.entry===s.entry&&Ky(r.indexes,s.indexes)||s.entry.pathInfo.wildcardParentPaths.some(e=>t.has(e)))&&(n??=new Set).add(s.entry)}if(null===n)return e;const o=new Set;for(const t of n){const n=e.filter(e=>e.entry===t),s=n[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(Ey(e,t.pathInfo,n));for(const e of n)s.has(e)||o.add(e)})}catch(e){Uy(0,t.path,"evaluate",e);for(const e of n)o.add(e)}}return e.filter(e=>!o.has(e))}(n,o);try{for(const n of s){if(!t.has(n.stateElement))continue;const o=vy(n.stateElement).get(n.entry.path)===n.entry,s=!0===Py(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(Ym(ty(e,n.absAddress)),Xy(n))}}finally{Zm()}}(e,t)}finally{hy.clear()}}function Ky(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Jy(e,t){if(e.entry.order!==t.entry.order)return e.entry.order-t.entry.order;const n=Math.min(e.indexes.length,t.indexes.length);for(let o=0;o<n;o++)if(e.indexes[o]!==t.indexes[o])return e.indexes[o]-t.indexes[o];return e.indexes.length-t.indexes.length}function Xy(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Vy(t,n);try{t.createState("writable",e=>{let i;try{i=function(e,t,n){if(0===t.pathInfo.wildcardCount)return e[t.path];return e.$resolve(t.path,n)}(e,n,s)}catch(e){return void Uy(0,n.path,"evaluate",e)}const a=r?function(e,t){return uy.get(e)?.get(t)}(t,o):gy(o);r&&fy(t,o,i),null!==Pt&&Pt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Uy(0,n.path,"handler",e)}}let Qy=!1;function Yy(){Qy||(Qy=!0,Bc("watch",Ay),Vc("watch",Zy),ti(Gy,10),ei(ey),mu={assertValidPath:ky,addEntries:Sy,start:qy})}const Zy={order:10,register(e,t){var n;n=e,wy.delete(n),Wg(n),my.delete(n),function(e){uy.delete(e)}(e);const o=Ny(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?V:H)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&qy(e)},deactivate(e){var t;t=e,wy.delete(t),Wg(t)}},ew={name:"temporal",install(){Yy(),Sm||(Sm=!0,Vc("scan",xm),ei(Fg)),dy()}},tw=new Set,nw=new Set;function ow(e){tw.has(e)||(tw.add(e),console.warn(`[@wcstack/state] [wcs/v4-migration] ${e} See "Preparing for 4.0" in the @wcstack/state README.`))}const sw=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],rw=["formats","diagnostics","temporal","list-keys","scopes","recursion","ssr","devtools"],iw=(e,t,n)=>ow(`${e}: "${t}" is not one of its options, or not ${n}. 4.0 throws on it.`);function aw(e,t){if(nw.has(e))return;nw.add(e);ow(`${"$"===e[0]?"":"filter "}"${e}" is removed in 4.0: write "${t}" (its name since 3.2).`)}const lw={substr:'filter "substr" is removed in 4.0: write slice(start, start + length) — slice takes the end index, not a length.'},cw={$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."},dw=new WeakSet,uw={state(e){const t=e;for(const e of Object.keys(_c))void 0!==t[e]&&aw(e,_c[e]);var n;void 0!==t[H]&&ow(`"${H}" is removed in 4.0: rewrite it with $watch (state paths) or $on (event tokens).`),dw.has(e)||(!function(e){if(null==e)return;if("object"!=typeof e)return void iw("state","$behavior","an object");const t=e;for(const e in t){const n=t[e];sw.includes(e)&&"boolean"==typeof n?n!==s[e]&&ow(`$behavior takes effect in 4.0; 3.x does not read it and runs this state with ${e}: ${!n}. Until you upgrade, pass bootstrapState({ ${e}: ${n} }).`):iw("$behavior",e,"a boolean")}}(t.$behavior),void 0!==(n=t.$features)&&(Array.isArray(n)&&!n.some(e=>!rw.includes(e))||ow(`$features is not an array of add-on names (${rw.join(", ")}). 4.0 throws on it.`)))},volumeLoaded(e){dw.add(e)},renamed:aw,removed(e){ow(lw[e])},volume(e,t,n){n>0&&ow(`volume "${e}" 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(cw))void 0!==t[n]&&ow(`volume "${e}" declares ${n}: 4.0 does not graft a volume that declares it. ${cw[n]}`)}};function fw(e){!function(e){he=e}(uw)}const hw=[rf,ew,Of,tg,Cg,Ou,Vu];await function(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(hw),fw(),gu(e,t)}();
1
+ const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.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;const r=Symbol.for("wcstack.binder");const i=Symbol.for("wcstack.binder.pending"),a=Symbol.for("wcstack.binder.taken");function l(){const e=function(){const e=globalThis[r];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;const t=function(){const e=globalThis;let t=e[i];return void 0===t&&(t=[],e[i]=t),t}();if(0===t.length)return;const n=t.splice(0,t.length),o=function(){const e=globalThis;let t=e[a];return void 0===t&&(t=new WeakSet,e[a]=t),t}();for(const t of n)o.add(t),e.bind(t)}const c=".",d="*",u=128,f=128,h=100,p="#",g="|",m="prevent",y="stop",w="ro",b="init",v="sync",$="else",x="...",S="on",I="eventToken",P="state",k="command",N="class",A="attr",_="style",C={};for(let e=0;e<u;e++)C[`$${e+1}`]=e;const E=Object.freeze(C),M="$connectedCallback",O="$disconnectedCallback",T="$renderedCallback",R="$errorCallback",j="$stateReadyCallback",L="$bindables",W="$commands",D="$commandTokens",B="$command",z="$eventTokens",F="$on",q="$stream",V="$watch",H="$scan",U="$recursion",G="**",K="$listKeys",J="$streamStatus",X="$streamError",Q="data-wc-definition",Y=/\{\{\s*(.+?)\s*\}\}/g,Z=new Set(["SCRIPT","STYLE"]);function ee(e,t){if(!s.enableMustache)return;!function(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o)e.parentElement&&Z.has(e.parentElement.tagName)||te(e,t)}(e,t);const n=Array.from(e.querySelectorAll("template"));for(const e of n)if("http://www.w3.org/2000/svg"===e.namespaceURI){const t=document.createElement("template"),n=Array.from(e.childNodes);for(let e=0;e<n.length;e++){const o=n[e];t.content.appendChild(o)}for(const n of e.attributes)t.setAttribute(n.name,n.value);e.replaceWith(t),ee(t.content)}else ee(e.content)}function te(e,t){const n=e.data;if(Y.lastIndex=0,!Y.test(n)||t?.(e))return;Y.lastIndex=0;const o=document.createDocumentFragment();let s,r=0;for(;null!==(s=Y.exec(n));){s.index>r&&o.appendChild(document.createTextNode(n.slice(r,s.index)));const e=s[1];o.appendChild(document.createComment(`@@: ${e}`)),r=s.index+s[0].length}r<n.length&&o.appendChild(document.createTextNode(n.slice(r))),e.parentNode.replaceChild(o,e)}function ne(e){throw new Error(`[@wcstack/state] ${e}`)}const oe=new Map;let se=0;function re(e){let t=oe.get(e);if(void 0!==t)return t;-1!==e.indexOf(G)&&ne(`[wcs/recursion-unsupported] "${e}" uses "${G}", 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(e){let t=1;for(let n=0;n<e.length;n++)e[n]===c&&t++;return t}(e);return n>512&&ne(`[wcs/binding-syntax] "${e}" 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.`),t=Object.freeze(new ie(e)),oe.set(e,t),t}class ie{id=++se;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(e){const t=t=>e===t?this:re(t),n=e.split("."),o=[],s=[],r=[],i={},a=[],l=[],c=[],u=[];let f="",h="",p=0;for(let e=0;e<n.length;e++)f+=n[e],n[e]===d&&(r.push(f),i[f]=p,a.push(t(f)),l.push(h),c.push(t(h)),u.push(e),p++),o.push(f),s.push(t(f)),h=f,f+=".";const g=r.length>0?r[r.length-1]:null,m=o.length>1?o[o.length-2]:null;this.path=e,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=c,this.wildcardParentPathInfoSet=new Set(c),this.wildcardPositions=u,this.lastWildcardPath=g,this.lastWildcardInfo=g?t(g):null,this.parentPath=m,this.parentPathInfo=m?t(m):null,this.wildcardCount=p}}function ae(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;const o=new Array(t.length+1),s=new Array(t.length+1);for(let e=0;e<=t.length;e++)o[e]=e;for(let n=1;n<=e.length;n++){s[0]=n;for(let r=1;r<=t.length;r++){const i=e[n-1]===t[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let e=0;e<=t.length;e++)o[e]=s[e]}return o[t.length]}function le(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ae(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ce=" Validate statically: npx @wcstack/lint <file>.",de=new Set(["if","elseif","else","for"]);function ue(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}function fe(e){if(0===e.length)return"";let t="";for(let n=0;n<e.length;n++){const o=e[n];n>0&&(t+="|"),t+=`${o.filterName}(${ue(o.args,o.literals??o.args)})`}return t}let he=null;const pe=new Map([["not",()=>e=>!e]]),ge=new Map([["not",[0,0]]]),me={input:new Map,output:new Map},ye={input:new Map,output:new Map},we={input:new Map,output:new Map},be=new Map;function ve(e,t,n,o){const s=me[e],r=ye[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}const i=o??{},a=we[e];for(const[e,n]of[...a])Object.prototype.hasOwnProperty.call(t,n)&&i[e]!==n&&a.delete(e);for(const e of Object.keys(i))a.set(e,i[e]);be.clear()}function $e(e,t,n,o=t){const s=we[n].get(e);void 0!==s&&he?.renamed(e,s);const r=s??e,i=`${r}${ue(t,o)}:${n}`,a=be.get(i);if(void 0!==a)return a;const l=me[n].get(r)??pe.get(r);if(void 0===l){const t=0===me[n].size?' No formatting filters are installed — add them with installFeatures([...]) from "@wcstack/state/features/formats".':"";ne(`[wcs/filter-unknown] filter not found: ${e}.${le(e,function(e){return[...new Set([...pe.keys(),...me[e].keys()])]}(n))}${t}${ce}`)}const c=ye[n].get(r)??ge.get(r);void 0!==c&&(t.length<c[0]||t.length>c[1])&&ne(t.length<c[0]?`[wcs/filter-arity] filter "${e}" requires at least ${c[0]} argument(s) (${t.length} given).${ce}`:`[wcs/filter-arity] filter "${e}" accepts at most ${c[1]} argument(s) (${t.length} given).${ce}`);const d=l(t,o);return be.set(i,d),d}function xe(e,t,n){const o=-1===t?e.length:t;let s=0;for(;s<o&&/\s/.test(e[s]);)s++;const r=-1===n?0:n;let i=e.length;for(;i>r&&/\s/.test(e[i-1]);)i--;return e.slice(s,i)}const Se=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function Ie(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:Se.test(e)?Number(e):e)}function Pe(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=xe(o,i,a);t.push(e),n.push(Ie(e,r)),o="",r=!1,i=-1,a=-1};for(let t=0;t<e.length;t++){const n=e[t];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&&ne(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ce}`);const c=xe(o,i,a);return(c||r)&&(t.push(c),n.push(Ie(c,r))),{args:t,literals:n}}const ke=e=>e.trim(),Ne=e=>"'"===e||'"'===e;function Ae(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(null!==n)s===n&&(n=null);else if(Ne(s))n=s;else if(s===t)return o}return-1}function _e(e,t){const n=[];let o=null,s=0;for(let r=0;r<e.length;r++){const i=e[r];null!==o?i===o&&(o=null):Ne(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}function Ce(e,t,n){const o=n??e.join("|");return e.map(e=>{const n=Ae(e,"(");let s=function(e,t){let n=null,o=-1;for(let s=0;s<e.length;s++){const r=e[s];null!==n?r===n&&(n=null):Ne(r)?n=r:r===t&&(o=s)}return o}(e,")");if(-1===s&&(s=e.lastIndexOf(")")),-1!==n&&-1===s&&ne(`[wcs/binding-syntax] Invalid filter format: missing closing parenthesis in "${e}".${ce}`),-1!==s&&-1===n&&ne(`[wcs/binding-syntax] Invalid filter format: missing opening parenthesis in "${e}".${ce}`),-1!==s&&s<n&&ne(`[wcs/binding-syntax] Invalid filter format: ")" comes before "(" in "${e}".${ce}`),-1!==s&&e.slice(s+1).trim().length>0){const t=e.slice(s+1).trim();ne(`[wcs/binding-syntax] "${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,s+1)}|${t}").${ce}`)}const r=(-1===n?e:e.substring(0,n)).trim();if(0===r.length&&ne(`[wcs/binding-syntax] an empty filter in "${o}" — remove the extra "|" or name the filter.${ce}`),r.includes(p)){const[e,n]=r.split(p);ne("input"===t?`[wcs/binding-syntax] "${r}" is not a filter name: a modifier list "${p}${n}" comes before the input filters, not inside one — write "<property>${p}${n}|${e}".${ce}`:`[wcs/binding-syntax] "${r}" is not a filter name: "${p}" cannot appear in one. Modifiers belong on the left side of the binding, before the ":" — write "${e}" here.${ce}`)}if(-1===n)return{filterName:r,args:[],literals:[]};return{filterName:r,...Pe(e.substring(n+1,s))}})}const Ee=new Map;function Me(e){const t=Ae(e,g);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ee.has(s)?r=Ee.get(s):(o=_e(s,g).map(ke),r=Ce(o,"input",e),Ee.set(s,r))):n=e.trim();const i=n.split(p).map(ke);i.length>2&&ne(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${p}" — write "${i[0]}${p}${i.slice(1).join(",")}".${ce}`);const[a,l]=i,d=a.split(c).map(ke);d.length>1&&""===d[0]||0!==a.length&&!d.some(e=>0===e.length)||ne(`[wcs/binding-syntax] "${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).${ce}`);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(ke):[],inFilters:r}}const Oe=new Map;function Te(e){const t=Ae(e,g);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Oe.has(s)?r=Oe.get(s):(o=_e(s,g).map(ke),r=Ce(o,"output",e),Oe.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&ne(`"${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(c),l=a?i.slice(1):i;(l.length>0&&l.split(c).some(e=>0===e.length)||!a&&0===l.length)&&ne(`[wcs/binding-syntax] "${e}": 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).${ce}`);return{statePathName:i,statePathInfo:re(i),outFilters:r}}const Re=new Set([$,"if","elseif","for",x]),je=new Set([N,A,_,k,I,P]);function Le(e){const[...t]=function(e){return _e(e,";")}(e).map(ke).filter(e=>e.length>0),n=t.map(e=>{const t=Ae(e,":");-1===t&&ne(`[wcs/binding-syntax] Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.${ce}`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(p)[0].split(g)[0].trim();if(s!==n&&Re.has(s)&&ne(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ce}`),n===$){o.length>0&&ne(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ce}`);const t=re("#else");return{propName:$,propSegments:[$],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===x){0===o.length&&ne(`[wcs/binding-syntax] Invalid spread binding "${e}": spread target path is required.${ce}`);const t=Te(o);return t.outFilters.length>0&&ne(`[wcs/binding-syntax] Invalid spread binding "${e}": filters are not allowed on spread targets.${ce}`),{propName:x,propSegments:[x],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Te(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Te(o);return{...Me(n),...e,bindingType:s}}{const e=Te(o),t=Me(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||je.has(o[0]))&&ne(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...je].join(", ")}).${ce}`),{...t,propName:o.join(c),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===I||t.propSegments[0].startsWith(S)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>de.has(e.bindingType))&&ne(`[wcs/template-syntax] Invalid bindText: "${e}". '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">).${ce}`)}return n}const We=new WeakMap,De=new Set([s.commentTextPrefix,s.commentForPrefix,s.commentIfPrefix,s.commentElseIfPrefix,s.commentElsePrefix]),Be=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function ze(e){const t=We.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),o=Be.exec(n);if(null===o)return null;const r=o[1]||s.commentTextPrefix;return De.has(r)?(We.set(e,o[2]),o[2]):null}function Fe(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Te(e),bindingType:"text"}}const qe=new WeakMap,Ve=new WeakSet;let He=0;async function Ue(e){const t=function(e){let t,n=qe.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++He,promise:o,resolve:t},qe.set(e,n),Ve.has(e)&&n.resolve(),n}(e);await t.promise}function Ge(e){const t=qe.get(e);void 0===t?Ve.add(e):t.resolve()}const Ke=new WeakMap;function Je(e){const t=Ke.get(e);if(void 0!==t)return t;let n=null;try{if(e.nodeType!==Node.ELEMENT_NODE)return n;const t=e,o=t.tagName.toLowerCase();if(o.includes("-"))return n=o;if(t.hasAttribute("is")){const e=t.getAttribute("is");if(e.includes("-"))return n=e}return n}finally{Ke.set(e,n)}}function Xe(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Qe(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Xe(t);if(void 0!==n)return Xe(n)}return Xe(globalThis.customElements)}function Ye(e,t){e.upgrade?.(t)}function Ze(e){try{if(null===e||"object"!=typeof e&&"function"!=typeof e)return null;const t=e,n=t.addEventListener,o=t.removeEventListener,s=t.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=ot(s.properties,et);if(null===r)return null;const i=void 0===s.inputs?new Map:ot(s.inputs,tt);if(null===i)return null;const a=void 0===s.commands?new Map:ot(s.commands,nt);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function et(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&("string"==typeof t.event&&0!==t.event.length&&(void 0===t.getter||"function"==typeof t.getter))}function tt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.attribute||"string"==typeof t.attribute)}function nt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&0!==t.name.length&&(void 0===t.async||"boolean"==typeof t.async)}function ot(e,t){if(!Array.isArray(e))return null;const n=new Map;for(const o of e){if(!t(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function st(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:re(n),inFilters:[],outFilters:[],bindingType:"prop"}}function rt(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function it(e,t,n={}){const o=n.allowDeferred??!0;if(!t.some(e=>"spread"===e.bindingType))return t;const r=[],i=new WeakSet;for(const n of t){if("spread"!==n.bindingType){r.push(n);continue}e.nodeType!==Node.ELEMENT_NODE&&ne("Spread binding requires an element node.");const t=e,s=Je(t);null===s&&ne(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Qe(t);null===a&&ne(`CustomElementRegistry is unavailable for <${s}>.`);if(void 0===a.get(s)){o||ne(`Spread binding "${n.statePathName}" requires <${s}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Ye(a,t);const l=Ze(t);null===l&&ne(`Spread binding "${n.statePathName}" requires <${s}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const e of l.knownProperties.keys()){if(d.has(e))continue;d.add(e);const t=st(e,c);i.add(t),r.push(t)}for(const e of l.declaredInputs.keys()){if(d.has(e))continue;d.add(e);const t=st(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=rt(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=rt(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(s.debug&&i.has(r[t])){const o=r[a.get(n)],s=e.nodeType===Node.ELEMENT_NODE?`<${e.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[t].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[t])}return l}function at(e,t){let n=e;for(let e=0;e<t.length;e++){let o=t[e];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function lt(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.literals??s.args;n.push({filterName:s.filterName,args:s.args,literals:r,filterFn:$e(s.filterName,s.args,t,r)})}return n}function ct(e){return{...e,inFilters:lt(e.inFilters,"input"),outFilters:lt(e.outFilters,"output")}}const dt=new WeakMap;function ut(e){return dt.get(e)||null}function ft(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(s.bindAttributeName)}function ht(e){const t=[],n=e.querySelectorAll(`${s.tagNames.state}[bind-component]`);for(const o of n){if(!ft(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function pt(e,t){for(let n=0;n<t.length;n++){const o=t[n];if(o!==e&&o.contains(e))return!0}return!1}function gt(e){const t=[],n=ht(e),o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(s.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==ze(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();){const e=o.currentNode;n.length>0&&pt(e,n)||t.push(e)}return t}const mt=new WeakSet;function yt(e,t,n,o){const s=it(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Je(e):null;return null===n&&ne("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}mt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=lt(o.inFilters,"input"),s=lt(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:e});else{const r=e.nodeType===Node.TEXT_NODE?e:document.createTextNode("");n.push({...o,inFilters:t,outFilters:s,node:e,replaceNode:r})}}return n}(e,function(e,t){return void 0===t?e:e.map(e=>null!=e.uuid?e:t(e))}(s,o));return function(e,t){dt.set(e,t)}(e,r),Ge(e),{bindings:r,deferred:null}}function wt(e,t){const n=[],o=[];for(const s of e){if(mt.has(s))continue;const e=yt(s,Yl(s),{allowDeferred:!0},t);null===e.deferred?n.push(...e.bindings):o.push(e.deferred)}return[e,n,o]}function bt(e){mt.add(e)}function vt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){mt.delete(e)}(t);return yt(t,n,{allowDeferred:!1},o).bindings}const $t=new WeakMap;let xt=null;function St(e){let t=e;for(;t;){const e=$t.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==xt&&t instanceof ShadowRoot&&(n=xt(t)),t=n}return null}function It(e,t){null!==t?$t.set(e,t):$t.delete(e)}let Pt=null;let kt=0;function Nt(){return`u${(kt++).toString(36)}`}let At=0,_t=0;const Ct=Symbol("wcs.listIndex.noValue");class Et{uuid=Nt();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;cacheStamp=0;ref;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ct,this._index=t,this._version=At,this._chainGeneration=_t}get index(){return this._index}set index(e){this._index=e,this._version=++At,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}set homeParentListIndex(e){this._homeParentListIndex=e}get value(){return this._value}set value(e){this._value=e}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=At),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===_t||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=_t),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++At,_t++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Mt(e,t,n=e){return new Et(e,t,n)}function Ot(e,t){e.reparent(t)}function Tt(e){return e.homeParentListIndex}function Rt(e,t){e.homeParentListIndex=t}function jt(e){return e?.cacheStamp}function Lt(e,t){const n=e,o=n.value,s=o!==Ct&&!Object.is(o,t);return o!==t&&(Wt.get(o)?.delete(n.ref),function(e,t){if("object"!=typeof e||null===e||null===t.parentListIndex)return;let n=Wt.get(e);void 0===n?(n=new Set,Wt.set(e,n)):n.size>=(Dt.get(n)??8)&&(Bt(n,t,!0),Dt.set(n,2*n.size+8));n.add(t.ref??=new WeakRef(t))}(t,n)),n.value=t,s}const Wt=new WeakMap,Dt=new WeakMap;function Bt(e,t,n=!1){const o=[];return e?.forEach(s=>{const r=s.deref();void 0===r||n&&Ft(r)?e.delete(s):r!==t&&o.push(r)}),o}const zt=new WeakSet;function Ft(e){for(let t=e;null!==t;t=t.parentListIndex)if(zt.has(t))return!0;return!1}function qt(e){return e.value}function Vt(e,t){const n=e.value;return n!==Ct&&n===t.value}let Ht=0;const Ut=new WeakSet;function Gt(e){Ut.add(e)}function Kt(e){return Ut.has(e)}const Jt=new WeakMap;function Xt(e){return zt.has(e)}const Qt=new WeakMap;const Yt=new WeakMap,Zt=new WeakMap;function en(e,t){return!0===Qt.get(t)?.has(e)}function tn(e,t){return en(e,t)||Ft(t)}const nn=new WeakMap;function on(e){nn.delete(e)}function sn(e,t,n){const o=Object(qt(t)),s=qt(n);for(const t in s)if(s[t]===e&&o[t]!==e)return!1;return!0}function rn(e,t){return!tn(e,t)&&nn.get(t)!==Ht}const an=new WeakMap,ln=new WeakMap;const cn=new WeakSet;function dn(e,t){const n=(o=e,Bt(Wt.get(o.value),o));var o;if(0===n.length)return n;const s=new Set(Jt.get(t()));return n.filter(t=>t.position===e.position&&!s.has(t)&&!Ft(t))}function un(e,t,n){const o=Tt(t),s=t.parentListIndex;return null!==o&&o!==s&&!tn(e,o)&&sn(e,o,s)?o:function(e,t,n,o){return null!==t&&null!==o&&o!==n&&!!zt.has(t)&&!(!rn(e,o)||o.position!==t.position)&&!en(e,t)&&Vt(o,t)}(e,o,s,n)||function(e,t,n){return t!==n&&null!==t&&null!==n&&t.position===n.position&&tn(e,t)&&rn(e,n)}(e,s,n)?n:null}function fn(e){const t=Jt.get(e);return void 0===t?null:t}function hn(e,t){const n=Jt.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o&&!Kt(e)){const s=null!==t&&o.parentListIndex!==t&&nn.get(t)!==Ht,r=un(e,o,t);if(null!==r&&cn.has(e)){cn.delete(e);const t=[...e];Gt(t),Jt.set(t,n),bn(e,t);const o=n.map((t,n)=>{const o=Mt(r,n);return Lt(o,e[n]),o});return Jt.set(e,o),o}if(null!==r)for(const e of n)Ot(e,r);else if(s){!function(e,t){let n=an.get(e);void 0===n?(n=new Set,an.set(e,n)):n.size>=(ln.get(e)??8)&&(n.forEach(t=>{tn(e,t)&&n.delete(t)}),ln.set(e,2*n.size+8));for(const e of t)n.add(e)}(e,[o.parentListIndex,t]);const s=o.parentListIndex;if(null!==s&&s.position===t.position&&!sn(e,s,t)&&sn(e,t,s))for(const e of n)Ot(e,t)}}return n}const pn=new WeakSet;function gn(e){pn.delete(e)}function mn(e,t,n=!1){null!==t?(n?pn.add(t):gn(t),Jt.set(e,t)):Jt.delete(e)}const yn=new WeakMap;function wn(e){let t=yn.get(e);return void 0===t&&(t={value:e},yn.set(e,t)),t}function bn(e,t){const n=yn.get(e);void 0!==n&&(n.value=t,yn.delete(e))}const vn=new WeakMap,$n=new WeakMap,xn=new Set,Sn=new WeakMap,In=new WeakMap;function Pn(e){const t=e.absolutePathInfo.stateElement;let n=$n.get(t);return void 0===n&&(n=new WeakMap,$n.set(t,n)),n}function kn(e){return vn.get(e)??[]}function Nn(e,t){const n=vn.get(e);vn.set(e,t),In.delete(e);const o=Pn(e);n!==t&&void 0!==n&&o.get(n).delete(e);const s=o.get(t);void 0===s?o.set(t,new Set([e])):s.has(e)||(s.size>=(Sn.get(s)??8)&&(s.forEach(e=>{An(e.listIndex)&&s.delete(e)}),Sn.set(s,Math.max(8,2*s.size))),s.add(e))}function An(e){for(let t=e;null!==t;t=t.parentListIndex)if(Xt(t))return!0;return!1}function _n(e,t){const n=Pn(e).get(t);return void 0===n?xn:(n.forEach(e=>{An(e.listIndex)&&n.delete(e)}),n)}function Cn(e,t){return!In.has(e)&&(In.set(e,t),!0)}function En(e){return vn.has(e)}const Mn=new WeakMap;let On=null,Tn=0;function Rn(e){return Mn.get(e)??[]}function jn(e,t){null===On?Mn.set(e,t):On.set(e,t)}function Ln(){Tn++,null===On&&(On=new Map)}function Wn(){if(0!==Tn&&(Tn--,!(Tn>0||null===On))){for(const[e,t]of On)Mn.set(e,t);On=null}}function Dn(e){return(On?.has(e)??!1)||Mn.has(e)}const Bn=Symbol("$$setLoopContext"),zn=Symbol("$$getByAddress"),Fn=Symbol("$$hasByAddress"),qn=Symbol("$$connectedCallback"),Vn=Symbol("$$disconnectedCallback"),Hn=Symbol("$$updatedCallback"),Un=Symbol("$$errorCallback"),Gn=new WeakMap,Kn=new WeakMap;class Jn{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Xn(e,t){if(null===t){let t=Kn.get(e);return void 0!==t||(t=new Jn(e,null),Kn.set(e,t)),t}{let n=Gn.get(t);void 0===n&&(n=new WeakMap,Gn.set(t,n));let o=n.get(e);return void 0!==o||(o=new Jn(e,t),n.set(e,o)),o}}const Qn=new WeakMap;function Yn(e,t){let n=Qn.get(e);void 0===n&&(n=new Map,Qn.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Zn(e,t)),n.set(t,o)),o}class Zn{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function eo(e,t){return Xn(Yn(e,t.pathInfo),t.listIndex)}function to(e,t,n){return Xn(Yn(e,t),n)}const no=new WeakMap;function oo(e,t){null===t?no.delete(e):no.set(e,t)}function so(e){return no.get(e)||null}const ro=new Map;function io(e,t){let n,o;if(0===e.wildcardCount||0===t.wildcardCount)return 0;if(1===e.wildcardCount&&t.wildcardCount>0&&t.wildcardPathSet.has(e.path))return 1;e.id<t.id?(n=e,o=t):(n=t,o=e);const s=`${n.path}\t${o.path}`;let r=ro.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,ro.set(s,r),r}function ao(e,t,n){return t<0||t>=n?null:e.at(t-n)}function lo(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const co=new WeakMap;function uo(e){const t=St(e.node);if(null===t)return null;let n=co.get(t);if(void 0===n)n=new WeakMap,co.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=io(t.pathInfo,e.statePathInfo);return n>0&&(o=ao(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const fo=new WeakMap;function ho(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=so(n);null===t?ne(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function po(e,t){let n=null;if(n=fo.get(e)||null,null!==n)return n;const o=ho(e,t),s=uo(e),r=Vl(o);return null===r&&ne("No state tree found on this root for binding."),n=to(r,e.statePathInfo,s),fo.set(e,n),n}function go(e){fo.delete(e)}const mo=new WeakMap;function yo(e,t){const n=mo.get(e);void 0===n?mo.set(e,t):n instanceof Set?n.add(t):n!==t&&mo.set(e,new Set([n,t])),null!==Pt&&Pt({type:"state:binding-added",absoluteAddress:e,binding:t})}function wo(e,t){const n=mo.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&mo.delete(e),null!==Pt&&Pt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const bo=new WeakMap;function vo(e){const t=mo.get(e);return void 0!==t?t:null!==e.listIndex?bo.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const $o=new WeakMap,xo=new WeakMap;class So{pathInfo;listIndex;_parentAddress;_rowAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t,this._rowAddress=null!==t&&e.lastSegment===d}get parentAddress(){const e=this._parentAddress;if(void 0!==e&&(!this._rowAddress||e.listIndex===this.listIndex.parentListIndex))return e;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let n=null;n=this.pathInfo.segments[this.pathInfo.segments.length-1]===d?this.listIndex?.parentListIndex??null:this.listIndex;const o=Po(t,n);return void 0!==e&&!Io(o,this.listIndex)&&Io(e,this.listIndex)?e:this._parentAddress=o}}function Io(e,t){const n=e.pathInfo;let o=qt(e.listIndex);for(const e of n.segments.slice(n.wildcardPositions[n.wildcardCount-1]+1))o=Object(o)[e];return fn(o)?.[t.index]===t}function Po(e,t){if(null===t){let t=xo.get(e);return void 0!==t||(t=new So(e,null),xo.set(e,t)),t}{let n=$o.get(t);void 0===n&&(n=new WeakMap,$o.set(t,n));let o=n.get(e);return void 0!==o||(o=new So(e,t),n.set(e,o)),o}}const ko=new WeakMap;function No(e){let t=null;if(t=ko.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=uo(e);null===n&&ne(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=Po(e.statePathInfo,n)}else t=Po(e.statePathInfo,null);return ko.set(e,t),t}function Ao(e){ko.delete(e)}function _o(){const e=new Map,t=new Map;return{add(n,o){let s=e.get(n);return void 0===s&&(s=new WeakSet,e.set(n,s)),!s.has(o)&&(s.add(o),t.set(n,(t.get(n)??0)+1),!0)},remove(n,o){const s=e.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(t.get(n)??1)-1;return r<=0?(e.delete(n),t.delete(n),!0):(t.set(n,r),!1)},has:(t,n)=>e.get(t)?.has(n)??!1,countOf:e=>t.get(e)??0,get keyCount(){return t.size},clear(){e.clear(),t.clear()}}}const Co=new Map,Eo=_o();function Mo(e,t){const n=fe(e.inFilters);return`${e.statePathName}::${t}::${n}`}function Oo(e){let t="input";for(const n of e.propModifiers)n.startsWith(S)&&(t=n.slice(2));return t}function To(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(w)){const o=Oo(e),s=Mo(e,o);let r=Co.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.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 e of n)r=e.filterFn(r);const i=Vl(o.getRootNode());null===i&&ne("No state tree found on this root for two-way binding.");const a=St(o);i.createState("writable",e=>{e[Bn](a,()=>{let n=e[t];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(e[t]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(e[t]=n.toSpliced(o,1))}else e[t]=s?[r]:[]})})},Co.set(s,r)),e.node.addEventListener(o,r),Eo.add(s,e),!0}var t,n;return!1}function Ro(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function jo(e,t){console.error(`[wcstack/state] ${t} rejected.`,e)}function Lo(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Ro(e)&&Promise.resolve(e).catch(e=>jo(e,t))}class Wo{_name;_subscribers=new Set;constructor(e){this._name=e}get name(){return this._name}get size(){return this._subscribers.size}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}unsubscribe(e){return this._subscribers.delete(e)}emit(...e){const t=[];for(const n of this._subscribers)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[wcstack/state] a subscriber of token "${this.name}" threw; the remaining subscribers still received it.`,e)}return t}}class Do extends Wo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Pt&&Pt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Bo=new WeakMap;function zo(e,t){let n=Bo.get(e);void 0===n&&(n=new Map,Bo.set(e,n));let o=n.get(t);return void 0===o&&(o=new Do(t,e),n.set(t,o)),o}const Fo=new WeakMap;function qo(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Je(t),o=Qe(t);if(null!==n&&void 0===o?.get(n))return null===o&&ne(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Fo.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||ne('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Je(e)?null:Ze(e)}(t);null===r&&ne(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&ne(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${le(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(m)&&e.preventDefault(),c.includes(y)&&e.stopPropagation();const n=Vl(t.getRootNode());null===n&&ne("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||ne(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${le(l,n.eventTokenNames)}${ce}`);const o=St(t);n.createStateAsync("writable",async t=>{Lo(t[Bn](o,()=>{const s=null!==o?lo(o.listIndex,o.pathInfo.wildcardCount):[];return zo(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Fo.set(e,{eventName:a,handler:d}),!0}class Vo extends Wo{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==Pt&&Pt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Ho(e){return e instanceof Vo}const Uo=new Map,Go=_o();function Ko(e){const t=e.propModifiers.filter(e=>e===m||e===y).sort().join(",");return`${e.statePathName}::${t}`}const Jo=(e,t,n)=>o=>{t.includes(m)&&o.preventDefault(),t.includes(y)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Vl(r);null===i&&ne("No state tree found on this root for event handler.");const a=St(s),l=e.startsWith(B+".");i.createStateAsync("writable",async t=>{const c=t[Bn](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const e=i.addressHooks;if(e){const t=e.handlerScope;for(let e=0;e<t.length;e++)c=t[e](i,s,r,a,c)}}const d=null!==a?lo(a.listIndex,c):[];if(l){const s=t[zn](Po(n,null));return Ho(s)||ne(`Event binding "${e}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...d)}const u=t[e];return"function"!=typeof u&&ne(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Lo(c,`"${e}"`)}).catch(t=>jo(t,`"${e}"`))};function Xo(e){return"event"===e.bindingType&&e.propName.startsWith(S)}function Qo(e){if(!Xo(e))return!1;const t=Ko(e);let n=Uo.get(t);void 0===n&&(n=Jo(e.statePathName,e.propModifiers,e.statePathInfo),Uo.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Go.add(t,e),!0}function Yo(e){if(!Xo(e))return!1;const t=Ko(e),n=Uo.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Go.countOf(t)&&(Go.remove(t,e)&&Uo.delete(t),!0)}const Zo=new Map,es=_o();function ts(e,t){const n=fe(e.inFilters);return`${e.statePathName}::${t}::${n}`}function ns(e){let t="input";for(const n of e.propModifiers)n.startsWith(S)&&(t=n.slice(2));return t}function os(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(w)){const o=ns(e),s=ts(e,o);let r=Zo.get(s);return void 0===r&&(t=e.statePathName,n=e.inFilters,r=e=>{const o=e.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 e of n)s=e.filterFn(s);const r=Vl(o.getRootNode());null===r&&ne("No state tree found on this root for two-way binding.");const i=St(o);r.createState("writable",e=>{e[Bn](i,()=>{e[t]=s})})},Zo.set(s,r)),e.node.addEventListener(o,r),es.add(s,e),!0}var t,n;return!1}const ss=new Set(["radio","checkbox"]),rs=new Set(["value","valueAsNumber","valueAsDate"]);function is(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return!1;const n=e,o=n.tagName.toLowerCase();if("input"===o){const e=(n.getAttribute("type")||"text").toLowerCase();if("button"===e)return!1;if(ss.has(e)&&"checked"===t)return!0;if(rs.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Je(n);if(null!==s){const e=Qe(n)?.get(s);void 0===e&&ne(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ze(n);if(o?.knownProperties.has(t))return!0}return!1}let as=1,ls=1,cs=1;const ds=new WeakMap;function us(e,t,n){let o=ds.get(e);void 0===o&&(o=new Map,ds.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=as++,o.set(s,r)),r}function fs(e,t){return"to-element"===t?2*e:2*e+1}const hs=new Set;function ps(e){return{transactionId:ls++,originBindingId:e,visitedEdges:hs,hop:0}}function gs(e,t){const n=new Set(e.visitedEdges);return n.add(t),{transactionId:e.transactionId,originBindingId:e.originBindingId,visitedEdges:n,hop:e.hop+1}}let ms=null;function ys(){return ms}function ws(e,t){const n=ms;ms=e;try{return t()}finally{ms=n}}const bs=[];let vs=0;function $s(e,t,n,o,s=!1){vs=s?2:1;try{e.createState("writable",e=>{e[Bn](t,()=>{e[n]=o})})}finally{vs=0}}const xs=new Map,Ss=_o(),Is=new WeakMap,Ps=e=>e.detail,ks=new WeakMap;const Ns=new WeakMap;let As=0;const _s=new WeakMap;function Cs(e,t,n,o){const s=fe(e.inFilters);return`${e.propName}::${e.statePathName}::${t}::${s}::${function(e){if(null===e)return"n";let t=Ns.get(e);return void 0===t&&Ns.set(e,t=++As),`g${t}`}(n)}::${o?"o":"s"}`}const Es=(e,t,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!==Ps||r||function(e,t,n){const o=e[t];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${t} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${t}" key while element.${t} is ${typeof o}`),null===s)return;let r=ks.get(e);void 0===r&&(r=new Set,ks.set(e,r)),r.has(t)||(r.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.tagName.toLowerCase()}> "${t}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}(a,e,l);else{if(!(e in a))return void console.warn(`[@wcstack/state] Property "${e}" does not exist on target element.`);l=a[e]}let c=l;for(const e of n)c=e.filterFn(c);const d=Is.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(s.enablePropagationContext){const n=us(a,e,t),o=function(e,t){for(let n=bs.length-1;n>=0;n--){const o=bs[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==o&&Object.is(o.writtenValue,l))return s.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:o.transactionId,coveredBySameValueGuard:s.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==Pt&&Pt({type:"propagation:suppressed",reason:"confirmation",transactionId:o.transactionId,edgeId:fs(n,"to-state"),node:a,member:e}));const r=fs(n,"to-state"),i=ys();if(null!==i&&i.visitedEdges.has(r))return void(null!==Pt&&Pt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=gs(i??ps(n),r)}const f=Vl(a.getRootNode());null===f&&ne("No state tree found on this root for two-way binding.");const h=St(a),p=()=>$s(f,h,t,c,r);null!==u?ws(u,p):p()};function Ms(e){const t=Je(e.node);if(null!==t){const n=Qe(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&ne(`CustomElementRegistry is unavailable for <${t}>.`))}if(is(e.node,e.propName)&&-1===e.propModifiers.indexOf(w)){const t=function(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Je(e.node);if(null!==n){const o=Qe(e.node)?.get(n);void 0===o&&ne(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ze(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(S)&&(t=n.slice(2));return t}(e),n=function(e){if(null!==Je(e.node)){const t=Ze(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??Ps}return null}(e),o=function(e){if(null===Je(e.node))return!1;const t=Ze(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}(e),s=Cs(e,t,n,o);_s.set(e,{key:s,eventName:t});let r=xs.get(s);void 0===r&&(r=Es(e.propName,e.statePathName,e.inFilters,n,o),xs.set(s,r)),e.node.addEventListener(t,r),Ss.add(s,e)}}const Os=new WeakSet;function Ts(e){Os.add(e)}function Rs(e){return!!Os.has(e)&&(Os.delete(e),!0)}const js=new WeakMap;function Ls(e,t){const n=js.get(e);return!(void 0===n||n<t)&&(n===t?js.delete(e):js.set(e,n-t),!0)}const Ws=new WeakSet;function Ds(e){Ws.add(e)}function Bs(e){return!!Ws.has(e)&&(Ws.delete(e),!0)}let zs=0;function Fs(){zs--}function qs(){return zs>0}class Vs{registry;entries=new Map;constructor(e){this.registry=e}wait(e,t,n=()=>{}){const o=e.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),e=>this.settle(o,e)));const r={active:!0,resolve:t,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(e){return this.entries.get(e.toLowerCase())?.waiters.size??0}settle(e,t){const n=this.entries.get(e);if(void 0===n)return;this.entries.delete(e);const o=Array.from(n.waiters);n.waiters.clear();for(const e of o)e.active&&(e.active=!1,null===t?e.resolve():e.reject(t))}}const Hs=new WeakMap;function Us(e){let t=Hs.get(e);return void 0===t&&(t=new Vs(e),Hs.set(e,t)),t}const Gs=new Set([N,A,_,k]);function Ks(e,t){let n=null;for(const o of e.propModifiers){const e=o.indexOf("=");if(e<0)continue;const s=o.slice(0,e).trim(),r=o.slice(e+1).trim();s!==b&&s!==v&&ne(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&ne(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Js(e){return e.propModifiers.some(e=>e.includes("="))}const Xs=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Qs=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Ys(e,t){return"state"===e&&"call"===t?Xs:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Zs(e){if(!s.enableDirectionalInitialSync)return Js(e)&&ne("init=/sync= modifiers require enableDirectionalInitialSync."),Xs;const t=null===(n=Ks(e,b))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:ne(`Invalid init modifier value "${n}".`);var n;const o=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":ne(`Invalid sync modifier value "${e}".`)}(Ks(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&ne("Event bindings only allow init=none."),"call"===o?Qs:{authority:"none",syncOn:o,observable:!1,outputOnly:!1};if(Gs.has(e.propSegments[0]))return Ys("state",o);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&ne(`Binding type "${e.bindingType}" does not support init=${t}.`),Ys(t??"state",o);const r=Ze(e.node);if(null===r)return Ys(t??"state",o);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||ne(`Property "${e.propName}" is not declared by wcBindable.`);const l=t??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||ne(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==o||i||ne(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:o,observable:i,outputOnly:i&&!a}}function er(e){let t=e.getRootNode();return t instanceof DocumentFragment&&!(t instanceof ShadowRoot)&&(t=so(t)),null===t?null:Vl(t)}function tr(e,t){return"auto"!==t?t:function(e){const t=er(e.replaceNode);null===t&&ne("No state tree found on this root for binding.");const n=No(e);let o=!1;return t.createState("readonly",e=>{o=e[Fn](n)}),o}(e)?"state":"element"}let nr=0,or=null,sr=0;const rr=["active","disposed","failed"],ir=new WeakMap,ar=new WeakMap,lr=new WeakMap,cr=new WeakMap,dr=new WeakMap,ur=new WeakMap;function fr(e,t){const n=ur.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):ur.set(e,new Set([n,t]))):ur.set(e,t)}function hr(e){return ur.has(e)}function pr(e,t){const n=ur.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function gr(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))gr(n,t)}function mr(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class yr{root;observer;constructor(e){this.root=e;const t=globalThis.MutationObserver;this.observer="function"==typeof t?new t(e=>this.handleMutations(e)):null,this.observer?.observe(e,{childList:!0,subtree:!0})}handleMutations(e){const t=[],n=[];for(let o=0;o<e.length;o++){const s=e[o],r=s.removedNodes;if(0===r.length||!Ls(s.target,r.length))for(let e=0;e<r.length;e++)t.push(r[e]);const i=s.addedNodes;for(let e=0;e<i.length;e++)n.push(i[e])}const o=[];for(const e of t)Rs(e)||gr(e,e=>{pr(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Bs(e)&&!qs()||gr(e,e=>{pr(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&Tl(o)}}const wr=new WeakMap;function br(e){let t=wr.get(e);return void 0===t&&(t=new yr(e),wr.set(e,t)),t}function vr(e){const t=fe(e.inFilters),n=fe(e.outFilters);return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function $r(e,t,n){const o=Vl(ho(e,n));null===o&&ne("No state tree found on this root for binding.");const s=Yn(o,e.statePathInfo);return function(e,t,n){let o=bo.get(e);void 0===o&&(o=new WeakMap,bo.set(e,o));const s=o.get(t);void 0===s?o.set(t,n):s instanceof Set?s.add(n):s!==n&&o.set(t,new Set([s,n])),null!==Pt&&Pt({type:"state:binding-added",absoluteAddress:Xn(e,t),binding:n})}(s,t,e),s}function xr(e,t){const n=po(e,t);return yo(n,e),n}function Sr(e,t,n,o){null!==t?wo(t,e):function(e,t,n){const o=bo.get(e);if(void 0===o)return;const s=o.get(t);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(t),null!==Pt&&Pt({type:"state:binding-removed",absoluteAddress:Xn(e,t),binding:n}))}(n,o,e),Ao(e),go(e)}function Ir(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class Pr{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;disposedAt=0;constructor(e=null){null!==e&&this.observe(e)}initialize(e,t={},n){const o=t.registerAddress??!0,s={registerAddress:o,registerPathInfo:t.registerPathInfo??o,applyOnReconnect:t.applyOnReconnect??!0},r=[];for(const t of e){const e=this.remember(t,s),o=this.rowOf(e),i=null===o?-1:o.bindings.indexOf(e);if(null!==o&&0===o.phases[i]){const t=o;this.observe(e.replaceNode),s.registerAddress&&null===t.addresses[i]&&null===t.patternPathInfos[i]&&(t.registered=!0,this.registerRowSlot(t,i));continue}const a=lr.get(e);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(e,s,n),r.push(e)):(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(e=>this.shouldApplyState(e))}activate(e,t){if(mr(t)&&br(t),null===this.rowPlan)for(const n of e){const e=lr.get(n);if(void 0!==e&&e.session===this&&"disposed"!==e.phase&&"failed"!==e.phase){null===e.address&&null===e.patternListIndex&&(e.options.registerAddress=!0,this.registerAddress(e,t)),"active"===e.phase&&this.settleInitialRecord(e),this.settleConnectedSnapshot(e);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,t)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,e,t)}shouldApplyState(e){if(!s.enableDirectionalInitialSync)return Js(e)&&Zs(e),!0;const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0){if(!t.registered)return!0;if(2===t.phases[n])return!1;const e=t.plan.slots[n];return 1&t.flags[n]?"state"===e.authority||!e.policy.outputOnly:(t.flags[n]|=1,"state"===e.authority)}}const n=lr.get(e);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(e){const t=this.rowOf(e),n=null===t?-1:t.bindings.indexOf(e);if(null!==t&&n>=0){let o=ar.get(t);void 0===o&&ar.set(t,o=[]);return{id:o[n]??(o[n]=++nr),info:e,generation:t.generation,phase:rr[t.phases[n]],teardowns:null}}const o=lr.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=lr.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(Ir(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=this.deferredByNode.get(e)??new Set,r=()=>s.delete(a)&&this.deferred.delete(a),i=()=>{const s=Qe(e);null===s&&ne(`CustomElementRegistry is unavailable for <${t}>.`),a.cancel=Us(s).wait(t,()=>{if(r())try{Ye(s,e),n()}catch(e){o(e)}},e=>{r()&&o(e)})},a={node:e,born:++sr,cancel:null,arm:()=>{if(null===a.cancel&&this.deferred.has(a))try{i()}catch(e){r(),o(e)}}},l=e.getRootNode();if(null!==or||11===l.nodeType&&!mr(l)){if(null===or){const e=or=[];queueMicrotask(()=>{or=null;for(let t=0;t<e.length;t++)e[t].arm()})}or.push(a)}else i();return mr(l)&&br(l),fr(e,this),this.deferredByNode.set(e,s.add(a)),this.deferred.add(a),()=>{r(),a.cancel?.()}}disposeBinding(e){const t=this.rowOf(e);if(null!==t){const n=t.bindings.indexOf(e);if(n>=0)return void this.disposeRowSlot(t,n)}const n=lr.get(e);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(e){for(let t=0;t<e.length;t++)this.disposeBinding(e[t]);if(!(this.rows.size>0))for(const e of Array.from(this.deferred))e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}destroyRow(e){const t=e.length>0?this.rowOf(e[0]):null;null!==t?(this.destroyRowRecord(t),this.rows.delete(t)):this.destroyRecords()}destroyRowRecord(e){for(let t=0;t<e.bindings.length;t++){const n=e.addresses[t];null!==n&&(wo(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){this.disposedAt=sr;for(const e of Array.from(this.rows))for(let t=0;t<e.bindings.length;t++)this.disposeRowSlot(e,t);for(const e of Array.from(this.records))this.disposeRecord(e);for(const e of Array.from(this.deferred))e.cancel?.(),this.deferred.delete(e),this.deferredByNode.get(e.node)?.delete(e)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const e of this.records)if(e.pendingDefinitions>0||e.observationPending)return!1;return!0}destroyRecords(){this.disposedAt=sr;for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(wo(e.address,e.info),e.address=null),e.phase="disposed",e.teardowns=null;this.records.clear()}forEachActiveBindingNode(e){for(const t of this.rows)for(let n=0;n<t.bindings.length;n++)0===t.phases[n]&&e(t.bindings[n].node);for(const t of this.records)"active"===t.phase&&e(t.info.node)}rebindAddresses(){const e=[];for(const t of this.rows)for(let n=0;n<t.bindings.length;n++){if(0!==t.phases[n])continue;if(null===t.addresses[n]&&null===t.patternPathInfos[n])continue;const o=t.bindings[n];this.unregisterRowSlot(t,n),this.registerRowSlot(t,n),this.shouldApplyState(o)&&e.push(o)}for(const t of this.records){if("active"!==t.phase)continue;const n=t.info;if(null===t.address&&null===t.patternListIndex)continue;const o="for"===n.bindingType?po(n):null;if(Sr(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=po(n);e!==o&&En(o)&&Nn(e,kn(o)),e!==o&&Dn(o)&&jn(e,Rn(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return mr(t)?t:null}(e);null!==t&&br(t)}handleMutations(e,t,n){for(const n of t)gr(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)gr(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&Tl(o)}handleRemovedNode(e){const t=this.knownBindingsByNode.get(e);if(void 0!==t)if(t instanceof Map)for(const e of t.values())this.disposeBinding(e);else this.disposeBinding(t);this.deferredByNode.get(e)?.forEach(e=>{e.cancel?.(),e.cancel=null,this.deferred.delete(e)})}handleAddedNode(e,t,n){this.deferredByNode.get(e)?.forEach(e=>{e.born<=this.disposedAt||(this.deferred.add(e),e.arm())});const o=this.knownBindingsByNode.get(e);if(void 0===o)return;const s=o instanceof Map?o.values():[o];for(const e of s){const o=lr.get(e);if("active"===o?.phase){this.settleConnectedSnapshot(o);continue}if("disposed"!==o?.phase)continue;const s=this.optionsByBinding.get(e);if(void 0!==s)try{this.start(e,s),(s.applyOnReconnect||o.pendingDefinitions>0&&o.generation>this.disposedAt)&&this.shouldApplyState(e)&&t.push(e)}catch(e){n?.(e)}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=dr.get(t);void 0===e&&(e=vr(t),dr.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;fr(n,this);const o=this.knownMapFor(n);let s=dr.get(e);void 0===s&&(s=vr(e),dr.set(e,s));const r=o.get(s);if(void 0!==r){const e=this.optionsByBinding.get(r);return void 0!==e&&(e.registerAddress||=t.registerAddress,e.registerPathInfo||=t.registerPathInfo,e.applyOnReconnect||=t.applyOnReconnect),r}return o.set(s,e),this.optionsByBinding.set(e,{...t}),e}initializeRow(e,t){this.rowPlan=e;const n=e.slots,o=t.length,s={id:++nr,session:this,generation:++sr,plan:e,bindings:t,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 e=0;e<o;e++){const o=t[e],r=o.replaceNode;if(fr(r,this),this.addKnownRowBinding(r,o,e),ir.set(o,s),n[e].isEvent){let t=!1;try{t=Qo(o)}catch(t){throw s.phases[e]=2,t}t&&(s.flags[e]|=2)}}}activatePlanRows(e,t,n){const o=t.length>0?this.rowOf(t[0]):null;if(null===o||o.bindings!==t){for(const e of t)this.initialize([e],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=e.slots;let r=!1;for(let e=0;e<t.length;e++)if(0===o.phases[e])null===o.addresses[e]&&null===o.patternPathInfos[e]&&this.registerRowSlot(o,e,n);else{if(r||(o.generation=++sr,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){let n=!1;try{n=Qo(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}n&&(o.flags[e]|=2)}this.registerRowSlot(o,e,n)}}rowOf(e){const t=ir.get(e);return void 0!==t&&t.session===this?t:null}registerRowSlot(e,t,n){if(null!==e.addresses[t]||null!==e.patternPathInfos[t])return;const o=e.bindings[t],s=uo(o);null!==s?(e.patternPathInfos[t]=$r(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=xr(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(Sr(e.bindings[t],n,o,e.patternListIndexes[t]),e.addresses[t]=null,e.patternPathInfos[t]=null,e.patternListIndexes[t]=null)}disposeRowSlot(e,t){if(1!==e.phases[t]){e.phases[t]=1,this.runRowSlotTeardowns(e,t);for(let t=0;t<e.phases.length;t++)if(0===e.phases[t])return;this.rows.delete(e)}}runRowSlotTeardowns(e,t){try{this.unregisterRowSlot(e,t)}catch{}if(2&e.flags[t]){e.flags[t]&=-3;try{Yo(e.bindings[t])}catch{}}}addKnownRowBinding(e,t,n){const o=this.knownBindingsByNode.get(e);if(void 0===o)return void this.knownBindingsByNode.set(e,t);if(o instanceof Map)return void o.set("@plan:"+n,t);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,t),this.knownBindingsByNode.set(e,s)}start(e,t,n){!function(e){const t=e.node,n=e.replaceNode;t!==n&&null!==t.parentNode&&t.parentNode.replaceChild(n,t)}(e);const o=this.optionsByBinding.get(e)??{...t},s={id:++nr,info:e,generation:++sr,phase:"discovered",teardowns:null,session:this,anchor:e.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};lr.set(e,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(e){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),e}}attachListeners(e){const t=e.info;Qo(t)?e.eventAttached=!0:t.propSegments[0]!==I?(os(t)&&Ir(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(w)){const t=ns(e),n=ts(e,t),o=Zo.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==es.countOf(n)&&(es.remove(n,e)&&Zo.delete(n),!0))}return!1}(t)),To(t)&&Ir(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(w)){const t=Oo(e),n=Mo(e,t),o=Co.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Eo.countOf(n)&&(Eo.remove(n,e)&&Co.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(s.enableDirectionalInitialSync&&is(t.node,t.propName)&&-1===t.propModifiers.indexOf(w)){const n=function(e,t,n){let o=Is.get(e);void 0===o&&(o=new Map,Is.set(e,o));let s=o.get(t);return void 0===s&&(s=new Set,o.set(t,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(t),0===o?.size&&Is.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});Ir(e,n)}Ms(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{qo(t)&&Ir(e,()=>function(e){if(e.propSegments[0]!==I)return!1;const t=Fo.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Fo.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Je(e.info.node);if(null===n)return void t();const o=Qe(e.info.node);if(null===o&&ne(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation;Ir(e,this.deferUntilDefined(e.info.node,n,()=>{this.isAlive(e,s)&&(t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e)))},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))}))}settleInitialRecord(e){if(s.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Zs(e.info),n=tr(e.info,t.authority);if(e.initialPolicy=t,e.resolvedAuthority=n,e.initialSettled=!0,e.outputOnlyMember=t.outputOnly,e.phase="active",!t.observable)return;if("connect"===t.syncOn&&e.info.node instanceof HTMLElement&&!e.info.node.isConnected)return e.observationPending=!0,void zs++;this.readProducerSnapshot(e,"call"===t.syncOn)}catch(t){throw e.phase="failed",this.runTeardowns(e),this.records.delete(e),t}}}readProducerSnapshot(e,t){if(!this.isAlive(e,e.generation))return;const n=e.info.node,o=e.info.propName;if(!(o in n))return;const s=e.eventSequence,r=n[o];e.observationPending&&(e.observationPending=!1,Fs()),t&&e.eventSequence!==s||(e.hasProducerValue=!0,e.producerValue=r,"element"===e.resolvedAuthority&&function(e,t){let n=t;for(const t of e.inFilters)n=t.filterFn(n);const o=er(e.node);null===o&&ne("No state tree found on this root for initial binding sync."),$s(o,St(e.node),e.statePathName,n)}(e.info,r))}settleConnectedSnapshot(e){if(s.enableDirectionalInitialSync&&e.observationPending&&e.info.node instanceof HTMLElement&&e.info.node.isConnected)try{this.readProducerSnapshot(e,!1)}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}}registerAddress(e,t){if(null!==e.address||null!==e.patternListIndex)return;const n=e.info,o=uo(n);if(null!==o?(e.patternPathInfo=$r(n,o,t),e.patternListIndex=o):e.address=xr(n,t),!e.options.registerPathInfo)return;const s=Vl(n.replaceNode.getRootNode());null===s&&ne("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(e,t){return e.generation===t&&lr.get(e.info)===e&&"disposed"!==e.phase&&"failed"!==e.phase}disposeRecord(e){"disposed"!==e.phase&&(e.phase="disposed",this.runTeardowns(e),this.records.delete(e))}runTeardowns(e){e.observationPending&&(e.observationPending=!1,Fs());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{Sr(t,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null}catch{}if(e.twowayAttached){e.twowayAttached=!1;try{!function(e){const t=_s.get(e);if(void 0===t)return;_s.delete(e);const n=xs.get(t.key);void 0!==n&&(e.node.removeEventListener(t.eventName,n),Ss.remove(t.key,e)&&xs.delete(t.key))}(t)}catch{}}if(null!==e.teardowns){const t=Array.from(e.teardowns).reverse();e.teardowns=null;for(const e of t)try{e()}catch{}}if(e.eventAttached){e.eventAttached=!1;try{Yo(t)}catch{}}}}function kr(e){let t=cr.get(e);return void 0===t&&(t=new Pr(e),cr.set(e,t)),t}function Nr(e){return lr.get(e)?.session??ir.get(e)?.session??null}let Ar=null;function _r(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const Cr=Object.freeze([]);const Er=new WeakMap;const Mr=new WeakMap;function Or(e){return Mr.get(e)??[]}function Tr(e,t){Mr.set(e,t)}const Rr=new WeakMap;function jr(e){return Rr.get(e)??[]}function Lr(e,t){Rr.set(e,t)}function Wr(e,t){const n=jr(e);for(const e of n)It(e,t)}const Dr=new WeakMap;function Br(e){return Dr.get(e)??[]}function zr(e,t){Dr.set(e,t)}Set.prototype.difference||(Set.prototype.difference=function(e){const t=new Set(this);for(const n of e)t.delete(n);return t}),Set.prototype.intersection||(Set.prototype.intersection=function(e){const t=new Set;for(const n of e)this.has(n)&&t.add(n);return t});const Fr=new WeakMap,qr=new WeakSet;function Vr(e,t){if(null===t)Fr.delete(e);else{Fr.set(e,t);const{stateElement:n,pathInfo:o}=e.absolutePathInfo;if(o.wildcardCount>0){for(let e=o.parentPathInfo;null!==e&&e.wildcardCount===o.wildcardCount&&!qr.has(e);e=e.parentPathInfo)qr.add(e);n.setPathInfo(o.lastWildcardPath,"prop","internal")}}}function Hr(e){const t=Fr.get(e);t&&(t.dirty=!0),null!==e.listIndex&&qr.has(e.absolutePathInfo.pathInfo)&&e.listIndex.cacheStamp++}const Ur=Symbol.for("wcstack.transition-runner");function Gr(e){const t=globalThis[Ur];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}function Kr(e,t,n){const o=Gr(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Jr=[],Xr=[];let Qr=-1,Yr=0,Zr=!1;function ei(e){Xr.includes(e)||Xr.push(e)}function ti(e,t=0){const n=Jr.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Jr.push(o):Jr.splice(n,0,o)}function ni(e){queueMicrotask(()=>{throw e})}class oi{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Xr.length;t++)Xr[t](e);Qr>Yr&&(Yr=Qr),Qr<0&&(Zr=!0);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:e,context:t}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(e){const t=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(e),t&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){Ln(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],Ht++,this._applyChange(e,t)})}hasQueuedPath(e,t){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===e&&n.absoluteAddress.absolutePathInfo.pathInfo.path===t)}testApplyChange(e,t){this._applyChange(e.map((e,n)=>({absoluteAddress:e,context:t?.[n]??null})))}_applyChange(e,n=[]){let o=Zr?0:Yr;Yr=0,Zr=!1;const s=new Map,r=new Set;for(let t=0;t<e.length;t++){const n=e[t],o=s.get(n.absoluteAddress);null!==Pt&&null!=o&&null!==n.context&&o.transactionId!==n.context.transactionId&&Pt({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 e=0;e<n.length;e++){const t=n[e];s.has(t)||s.set(t,null)}const i=[],a=new Map;s.forEach((e,t)=>{if(null!==e&&e.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),void(null!==Pt&&Pt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=vo(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(i.push(t),null!==e&&a.set(t,e));else!1!==n.replaceNode.isConnected&&(i.push(n),null!==e&&a.set(n,e))});try{const e=()=>{Qr=o+1;try{a.size>0?Tl(i,a):Tl(i)}finally{Qr=-1}};if(o>h&&i.length>0){if(101===o++){const e=[...new Set(Array.from(r,e=>e.absolutePathInfo.pathInfo.path))];console.error("[@wcstack/state] render chain depth limit exceeded; bindings for this batch were not applied.",{maxDepth:h,paths:e}),null!==Pt&&Pt({type:"state:render-chain-limit",maxDepth:h,paths:e})}}else if(t()||0===i.length)e();else{const t=Kr("state",e);void 0!==t&&t.catch(ni)}}finally{Wn(),Qr=o,function(e){for(const t of Jr.slice())t.listener(e)}(r),Qr=-1}}}const si=new oi;function ri(){return si}const ii=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap;let di=!1;const ui=new WeakMap;function fi(e){const t=e.absolutePathInfo.stateElement;let n=ui.get(t);void 0===n&&ui.set(t,n=new Set),n.add(e)}function hi(e){const t=ui.get(e);return void 0===t?null:(ui.delete(e),t)}const pi=new WeakMap,gi=new WeakMap,mi=new WeakMap,yi=new WeakMap,wi=new WeakMap,bi=[];function vi(e,t){const n=$i(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=re(t).cumulativePaths;if(o.length<2)return;let s=wi.get(e);void 0===s&&wi.set(e,s=new Map);for(let e=0;e<o.length-1;e++){let n=s.get(o[e]);void 0===n&&s.set(o[e],n=new Set),n.add(t)}}function $i(e){let t=ii.get(e);return void 0===t&&ii.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function xi(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function Si(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function Ii(e,t,n,o){const s=function(e,t){let n=e.byPath.get(t);return void 0===n&&e.byPath.set(t,n=new Map),n}(e,t);let r=ai.get(o);if(void 0===r&&ai.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(Si(s,e,o),r.set(t,n),xi(s,n,o)),!1}return r.set(t,n),xi(s,n,o),!0}function Pi(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):(o.push(n),!1)}function ki(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&Pi(li,o.listIndex,r)&&function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){let n=mi.get(t);void 0===n&&mi.set(t,n=new Set),n.add(e)}}(o.listIndex),null!==r.levelListIndex&&Pi(ci,r.levelListIndex,r))}function Ni(e,t,n,o,s){di=!0;const r=$i(e);vi(e,t);ki(r,t,s,o,Ii(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function Ai(e,t){$i(e).tracked.add(t)}function _i(e,t){return!0===ii.get(e)?.byPath.has(t)||!0===pi.get(e)?.has(t)}function Ci(e,t,n){if("number"!=typeof t)return;const o=e.indexes[t];if(void 0!==o)for(const t of e.getters)n.push(eo(e.stateElement,Po(t,o)))}function Ei(e,t){if(!di||e===t)return;const n=gi.get(e);if(void 0===n)return;gi.delete(e);const o=gi.get(t);gi.set(t,void 0===o?n:o.concat(n)),gn(t);for(const o of n){o.indexes=t;const n=$i(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=e[n],r=t[n];if(s!==r)for(const e of[s,r])if(void 0!==e&&!Xt(e))for(const t of o.getters){const n=eo(o.stateElement,Po(t,e));Hr(n),ri().enqueueAbsoluteAddress(n,null),fi(n)}}}function Mi(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Oi(e,t,n,o,s){const r=ii.get(e),i=r?.byPath.get(t),a=pi.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return bi;const l=r.lastValue.has(t),c=r.lastValue.get(t);r.lastValue.set(t,s);const d=[],u=!n||!Object.is(o,s),f=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&Mi(i.get(o),d),f&&Mi(i.get(c),d),u&&Mi(i.get(s),d)),void 0!==a)for(const e of a)n&&Ci(e,o,d),f&&Ci(e,c,d),u&&Ci(e,s,d);return d}function Ti(e,t){return!0===wi.get(e)?.has(t)}function Ri(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function ji(e,t,n,o,s=!0){const r=re(t).segments.length,i=[];for(const a of wi.get(e).get(t)){const t=re(a).segments.slice(r);if(t.includes(d)){Li(e,a,i);continue}const l=s?Ri(n,t):void 0;for(const n of Oi(e,a,s,l,Ri(o,t)))i.push(n)}return i}function Li(e,t,n){const o=ii.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())Mi(e,n);const s=pi.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)Ci(e,t,n)}function Wi(e){const t=ci.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Di(e){const t=li.get(e);if(void 0!==t){li.delete(e),function(e){for(let t=e.parentListIndex;null!==t;t=t.parentListIndex){const n=mi.get(t);void 0!==n&&(n.delete(e),0===n.size&&mi.delete(t))}}(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=ai.get(o),r=s.get(n);s.delete(n),Si(ii.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Wi(e)}}}function Bi(e){const t=yi.get(e);if(void 0!==t){yi.delete(e);for(const e of t){const t=pi.get(e.stateElement),n=t.get(e.path);n.delete(e),0===n.size&&t.delete(e.path);const o=gi.get(e.indexes);o.splice(o.indexOf(e),1),0===o.length&&gi.delete(e.indexes)}}}function zi(e){if(!di)return;Di(e),Bi(e);const t=mi.get(e);if(void 0!==t){mi.delete(e);for(const e of t)Di(e),Bi(e),mi.delete(e)}}function Fi(e,t,n){if(!di)return;const o=ci.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=ii.get(e),i=o.byPath.get(s);Si(i,t,r),xi(i,n,r),ai.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Hr(r),ri().enqueueAbsoluteAddress(r,null),fi(r))}}const qi=new WeakMap,Vi=Object.freeze([]),Hi=new Set,Ui=new WeakMap,Gi=new WeakMap;function Ki(e,t){Gi.set(e,new WeakRef(Object(t)))}function Ji(e){return Gi.get(e)?.deref()}function Xi(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Qi(e){!function(e){for(const t of e)zt.add(t)}(e);for(const t of e)zi(t)}function Yi(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Vi,s=Array.isArray(n)&&n.length>0?n:Vi,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Vi,o=Array.isArray(t)&&t.length>0?t:Vi;let s=qi.get(n);return s&&s.get(o)||null}(o,s);if(r&&r.newIndexes===hn(s,e))return r;const i=hn(o,e)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:Hi,deleteIndexSet:new Set(i),addIndexSet:Hi};let t=hn(s,e);if(null===t&&null!==e&&function(e,t){const n=an.get(e);for(const o of n??[])if(tn(e,o))n.delete(o);else if(o!==t)return!0;return!1}(o,e)&&Ki(s,o),0===o.length||null===t&&Ji(s)===o){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Mt(e,n);t.push(o)}}return a={oldIndexes:i,newIndexes:t,changeIndexSet:Hi,deleteIndexSet:new Set(i),addIndexSet:new Set(t)}}if(Xi(o,s)&&(t??i)===i)return o!==s&&Zi(o,i,e),a={oldIndexes:i,newIndexes:i,changeIndexSet:Hi,deleteIndexSet:Hi,addIndexSet:Hi};if(null!==t)return ea(i,t);t=[];const n=new Map;for(let e=0;e<o.length;e++){const t=o[e];let s=n.get(t);s||(s=[],n.set(t,s)),s.push(e)}const r=new Set,l=new Set;let c=!1;for(let o=0;o<s.length;o++){const a=s[o],d=n.get(a),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=Mt(e,o);t.push(n),l.add(n)}else{const e=i[u];c=!0,u!==o&&r.add(e),t.push(e)}}c&&Zi(o,t,e);return a={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:l}}finally{void 0!==a&&(!function(e,t,n){let o=qi.get(e);o||(o=new WeakMap,qi.set(e,o)),o.set(t,n)}(o,s,a),gn(i),mn(s,a.newIndexes))}}(e,t,n);return function(e,t){const n=e.newIndexes;let o;for(let e=0;e<n.length;e++){if(n[e].index!==e){const t=n[e].index;n[e].index=e,Fi(n[e],t,e)}Lt(n[e],t[e])&&(o??=[]).push(n[e])}const s=Ui.get(t);s?.[0]===Ht&&(o=o?s[1].concat(o):s[1]),o&&Ui.set(t,[Ht,o]),e.valueChangeIndexes=o}(o,Array.isArray(n)&&n.length>0?n:Vi),function(e){for(const t of e)zt.delete(t)}(o.newIndexes),Ji(n)!==t&&(Qi(o.deleteIndexSet),Ei(o.oldIndexes,o.newIndexes)),o}function Zi(e,t,n){var o;if(o=e,cn.add(o),null!==n)for(const e of t)Rt(e,n)}function ea(e,t){const n=new Set(t),o=new Set(e),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let t=0;t<e.length;t++)a.set(e[t],t);for(let e=0;e<t.length;e++){const n=t[e];r.has(n)||a.get(n)!==e&&s.add(n)}return{oldIndexes:e,newIndexes:t,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}function ta(e){if(0===e.changeIndexSet.size||e.addIndexSet.size===e.newIndexes.length)return null;const t=new Map;for(let n=0;n<e.oldIndexes.length;n++)t.set(e.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of e.newIndexes){if(e.addIndexSet.has(i))continue;const a=t.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(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?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 e of i)a.add(n[e]);return a}const na=new WeakMap;function oa(e){return na.get(e)??null}function sa(e,t){na.set(e,t)}const ra=new WeakMap;const ia=new WeakMap;function aa(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function la(e,t,n,o,s){const r=function(e,t,n){let o=ia.get(e);void 0===o&&ia.set(e,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=t.map((t,o)=>{const s=e.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=t.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const e of a){if("*"===e)return null;c+="."+e,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(e,t,o.pathInfo.path),i=s.stateElement.getterPaths,a=0!==(s.stateElement.addressHooks?.readMissing.length??0);let l,c=!1;for(let e=0;e<t.length;e++){const d=t[e];if(!n.shouldApplyState(d))continue;const u=r[e];if(null===u||aa(u.prefixes,i)){Ml(d,s);continue}if(s.appliedBindingSet.has(d))continue;c||(l=s.state[zn](o),c=!0);const f=u.tail;let h=l,p=!1;for(let e=0;e<f.length;e++){if(null==h){h=void 0;break}if(a&&!(f[e]in Object(h))){p=!0;break}h=h[f[e]]}p?Ml(d,s):(s.appliedBindingSet.add(d),El(d,s,h))}}function ca(e,t,n){Wr(e,t);const o=Or(e),s=oa(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return ra.get(e)??null}(e);if(null!==r)return void la(r,o,s,t,n)}for(const e of o){if(null===s){yo(po(e),e)}(null===s||s.shouldApplyState(e))&&Ml(e,n)}e.spreads&&Rl(e.spreads,t,s,o,Br(e))}function da(e){if(!e.mounted)return;const t=Or(e),n=oa(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{wo(po(o),o)}}!function(e){const t=jr(e);for(let e=0;e<t.length;e++)It(t[e],null)}(e)}function ua(){return Object.freeze(new Set)}const fa=new WeakMap,ha=ua();function pa(e,t){const n=fa.get(e);n?n.add(t):fa.set(e,new Set([t]))}function ga(e){const t=fa.get(e);return void 0!==t?t:ha}function ma(e,t){const n=fa.get(e);n&&(n.delete(t),0===n.size&&fa.delete(e))}const ya=new Set(["if","elseif","else","for"]);class wa{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(e,t=!1){this._content=e,this._ranged=t;const n=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)n.push(t);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(e){const t=this._childNodeArray;for(let n=0;n<t.length;n++){const o=t[n];Ds(o),e.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const e=this._firstNode,t=this._lastNode;if(null===e||null===t||null===e.parentNode)return this._childNodeArray;const n=[];for(let o=e;null!==o;o=o.nextSibling)if(n.push(o),o===t)return n;return this._childNodeArray}mountAfter(e){const t=e.parentNode;if(t){let n=e;for(const e of this._movableNodes()){if(n.nextSibling!==e){Ds(e);const o=t;e.parentNode===t&&"function"==typeof o.moveBefore?o.moveBefore(e,n.nextSibling):t.insertBefore(e,n.nextSibling)}n=e}}this._mounted=!0}tryDestroy(){const e=oa(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(Or(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Ts(n),n.parentNode.removeChild(n))}const n=Or(this);for(let e=0;e<n.length;e++){const t=n[e];ya.has(t.bindingType)&&ga(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=oa(this);null!==e&&(e.isRowSession?e.disposeBindings(Or(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=Or(this);for(let t=0;t<e.length;t++){const n=e[t];ya.has(n.bindingType)&&ga(n.node).forEach(e=>{e.unmount()}),Ao(n),go(n)}}unmount(){{const e=oa(this);null!==e&&(e.isRowSession?e.disposeBindings(Or(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Ts(e),e.parentNode.removeChild(e));const e=Or(this);for(let t=0;t<e.length;t++){const n=e[t];ya.has(n.bindingType)&&ga(n.node).forEach(e=>{e.unmount()}),Ao(n),go(n)}this._mounted=!1}}function ba(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${s.commentForPrefix}|${s.commentIfPrefix}|${s.commentElseIfPrefix}|${s.commentElsePrefix}):`);for(let n=e.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&t.test(n.data))return!0;return!1}(e.fragment)),t}function va(e){return 1<<Math.min(e,31)}function $a(e){let t=e.indexBits;if(void 0===t){t=0;for(const n of e.nodeInfos)for(const e of n.parseBindTextResults)e.statePathName in E&&(t|=va(E[e.statePathName])),"string"==typeof e.uuid&&(t|=$a(Ql(e.uuid)));e.indexBits=t}return t}function xa(e){return $a(Ql(e.uuid))}function Sa(e,t){return e.statePathName in E||ya.has(e.bindingType)&&0!==(xa(e)&t)}function Ia(e,t){const n=document.createDocumentFragment(),o=new wa(n,t);return o._childNodeArray=e,o._firstNode=e.length>0?e[0]:null,o._lastNode=e.length>0?e[e.length-1]:null,o._mounted=!0,o}function Pa(e,t,n){const o=document.importNode(t.fragment,!0),s=t.nodeInfos,r=new Array(s.length);for(let e=0;e<s.length;e++){const t=at(o,s[e].nodePath);null===t&&ne(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),bt(t),Ge(t),r[e]=t}const i=n.slots,a=new Array(i.length),l=[];for(let e=0;e<i.length;e++){const t=i[e],n=r[t.nodeIndex],o={...t.template,node:n,replaceNode:n};a[e]=o,t.isIndexBinding&&l.push(o)}const c=function(e,t,n){let o=Ll.get(n);void 0!==o&&o.currentRowPlan===e||(o=new Pr,Ll.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new wa(o);return sa(d,c),Tr(d,a),function(e,t){ra.set(e,t)}(d,n),zr(d,l),Lr(d,r),pa(e.node,d),d}function ka(e){void 0!==e.uuid&&null!==e.uuid||ne("BindingInfo.uuid is null.");const n=Ql(e.uuid);n||ne(`Fragment with UUID "${e.uuid}" not found.`);const o=!t()&&ba(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==s.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=s.enableDirectionalInitialSync,n=[],o=e.nodeInfos;for(let t=0;t<o.length;t++){const s=o[t],r=at(e.fragment,s.nodePath);if(null===r)return null;for(const e of s.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===k||s===I)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Je(r))return null;if("prop"===o&&is(r,e.propName))return null;const i=ct(e);let a;try{a=Zs({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:t,template:i,isEvent:"event"===o,isIndexBinding:e.statePathName in E,policy:a,authority:a.authority})}}return 0===n.length?null:{directional:t,slots:n}}(n)),null!==r)return Pa(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o,s]=function(e,t){const n=[],o=[],s=[];for(const r of t){const t=at(e,r.nodePath);if(null===t&&ne(`Node not found by path [${r.nodePath.join(", ")}] in fragment.`),mt.has(t))continue;const i=yt(t,r.parseBindTextResults,{allowDeferred:!0});null!==i.deferred&&(s.push(i.deferred),mt.add(t)),o.push(...i.bindings),n.push(t)}return[n,o,s]}(e,t),r=new Pr,i=r.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:i,bindingSession:r,spreads:s}}(i,n.nodeInfos);o&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new wa(i,o);a.spreads.length>0&&(l.spreads=a.spreads),sa(l,a.bindingSession),Tr(l,a.bindingInfos);const c="for"===e.bindingType?(d=e.statePathInfo.wildcardCount+1,2**Math.min(d,32)-1):-1;var d;const u=[];for(const e of a.bindingInfos)Sa(e,c)&&u.push(e);return zr(l,u),Lr(l,a.nodes),pa(e.node,l),l}const Na=new WeakSet,Aa=Symbol.for("wcstack.state.view-transition-naming");function _a(){const e=Gr("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function Ca(e,t,n){const o=function(e){const t=e.firstNode;if(null===t)return null;const n=e.lastNode;for(let e=t;null!==e;e=e.nextSibling){if(e.nodeType===Node.ELEMENT_NODE)return e;if(e===n)break}return null}(e);if(null===o||Na.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[Aa]??={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.`)):(Na.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${t}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${t}`))}const Ea=new WeakMap,Ma=new WeakMap,Oa=new WeakMap,Ta=new WeakMap,Ra=new WeakMap,ja=new WeakMap;function La(e,t,n,o){let s=ja.get(e);void 0===s&&(s=[document.createComment(""),document.createComment("")],ja.set(e,s));const[r,i]=s;r.data=`@@wcs-for-start:${o}`,i.data=`@@wcs-for-end:${o}`,e.mounted||(r.remove(),i.remove());const a=null===n?null:n.nextSibling;if(null===r.parentNode)t.insertBefore(r,a),t.insertBefore(i,a),e.mountAfter(r);else if(a!==r){let e=r;for(;e!==i;){const n=e.nextSibling;t.insertBefore(e,a),e=n}t.insertBefore(i,a)}return i}function Wa(e,t,n){!function(e,t,n){let o=Ma.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,Ma.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function Da(e,t){Ea.set(e,t)}function Ba(e){return e.nodeType===Node.ELEMENT_NODE||(e.nodeType===Node.TEXT_NODE?""!==(e.textContent?.trim()??""):e.nodeType===Node.COMMENT_NODE&&e.data.startsWith("@@wcs-"))}function za(e,t){if(null===t)return!1;if(e.nextSibling===t)return!0;const n=e.compareDocumentPosition(t);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const Fa=new Set(["if","elseif","else","for"]);function qa(e,t){for(const n of Or(e))if(t.appliedBindingSet.delete(n),Fa.has(n.bindingType))for(const e of ga(n.node))qa(e,t)}function Va(e,t,n){for(const o of Br(e))if(Fa.has(o.bindingType)){if(o.statePathName in E&&Ml(o,t),0!==(xa(o)&n))for(const e of ga(o.node))e.mounted&&Va(e,t,n)}else Ml(o,t)}function Ha(e){for(const t of Or(e)){if(!Fa.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of ga(t.node))Ha(n),e&&n.mounted&&(da(n),n.unmount(),ma(t.node,n),Ra.delete(t.node),Ma.delete(t.node))}}function Ua(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ga(e,o,r){const i=Boolean(r);let a;const l=ga(e.node);a=0===l.size?ka(e):l.values().next().value;const c=t(),d=e.uuid??"",u=e.bindingType;if(i||(s.debug&&console.log(`unmount if content : ${Ua(e)}`),c&&a.mounted&&(n.seen=!0),da(a),a.unmount()),i){s.debug&&console.log(`mount if content : ${Ua(e)}`);const t=St(e.node);if(Wr(a,t),c){if(!a.mounted){const t=document.createComment(`@@wcs-${u}-start:${d}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),a.mountAfter(t);const n=document.createComment(`@@wcs-${u}-end:${d}:${e.statePathName}`),o=a.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}}else a.mountAfter(e.node);ca(a,t,o);const n=_a();null!==n&&Ca(a,"branch",n)}}const Ka=new WeakMap;function Ja(e){return Ka.get(e)??[]}const Xa=new Set;function Qa(){Xa.clear()}const Ya=Symbol.for("wcstack.trustedTypes.policy");function Za(){const e=globalThis[Ya];return null===e||"object"!=typeof e?null:e}let el;let tl=!1;function nl(e,t){if(tl)return;if(!function(){if(void 0!==el)return el;if(!("trustedTypes"in globalThis))return el=!1,el;try{document.createElement("div").innerHTML="<i></i>",el=!1}catch{el=!0}return el}())return;tl=!0;const n="function"==typeof Za()?.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 "${t}" 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:e,property:t})}const ol={value(e,t){"TEXTAREA"===e.tagName?e.textContent=String(t??""):e.setAttribute("value",String(t??""))},checked(e,t){t?e.setAttribute("checked",""):e.removeAttribute("checked")},selected(e,t){t?e.setAttribute("selected",""):e.removeAttribute("selected")},disabled(e,t){t?e.setAttribute("disabled",""):e.removeAttribute("disabled")},selectedIndex(e,t){const n=e.querySelectorAll("option"),o=Number(t);for(let e=0;e<n.length;e++)e===o?n[e].setAttribute("selected",""):n[e].removeAttribute("selected")}};function sl(e,n,o){if(1===e.propSegments.length){const t=e.propSegments[0];"textContent"===t||"innerText"===t?o=null==o?"":String(o):void 0===o&&"innerHTML"===t&&(o="")}if(void 0===o)return void(s.debug&&console.debug("Skipped property write: state value is undefined.",{element:e.node,propSegments:e.propSegments,statePathName:e.statePathName}));const r=e.node,i=e.propSegments;if(1===i.length){const c=i[0],d=r[c];if(d!==o){null!==Ar&&null!==d&&"object"==typeof d&&null!==o&&"object"==typeof o&&null!==Je(r)&&Ar.rememberOverwrittenObject(r,c,d);const t="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let e=!1;try{r[c]=t?function(e){if("string"!=typeof e)return e;const t=Za(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(o):o,e=!0}catch(e){t&&nl(r,c),s.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:o,error:e})}if(e){const e=function(e,t){const n=Je(e);if(null===n)return null;const o=Qe(e)?.get(n);if(void 0===o)return null;const s=Ze(e)?.declaredInputs.get(t);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==e)try{!function(e,t,n){if(null==n)return void e.removeAttribute(t);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);e.setAttribute(t,o)}(r,e,o)}catch(t){s.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:o,error:t})}}};if(s.enablePropagationContext&&is(r,c)){const t=us(r,c,e.statePathName),s=fs(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??ys()??ps(t);if(a.visitedEdges.has(s))null!==Pt&&Pt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:s,node:r,member:c});else{const e=gs(a,s);ws(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:cs++,writtenValue:n};bs.push({receipt:i,node:e});try{return r()}finally{bs.pop()}}(r,c,o,t,e.transactionId,i))}}else i()}if(t()){const e=ol[c];e?e(r,o):(!function(e,t,n){let o=Ka.get(e);o||(o=[],Ka.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,o),a=r,Xa.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let e=1;e<i.length-1;e++){const t=i[e];if(null==d)return;d=d[t]}const u=i[i.length-1],f=d[u];if(f!==o){if(Object.isFrozen(d))return void(s.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:o}));null!==Ar&&2===i.length&&"object"==typeof d&&null!==d&&null!==Je(r)&&(u in d?Ar.rememberOverwrittenValue(r,c,u,d[u]):Ar.recordInjectedKey(r,c,u));try{d[u]=o}catch(e){s.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:o,error:e})}}}const rl={watch:"temporal",scan:"temporal",streams:"temporal",scopes:"scopes",dcc:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function il(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${rl[e]??e}" before the state is defined.`}let al=null;function ll(e){return null===al&&ne(il("ssr",e)),al}const cl=new WeakSet;function dl(e,t,n){}function ul(e,t){let n=e;for(;null!==n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e;n=Object.getPrototypeOf(n)}}const fl=new WeakMap;function hl(e,t,n,o){const s=function(e){const t=[];let n=e;for(;null!==n&&n!==Object.prototype;){for(const e of Object.getOwnPropertyNames(n))t.push(e);n=Object.getPrototypeOf(n)}return t}(e),r=t.length>0?t+c:"";for(const e of n){if(r.length>0&&!e.startsWith(r))continue;const t=e.slice(r.length);t.length>0&&-1===t.indexOf(c)&&!fl.has(ul(o,e)?.get)&&s.push(t)}return s}const pl={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},gl={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function ml(e,t,n,o){return`[wcs/index-arity] ${e}("${t}") requires ${"$resolve"===e?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${ce}`}function yl(e,t){return`[wcs/recursion-anchor] "${e}" does not match the declared recursion anchor "${t}". 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 wl(e,t){return`$setAll("${e}") ${t}`}function bl(e,t,n){return`[wcs/wildcard-rank] ${e} needs ${t} 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.${ce}`}function vl(e,t){const n=No(t);if(n.pathInfo.path in E){const e=St(t.node);return null===e&&ne(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&ne("ListIndex not found for loopContext:");const n=E[t];void 0===n&&ne(`Invalid index name: ${t}`);const o=ao(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&ne(bl(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[zn](n)}const $l=new WeakSet;function xl(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Sl=Object.freeze({[N]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?("boolean"!=typeof n&&ne(`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)},[A]:function(e,t,n){const o=e.node,s=e.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)},[_]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[k]:function(e,t,n){Ho(n)||ne("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Er.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||ne('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Je(e);if(null===t)return null;const n=Qe(e)?.get(t);return void 0===n&&ne(`Custom element <${t}> is not defined for command binding.`),Ze(e)}(r);null===a&&ne(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||ne(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${le(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Er.delete(e));const l=new WeakRef(r);let c=null;c=o.subscribe((...t)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void Er.delete(e);const o=n[i];return"function"!=typeof o&&ne(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),Er.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Il={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!cl.has(e.replaceNode)){cl.add(e.replaceNode);const t=e.replaceNode.parentNode;if(t){const n=al?.textMarker(e)??e.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);t.insertBefore(o,e.replaceNode),t.insertBefore(s,e.replaceNode.nextSibling)}}},for:function(e,o,s){const r=e.statePathInfo,i=uo(e),a=po(e),l=kn(a),c=Ra.get(e.node);let u,f;const h=void 0!==c&&function(e,t){const n=In.get(e);return void 0!==n&&(n===t||fn(t)===fn(n))}(a,s),p=h||void 0===c||c.value===l?null:Yi(i,l,s);h?(u=c.value,f=ea(fn(u),fn(s))):null!==p&&p.newIndexes.every(e=>e.parentListIndex===i||Xt(e.parentListIndex)||!en(s,e.parentListIndex))?(u=c.value,f=ea(fn(u)??[],p.newIndexes)):(u=l.length>0&&!Ma.has(e.node)?[]:l,f=Yi(i,u,s));const g=Array.isArray(s)?s:[];o.newListValueByAbsAddress.set(a,g),Ra.set(e.node,wn(g));let m=Ma.get(e.node);const y=void 0!==m?function(e,t,n){if(!Kt(t))return null;let o=null;for(let t=0;t<n.newIndexes.length;t++){const s=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(s)&&n.deleteIndexSet.has(r)?e.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}(m,u,f):null,w=Array.isArray(u)&&u.length===f.deleteIndexSet.size&&f.deleteIndexSet.size>0;if(w&&null===y&&null!==e.node.parentNode){let t=Ta.get(e.node);if(void 0===t){const n=Ea.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(Ba(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Ba(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n.parentNode===e.node.parentNode?n:e.node),Ta.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){js.set(e,(js.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let b=w?1e3-function(e){return Oa.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;const v=t();if(void 0!==m){const t=m;f.deleteIndexSet.forEach(o=>{const s=t.get(o);void 0!==s&&(v&&(ja.get(s)?.forEach(e=>e.remove()),n.seen=!0),null!==y&&y.reused.has(s)?(da(s),Ha(s),s.unmountInPlace()):b<=0&&s.tryDestroy()?ma(e.node,s):(da(s),s.unmount(),function(e,t){let n=Oa.get(e.node);void 0===n&&(n=[],Oa.set(e.node,n)),n.length<1e3?n.push(t):ma(e.node,t)}(e,s),b-=1),w||t.delete(o))}),w&&(Ma.delete(e.node),m=void 0)}let $=e.node;const x=re(r.path+"."+d),S=o.stateElement.loopContextStack,I=ta(f);let P=null;f.newIndexes.length==f.addIndexSet.size&&f.newIndexes.length>0&&$.isConnected&&null===y&&(P=document.createDocumentFragment(),oo(P,o.rootNode));const k=v?`${e.uuid}:${r.path}:`:"",N=_a(),A=Oa.get(e.node);for(const t of f.newIndexes){let n;if(f.addIndexSet.has(t)){const s=Po(x,t);if(S.createLoopContext(s,s=>{n=y?.byAddedIndex.get(t)??(void 0!==A?A.pop():void 0),void 0===n?n=ka(e):(qa(n,o),Wr(n,s)),v?$=null!==P?La(n,P,null,k+t.index):La(n,$.parentNode,$,k+t.index):null!==P?n.appendTo(P):$.nextSibling!==n.firstNode&&n.mountAfter($),ca(n,s,o),null!==N&&Ca(n,"row",N)}),void 0===n&&ne(`Content not found for ListIndex: ${t.index} at path "${r.path}"`),null!==y&&y.reused.has(n)){const e=o.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](o.stateElement,n)}}}else{n=void 0!==m?m.get(t)??null:null,f.changeIndexSet.has(t)&&Va(n,o,va(r.wildcardCount)),null===n&&ne(`Content not found for ListIndex: ${t.index} at path "${r.path}"`);const e=!n.mounted;if(v?$=La(n,$.parentNode,$,k+t.index):null!==I&&I.has(t)&&za($,n.firstNode)||$.nextSibling===n.firstNode||n.mountAfter($),e){const e=n,s=Po(x,t);S.createLoopContext(s,t=>{ca(e,t,o)})}}v||($=n.lastNode||$),void 0===m&&(m=new WeakMap,Ma.set(e.node,m)),m.set(t,n)}Ea.set(e.node,$),null!==P&&(e.node.parentNode.insertBefore(P,e.node.nextSibling),oo(P,null))},if:Ga,else:Ga,elseif:Ga,radio:function(e,t,n){const o=e.node,s=_r(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=_r(o.value,e.inFilters),r=Array.isArray(n)?n:Cr;o.checked=r.includes(s)}},Pl=new WeakMap,kl=new WeakMap,Nl=new WeakMap;function Al(){}function _l(e){const t=Ar;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return dl;if(t.isDeclared(n,o))return Al}return sl}function Cl(e,t){El(e,t,vl(t.state,e))}function El(e,t,n){const o=_r(n,e.outFilters);if(!0===kl.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=Pl.get(e);if(void 0===s){if(Pl.has(e))return s=_l(e),s===dl&&Pl.set(e,s),void s(e,t,o);if(s=Il[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Sl[t],Pl.set(e,s),void 0===s){Je(e.replaceNode)?(s=_l(e),s===dl&&Pl.set(e,s)):(s=sl,Pl.set(e,s))}}if(s===sl){if("SELECT"===e.node.tagName){const n=e.propSegments[0];if("value"===n||"selectedIndex"===n)return t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement}),void kl.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function Ml(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=po(e);if(t.updatedAbsAddressSetByStateElement.has(t.stateElement)){t.updatedAbsAddressSetByStateElement.get(t.stateElement).add(n)}else t.updatedAbsAddressSetByStateElement.set(t.stateElement,new Set([n]))}const n=Nr(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Nl.get(e)){const t=Je(e.replaceNode);if(t&&(void 0===Qe(e.replaceNode)?.get(t)||function(e){return"waiting-definition"===lr.get(e)?.phase}(e)))return void function(e,t){if($l.has(e))return;$l.add(e);const n=()=>{$l.delete(e);const t=Nr(e);(null===t||t.shouldApplyState(e))&&Tl([e])},o=n=>{$l.delete(e),xl(t,n)},s=Nr(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{$l.delete(e),r()})||($l.delete(e),r()))}const r=Qe(e.replaceNode);if(null===r)return $l.delete(e),void xl(t,new Error("CustomElementRegistry is unavailable."));Us(r).wait(t,()=>{e.replaceNode.isConnected?n():$l.delete(e)},o)}(e,t);Nl.set(e,!0)}if(!0===t.sameRootVerified)return void Cl(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=so(o),null===o&&ne("Root node for fragment not found for binding.")),o!==t.rootNode){const n=Vl(o);null===n&&ne("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:t.appliedBindingSet,newListValueByAbsAddress:t.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:t.updatedAbsAddressSetByStateElement,deferredSelectBindings:t.deferredSelectBindings};Cl(e,r)})}else Cl(e,t)}function Ol(e,t,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:e.statePathName,bindingType:e.bindingType,node:e.node},r=o.get(n);void 0===r?o.set(n,[{error:t,info:s}]):r.push({error:t,info:s})}else console.error(`[@wcstack/state] binding "${e.bindingType}: ${e.statePathName}" failed to apply; the rest of this batch continues.`,{node:e.node,error:t});null!==Pt&&Pt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function Tl(e,t,n){let o=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;o<e.length;){let n=e[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 d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=so(d),null===d&&ne("Root node for fragment not found for binding."));const u=Vl(d);null===u&&ne("No state tree found on this root for binding."),u.createState("readonly",s=>{const f={rootNode:d,stateElement:u,state:s,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{Ml(n,f)}catch(e){Ol(n,e,u,c)}o++;const t=e[o];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{sl(e,{propagationContextByBinding:t},n)}catch(t){Ol(e,t,o??null,c)}for(const[e,t]of i.entries())Nn(e,t),jn(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Hn](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Un](n,o)}catch(e){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:e,original:n,node:o.node})}})}function Rl(e,t,n,o,s){for(const r of e)r.cancel?.(),r.cancel=n.deferUntilDefined(r.node,r.tagName,()=>{const i=vt(r);if(o&&(e.splice(e.indexOf(r),1),o.push(...i),s.push(...i.filter(e=>e.statePathName in E))),0===i.length)return;It(r.node,t);Tl(n.initialize(i,o&&{registerPathInfo:!1,applyOnReconnect:!1}))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${r.tagName}>.`,e)})}function jl(e,t,n,o=gt(e),s=kr(e)){const[r,i,a]=wt(function(e){return e.filter(e=>!mt.has(e))}(o),n);for(const e of r)It(e,t);Tl(s.initialize(i)),Rl(a,t,s)}const Ll=new WeakMap;async function Wl(e){const t=e.querySelectorAll(s.tagNames.state),n=[],o=Qe(e);null===o&&ne(`CustomElementRegistry is unavailable for <${s.tagNames.state}>.`),await o.whenDefined(s.tagNames.state);for(const e of t){if(ft(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function Dl(e){if(e===document)await Wl(document),ee(document),mc(document,document),jl(document.body,null);else{const t=e;t.host.hasAttribute(s.bindAttributeName)&&await Ue(t.host),await Wl(t),ee(t),mc(t,t),jl(t,null)}}const Bl=new WeakMap,zl=new WeakMap,Fl=new Set,ql=[];function Vl(e){return Bl.get(e)??null}function Hl(e){return zl.get(e)??Promise.resolve()}const Ul=new WeakSet;function Gl(e){Ul.add(e)}function Kl(e,n){const o=Bl.get(e);if(null===n){if(void 0===o)return;Bl.delete(e),Fl.delete(o),null!==Pt&&Pt({type:"state:element-unregistered",rootNode:e,element:o}),s.debug&&console.debug("State element unregistered")}else{if(o===n)return;if(void 0===o){const o=!t()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===e.constructor.name||"Document"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{if(o){await ll('the "enable-ssr" attribute').hydrate(e)||await Dl(e)}else await Dl(e);Gl(e),xc(),t()}catch(e){n(e)}})});zl.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await Dl(e),Gl(e),xc(),t()}catch(e){n(e)}})});zl.set(e,t)}}void 0!==o&&ne('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="...">.'),Bl.set(e,n),Fl.add(n);for(let t=0;t<ql.length;t++)ql[t](e,n);null!==Pt&&Pt({type:"state:element-registered",rootNode:e,element:n}),s.debug&&console.debug("State element registered",n)}}const Jl=new Map;function Xl(e,t,n){if(null===n)Jl.delete(e);else{Jl.set(e,n);const o=Vl(t);null===o&&ne("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const e of n.nodeInfos)for(const t of e.parseBindTextResults)o.setPathInfo(t.statePathName,t.bindingType)}}function Ql(e){return Jl.get(e)||null}function Yl(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Le(t.getAttribute(s.bindAttributeName)||"");if(t.localName===s.tagNames.state){if(t.hasAttribute("mount"))return n.filter(e=>e.propSegments[0]!==P);const e=n.find(e=>e.propSegments[0]===P);if(void 0!==e){const t=`on a volume element — a <${s.tagNames.state}> with a "mount" attribute`;ne(1===e.propSegments.length?`[wcs/mount-path-invalid] "${e.propName}" is the reserved namespace for volume injection, so it cannot be bound as an element property. Write one key at a time ("${P}.<key>: <path>") ${t}.`:`[wcs/mount-path-invalid] "${e.propName}: ${e.statePathName}" is a volume injection declaration, and it can only be written ${t}. Add mount="<path>", or bind an element property instead.`)}}return n}if(e.nodeType===Node.COMMENT_NODE){const t=ze(e);null===t&&ne("Comment node binding text not found.");const n=Ql(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Fe(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Zl;function ec(){return Zl??={filterName:"not",args:[]}}const tc=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function nc(e,t){const n=t+c+d,o=Ae(e,"|");let s,r;if(-1!==o?(s=e.slice(0,o).trim(),r=e.slice(o)):(s=e.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return e;s=n+c+s.slice(1)}return r.length>0?s+r:s}function oc(e,t){const n=tc.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+nc(s,t)+r}function sc(e,t){const n=_e(e,";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=Ae(n,":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=nc(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function rc(e,t){return sc(e,t)}function ic(e,t){const n=s.bindAttributeName,o=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;o.nextNode();){const e=o.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=oc(n.data,t);continue}const s=e;if(s instanceof HTMLTemplateElement)continue;const r=s.getAttribute(n);if(null!==r){const e=sc(r,t);e!==r&&s.setAttribute(n,e)}}}function ac(e){let t=e;const n=[];for(;null!==t.parentNode;){const e=Array.from(t.parentNode.childNodes).indexOf(t);n.unshift(e),t=t.parentNode}return n}const lc=new WeakMap;function cc(e){return lc.get(e)??null}function dc(e){const t=[],n=gt(e);for(const e of n){const n=Yl(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");lc.set(t,e.data),e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:ac(o),parseBindTextResults:n})}return t}function uc(e){const t=Array.from(e.childNodes);for(const n of t)if(n.nodeType===Node.TEXT_NODE){""===(n.textContent||"").trim()&&e.removeChild(n)}}const fc=new Map([["for",s.commentForPrefix],["if",s.commentIfPrefix],["elseif",s.commentElseIfPrefix],["else",s.commentElsePrefix]]),hc=ec();function pc(e,t){const n=t.outFilters;return{...t,outFilters:[...n,hc],bindingType:e}}function gc(e,t,n,o,s,r=!0){uc(t),"string"==typeof o&&ic(t,o),mc(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:dc(t)};return void 0!==s&&function(e,t,n){for(const o of e)for(let e=0;e<o.parseBindTextResults.length;e++){const s=o.parseBindTextResults[e];null==s.uuid&&(o.parseBindTextResults[e]=t(s,n))}}(i.nodeInfos,s,o),i}function mc(e,t,n,o){const r=s.commentElsePrefix,i=ht(t),a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode(e){const t=e;if(i.length>0&&-1!==i.indexOf(t))return NodeFilter.FILTER_REJECT;if("template"===t.tagName.toLowerCase()){if((t.getAttribute(s.bindAttributeName)||"").length>0)return NodeFilter.FILTER_ACCEPT}return NodeFilter.FILTER_SKIP}});let l=null;const c=[],d=[];for(;a.nextNode();){const e=a.currentNode;d.push(e)}for(const t of d){let i=t.getAttribute(s.bindAttributeName)||"";"string"==typeof n&&(i=rc(i,n));let a=Le(i)[0];const d=fc.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Nt();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&ne("'else' binding found without preceding 'if' or 'elseif' binding."),a=pc("else",l.parseBindTextResult),p=gc(e,f,a,g,o,!1),Xl(h,e,p);const n=c.at(-1),s=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(s),n.nodeInfos.push({nodePath:ac(s),parseBindTextResults:Yl(s)})):t.replaceWith(s)}else if("elseif"===u){null===l&&ne("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=gc(e,f,a,g,o),Xl(h,e,p);const n=document.createComment(`@@${d}:${h}`),s=Nt(),i={fragment:document.createDocumentFragment(),parseBindTextResult:pc("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ac(n),parseBindTextResults:Yl(n)}),Xl(s,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${s}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:ac(m),parseBindTextResults:Yl(m)})):t.replaceWith(m)}else{p=gc(e,f,a,g,o),Xl(h,e,p);const n=document.createComment(`@@${d}:${h}`);t.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}const yc=()=>`[${s.bindAttributeName}]`;function wc(e){if(hr(e))return!0;if(!bc(e))return!1;if(e.hasAttribute(s.bindAttributeName))return!1;const t=e.querySelector(yc());return null!==t&&hr(t)}function bc(e){return 1===e.nodeType}function vc(e){if(!e.isConnected||wc(e))return;const t=e.hasAttribute(s.bindAttributeName)?[e]:[];Array.from(e.children).some(e=>e.localName===s.tagNames.state&&ft(e))||(ee(e),mc(e.getRootNode(),e),t.push(...gt(e))),jl(e,null,void 0,t,new Pr)}const $c=[];function xc(){const e=$c.splice(0,$c.length);for(const t of e)vc(t);l()}const Sc={protocol:"wcs-binder",version:1,bind:function(e){var t;bc(e)&&e.isConnected&&!wc(e)&&(t=e.getRootNode(),Ul.has(t)?vc(e):$c.push(e))}};const Ic="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Pc=0;async function kc(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Pc}\n`;let s=!1;const r=e=>{e.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const t=new Blob([e.text+o],{type:"application/javascript"}),s=URL.createObjectURL(t);try{n=await import(s)}finally{URL.revokeObjectURL(s)}}else{const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(e.text+o)));n=await import(`data:application/javascript;base64,${t}`)}}catch(e){throw await new Promise(e=>setTimeout(e)),new Error(`[@wcstack/state] ${function(e,t,n){const o=t?.message??String(t);return n?`The inline <script> of state "${e}" 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 "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Ic}`}(t,e,s)}`,{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Nc(e){const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}class Ac{_loopContextStack=Array(f).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&ne("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=f&&ne("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&&ne("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const e=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==e&&ne("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&&ne(`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=t(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 _c={$updatedCallback:T,$streams:q},Cc=new WeakSet;function Ec(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function Mc(e){if((null===e||"object"!=typeof e&&"function"!=typeof e)&&ne(`The state must be an object, got ${null===e?"null":typeof e}. Check the source of the state element (json / src / the inline <script>).`),!Cc.has(e)){he?.state(e);for(const t of Object.keys(_c)){if(!(t in e))continue;const n=_c[t];n in e&&ne(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".${ce}`),Object.isExtensible(e)||ne(`[wcs/declaration-alias] The state is not extensible, so the old name "${t}" cannot be rewritten to "${n}". Declare "${n}" directly (the old name works through 3.x only on an extensible state).${ce}`);const o=Ec(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}Cc.add(e)}}const Oc=new WeakMap;function Tc(e,t){let n=Oc.get(e);void 0===n&&(n=new Map,Oc.set(e,n));let o=n.get(t);return void 0===o&&(o=new Vo(t,e),n.set(t,o)),o}const Rc=new WeakMap;function jc(e){const t=Rc.get(e);if(void 0!==t)return t;const n=new Proxy(Object.create(null),{get(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return Tc(e,n)},has:(t,n)=>"string"==typeof n&&e.commandTokenNames.has(n),ownKeys:()=>Array.from(e.commandTokenNames),getOwnPropertyDescriptor(t,n){if("string"==typeof n&&e.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Tc(e,n)}},set(){ne("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){ne("$command namespace is read-only; deleting from it is not allowed.")}});return Rc.set(e,n),n}const Lc=Symbol("wcs.notHandled"),Wc=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Dc=new Map;function Bc(e,t){Dc.set(e,t)}const zc=new Map;let Fc=[],qc=[];function Vc(e,t){zc.set(e,t),Fc=Array.from(zc.values()).sort((e,t)=>e.order-t.order),qc=Fc.slice().reverse()}function Hc(e){return zc.has(e)}function Uc(e,t){for(let n=0;n<Fc.length;n++)Fc[n].activate?.(e,t)}const Gc=new Map;class Kc{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(e){const t=e.split("."),n=t.slice();let o=0,s=0,r=0,i="none";const a=[];for(let e=0;e<t.length;e++){const i=t[e];if("*"===i)n[e]="*",a.push(null),o++,r++;else{const t=Number(i);Number.isNaN(t)||(n[e]="*",a.push(t),s++,r++)}}const l=re(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=e,this.segments=t,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Jc(e){let t;return Gc.get(e)??(Gc.set(e,t=new Kc(e)),t)}function Xc(e){"readonly"===e.mutability&&ne("This state is readonly.")}function Qc(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[t];return void 0===o||null===n.listIndex?null:ao(n.listIndex,o,n.pathInfo.wildcardCount)}function Yc(e,t){if(!e.untracking&&e.addressStackLength>0){const n=e.lastAddressStack,o=n?.pathInfo??null,s=e.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==t.pathInfo.path&&(s.addDynamicDependency(t.pathInfo.path,o.path),t.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const e=io(t.pathInfo,o);if(e>0){let r=!1;const i=t.listIndex??null,a=n.listIndex??null;for(let n=0;n<e;n++){if((null!==i?ao(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?ao(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function Zc(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function ed(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](e,t,n,o,s);if(a!==Lc)return a}}return Lc}function td(e,t,n,o,s){if(t.pathInfo.segments[0]===B)return function(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}(jc(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=ed(s,t,null,n,o);if(r!==Lc)return r;ne(function(e,t,n){return`[${pl.binding}] Path "${e}" does not exist on the state tree.${le(e,hl(t,"",n,t))}${ce}`}(t.pathInfo.path,e,s.getterPaths))}const r=rd(e,t.parentAddress,n,o);if(null==r)return;const i=t.pathInfo.segments[t.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==d&&!(i in Object(r))){const e=ed(s,t,Object(r),n,o);if(e!==Lc)return e}if(i===d){const e=t.listIndex?.index??ne(bl(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.get(r,e)}return Reflect.get(r,i)}if(!s.getterPaths.has(t.pathInfo.path))return Reflect.get(e,t.pathInfo.path);o.pushAddress(t);try{return Reflect.get(e,t.pathInfo.path,n)}finally{o.popAddress()}}function nd(e,t,n,o,s){const r=eo(s,t),i=function(e){return Fr.get(e)??null}(r),a=s.stateGeneration,l=t.pathInfo.lastSegment===d?void 0:jt(t.listIndex);if(null!==i&&!1===i.dirty&&i.generation===a&&i.rowStamp===l)return i.value;const c=td(e,t,n,o,s);"function"!=typeof c&&Vr(r,{value:c,dirty:!1,generation:a,rowStamp:l});const u=i?.value;return Array.isArray(c)&&c!==u&&s.getterPaths.has(t.pathInfo.path)&&function(e,t,n,o,s,r){const{path:i,wildcardCount:a}=t.pathInfo;r.beginUntrack();try{for(const[l,c]of r.stateElement.dynamicDependency){const d=re(l);if(!c.includes(i)||d.wildcardCount>a)continue;const u=rd(e,Po(d,ao(t.listIndex,d.wildcardCount-1,a)),s,r);u===n?od.add(t.pathInfo):u===o&&Ki(n,o)}}finally{r.endUntrack()}}(e,t,c,u,n,o),c}const od=new WeakSet;function sd(e){return od.has(e)}function rd(e,t,n,o){Yc(o,t),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,t.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const e=r.read;for(let r=0;r<e.length;r++){const i=e[r](s,t,n,o);if(i!==Lc)return i}}return Zc(s,t)?nd(e,t,n,o,s):td(e,t,n,o,s)}function id(e,t,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const f=o[s]??null;if(null===f)return void u.push(d);const h=Po(f,r),p=eo(n.stateElement,h),g=Rn(p),m=rd(e,h,t,n),y=Yi(r,g,m).newIndexes,w=l[c]??null;if(i.set(p,m),null===w)for(let e=0;e<y.length;e++){const t=y[e];a(o,s+1,t,l,c+1,d.concat(t.index),u)}else{const e=y[w]??ne(`ListIndex not found at index ${w} of ${f.path}`);s+1<o.length?a(o,s+1,e,l,c+1,d.concat(e.index),u):u.push(d.concat(e.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[e,t]of i.entries())jn(e,Array.isArray(t)?t:[]);return l}function ad(e,t,n){const o=hn(n,t.listIndex);if(null!==o)return o;const s=eo(e.stateElement,t),r=Yi(t.listIndex,Rn(s),n);return jn(s,Array.isArray(n)?n:[]),r.newIndexes}function ld(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Po(a,r),c=ad(n,l,rd(e,l,t,n)),d=s[i];r=c[d]??ne(`ListIndex not found at index ${d} of ${a.path}`)}return r}function cd(e,t,n,o){"object"==typeof e&&null!==e||ne(`${K} list "${t}": ${n} row at index ${o} must be a plain object (got ${null===e?"null":typeof e}).`);const s=Object.getPrototypeOf(e);s!==Object.prototype&&null!==s&&ne(`${K} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function dd(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&ne(`${K} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function ud(e,t,n,o){const s=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){const a=e[i];cd(a,n,o,i);const l=dd(a,t,n,o,i);r.has(l)&&ne(`${K} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function fd(e,t){const n=[];for(const o of Object.keys(t))Object.is(e[o],t[o])||n.push({field:o,value:t[o]});for(const o of Object.keys(e))Object.hasOwn(t,o)||null==e[o]||n.push({field:o,value:null});return n}function hd(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=rd(e,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=t.pathInfo.lastSegment;if(i===d){const e=t.listIndex?.index;return"number"==typeof e&&e in r}return i in r}const pd=new WeakMap;function gd(e){return pd.get(e)??null}function md(e,t){null===t?pd.delete(e):(gn(t.listIndexes),pd.set(e,t))}function yd(e,t,n){const o=Po(re(e.wildcardParentPaths[t]),n),r=eo(e.stateElement,o),i=Rn(r),a=e.stateProxy[zn](o),l=Yi(o.listIndex,i,a);e.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(e,t){switch(t){case"old":return e.oldIndexes;case"new":return e.newIndexes;case"add":return e.addIndexSet;case"change":return e.changeIndexSet;case"delete":return e.deleteIndexSet;default:return s.debug&&console.log(`Invalid search type: ${t}`),[]}}(l,e.searchType);if(t===e.wildcardPaths.length-1)e.targetListIndexes.push(...c);else for(const n of c)yd(e,t+1,n)}function wd(e,t,n,o){n?e.result.has(t)||e.quiet.add(t):e.quiet.delete(t),e.result.add(t),o.push(t)}const bd=[];function vd(e,t,n){return"full"!==e.listExpansion&&e.listPathSet.has(t)?e.stateElement.crossRowListPaths?.has(t)?{fullRows:n.newIndexes,movedRows:null}:0===n.addIndexSet.size&&0===n.changeIndexSet.size?0===n.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:bd,movedRows:null}:{fullRows:n.newIndexes,movedRows:null}:{fullRows:bd,movedRows:null}:{fullRows:n.addIndexSet,movedRows:n.changeIndexSet}:{fullRows:n.newIndexes,movedRows:null}}const $d=[];function xd(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return $d;let s=null;const r=t+c;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=re(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??$d}function Sd(e,t,n){const o=[],s=e.ranks,r=(e,t)=>{let n=s.get(e.pathInfo.path)??t;n<t&&(n=t),(o[n]??=[]).push(e)};r(t,0);const i=[];for(let t=0;t<o.length;t++){const s=o[t];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!e.visited.has(a)){e.visited.add(a),e.quiet.has(a)?Hr(eo(e.stateElement,a)):n(a),i.length=0,Id(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}function Id(e,t,n){const o=t.pathInfo.path,s=e.quiet.has(t),r=e.staticMap.get(o);if(r)for(const i of r){const r=re(i);if(r.lastSegment===d){const a=e.stateProxy[zn](t),l=Array.isArray(a)?a:[],c=eo(e.stateElement,t),d=Rn(c),u=e.listPathSet.has(o);if(!u&&"diff"===e.listExpansion&&(e.keyedMergePath===o||fn(l)?.length!==l.length&&!Xi(d,l)))continue;const f=Yi(t.listIndex,d,l);e.observedListValueByAbsAddress.set(c,l);const h=vd(e,o,f);for(const t of h.fullRows)wd(e,Po(r,t),s||!u,n);for(const t of f.valueChangeIndexes??bd)wd(e,Po(r,t),s||!u,n);if(null!==h.movedRows){const t=xd(e,i,r);if(null===t)for(const t of h.movedRows)wd(e,Po(r,t),s,n);else if(t.length>0)for(const o of h.movedRows)for(const r of t)wd(e,Po(r,o),s,n)}}else wd(e,Po(r,t.listIndex),s,n)}const i=e.dynamicMap.get(o);if(i)for(const o of i){const r=re(o),i=[];if(r.wildcardCount>0){const n=io(t.pathInfo,r);if(r.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&ne(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=ao(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const s={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:r.wildcardPaths,wildcardParentPaths:r.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};yd(s,n,o),i.push(...s.targetListIndexes)}else{null===t.listIndex&&ne(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=ao(t.listIndex,n-1,t.pathInfo.wildcardCount);i.push(e)}}else i.push(null);for(const t of i)wd(e,Po(r,t),s,n)}}function Pd(e,t,n,o,s,r,i,a,l){const c=t.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(t),[];const d=function(e,t,n,o){const s=new Map,r=new Map,i=[e];for(r.set(e,0);i.length>0;){const e=i.pop();if(s.has(e))continue;const o=t.get(e),a=n.get(e);let l;l=void 0===o?a??[]:void 0===a?o:o.concat(a),s.set(e,l);for(let e=0;e<l.length;e++){const t=l[e];r.set(t,(r.get(t)??0)+1),s.has(t)||i.push(t)}}const a=new Map,l=new Set,c=[];for(const[e,t]of r)0===t&&(a.set(e,0),l.add(e),c.push(e));for(let e=0;e<c.length;e++){const t=c[e],n=a.get(t)+1;n>o&&ne(`Maximum dependency depth of ${o} exceeded. Possible circular dependency detected at path: ${t}`);const i=s.get(t);for(let e=0;e<i.length;e++){const t=i[e];n>(a.get(t)??-1)&&a.set(t,n);const o=r.get(t)-1;r.set(t,o),0===o&&(l.add(t),c.push(t))}}if(l.size!==s.size){let e=-1;for(const t of l){const n=a.get(t);n>e&&(e=n)}const t=e+1;for(const e of s.keys())l.has(e)||a.set(e,t)}return a}(c,n,o,1e3),u={ranks:d,stateElement:e,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};Sd(u,t,a),function(e,t){for(let n=0;n<1e3;n++){const n=hi(e.stateElement);if(null===n)return;n.forEach(n=>{Sd(e,Po(n.absolutePathInfo.pathInfo,n.listIndex),t)})}}(u,a);for(const[e,t]of u.observedListValueByAbsAddress)jn(e,t);return Array.from(u.result)}function kd(e,t,n,o,s){const r=e.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](e,t,n,o,s)}}function Nd(e,t,n){const o=e.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function Ad(e,t,n){const o=e.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](e,t,n)}}function _d(e,t,n,o,s,r){const i=_i(e,t),a=Ti(e,t);if(!i&&!a)return null;const l=[],c=Ed(l);return i&&Oi(e,t,n,o,s).forEach(c),a&&ji(e,t,n?o:r(),s).forEach(c),l}function Cd(){return s.enablePropagationContext?ys()??null:null}function Ed(e){const t=ri(),n=Cd();return o=>{Hr(o),t.enqueueAbsoluteAddress(o,n),e.push(o)}}function Md(e,t,n){if(null===e||0===e.length)return;const o=n.stateElement,s=o.staticDependency,r=o.dynamicDependency,i=ri(),a=Cd();for(let n=0;n<e.length;n++){const l=e[n].absolutePathInfo,c=l.pathInfo.path;if(!s.has(c)&&!r.has(c))continue;const d=Po(l.pathInfo,e[n].listIndex);Pd(o,d,s,r,o.listPaths,t,"new",e=>{if(e===d)return;const t=eo(o,e);Hr(t),i.enqueueAbsoluteAddress(t,a)},{listExpansion:"diff"})}}function Od(e,t,n,o,r,i,a="diff"){const l=s.enablePropagationContext?ys()??ps(-1):null,u=ri(),f=o.stateElement;u.enqueueAbsoluteAddress(t,l),i&&Hr(t);const h=t=>Pd(f,t,f.staticDependency,f.dynamicDependency,f.listPaths,n,"new",t=>{if(t===e)return;const n=eo(f,t);Hr(n),u.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r});if(h(e),e.pathInfo.lastSegment!==d&&null!==e.listIndex&&null!==e.listIndex.parentListIndex){const t=e.listIndex,o=e.pathInfo.wildcardParentPathInfos[t.position],s=Po(o,t.parentListIndex),r=()=>n[zn](s),i=e=>{Hr(e),u.enqueueRenderOnlyAddress(e)};for(const n of dn(t,r))i(eo(f,Po(e.pathInfo,n)));const a=e.pathInfo.path.slice(e.pathInfo.wildcardPaths[t.position].length);for(const e of _n(eo(f,s),r())){const n=e.absolutePathInfo.pathInfo;n!==o&&n.wildcardCount===o.wildcardCount&&i(to(f,re(n.path+c+d+a),t))}}const{path:p,lastSegment:g,wildcardCount:m,wildcardParentPaths:y,wildcardParentPathInfos:w}=e.pathInfo,b=e.listIndex;for(let e=0;b&&e<m;e++){const t=ao(b,e-1,m);for(const o of f.dynamicDependency.get(y[e])??[]){const s=re(o);if(f.listPaths.has(o)&&s.wildcardCount===e&&sd(s)&&n[zn](Po(s,t))===n[zn](Po(w[e],t))){const t=Po(re(o+p.slice(y[e].length)),b);h(t),g===d&&u.enqueueRenderOnlyAddress(eo(f,t.parentAddress))}}}}function Td(e,t,n,o,s){s&&(e.getterPaths.has(t)?Hr(n):Vr(n,{value:o,dirty:!1,generation:e.stateGeneration,rowStamp:n.absolutePathInfo.pathInfo.lastSegment===d?void 0:jt(n.listIndex)}))}function Rd(e,t,n,o,s){const r=t.listIndex,i=fn(n);if(i?.[o]!==r||n[o]===s)return t;const a=Mt(r.parentListIndex,o,Tt(r));if(function(e){return yn.has(e)}(n)){const e=gd(n)??{value:n.slice(),listIndexes:i};mn(e.value,e.listIndexes),bn(n,e.value)}const l=function(e){return pn.has(e)}(i)?i:i.slice();l[o]=a,mn(n,l,!0),Ei(i,l),Qi([r]);const c=Po(t.pathInfo,a);return Ad(e,eo(e,c),eo(e,t)),c}function jd(e,t,n,o,s,r,i,a,l=!0){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=rd(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??ne(bl(`path "${t.pathInfo.path}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0));return Reflect.set(i,e,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(t.pathInfo.path))return Reflect.set(e,t.pathInfo.path,o);r.pushAddress(t),r.beginUntrack();try{return Reflect.set(e,t.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{l&&Od(t,n,s,r,i,a)}}function Ld(e,t,n,o,s,r,i,a,l){const u=t.parentAddress??ne(`address.parentAddress is undefined path: ${t.pathInfo.path}`),f=rd(e,u,s,r)??[],h=gd(f);if(l)return h&&(h.value[t.listIndex.index]=o),Lt(t.listIndex,o),jd(e,t,n,o,s,r,i,a);const p=t.listIndex,g=h??{value:[...f],listIndexes:fn(f)??[],written:new Map};try{return jd(e,t,n,o,s,r,i,a,!1)}finally{const e=function(e,t,n){const{value:o,listIndexes:s}=e,r=new Map;s.forEach((e,n)=>{if(t[n]!==o[n]){const t=r.get(o[n]);t?t.push(e):r.set(o[n],[e])}});let i,a=0;const l=[];for(let e=0;e<s.length;e++){const n=t[e]===o[e]?s[e]:r.get(t[e])?.shift();if(!n&&(a++?(i??=new Set(o)).has(t[e]):o.includes(t[e])))return null;l.push(n)}return l.map((e,t)=>e??Mt(n,t))}(g,f,u.listIndex);if(null===e)md(f,g),Lt(p,o),g.written.set(p,Ht),function(e){nn.set(e,Ht)}(p),Od(t,n,s,r,i,a);else{md(f,null);const t=[p.index];on(p),g.written.forEach((e,n)=>{on(n),Lt(n,g.value[n.index]),e===Ht&&t.push(n.index)}),g.written.delete(p),e.forEach((e,t)=>{e.index=t}),mn(f,e),Ei(g.listIndexes,e),function(e,t,n,o,s,r,i){const a=r.stateElement,l=ri(),u=eo(a,e);mn(t.value,t.listIndexes),Gt(t.value),bn(n,t.value),kn(u)===n&&Nn(u,t.value);l.enqueueRenderOnlyAddress(u);for(const e of _n(u,n))Cn(e,n)&&l.enqueueRenderOnlyAddress(e);const f=new Map;t.listIndexes.forEach((e,t)=>f.set(e,t));const h=re(e.pathInfo.path+c+d);for(let e=0;e<o.length;e++){const n=o[e],i=f.get(n);if(i===e)continue;const c=Po(h,n),d=eo(a,c);if(void 0===i){const n=to(a,h,t.listIndexes[e]);Ad(a,d,n),Od(c,d,s,r,null,Zc(a,c),"full");continue}Pd(a,c,a.staticDependency,a.dynamicDependency,a.listPaths,s,"new",e=>{const t=eo(a,e);Hr(t),l.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}for(const e of i){const n=o[e];if(f.has(n)&&t.written.get(n)!==Ht){const o=Po(h,n),i=eo(a,o);Ad(a,i,to(a,h,t.listIndexes[e])),Od(o,i,s,r,null,Zc(a,o))}}}(u,g,f,e,s,r,t)}}}function Wd(e,t,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(t.pathInfo.path);if(void 0!==i){const r=rd(e,t,o,s),a=function(e,t,n,o){const s=ud(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=ud(r,t,e,"current"),a=new Map;for(let e=0;e<r.length;e++)a.set(i[e],r[e]);const l=new Array(o.length),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=a.get(s[e]);void 0!==n&&n!==t?(l[e]=n,c.push({position:e,oldRow:n,newRow:t})):l[e]=t}return c.length>0?{list:l,matched:c}:null}(t.pathInfo.path,i,r,n);if(null!==a)return function(e,t,n,o,s,r){const i=t.pathInfo.path,a=t.listIndex;null===fn(o)&&Yi(a,null,o);const l=Yi(a,o,n.list),u=Dd(e,t,n.list,s,r,i),f=re(i+c+d);for(const t of n.matched){const n=fd(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?Wd(e,Po(re(f.path+c+i.field),o),i.value,s,r):t.oldRow[i.field]=i.value}return u}(e,t,a,r,o,s)}}return Dd(e,t,n,o,s,null)}function Dd(e,t,n,o,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let s=0;s<e.length;s++){const i=e[s](a,t,n,o,r);if(i!==Lc)return i}}const u=function(){const e=vs;return vs=0,e}(),f=u>1;if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const u=rd(e,t.parentAddress,o,r);if("object"==typeof u&&null!==u){const e=t.pathInfo.lastSegment,h=e===d?t.listIndex?.index:e;let p,g=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in u,t=void 0!==h?u[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}e===d&&(t=Rd(a,t,u,h,n));const m=_d(a,l,g,p,n,()=>u[h]),y=Zc(a,t),w=eo(a,t);null!==Pt&&Pt({type:"state:write",absoluteAddress:w,value:n,oldValue:p,hasOldValue:g}),kd(a,l,w,p,g);let b=!1;try{if(void 0===h&&ne(bl(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==d&&!(h in u)){const e=c.writeMissing;for(let s=0;s<e.length;s++){b=!0;const i=e[s](a,t,u,h,n,o,r);if(i!==Lc)return i;b=!1}}if(e!==d&&null!==t.listIndex){const o=u[h];o!==n&&(function(e,t,n,o){if(!Jt.has(e))return!1;let s=!1;for(const t in n)s||=t!==o&&n[t]===e;if(!s){let n=Qt.get(t);void 0===n&&(n=new WeakSet,Qt.set(t,n)),n.add(e)}const r=Jt.get(e),i=Zt.get(e);if(r[0]?.parentListIndex===t&&(!s||i?.[0]!==t||i[1]!==Ht))for(const n of an.get(e)??[])if(n!==t&&n.position===t.position&&rn(e,n)&&Object(qt(n))[o]===e){r.forEach(e=>Ot(e,n)),Yt.set(e,[t,Ht]);break}return s}(o,t.listIndex,u,e)&&Array.isArray(n)&&Ki(n,o),function(e,t){Qt.get(t)?.delete(e);const n=Jt.get(e);if(void 0!==n){Zt.set(e,[t,Ht]);const o=Yt.get(e);o?.[0]===t&&o[1]===Ht&&n.forEach(e=>Ot(e,t))}}(n,t.listIndex))}return Reflect.set(u,h,n)}finally{Od(t,w,o,r,i,y),Md(m,o,r),b?Hr(w):Td(a,l,w,n,y),Nd(a,t.pathInfo,{value:n})}}}let h,p=!1;if(!f&&s.sameValueGuard&&(null===n||"object"!=typeof n)){const s=rd(e,t,o,r);if(hd(e,t,o,r)&&Object.is(s,n))return!0;h=s,p=!0}const g=_d(a,l,p,h,n,()=>rd(e,t,o,r)),m=a.elementPaths.has(t.pathInfo.path),y=Zc(a,t),w=eo(a,t);null!==Pt&&Pt({type:"state:write",absoluteAddress:w,value:n,oldValue:h,hasOldValue:p}),kd(a,l,w,h,p);try{return m?Ld(e,t,w,n,o,r,i,y,u):jd(e,t,w,n,o,r,i,y)}finally{Md(g,o,r),m||Td(a,l,w,n,y),Nd(a,t.pathInfo,{value:n})}}function Bd(e,t,n,o){return(t,s,...r)=>{Array.isArray(s)||ne(`$resolve("${t}") requires an explicit indexes array (pass [] when the path has no wildcards) — got `+(null===s?"null":typeof s)+"."),r.length>1&&ne(`$resolve("${t}") takes 2 arguments to read and 3 to write (path, indexes, value) — got ${2+r.length}.`);const i=re(t);if(o.addressStackLength>0){const e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}s.length!==i.wildcardParentPathInfos.length&&ne(ml("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=Po(i,ld(e,n,o,i,s));if(0===r.length)return rd(e,a,n,o);Xc(o),Wd(e,a,r[0],n,o)}}function zd(e,t,n,o){const s=Bd(e,0,n,o);return(t,r)=>{const i=re(t);if(void 0===r||Array.isArray(r)||ne(`$getAll("${t}") 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 e=o.lastAddressStack?.pathInfo??null,t=o.stateElement;null!==e&&e.path!==i.path&&t.getterPaths.has(e.path)&&t.addDynamicDependency(i.path,e.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&ne(ml("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=Qc(o,i.wildcardPaths[e]);if(t){r=lo(t,t.length);break}}if(void 0===r){const e=o.addressStackLength>0?o.lastAddressStack:null,n=e?.listIndex??null;i.wildcardCount>0&&null!==e&&null!==n&&n.length>0&&ne(function(e,t){return`$getAll("${e}") was called without indexes inside the loop context of "${t}", 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).`}(t,e.pathInfo.path)),r=[]}}const a=id(e,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let e=0;e<a.length;e++)l.push(s(i.path,a[e]));return l}}function Fd(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Qc(o,s.wildcardPaths.at(-1)??ne(`lastWildcardPath is null: ${t.pathInfo.path}`))??ne(`ListIndex not found: ${t.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<t.pathInfo.wildcardCount;r++){const i=t.pathInfo.wildcardParentPathInfos[r]??ne(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Po(i,s),l=ad(o,a,rd(e,a,n,o)),c=t.wildcardIndexes[r]??ne(`wildcardIndex is null: ${t.pathInfo.path}`);s=l[c]??ne(`ListIndex not found at index ${c} of ${i.path}`)}return s}case"partial":ne(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function qd(e,t,n,o){const s=o.stateElement;return t=>{const r=Jc(t),i=Fd(e,r,n,o),a=Po(r.pathInfo,i),l=eo(s,a),c=ri();c.enqueueAbsoluteAddress(l),function(e,t,n,o,s){const r=_i(e,t),i=Ti(e,t);if(!r&&!i)return;const a=n(),l=[],c=Ed(l);r&&Oi(e,t,!1,void 0,a).forEach(c),i&&ji(e,t,void 0,a,!1).forEach(c),Md(l,o,s)}(s,r.pathInfo.path,()=>rd(e,a,n,o),n,o),Pd(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=eo(s,e);Hr(t),c.enqueueAbsoluteAddress(t)});const d=s.addressHooks;if(d){const e=d.written;for(let t=0;t<e.length;t++)e[t](s,a.pathInfo)}}}function Vd(e,t,n,o){return(t,s,r,i)=>{Xc(o);const a=re(t);Array.isArray(s)||ne(wl(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&ne(ml("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&ne(wl(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&ne(wl(t,"requires an array as the value when { spread: true } is set."));const u=id(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&ne(function(e,t,n){return`$setAll("${e}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${t}) but got ${n}. Did the list change between $getAll and $setAll?`}(t,u.length,r.length));const f=[];for(let t=0;t<u.length;t++){const s=ld(e,n,o,a,u[t]);f.push(Po(a,s))}const h=a.lastSegment===d;let p=0;for(let t=0;t<f.length;t++){const s=h?Po(a,ld(e,n,o,a,u[t])):f[t];let i;if(c){i=r(rd(e,s,n,o),...u[t])}else i=l?r[t]:r;void 0!==i&&(Wd(e,s,i,n,o),p++)}return p}}function Hd(e,t){if("all"===Jc(t).wildcardType)return!0;const n=e.getterPaths;if(0===n.size)return!1;for(const e of re(t).cumulativePaths)if(n.has(e))return!0;return!1}const Ud=/^\$\d+$/,Gd=`${J}${c}`,Kd=`${X}${c}`,Jd=new WeakMap;function Xd(e,t,n,o){const s=E[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&Ud.test(t)&&ne(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&ne(`No active state reference to get list index for "${t.toString()}".`);const e=o.lastAddressStack,n=e?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=e?.listIndex;null==r&&ne(`ListIndex not found: ${t.toString()}`);let i=s;const a=e.pathInfo,l=o.stateElement?.addressHooks;if(l){const t=l.indexShift;for(let n=0;n<t.length;n++)i+=t[n](o,e)}const c=ao(r,i,a.wildcardCount);return c?.index??ne(`ListIndex not found: ${t.toString()}`)}if("string"==typeof t){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,t,n,e);if(i!==Lc)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>zd(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>Vd(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>qd(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Bd(e,0,n,o)(t,s,...r);case"$trackDependency":he?.renamed(t,"$dependOn");case"$dependOn":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(G)&&ne(`[wcs/recursion-unsupported] ${String(t)}("${e}") 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&&ne(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??ne("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==e&&s.addDynamicDependency(e,n.path)}}(0,t,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Hd(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ai(o.stateElement,e),Object.is(n[e],t);let r;o.beginUntrack();try{r=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&Ni(o.stateElement,e,t,eo(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Hd(o.stateElement,e);let i,a=r?n[e]:void 0;o.beginUntrack();try{r||(a=n[e]),i=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?Ai(o.stateElement,e):Ni(o.stateElement,e,i,eo(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(e,t=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||ne(`$eqIndex("${e}") needs a list row scope.`);const r=ao(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&ne(`$eqIndex("${e}", ${t}): no list index at that level.`),Hd(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&(Ai(o.stateElement,e),o.stateElement.addIndexDependentGetterPath?.(s.pathInfo.path)),Object.is(n[e],r.index);const i=t===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[e],i&&(l=n[s.pathInfo.wildcardParentPaths[t-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const t=i?fn(l):null;null!==t?function(e,t,n,o,s){di=!0,$i(e).lastValue.set(t,s),vi(e,t);let r=pi.get(e);void 0===r&&pi.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=gi.get(o);if(void 0===l?(gi.set(o,l=[]),gn(o)):a=l.find(n=>n.stateElement===e&&n.path===t),void 0===a){a={stateElement:e,path:t,indexes:o,getters:new Set},l.push(a),i.add(a);const n=o[0]?.parentListIndex??null;if(null!==n){let e=yi.get(n);void 0===e&&yi.set(n,e=new Set),e.add(a)}}a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){di=!0;const r=$i(e);vi(e,t),ki(r,t,s,o,Ii(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,eo(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":he?.renamed(t,"$untracked");case"$untracked":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case B:return jc(o.stateElement)}if(!t.startsWith(Gd)&&!t.startsWith(Kd))return}const r=Jc(t),i=Fd(e,r,n,o),a=Po(r.pathInfo,i);return rd(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=Jd.get(e);return void 0===t&&(t=new Map,Jd.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Bn:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&ne("already in loop context"),e.setLoopContext(t);try{e.pushAddress(t);try{return n()}finally{e.popAddress()}}finally{e.clearLoopContext()}}(o,e,t);break;case zn:i=t=>rd(e,t,n,o);break;case Fn:i=t=>hd(e,t,n,o);break;case qn:i=()=>async function(e,t,n){const o=Reflect.get(e,M);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Vn:i=()=>function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&o.call(n)}(e,0,n);break;case Hn:i=t=>function(e,t,n,o){const s=Reflect.get(e,T);let r;if("function"==typeof s){const e=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const t=n.absolutePathInfo.pathInfo,s=t.path;if(-1===s.indexOf("#")&&(e.add(s),t.wildcardCount>0)){const e=lo(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}(e.size>0||0===t.length)&&(r=s.call(n,Array.from(e),i))}const i=o.stateElement?.addressHooks;if(i){const e=i.updated;for(let s=0;s<e.length;s++)e[s](o.stateElement,t,n)}return r}(e,t,n,o);break;case Un:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,R);"function"==typeof s&&s.call(o,t,n)}(e,t,o,n);break;default:return Reflect.get(e,t,n)}return s.set(t,i),i}}class Qd{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=Vl(e);null===n&&ne("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=t}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let e;return this._addressStackIndex>=0&&(e=this._addressStack[this._addressStackIndex]),void 0===e&&ne("Last address stack is undefined."),e}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(e){this._addressStackIndex+1>=f&&(this._hasRepeatedAddress()&&ne(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),ne(`[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]=e}_hasRepeatedAddress(){const e=new Set;for(let t=0;t<=this._addressStackIndex;t++){const n=this._addressStack[t];if(n){if(e.has(n))return!0;e.add(n)}}return!1}_tailAddressPaths(){const e=[];for(let t=this._addressStackIndex;t>=0&&e.length<8;t--){const n=this._addressStack[t];n&&e.push(n.pathInfo.path)}return e}_describeAddressCycle(){const e=this._tailAddressPaths();return`${Array.from(new Set(e)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const e=this._addressStack[this._addressStackIndex];return void 0===e&&ne(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,e}setLoopContext(e){this._loopContext=e}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(e,t,n){return Xd(e,t,n,this)}set(e,t,n,o){return Xc(this),function(e,t,n,o,s){if("string"==typeof t){const r=Jc(t),i=Fd(e,r,o,s);return Wd(e,Po(r.pathInfo,i),n,o,s)}return Reflect.set(e,t,n,o)}(e,t,n,o,this)}has(e,t){return Reflect.has(e,t)}deleteProperty(e,t){return Xc(this),Reflect.deleteProperty(e,t)}defineProperty(e,t,n){return Xc(this),Reflect.defineProperty(e,t,n)}}const Yd=Promise.resolve(),Zd=new Map;let eu=[];function tu(e,t){Zd.set(e,t),eu=Array.from(Zd.values()).sort((e,t)=>e.order-t.order)}function nu(e,t){return ne(il(e,t))}const ou="undefined"==typeof HTMLElement?class{}:HTMLElement;function su(e){const t=[];let n=e;for(;n&&n!==Object.prototype;)t.push(n),n=Object.getPrototypeOf(n);const o={};for(let e=t.length-1;e>=0;e--)Object.assign(o,Object.getOwnPropertyDescriptors(t[e]));return o}let ru=null;const iu=new Set(["for","if","elseif","else"]);function au(e,n,o){const s=new Map;for(const e of o){const t=re(e);if(null===t.lastWildcardPath)continue;const n=s.get(t.lastWildcardPath);void 0===n?s.set(t.lastWildcardPath,[t]):n.push(t)}const r=[],i=new Set,a=t=>{const n=eo(e,t);if(i.has(n))return;i.add(n);const o=vo(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==t.listIndex){const e=s.get(t.pathInfo.path);if(void 0!==e)for(const n of e)a(Po(n,t.listIndex))}};Ln();try{if(e.createState("readonly",t=>{for(const o of n){const n=Po(re(o),null);a(n);try{Pd(e,n,e.staticDependency,e.dynamicDependency,e.listPaths,t,"new",a)}catch{}}}),0===r.length)return;const o=function(e){const t=[],n=[];for(const o of e)iu.has(o.bindingType)?t.push(o):n.push(o);return t.sort((e,t)=>0!==(e.replaceNode.compareDocumentPosition(t.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),t.concat(n)}(r),s=()=>{Tl(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Kr("state",s);void 0!==i&&i.catch(ni)}finally{Wn()}}const lu=[[V,"watch"],[H,"scan"],[q,"streams"],[U,"recursion"]];class cu extends ou{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Hl(e)}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 Ac}();_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(e=>{this._resolveInitialize=e}),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),this._loadingPromise=new Promise(e=>{this._resolveLoading=e}),this._setStatePromise=new Promise(e=>{this._resolveSetState=e})}get _state(){return void 0===this.__state&&ne(`${s.tagNames.state} _state is not initialized yet.`),this.__state}set _state(e){Mc(e),function(e){for(let t=0;t<lu.length;t++){const[n,o]=lu[t];n in e&&!Hc(o)&&ne(il(o,`"${n}"`))}}(e);const t=this.__state,n=function(){const e=new Map;return{get:t=>e.get(t),set(t,n){e.set(t,n)}}}();n.set("previousState",t),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[D];if(void 0===n)return t;Array.isArray(n)||ne(`${D} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ne(`${D} entries must be non-empty strings.`),e===B&&ne(`${D} entry "${e}" conflicts with the reserved namespace name "${B}".`),t.has(e)&&ne(`${D} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[z];if(void 0===n)return t;Array.isArray(n)||ne(`${z} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||ne(`${z} entries must be non-empty strings.`),t.has(e)&&ne(`${z} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[K];if(void 0===t)return null;"object"==typeof t&&null!==t||ne(`${K} must be an object mapping list paths to key specs.`);const n=new Map;for(const[e,o]of Object.entries(t)){0===e.length&&ne(`${K} entry path must be a non-empty string.`);const t=e.split(c);t.some(e=>0===e.length)&&ne(`${K} entry "${e}" must not contain empty path segments.`),t[t.length-1]===d&&ne(`${K} entry "${e}" must be the list path itself, not the element path (drop the trailing "${c}${d}").`),-1!==e.indexOf(G)&&ne(`[wcs/recursion-unsupported] ${K} entry "${e}" uses "${G}", which ${K} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${c}${d}${c}children").`),"function"!=typeof o?("string"!=typeof o&&ne(`${K} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&ne(`${K} entry "${e}" key field name must be a non-empty string.`),(o.includes(c)||o.includes(d))&&ne(`${K} entry "${e}" key field name "${o}" must be a flat property name ("${c}" / "${d}" are not allowed).`),o in Object.prototype&&ne(`${K} entry "${e}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(e,o)):n.set(e,o)}return n.size>0?n:null}(e);var i;n.set("eventTokenNames",s),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&ru?.reset(this),this._hasUpdatedCallback=T in e,this._hasErrorCallback=R in e,i=this,Bo.delete(i),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[F];if(void 0!==o){"object"==typeof o&&null!==o||ne(`${F} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||ne(`${F} entry "${t}" is not declared in $eventTokens.${le(t,n)}`),"function"!=typeof s&&ne(`${F} entry "${t}" must be a function.`),zo(e,t).subscribe(s)}}(this,e,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const a=function(e){const t=new Set,n=new Set,o=su(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterPaths:t,setterPaths:n}}(e);for(const e of a.getterPaths)this._getterPaths.add(e);for(const e of a.setterPaths)this._setterPaths.add(e);!function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<Fc.length;o++)Fc[o].register?.(e,t,n)}(this,e,n),Uc(this,null),this._resolveLoading?.()}attributeChangedCallback(e,t,n){this._initialized&&t!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===t?"absent":`"${t}"`}, 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")?ll('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);return t&&"application/json"===t.type?JSON.parse(t.textContent||"{}"):(console.warn(`[@wcstack/state] state="${e}": no <script type="application/json" id="${e}"> 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 e=this.getAttribute("json");return JSON.parse(e)}{const e=this.querySelector('script[type="module"]');if(e)return await kc(e,s.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${s.tagNames.state}> element.`)},6e4),t=await this._setStatePromise;return clearTimeout(e),t}}}{const e=this.getAttribute("src");if(e&&e.endsWith(".json"))return await async function(e){let t;try{const n=await fetch(e);if(n.ok)return await n.json();t=`HTTP ${n.status} ${n.statusText}`}catch(e){t=e}return console.error(`[@wcstack/state] Failed to load JSON file "${e}", so the state starts empty (4.0 rejects instead):`,t),{}}(e);if(e&&e.endsWith(".js"))return await Nc(e);ne(`Unsupported src file type: ${e}`)}}async _initialize(){const e=t()?null:this._loadFromSsrElement();if(null!==e&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==e&&this.__state)for(const[t,n]of Object.entries(e)){if(t in this.__state){const e=Object.getOwnPropertyDescriptor(this.__state,t);if(e&&(e.get||e.set))continue;if("function"==typeof this.__state[t])continue}this.__state[t]=n}return await this._loadingPromise,null!==this._rootNode&&(Kl(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),ne(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;this._initializeFailed=!0;const n=["state","src"].find(e=>this.hasAttribute(e));throw console.error(`[@wcstack/state] <${s.tagNames.state}${n?` ${n}="${this.getAttribute(n)}"`:""}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===Vl(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),zl.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<eu.length;o++)eu[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{M in e&&await e[qn]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{O in e&&e[Vn]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<eu.length;t++)if(!0===eu[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Vl(this._rootNode)===this||Kl(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(e){for(let t=0;t<eu.length;t++){const n=eu[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;if(this.hasAttribute("mount"))try{nu("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(Q))try{nu("dcc",`a <${s.tagNames.state}> inside a [${Q}] host`)}catch(e){this._failInitializeLoudly(e)}let n=!1;try{const e=function(e){for(let t=0;t<eu.length;t++){const n=eu[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&nu("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let o=!1;try{o=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!o)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const e=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(e)}if(this.hasAttribute("enable-ssr")&&!t()||e!==this._connectGeneration||await this._callStateConnectedCallback(),t()&&this.hasAttribute("enable-ssr")&&!function(){const e=document.documentElement;return!!e&&"orchestrated"===e.getAttribute("data-wcs-server")}())try{await ll('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}Uc(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<eu.length;t++)if(!0===eu[t].disconnecting?.(e))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(e,t){for(let n=0;n<eu.length;n++)eu[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Kl(this.rootNode,null),e=this,Rc.delete(e),function(e){for(let t=0;t<qc.length;t++)qc[t].deactivate?.(e)}(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(e=>(he?.volumeLoaded(e),Mc(e),e))}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}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(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t,this.attachAddressHooks("watch",V)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&ne(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),t.set(n,o);this._listKeys=t}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(e){this._listPaths.add(e)}findStateDescriptor(e){return ul(this._state,e)}defineTreeAccessor(e,t){Object.defineProperty(this._state,e,t),"function"==typeof t.get&&this._getterPaths.add(e),"function"==typeof t.set&&this._setterPaths.add(e),this.setPathInfo(e,"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&&ne("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(e,t){const n=function(e,t){const n=Dc.get(e);return void 0===n&&ne(il(e,`"${t}"`)),n}(e,t);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(e,t){for(let n=0;n<Wc.length;n++){const o=Wc[n],s=t[o];if(void 0===s)continue;const r=e[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(e){this.attachAddressHooks("scopes",e)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(e){this._bindableEventMap=e,this.attachAddressHooks("dcc",L)}_addDependency(e,t,n){const o=e.get(t);return void 0===o?(e.set(t,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(e,t){if(!this._addDependency(this._dynamicDependency,e,t))return!1;const n=re(e);for(let e=n.parentPathInfo;null!==e&&e.wildcardCount>0&&e.wildcardCount===n.wildcardCount;e=e.parentPathInfo)this._addDependency(this._dynamicDependency,e.path,t);return!0}addStaticDependency(e,t){return this._addDependency(this._staticDependency,e,t)}setPathInfo(e,t,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(e);void 0===o?this._pathRegistrations.set(e,{bindingType:t,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(e,{bindingType:t,bound:o.bound||"binding"===n})}if("for"===t&&(this._listPaths.add(e),this._elementPaths.add(e+"."+d)),!this._pathSet.has(e)){const t=re(e);this._pathSet.add(e);const o=function(e,t){const n=Jc(t);return"all"===n.wildcardType&&1===n.wildcardIndexes.length&&isNaN(+n.segments[0])&&!t.includes("#")&&Object.isExtensible(e)&&!(t in e)}(this.__state,e);if(ru?.check(this,this.__state,e,n,o),o&&function(e,t){const{segments:n,cumulativePaths:o}=re(t),s=n.length-1,r=(e,r,i)=>{let a,l=!1;for(let c=0;c<=s;c++){const d=n[c];if(l||=!(isNaN(+d)||Array.isArray(a)&&+d in a),r&&c===s)return l?a[d]=i:e[t]=i;a=l?a?.[d]:e[o[c]]}return a},i=function(){return r(this)};fl.set(i,Jc(t).pathInfo.path),e.defineTreeAccessor(t,{get:i,set(e){r(this,!0,e)},configurable:!0})}(this,e),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=re(e.parentPath)}}}_rebuildPathInfo(){for(const[e,t]of Array.from(this._pathRegistrations))t.bound&&!this._generatedPaths.has(e)&&this.setPathInfo(e,t.bindingType)}_createState(e,t,n){try{const o=function(e,t,n){const o=new Qd(e,n);return new Proxy(t,o)}(e,this._state,t);return n(o)}finally{}}async createStateAsync(e,t){return await this._createState(this.rootNode,e,t)}createState(e,t){this._createState(this.rootNode,e,t)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(e){this._crossRowListPaths.add(e)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(e){this._indexDependentGetterPaths.add(e)}setInitialState(e){if(!this._initialized)return this._initializeFailed&&ne(`<${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?.(e);!function(e){for(let t=0;t<eu.length;t++)eu[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&ne("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 t=this.__state;this._state=e;const n=function(e){const t=new Set;for(const n of e)if(void 0!==n)for(const[e,o]of Object.entries(su(n)))e.startsWith("$")||e.includes(d)||"function"==typeof o.value||t.add(e);return t}([t,e]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(e){au(this,e,this._pathRegistrations.keys())}}const du=[],uu=[];function fu(){const e=[];let t=0;for(let n=0;n<uu.length;n++){const o=uu[n].deref();void 0!==o&&(e.push(o),uu[t++]=uu[n])}return uu.length=t,e}function hu(e=customElements){fu().includes(e)||uu.push(new WeakRef(e));for(let t=0;t<du.length;t++)du[t](e);e.get(s.tagNames.state)||e.define(s.tagNames.state,cu)}function pu(e){const t=function(){const e=document.documentElement?.lang;if(e)try{return Intl.getCanonicalLocales(e),e}catch{return void console.warn(`[@wcstack/state] <html lang="${e}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===t?e:{...e,locale:t}}function gu(e,t){const n=pu(e);var s;n&&((s=n).tagNames&&Object.assign(o.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(o.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(o.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(o.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(o.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(o.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(o.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(o.locale=s.locale),"boolean"==typeof s.debug&&(o.debug=s.debug),"boolean"==typeof s.enableMustache&&(o.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(o.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(o.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(o.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(o.sameValueGuard=s.sameValueGuard)),hu(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=Sc)}()}let mu=null;function yu(e){return mu??ne(il("watch",`"$watch" in <wcs-state mount="${e}">`))}let wu=null;const bu=Object.freeze([]);const vu="3.5.4",$u=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function xu(e,t,n,o){return{node:e,propName:t.propName,statePathName:t.statePathName,bindingType:t.bindingType,inFilters:t.inFilters,outFilters:t.outFilters,origin:n,raw:o}}function Su(e){const t=[],n=new Set,o=new Set,r=e=>{const o=function(e){const t=`${fe(e.inFilters)}\0${fe(e.outFilters)}`;return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(o.has(e))return;o.add(e);const t=Ql(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(xu(null,t,"fragment","")),null!=t.uuid&&i(t.uuid)},a=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let e=a.nextNode();null!==e;e=a.nextNode()){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=t.getAttribute(s.bindAttributeName);if(null===n||0===n.length)continue;try{const e=it(t,Le(n));for(const o of e)r(xu(t,o,"attribute",n))}catch{}continue}const t=$u.exec(e.data.trim());if(null===t)continue;const n=t[1]||s.commentTextPrefix,o=t[2],a=Ql(o);if(null===a){if(n===s.commentTextPrefix)try{r(xu(e,Fe(o),"comment",o))}catch{}}else r(xu(e,a.parseBindTextResult,"comment",o)),i(o)}return t}function Iu(e){const t=function(e){const t=ii.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:pi.get(e)}}(e);if(null===t)return[];const n=new Set([...t.byPath.keys(),...t.tracked]);if(void 0!==t.watchers)for(const e of t.watchers.keys())n.add(e);const o=[];for(const e of[...n].sort()){const n=t.byPath.get(e);let s=0;if(void 0!==n)for(const e of n.values())s+=e.size;o.push({path:e,tracked:t.tracked.has(e),rows:s,keys:n?.size??0,lists:t.watchers?.get(e)?.size??0,lastValue:t.lastValue.get(e)})}return o}const Pu="__WCSTACK_DEVTOOLS_HOOK__";function ku(){const e=globalThis,t=e[Pu];if(void 0!==t)return 2!==t.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${t.version}, expected 2. Keeping the existing registry (first-wins).`),t;const n=function(){const e=new Map,t=new Set,n=e=>{if(0===t.size)return void e._setSink(null);const n=e.id;e._setSink(e=>{for(const o of t)o.onEvent?.(n,e)})};return{version:2,sources:e,register(o){if(!e.has(o.id)){e.set(o.id,o),n(o);for(const e of t)e.onSourceRegistered?.(o)}},unregister(n){const o=e.get(n);if(void 0!==o){o._setSink(null),e.delete(n);for(const e of t)e.onSourceUnregistered?.(n)}},addListener(o){t.add(o);for(const t of e.values())n(t),o.onSourceRegistered?.(t);return()=>{if(t.delete(o))for(const t of e.values())n(t)}}}}();return e[Pu]=n,n}const Nu=e=>{null!==Pt&&Pt({type:"state:update-batch",addresses:e})};function Au(e){const t=null!==Pt;!function(e){Pt=e}(e);const n=null!==e;n&&!t?ti(Nu,0):!n&&t&&function(e){const t=Jr.findIndex(t=>t.listener===e);-1!==t&&Jr.splice(t,1)}(Nu)}function _u(e){return{rootNode:e.rootNode,element:e,paths:{list:e.listPaths,element:e.elementPaths,getter:e.getterPaths,setter:e.setterPaths},commandTokenNames:e.commandTokenNames,eventTokenNames:e.eventTokenNames,staticDependency:e.staticDependency,dynamicDependency:e.dynamicDependency,watchPaths:e.watchPaths??null,keyedListPaths:void 0===e.listKeys||null===e.listKeys?null:new Set(e.listKeys.keys())}}function Cu(e){return Vl(e)??ne("devtools: no state tree on this root")}let Eu=null;function Mu(){if(t())return;if(null!==Eu)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:vu,getStateElements(){const e=[];for(const t of Fl)e.push(_u(t));return e},overlays(e){return t=Cu(e),null===wu?bu:wu(t);var t},keyedSubscriptions:e=>Iu(Cu(e)),keys(e){const t=Cu(e),n=[];return t.createState("readonly",e=>{for(const t of Object.keys(e))if(!t.includes("*")&&!t.startsWith("$")){try{if("function"==typeof e[t])continue}catch{}n.push(t)}}),n},read(e,t,n){let o;return Cu(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){Cu(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>Su(e),_setSink:Au};Eu=e,ku().register(e)}const Ou={name:"devtools",install(){Mu()}},Tu=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Ru=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const ju=new WeakMap;const Lu=new WeakMap,Wu=new WeakSet,Du=new WeakMap;function Bu(e,t,n,o){console.warn(`[@wcstack/state] [${pl[n]}] ${gl[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${le(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ce}`),null!==Pt&&Pt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const zu={check:function(e,t,n,o,s){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const r=e.addressHooks;if(r){const t=r.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const i=re(n).segments;if("binding"===o&&i.length<2)return;if(function(e,t){let n=ju.get(e);return void 0===n&&(n=new Set,ju.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const a=function(e,t,n,o){if(void 0!==ul(e,t))return Ru;const s=re(t).segments;let r=e,i="";for(let t=0;t<s.length;t++){const a=o&&Array.isArray(r)&&+s[t]>=0?d:s[t],l=i;i=0===t?a:i+c+a;const u=t>0&&ul(e,i),f=u&&fl.get(u.get);if(u&&(!f||ul(e,f)))return t<s.length-1?Tu:Ru;if(Object(r)!==r)return Tu;if(a===d){if(!Array.isArray(r)||0===r.length)return Tu;r=r[0];continue}const h=ul(r,a);if(void 0===h)return{existence:"missing",missingSegment:a,candidates:hl(r,l,n,e)};if("function"==typeof h.get)return t===s.length-1?Ru:Tu;r=h.value}return Ru}(t,n,e.getterPaths,s);"missing"===a.existence&&(function(e,t){return!0===Du.get(e)?.has(t)}(e,n)||("binding"!==o?Bu(e,n,o,a):function(e,t,n){let o=Lu.get(e);void 0===o&&(o=new Map,Lu.set(e,o));if(o.set(t,n),Wu.has(e))return;Wu.add(e),setTimeout(()=>function(e){Wu.delete(e);const t=Lu.get(e);if(void 0===t)return;Lu.delete(e);for(const[n,o]of t)Bu(e,n,"binding",o)}(e),0)}(e,n,a)))},reset:function(e){ju.delete(e),Lu.delete(e)},markExported:function(e,t){let n=Du.get(e);void 0===n&&(n=new Set,Du.set(e,n)),n.add(t),Lu.get(e)?.delete(t)}};let Fu=!1;function qu(){Fu||(Fu=!0,function(e){ru=e}(zu))}const Vu={name:"diagnostics",install(){qu()}};function Hu(e){ne(`filter ${e} requires at least one option`)}function Uu(e){ne(`filter ${e} requires a number as option`)}function Gu(e){ne(`filter ${e} requires a number value`)}function Ku(e){ne(`filter ${e} requires a date value`)}const Ju={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function Xu(e){return!(!e||isNaN(Number(e)))}function Qu(e,t){return Xu(e)||Uu(t),Number(e)}function Yu(e,t,n){return Qu(e?.[t]??Hu(n),n)}const Zu=e=>t=>{const n=e(t);return e=>null==e?e:n(e)},ef={eq:(e,t)=>{const n=e?.[0]??Hu("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e===o:(Xu(n)||Uu("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Hu("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?"string"!=typeof o?e!==o:(Xu(n)||Uu("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>!e,lt:e=>{const t=Yu(e,0,"lt");return e=>("number"!=typeof e&&Gu("lt"),e<t)},le:e=>{const t=Yu(e,0,"le");return e=>("number"!=typeof e&&Gu("le"),e<=t)},gt:e=>{const t=Yu(e,0,"gt");return e=>("number"!=typeof e&&Gu("gt"),e>t)},ge:e=>{const t=Yu(e,0,"ge");return e=>("number"!=typeof e&&Gu("ge"),e>=t)},add:e=>{const t=Yu(e,0,"add");return e=>("number"!=typeof e&&Gu("add"),e+t)},sub:e=>{const t=Yu(e,0,"sub");return e=>("number"!=typeof e&&Gu("sub"),e-t)},mul:e=>{const t=Yu(e,0,"mul");return e=>("number"!=typeof e&&Gu("mul"),e*t)},div:e=>{const t=Yu(e,0,"div");return e=>("number"!=typeof e&&Gu("div"),e/t)},mod:e=>{const t=Yu(e,0,"mod");return e=>("number"!=typeof e&&Gu("mod"),e%t)},abs:e=>e=>("number"!=typeof e&&Gu("abs"),Math.abs(e)),clamp:e=>{const t=Yu(e,0,"clamp"),n=Yu(e,1,"clamp");return e=>("number"!=typeof e&&Gu("clamp"),Math.min(Math.max(e,t),n))},toFixed:e=>{const t=Qu(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&Gu("toFixed"),e.toFixed(t))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Gu("locale"),e.toLocaleString(t??s.locale))},upper:Zu(e=>e=>String(e).toUpperCase()),lower:Zu(e=>e=>String(e).toLowerCase()),capitalize:Zu(e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),trim:Zu(e=>e=>String(e).trim()),slice:Zu(e=>{const t=[Yu(e,0,"slice")],n=e?.[1];return void 0!==n&&t.push(Qu(n,"slice")),e=>String(e).slice(...t)}),substr:Zu(e=>{he?.removed("substr");const t=Yu(e,0,"substr"),n=Yu(e,1,"substr");return e=>String(e).substr(t,n)}),padStart:Zu(e=>{const t=Yu(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),padEnd:Zu(e=>{const t=Yu(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),repeat:Zu(e=>{const t=Yu(e,0,"repeat");return e=>String(e).repeat(t)}),reverse:Zu(e=>e=>String(e).split("").reverse().join("")),truncate:Zu(e=>{const t=Yu(e,0,"truncate"),n=e?.[1]??"…";return e=>{const o=String(e);return o.length<=t?o:o.slice(0,t)+n}}),join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||ne(`filter ${"join"} requires an array value`),e.join(t))},int:e=>e=>parseInt(String(e),10),float:e=>e=>parseFloat(String(e)),round:e=>{const t=Math.pow(10,Qu(e?.[0]??"0","round"));return e=>("number"!=typeof e&&Gu("round"),Math.round(e*t)/t)},floor:e=>{const t=Math.pow(10,Qu(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&Gu("floor"),Math.floor(e*t)/t)},ceil:e=>{const t=Math.pow(10,Qu(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&Gu("ceil"),Math.ceil(e*t)/t)},percent:e=>{const t=Qu(e?.[0]??"0","percent");return e=>("number"!=typeof e&&Gu("percent"),`${(100*e).toFixed(t)}%`)},unit:Zu(e=>{const t=e?.[0]??Hu("unit");return e=>String(e)+t}),date:e=>{const t=e?.[0];return e=>(e instanceof Date||Ku("date"),e.toLocaleDateString(t??s.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Ku("time"),e.toLocaleTimeString(t??s.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Ku("datetime"),e.toLocaleString(t??s.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Ku("ymd");const n=e.getFullYear().toString(),o=(e.getMonth()+1).toString().padStart(2,"0"),s=e.getDate().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},hms:e=>{const t=e?.[0]??":";return e=>{e instanceof Date||Ku("hms");const n=e.getHours().toString().padStart(2,"0"),o=e.getMinutes().toString().padStart(2,"0"),s=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${o}${t}${s}`}},falsy:e=>e=>!e,truthy:e=>e=>!!e,defaults:(e,t)=>{const n=e?.[0]??Hu("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Hu("coalesce"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e??o},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),nullIfEmpty:e=>e=>""===e?null:e},tf={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]},nf=ef,of=ef;let sf=!1;const rf={name:"formats",install(){sf||(sf=!0,ve("input",of,tf,Ju),ve("output",nf,tf,Ju))}};function af(e){return-1!==e.indexOf(G)}function lf(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+c;if(!t.startsWith(n))return null;const o=t.slice(e.recursiveAnchor.length);if(af(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function cf(e){return 0===e.length?e:c+ff(e.slice(1))}function df(e,t,n){const o=c+e.repeat,s=t.length<=n.length?t:n,r=t.length<=n.length?n:t;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 e=0;e<i.length;e+=o.length)if(!i.startsWith(o,e))return!1;return!0}function uf(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(df(e,t,n.slice(0,o)))return!0;return!1}function ff(e){const t=e.split(c);for(let e=0;e<t.length;e++)t[e]===d||Number.isNaN(Number(t[e]))||(t[e]=d);return t.join(c)}function hf(e,t){const n=e.repeat.split(c),o=c+e.repeat;let s=t;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===c+e.repeatList+c+"length")return!0;for(let e=1;e<n.length;e++)if(s===c+n.slice(0,e).join(c))return!0;return!1}function pf(e,t,n){n<0&&ne(`Recursion depth must not be negative (got ${n}).`);let o=e.anchor;for(let t=0;t<n;t++)o+=c+e.repeat;const s=o+t;let r=0;for(const e of s.split(c))e===d&&r++;return r>u&&ne(`[wcs/recursion-depth-exceeded] Recursion on "${e.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 gf(e,t){return pf(e,"",t)}function mf(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const o=n.slice(e.anchor.length,n.length-t.length);if(0===o.length)return 0;const s=c+e.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function yf(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const o=t.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const o=c+n.repeat;let s=0,r=n.anchor.length;for(;t.startsWith(o,r);)r+=o.length,s++;return r!==t.length&&46!==t.charCodeAt(r)?null:s}(t,n.pathInfo.path)}function wf(e,t,n){const o=e.recursionRegistry,s=lf(o.spec,n);null===s&&ne(yl(n,o.spec.recursiveAnchor));const r=yf(t,o);return null===r&&ne(`[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 bf(e,t,n,o,s){const r=o.spec,i=[],a=new Map,l=[],d=r.repeatList,u=r.anchorList,f=new Set,h=new Set,p=(e,t,n)=>{const o=e.wildcardParentPathInfos;if(t>=o.length)return void i.push(Po(e,n));const s=g(o[t],n,null).rows;for(let n=0;n<s.length;n++)p(e,t+1,s[n])};function g(o,s,i){const l=Po(o,s),c=eo(n.stateElement,l),u=rd(e,l,t,n),h=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const o=t;return f.has(o)&&ne(`[wcs/recursion-cycle] "${e}" 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)&&ne(`[wcs/recursion-shared-list] "${e}" 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 "${d}" array.`),o})(o.path,u,i),p=Yi(s,Rn(c),u);return a.set(c,Array.isArray(u)?u:[]),null!==h&&null!==i&&i.add(h),{rows:p.newIndexes,tracked:h}}const m=(e,t,n)=>{const{rows:r,tracked:a}=g(t,n,h);if(0===r.length)return;const u=(e=>{const t=l[e];if(void 0!==t)return t;const n=o.concretePathAt(s,e),r=0===s.length?n:o.concretePathAt("",e),i={nodePath:r,concretePathInfo:re(n),childListPathInfo:re(r+c+d)};return l[e]=i,i})(e),y=a;f.add(y);const w=u.concretePathInfo.wildcardCount===e+1;for(let t=0;t<r.length;t++){const n=r[t];w?i.push(Po(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,re(u),null);for(const[e,t]of a)jn(e,t);return i}function vf(e,t,n,o,s,r,i){Xc(n);const a=n.stateElement.recursionRegistry,l=lf(a.spec,o);null===l&&ne(yl(o,a.spec.recursiveAnchor));const c=cf(l);Array.isArray(s)||ne(wl(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&ne(`[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&&ne(wl(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&ne(wl(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(e,t,n){hf(e,n)&&ne(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.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 d=a.conflictingRecursiveGetter(c);null!==d&&ne(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${d}", 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 u=bf(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Wd(e,u[o],r,t,n),f++);return f}const $f={write(e,t){if(!0!==e.hasRecursion)return Lc;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&ne(`[wcs/recursion-readonly] "${t.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.`),Lc},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return Lc;if("$getAll"===t)return(t,s)=>{if(af(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=lf(r.spec,o);null===i&&ne(yl(o,r.spec.recursiveAnchor)),Array.isArray(s)||ne(`[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&&ne(`[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=bf(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(rd(e,a[o],t,n));return l}(o,n,e,t,s);t=wf(e.stateElement,e,t)}return zd(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>af(t)?vf(o,n,e,t,s,r,i):Vd(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&af(t)){const s=Jc(wf(e.stateElement,e,t)),r=Fd(o,s,n,e);return rd(o,Po(s.pathInfo,r),n,e)}return Lc}};let xf=!1;function Sf(e,t){"string"==typeof t&&0!==t.length||ne(`[wcs/recursion-declaration-invalid] ${U} ${e} must be a non-empty string.`);const n=t.split(c);n.some(e=>0===e.length)&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not contain empty path segments.`),n.length<2&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must name a list element: a property path ending with "${c}${d}" (for example "nodes${c}${d}").`),n[n.length-1]!==d&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must end with "${c}${d}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===d&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must have exactly one "${d}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===G&&ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not contain "${G}" — the declaration is what gives "${G}" its meaning.`),isNaN(Number(n[o]))||ne(`[wcs/recursion-declaration-invalid] ${U} ${e} "${t}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const If=new WeakSet;function Pf(e){return"function"==typeof e.get&&If.has(e.get)}const kf="[wcs/recursion-declaration-invalid]";class Nf{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(e,t){this.spec=e;const n=su(t);for(const[t,o]of Object.entries(n)){if(!af(t))continue;"function"==typeof o.set&&ne(`${kf} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&ne(`${kf} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=lf(e,t);null===n&&ne(yl(t,e.recursiveAnchor)),0===n.length&&ne(`${kf} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),hf(e,cf(n))&&ne(`${kf} "${t}" names the recursion structure itself (a node, its "${e.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 "${e.recursiveAnchor}${c}total").`),this._definitions.set(t,{recursivePath:t,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(af(t)||Pf(n))continue;const e=this._matchExpansion(t);null!==e&&ne(`${kf} "${t}" is already defined on the state, so the recursive getter "${e}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const e=Array.from(this._definitions.values());for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)df(this.spec,e[t].suffix,e[n].suffix)&&ne(`${kf} "${e[t].recursivePath}" and "${e[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(e){for(const t of this._definitions.values())if(uf(this.spec,t.suffix,e))return t.recursivePath;return null}recursiveGetterOwningPath(e){const t=this._ownerByPathInfo.get(e);if(void 0!==t)return t;const n=this.recursiveGetterOwning(e.path);return this._ownerByPathInfo.set(e,n),n}recursiveGetterOwning(e){const t=this._accessors.get(e);if(void 0!==t)return t.recursivePath;const n=ff(e),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 e=n.lastIndexOf(c);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(c,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==mf(this.spec,t.suffix,e))return t.recursivePath;return null}materializeForPathInfo(e,t){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(t);if(void 0!==n)return n;const o=this.materializeFor(e,t.path);return this._accessorByPathInfo.set(t,o),o}materializeFor(e,t){const n=this._accessors.get(t);if(void 0!==n)return n;if(!t.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const e of this._definitions.values()){const n=mf(this.spec,e.suffix,t);null!==n&&(null!==o&&ne(`"${t}" matches both "${o.recursivePath}" and "${e.recursivePath}".`),o=e,s=n)}return null===o?null:this._define(e,o,s,t)}_define(e,t,n,o){const s=e.findStateDescriptor(o);void 0===s||Pf(s)||ne(`"${o}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:t.recursivePath,depth:n}),i=t.get,a=function(){return i.call(this)};var l;return l=a,If.add(l),e.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(e,n),this._accessors.set(o,r),r}_registerListPaths(e,t){for(const n of function(e,t){const n=[];n.push(e.anchorList);for(let o=0;o<t;o++)n.push(gf(e,o)+c+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return function(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Pf(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,o]of t){let s=null;for(let e=0;e<o.length;e++)n.has(o[e])?s??=o.slice(0,e):s?.push(o[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}}}(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let o=n[t];return void 0===o&&(o=pf(this.spec,e,t),n[t]=o),o}accessorFor(e){return this._accessors.get(e)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const Af="recursionSpec",_f="recursionRegistry",Cf={order:5,validateEarly(e,t,n){const o=function(e){const t=e[U];if(void 0===t)return null;"object"==typeof t&&null!==t||ne(`[wcs/recursion-declaration-invalid] ${U} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&ne(`[wcs/recursion-declaration-invalid] ${U} must declare exactly one anchor; it is empty.`),n.length>1&&ne(`[wcs/recursion-declaration-invalid] ${U} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Sf("anchor",o),"string"!=typeof s&&ne(`[wcs/recursion-declaration-invalid] ${U} entry "${o}" must map to the repeating sub-path as a string (for example "children${c}${d}").`),Sf("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(c)),i=s.slice(0,s.lastIndexOf(c)),a=r+c+G;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(Af,o),n.set(_f,null===o?null:new Nf(o,t))},preCommit(e,t,n){const o=e.recursionRegistry;if(null!==o)for(const t of o.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(_f)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",U)},apply(e,t,n){const o=n.get(Af)??null;null!==o&&e.addListPath(o.anchorList)}};let Ef=!1;function Mf(){Ef||(Ef=!0,xf||(xf=!0,Bc("recursion",$f)),Vc("recursion",Cf))}const Of={name:"recursion",install(){Mf()}};const Tf={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1&&-1===t.path.indexOf("#")?o[t.segments[0]]:void 0;if("string"!=typeof i)return;const a=e.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let Rf=!1;function jf(e){return function(){const t=this.stateElement;if(!t)return;if(!0!==t.initialized)return;let n;try{t.createState("readonly",t=>{n=t[e]})}catch(t){return void console.warn(`[@wcstack/state] DCC getter "${e}" failed:`,t)}return n}}function Lf(e){return function(t){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[e]=t})}):n.createState("writable",n=>{n[e]=t}))}}function Wf(e,t){return t?function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[e](...t)}).then(()=>o)})}:function(...t){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[e](...t)}),o})}}function Df(e){return e.startsWith("$")}function Bf(e,t){return Object.keys(e).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof e[n].value;return"method"===t?o:!o})}function zf(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||ne(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||ne(`${t} entries must be non-empty strings.`),e.startsWith("$")&&ne(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&ne(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function Ff(e){Mc(e);const t=zf(e,L)??[],n=zf(e,W)??[],o=su(e),s=function(e){const t=e[q];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),r=[];for(const e of t){const t=o[e];if(void 0===t){if(s.has(e)){r.push(e);continue}ne(`${L} entry "${e}" is not declared on the state.${le(e,Bf(o,"value"))}`)}"function"==typeof t.value&&ne(`${L} entry "${e}" is a method. Declare it in ${W} instead.`)}for(const e of n){const t=o[e];void 0===t&&ne(`${W} entry "${e}" is not declared on the state.${le(e,Bf(o,"method"))}`),"function"!=typeof t.value&&ne(`${W} entry "${e}" is not a method. Declare it in ${L} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function qf(e,t,n){const o=e.tagName.toLowerCase();o.includes("-")||ne(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const r=Qe(e);null!==r&&"function"==typeof r.define||ne(`DCC: CustomElementRegistry is unavailable for "${o}".`),r.get(o)&&ne(`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 e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=Ff(n),f=c.length>0||d.length>0?function(e,t,n=[]){const o={protocol:"wc-bindable",version:1,properties:t.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:t.map(e=>({name:e}))};if(0===n.length)return o;const s=n.map(e=>({name:e,async:!0}));return{...o,commands:s}}(o,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(o,c):{},p=s.tagNames.state,g=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=f;static bindableEventMap=h;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(Q))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=Qe(this._shadow);return null!==e&&Ye(e,this._shadow),this._shadow}connectedCallback(){const e=this._ensureShadow();if(null!==e&&Object.keys(g.bindableEventMap).length>0){const t=e.querySelector(p);t?(Rf||(Rf=!0,Bc("dcc",Tf)),t.setBindableEventMap(g.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}},m=su(n);for(const[e,t]of Object.entries(m)){if(Df(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=Wf(e,o)}else n.get=jf(e),n.set=Lf(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:jf(e),set:Lf(e)});r.define(o,g)}async function Vf(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&ne(`"bind-component" cannot be used inside a [${Q}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await Nc(t);ne(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await kc(n,t.tagName.toLowerCase());ne(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}(o,t);qf(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const Hf={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Q)?Vf(e,t.host,t):null}};let Uf=!1;function Gf(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function Kf(e,t){for(const n of e)if(Gf(t,n.innerSegments))return n;return null}function Jf(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+c+n.join(c)}const Xf=new Map([["$eq",[0]],["$eqPath",[0,1]],["$eqIndex",[0]],["$dependOn",[0]],["$trackDependency",[0]]]);function Qf(e,t,n){const o=Xf.get(e);return void 0===o?null:(...e)=>{const s=e.slice();for(let e=0;e<o.length;e++){const n=o[e];"string"==typeof s[n]&&(s[n]=t(s[n]))}return n(s)}}const Yf=new WeakMap;function Zf(e,t,n){let o=Yf.get(e);void 0===o&&(o=new Map,Yf.set(e,o));const s=o.get(t);null!=s&&ne(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function eh(e,t){if(null===e)return!1;const n=Yf.get(e);if(void 0===n||0===n.size)return!1;for(const e of n.keys())if(t===e||t.startsWith(e+c)||e.startsWith(t+c))return!0;return!1}const th=new WeakMap;const nh=[];function oh(e,t,n,o){if(t.length>0){const s=n.split(c),r=Kf(t,s);if(null!==r)return o&&r.readonly&&ne(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${P}.${r.innerSegments.join(c)}#${w}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${w} from the injection.`),Jf(r,s)}return e+c+n}function sh(e,t,n){let o=-1,s=null;for(const e of t){const t=e.outerPathInfo.path;t.length<=o||(n===t?(o=t.length,s=e.innerSegments.join(c)):n.startsWith(t+c)&&(o=t.length,s=e.innerSegments.join(c)+n.slice(t.length)))}if(e.length>o){if(n===e)return"";if(n.startsWith(e+c))return n.slice(e.length+1)}return s}function rh(e,t,n=nh){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)=>t[o](oh(e,n,s,!1),...r)}if("$setAll"===s)return(o,...s)=>t.$setAll(oh(e,n,o,!0),...s);if("$resolve"===s)return(o,...s)=>t.$resolve(oh(e,n,o,s.length>1),...s);const o=Qf(s,t=>oh(e,n,t,!1),e=>t[s](...e));return null!==o?o:t[s]}return t[oh(e,n,s,!1)]}},set:(o,s,r)=>"string"!=typeof s||("$"===s[0]?(t[s]=r,!0):(t[oh(e,n,s,!0)]=r,!0)),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const ih=new WeakMap,ah=[];const lh=new WeakMap,ch=new WeakSet;function dh(e){console.error(`[@wcstack/state] volume "${e.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>.`),e.onGrafted(null)}let uh=null;let fh=0;const hh=["$watch",q,"$scan","$listKeys",T,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],ph=new Set;function gh(e,t,n){const o=e.stateObject[t];if("function"==typeof o)try{const s=o.call(n());s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${e.component.tagName.toLowerCase()}> ${t} failed.`,n)}}function mh(e,t,n,o,s,r=new Set){0===n.length&&ne(`Cannot build a mount record without host bindings for "${t}".`),Mc(s);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(c);a.has(n)&&ne("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(w)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++fh,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=su(e);for(const[e,s]of Object.entries(o))"function"==typeof s.get&&t.add(e),"function"==typeof s.set&&n.add(e);return{getterKeys:t,setterKeys:n}}(s),p=new Set;for(const e of i)1===e.innerSegments.length&&p.add(e.innerSegments[0]);const g={};for(const e of Object.keys(s))e.startsWith("$")||f.has(e)||h.has(e)||"function"!=typeof s[e]&&(r.has(e)||p.has(e)||(g[e]=s[e]));return{id:d,marker:u,component:e,stateProp:t,parentStateElement:o,entries:i,rootEntry:l,delta:null===l?0:l.outerPathInfo.wildcardCount,markerBasePath:null===l?u:l.outerPathInfo.path+c+u,stateObject:s,getterKeys:f,setterKeys:h,injectedKeys:r,mappedKeys:p,hasReadonlyEntries:i.some(e=>e.readonly),privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function yh(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function wh(e,t){const n=Kf(e.entries,t);return null===n?null:Jf(n,t)}function bh(e,t){return e.markerBasePath+c+t}function vh(e,t,n,o){let s=e.accessorBySuffixByMarkerParent.get(t);void 0===s&&(s=new Map,e.accessorBySuffixByMarkerParent.set(t,s));const r=t+c+n;s.set(n,{accessorName:o,indexShift:re(r).wildcardCount-re(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function $h(e,t){return!e.injectedKeys.has(t)&&(!e.getterKeys.has(t)&&"function"==typeof e.stateObject[t]||!e.mappedKeys.has(t)&&(Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t)))}function xh(e,t){return`Path "${t}" in <${e.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${e.entries.filter(e=>e.innerSegments.length>0).map(e=>e.innerSegments.join(c)).join(", ")}). Mount it from the host ("${e.stateProp}: path" / "${e.stateProp}.${yh(t)}: path") or declare the key on the component state.`}const Sh=/^\$(\d+)$/;function Ih(e,t){if(!e.hasReadonlyEntries)return null;const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=yh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||$h(e,o))return null;const s=function(e,t){return Kf(e.entries,t)}(e,t.split(c));return null!==s&&s.readonly?s:null}function Ph(e,t){const n=Ih(e,t);if(null!==n){const o=0===n.innerSegments.length?"":c+n.innerSegments.join(c);ne(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${w}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${w} from the mount.`)}return kh(e,t)}function kh(e,t){const n=t[0];if("$"===n||"#"===n)return t;if(e.getterKeys.has(t)||e.setterKeys.has(t))return function(e,t){const n=t.split(c);let o=-1;for(let e=n.length-1;e>=0;e--)if(n[e]===d){o=e;break}if(-1===o)return vh(e,e.markerBasePath,t,t),bh(e,t);if($h(e,n[0]))return vh(e,e.markerBasePath,t,t),bh(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=wh(e,s);null===i&&ne(xh(e,t)),0===r.length&&ne(`Wildcard-terminal accessor "${t}" on mounted <${e.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+c+e.marker;return vh(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=yh(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return bh(e,t);if($h(e,o))return bh(e,t);const s=wh(e,t.split(c));if(null!==s)return s;ne(xh(e,t))}const Nh=new Set(["prop","radio","checkbox"]);function Ah(e,t,n){let o;const s=Sh.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:re(kh(e,t)).wildcardCount-re(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=kh(e,t.statePathName),"for"===t.bindingType){const n=re(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+c+d,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&Nh.has(t.bindingType??"")&&!r.includes(w)&&null!==Ih(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:re(o),...i?{propModifiers:[...r,w]}:{}}:t}function _h(e,t,n,o,s){if(void 0===o)return;const r=re(n).wildcardCount-re(t).wildcardCount;return 0===r?o:(s.length<r&&ne(`Cannot resolve "${t}" 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 Ch(e,t,n){if(-1!==e.indexOf(d))return t;const o=t.split(c);let s=0;for(let e=0;e<o.length&&s<n.length;e++)o[e]===d&&(o[e]=String(n[s++]));return o.join(c)}const Eh=new WeakMap,Mh=new WeakMap;const Oh=new WeakMap;const Th=new FinalizationRegistry(function(e){const t=e.byMarker.get(e.marker);if(void 0!==t&&void 0===t.deref()&&e.byMarker.delete(e.marker),void 0!==e.getterPaths)for(const t of e.addedGetterPaths)e.getterPaths.delete(t)}),Rh=new WeakMap;function jh(e){return Rh.get(e)??null}let Lh=!1;function Wh(){Lh||(Lh=!0,xt=e=>Eh.has(e)?e.host:null)}function Dh(e){return Eh.get(e)??null}function Bh(e){return zh(e).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join(c),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]}))}function zh(e){const t=Oh.get(e);if(void 0===t)return[];const n=[];for(const e of t.values()){const t=e.deref();void 0!==t&&n.push(t)}return n}function Fh(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Oh.get(e);if(void 0===o)return null;const s=t.indexOf(c,n),r=-1===s?t.slice(n):t.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 qh=new WeakMap,Vh=new Set;function Hh(e,t,n,o){let s=qh.get(e);if(void 0===s){if(!o)return null;s=new Map,qh.set(e,s)}let r=s.get(t);if(void 0===r){if(!o)return null;r=new Map,s.set(t,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 Uh(e,t){if(!e.component.isConnected)return!1;const n=St(e.component)?.listIndex??null;if(null===t)return null===n;let o=n;for(;null!==o;){if(o===t)return!0;o=o.parentListIndex}return!1}function Gh(e,t,n,o){const s=Hh(e,t,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const e=function(e,t){const n=e.ref.deref();return void 0!==n&&Uh(n,t)?n:null}(r,o);if(null!==e)return{record:e,entry:r.entry}}let i=null,a=null;for(const e of s.holders){const r=e.ref.deref();void 0!==r?Uh(r,o)&&(null!==a&&ne(`[wcs/mount-export-ambiguous] "${t}${c}${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=e,a=r):s.holders.delete(e)}return null===i||null===a?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:a,entry:i.entry})}function Kh(e){const t=e.parentStateElement,n=St(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Bn](n,()=>{e.$postUpdate(o.exportedPath)})})}const Jh=new WeakMap,Xh=new WeakMap,Qh=new WeakMap,Yh=new WeakMap;function Zh(e,t){Xh.set(e,t);const n=[];for(let e=t?.listIndex.parentListIndex??null;null!==e;e=e.parentListIndex)n.push(e);Yh.set(e,n)}function ep(e){return St(e.component)??Xh.get(e)??null}function tp(e){return ep(e)?.listIndex??null}function np(e){ne(`The host row of <${e.component.tagName.toLowerCase()}> was removed.`)}function op(e){for(;null!==e;e=e.parentListIndex)if(Xt(e))return!0;return!1}function sp(e,t){return!e.component.isConnected&&(op(t)||!0===Yh.get(e)?.some(e=>Xt(e)))}class rp{record;markerParentPath;listIndex;hostRow;isBase;receiver;handler;authorFacing;constructor(e,t,n,o,s,r,i,a=!1){this.record=e,this.markerParentPath=t,this.listIndex=n,this.hostRow=o,this.isBase=s,this.receiver=r,this.handler=i,this.authorFacing=a}authorThis(e,t){return this.authorFacing?t:new Proxy(e,new rp(this.record,this.markerParentPath,this.listIndex,this.hostRow,this.isBase,this.receiver,this.handler,!0))}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return Po(re(this.markerParentPath+c+e),this.listIndex)}hostIndexes(){const e=this.listIndex??tp(this.record),t=this.hostRow??e;return(null===this.listIndex?t!==e||sp(this.record,t):op(t))&&np(this.record),t?.indexes??[]}resolveTreePath(e,t){return-1===t.indexOf(d)||null!==this.listIndex&&0!==this.handler.addressStackLength&&"partial"!==Jc(t).wildcardType&&!sp(this.record,this.listIndex)?t:Ch(e,t,this.hostIndexes())}get(e,t,n){if("string"!=typeof t)return Reflect.get(e,t);if("then"===t)return;if("$"===t[0]){if("$postUpdate"===t)return e=>{this.receiver.$postUpdate(this.resolveTreePath(e,kh(this.record,e)))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.hostIndexes(),o=this.receiver,s=this.handler,r=this.listIndex;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Ph(e,t):kh(e,t),a=_h(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const i=t;return(t,a,...l)=>{const c="$setAll"===i?Ph(e,t):kh(e,t),d=_h(0,t,c,void 0===a&&"$getAll"===i&&null===r&&null===Qc(s,re(c).wildcardPaths[0])?[]:a,n);return o[i](c,d,...l)}}const e=this.record,n=this.receiver,o=Qf(t,t=>this.resolveTreePath(t,kh(e,t)),e=>n[t](...e));return null!==o?o:this.receiver[t]}const o=this.accessorNameFor(t);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(t));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return Yc(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(this.authorThis(e,n))}return this.receiver[this.resolveTreePath(t,kh(this.record,t))]}set(e,t,n,o){if("string"!=typeof t)return Reflect.set(e,t,n);const s=this.accessorNameFor(t);if(void 0!==s){this.record.setterKeys.has(s)||ne(`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(t)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,this.authorThis(e,o))}finally{this.handler.endUntrack(),this.handler.popAddress()}}if(this.isBase&&Object.prototype.hasOwnProperty.call(e,t)){if(this.authorFacing&&"readonly"!==this.handler.mutability){null===this.listIndex&&this.hostIndexes(),this.handler.pushAddress(Po(re(this.markerParentPath),this.listIndex));try{this.receiver[this.markerParentPath+c+t]=n}finally{this.handler.popAddress()}return!0}return e[t]=n,!0}return this.receiver[this.resolveTreePath(t,Ph(this.record,t))]=n,!0}has(e,t){if("string"!=typeof t)return Reflect.has(e,t);if("$"===t[0]||"#"===t[0])return!1;if(void 0!==this.accessorNameFor(t))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(e,t))return!0;if("function"==typeof this.record.stateObject[t])return!0}try{return kh(this.record,t),!0}catch{return!1}}}function ip(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Jh.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Jh.set(e,n)),null===t)return n.noIndex??={...e.privateSnapshot};let o=n.byListIndex.get(t);return void 0===o&&(o={...e.privateSnapshot},n.byListIndex.set(t,o)),o}(e,t.listIndex):{};return new Proxy(i,new rp(e,s,t.listIndex,t.listIndex??tp(e),r,n,o))}function ap(e){if(null===tp(e))return e.component[e.stateProp];let t=Qh.get(e);if(void 0===t){const n={row:null};Qh.set(e,t=[lp(e,n),n])}return t[0]}function lp(e,t){const n=()=>{const n=ep(e);return void 0!==t&&Qh.get(e)?.[0]!==i&&n.listIndex!==t.row&&np(e),n},o=()=>{const t=n();return sp(e,t?.listIndex??null)&&np(e),t?.listIndex.indexes??[]},s=(t,n)=>-1===n.indexOf(d)?n:"partial"===Jc(n).wildcardType?Ch(t,n,o()):-1===n.indexOf("#")&&sp(e,tp(e))?np(e):n,r=(t,o)=>{let s;const r=n();return e.parentStateElement.createState(t,e=>{s=e[Bn](r,()=>o(e))}),s},i=new Proxy({},{get(t,n){if("string"!=typeof n||"then"===n)return;if("$getAll"===n||"$setAll"===n||"$resolve"===n||"$postUpdate"===n)return function(e,t,n,o,s){return"$postUpdate"===t?t=>n("readonly",n=>n.$postUpdate(s(t,kh(e,t)))):(s,r,...i)=>{const a="$setAll"===t||"$resolve"===t&&i.length>0,l=a?Ph(e,s):kh(e,s),c=_h(0,s,l,"$resolve"===t?r??[]:r,o());return n(a?"writable":"readonly",e=>e[t](l,c,...i))}}(e,n,r,o,s);const i=Qf(n,t=>s(t,kh(e,t)),e=>r("readonly",t=>t[n](...e)));if(null!==i)return i;const a=t=>t["$"===n[0]?n:s(n,kh(e,n))],l=r("readonly",a);return"$"===n[0]||e.getterKeys.has(n)||"function"!=typeof e.stateObject[n]?l:function(...e){return r("writable",t=>a(t).apply(this,e))}},set:(t,n,o)=>("string"==typeof n&&r("writable",t=>{t["$"===n[0]?n:s(n,Ph(e,n))]=o}),!0),has(t,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(e.stateObject,n))return!0;try{return kh(e,n),!0}catch{return!1}}});return i}function cp(e,t){const n=Dh(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&ne(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${e.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&function(e){const t=kr(e);t.dispose();const n=[],o=document.createTreeWalker(e);for(;o.nextNode();)t.handleAddedNode(o.currentNode,n,e=>{console.error("[@wcstack/state] a binding failed to start again on the mount scope's re-initialization.",e)});Tl(n)}(t),function(e,t){Wh(),Eh.set(e,t),Rh.set(t,e);let n=Oh.get(t.parentStateElement);void 0===n&&(n=new Map,Oh.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Mh.get(t.component);void 0===o&&(o=new Map,Mh.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Th.register(t,{byMarker:n,marker:t.marker,getterPaths:t.parentStateElement.getterPaths,addedGetterPaths:t.addedGetterPaths}),t.parentStateElement.markHasMounts?.()}(t,e),t instanceof ShadowRoot&&function(e,t){const n=Bl.get(e);if(void 0!==n){if(n===t)return;ne("A state tree is already registered on this root.")}Bl.set(e,t)}(t,e.parentStateElement),function(e,t,n){const o=(t,n)=>Ah(e,t,n);ee(t,n?e=>function(e,t){for(let n=e;n!==t;n=n.parentNode)if(hr(n))return!0;return!1}(e,t):void 0);const s=St(e.component);Zh(e,s);mc(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,o),jl(t,s,o)}(e,t,null!==n),function(e){if(e.exports.size>0||null===e.rootEntry)return;const t=new Set([...e.getterKeys,...e.setterKeys]);for(const n of t){let t;try{t=kh(e,n)}catch{continue}const o=t.indexOf(c+e.marker);if(-1===o)continue;const s=t.slice(0,o+1+e.marker.length),r=t.slice(s.length+1),i=t.slice(0,o)+c+r,a=re(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Hh(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),ru?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=St(e.component);if(e.delta>0&&null===t)return;const n=e.component.tagName.toLowerCase();for(const o of e.exports.values()){const s=`${n}|${o.exportedPath}`;if(Vh.has(s))continue;const r=re(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Bn](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Vh.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${e.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.`))}}(e),Kh(e),o=t,s=Promise.resolve(),zl.set(o,s),s.then(()=>Gl(o),()=>{})}function dp(e,t){Tl(up(e,t).rebindAddresses()),Kh(e)}function up(e,t){const n=kr(t),o=St(e.component);return Zh(e,o),n.forEachActiveBindingNode(e=>It(e,o)),n}function fp(e){for(let t=e.parentNode;null!==t;t=t.parentNode){const e=Dh(t);if(null!==e)return fp(e.component),void up(e,t)}}function hp(e,t){if(function(e){const t=Oh.get(e);return void 0!==t&&t.size>0}(t))for(const n of zh(t)){if(!pp(n.component,e))continue;const t=jh(n);null!==t&&dp(n,t)}}function pp(e,t){for(let n=t.firstNode;null!==n;n=n.nextSibling){if(n===e||n.contains(e))return!0;if(n===t.lastNode)break}return!1}const gp={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Fh(e,t.pathInfo.path);if(null!==s)return ip(s,t,n,o)}return Lc},readMissing(e,t,n,o,s){if(null===n){if(eh(e.rootNode??null,t.pathInfo.path))return;return Lc}if(!0===e.hasMounts){const n=Gh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=ip(e,Po(re(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return Lc},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=th.get(e);if(void 0===n||0===n.size)return null;const o=t+c;for(const e of n)if(e.startsWith(o))return e;return null}(e,n);null!==o&&ne(`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 Lc},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Gh(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=ip(e,Po(re(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return Lc},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Fh(n,o);if(null!==e)return function(e,t){const n=t.lastIndexOf("#");if(-1===n)return e.delta;const o=t.indexOf(c,n);if((-1===o?t.slice(n):t.slice(n,o))!==e.marker)return e.delta;const s=-1===o?t:t.slice(0,o),r=-1===o?"":t.slice(o+1),i=e.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:e.delta}(e,o)}return 0},handlerScope(e,t,n,o,s){if(!0!==e.hasMounts)return s;const r=function(e,t){let n=e;for(;null!==n&&n!==t;){const e=Eh.get(n);if(void 0!==e)return e;n=n.parentNode}return Eh.get(t)??null}(t,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(e,t,n){const o=function(e){return ih.get(e)??ah}(e);for(const s of o){const o=new Set,r={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(-1!==t.indexOf("#"))continue;const i=sh(s.mountPath,s.injections,t);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const e=lo(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(rh(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>eh(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){hp(t,e)}};let mp=!1;function yp(){mp||(mp=!0,Bc("scopes",gp),wu=Bh)}const wp=new WeakMap;function bp(e){let t=wp.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},wp.set(e,t)),t}function vp(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Yf.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function $p(e,t,n){if(t.slotRootNode===n)return!0;const o=t.mountPath;try{Zf(n,o,e)}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 Vl(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function xp(e,t){const n=e,o=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&ne('"mount" requires a non-empty tree path.');const t=re(e);for(const n of t.segments)0===n.length&&ne(`"mount" path "${e}" has an empty segment.`),n===d&&ne(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&ne(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],o=new Set;let r;try{r=Le(e)}catch(e){ne(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> has an invalid ${s.bindAttributeName}: ${e instanceof Error?e.message:String(e)}`)}for(const e of r){if(e.propSegments[0]!==P)continue;const r=e.propSegments.slice(1),i=e.statePathInfo,a=n=>ne(`[wcs/mount-path-invalid] <${s.tagNames.state} mount="${t}"> "${e.propName}: ${e.statePathName}": ${n}`);1===r.length&&r[0]&&r[0]!==d&&"$"!==r[0][0]&&"#"!==r[0][0]||a(`inject one key at a time ("${P}.<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)."),(e.inFilters.length>0||e.outFilters.length>0)&&a("an injection takes no filters."),e.propModifiers.some(e=>e!==w)&&a(`an injection accepts only #${w}.`),o.has(r[0])&&a(`"${r[0]}" is injected twice.`),o.add(r[0]),n.push({innerSegments:r,outerPathInfo:i,readonly:e.propModifiers.includes(w)})}return n.sort((e,t)=>t.innerSegments.length-e.innerSegments.length),n}(n.getAttribute(s.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&ne('"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).`),Zf(o,r,e),Vl(o)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=o}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===Vl(o)&&function(e,t){const n=()=>{if(null!==Vl(e))return;const n=e.querySelectorAll(s.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${s.tagNames.state} mount="${t}"> 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=e.ownerDocument??e;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&vp(e,t),e.settleInitialization()};let l;try{await Promise.resolve(),l=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void a(null)}const c=e.connectedRootNode??null;null!==c&&$p(e,t,c)?function(e,t,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};if(null!==t)return void Qp(t,a);Zp(),function(e,t){if(ch.has(e))return void dh(t);let n=lh.get(e);void 0===n&&(n=[],lh.set(e,n)),n.push(t)}(e,a)}(c,Vl(c),r,l,a,()=>$p(e,t,c),i):a(null)}const Sp={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=bp(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{Zf(n,t.mountPath,e),Vl(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,Yd}return xp(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=bp(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&Vl(n)===t.graftInfo.rootStateElement&&Kp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==wp.get(e)?.initializing)return;const t=e.getAttribute("mount");ne(`Cannot replace the state of <${s.tagNames.state} mount="${t}"> 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 "${t}" on the root state instead.`)},initializeFailed(e,t){!function(e){ch.add(e);const t=lh.get(e);if(void 0!==t){lh.delete(e);for(const e of t)dh(e)}}(t)},initializeFailureCleared(e,t){!function(e){ch.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=bp(e);return null!==t.graftInfo&&Kp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,vp(e,t)),e.clearConnectedRootNode(),!0}};let Ip=!1;const Pp=new WeakMap;function kp(e,t){let n=Pp.get(e);n||(n=new Set,Pp.set(e,n)),n.add(t)}const Np=new WeakMap;const Ap=new WeakMap,_p=new WeakMap;const Cp=new WeakMap;const Ep={isComplete:function(e,t){return!0===Pp.get(e)?.has(t)},isDeclared:function(e,t){return!0===Np.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=Ap.get(e);o||(o=new Map,Ap.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=_p.get(e);o||(o=new Map,_p.set(e,o));let s=o.get(t);s||(s=new Set,o.set(t,s)),s.add(n)},rememberOverwrittenValue:function(e,t,n,o){let s=Cp.get(e);s||(s=new Map,Cp.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function Mp(e){return function(e){const t=Object.getPrototypeOf(e),n=Object.create(t),o=Object.getOwnPropertyDescriptors(e);for(const e in o){const t=o[e];!1===t.writable&&(t.writable=!0)}return Object.defineProperties(n,o),n}(e)}const Op=new WeakMap;class Tp{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=Op.get(e);return n?n.get(t)??null:null}(e,t)??ne("State element not found for web component.")}get(e,t,n){if("string"==typeof t){let e;return this._innerStateElement.createState("readonly",n=>{e=n[t]}),e}return Reflect.get(e,t,n)}set(e,t,n,o){return"string"==typeof t?(this._innerStateElement.createState("writable",e=>{e[t]=n}),!0):Reflect.set(e,t,n,o)}}const Rp=e=>()=>e;function jp(e,t,n,o){!function(e,t,n){let o=Op.get(e);o||(o=new Map,Op.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(Mp(o));const s=function(e,t){const n=new Tp(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Rp(s),enumerable:!0,configurable:!0}),kp(t,n),Lp(t,n)}function Lp(e,t){if(j in e){const n=e[j];"function"==typeof n?n.call(e,t).catch(e=>{ne(`Error in ${j}: ${e instanceof Error?e.message:String(e)}`)}):ne(`${j} is not a function.`)}}const Wp=new Set;function Dp(e,t){Wp.has(e)||(Wp.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function Bp(e){!function(e){const t=e.component.tagName.toLowerCase(),n=e.stateProp;let o=null;for(const s of e.entries){if(0===s.innerSegments.length)continue;const r=s.innerSegments[0];o??=su(e.stateObject);const i=o[r];let a;if(e.getterKeys.has(r)||e.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(e.mappedKeys.has(r)||e.injectedKeys.has(r)||!Object.prototype.hasOwnProperty.call(e.stateObject,r))continue;a="an own data key"}const l=s.innerSegments.join(c);Dp(`${t}|${n}|${l}|entry`,`<${t}>.${n} declares "${r}" as ${a}, which hides the mounted entry "${n}.${l}: ${s.outerPathInfo.path}" (the host value never reaches it). Rename one of them.`)}}(e);const t=Object.keys(e.privateSnapshot);if(0===t.length)return;const n=e.component.tagName.toLowerCase(),o=e.stateProp;let s,r=!1;for(const i of t){if(null===e.rootEntry)continue;if(r||(s=zp(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;Dp(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${t}.${i}" (${o}: ${t}). Remove the default to read the tree, or rename it to keep it private.`)}}function zp(e){const t=e.rootEntry,n=St(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Bn](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Fp=new WeakMap;function qp(e,t){e.landInitialization(),ne(t)}async function Vp(e,t){const n=e;if(n.hasAttribute("bind-component")){const i=n.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?Je(a):null;null!==a&&null!==l||ne(`"bind-component" requires <${s.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(s.bindAttributeName)||qp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(e=>n.hasAttribute(e));null!==n.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&ne(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(e,t){let n=Np.get(e);n||(n=new Set,Np.set(e,n)),n.add(t)}(a,d);const u=Qe(a);null===u&&ne(`CustomElementRegistry is unavailable for <${l}>.`);const f=e.connectGeneration;if(await u.whenDefined(l.toLowerCase()),a.hasAttribute(s.bindAttributeName)&&await Ue(a),e.connectGeneration!==f)return!0;d in a||ne(`Component does not have property "${d}" for state binding.`);let h=a[d];"object"==typeof h&&null!==h||ne(`Component property "${d}" is not an object for state binding.`);const p=function(e,t){const n=Ap.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==p&&function(e,t){if(!e.hasAttribute(s.bindAttributeName))return!1;const n=ut(e);if(null===n)return!1;for(const e of n)if(1===e.propSegments.length&&e.propSegments[0]===t)return!0;return!1}(a,d)&&(a[d]=p,h=p),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(ut(a)??[]).some(e=>e.propSegments[0]===d)||qp(e,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${d}: path").`),a.hasAttribute(s.bindAttributeName)){const s=(ut(a)??[]).filter(e=>e.propSegments[0]===d);if(s.length>0){const c=Vl(a.getRootNode())??qp(e,`No state tree found on this root for mount host <${l}>.`);let u=(o=a,r=d,Mh.get(o)?.get(r)??null);const f=null!==u;if(null===u&&(!function(e,t,n){const o=Cp.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;Cp.get(e).delete(t)}}(a,d,h),u=mh(a,d,s,c,h,function(e,t){return _p.get(e)?.get(t)}(a,d)),Bp(u)),t.mountRecord=u,n.parentNode!==i)return!1;try{cp(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!f){const e=lp(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),kp(a,d)}return Lp(a,d),function(e){const t=hh.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(G)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;ph.has(n)||(ph.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${e.stateProp} declares ${t.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.`))}(u),gh(u,"$connectedCallback",()=>ap(u)),!1}}jp(e,t.boundComponent,t.boundComponentStateProp,h)}var o,r;return!1}const Hp={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=Fp.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Fp.set(e,t)),t}(e);return Vp(e,t).then(n=>!!n||null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Fp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&dp(n,o)}),e.isConnected&&(fp(n.component),up(n,o)),gh(n,"$connectedCallback",()=>ap(n)),!0},disconnecting(e){const t=Fp.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord;return gh(n,"$disconnectedCallback",()=>ap(n)),function(e){const t=Qh.get(e);void 0!==t&&(t[1].row=tp(e),Qh.delete(e))}(n),Kh(t.mountRecord),e.clearConnectedRootNode(),!0}};let Up=!1;function Gp(){Up||(Up=!0,tu("bindComponent",Hp),Ar=Ep)}function Kp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(rh(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function Jp(e,t,n,o){const s=n[V];if(void 0!==s){const n=yu(t),r=[],i=new Set;let a=0;for(const[n,l]of Object.entries(s)){const s=oh(t,o,n,!1),c=function(e,n,...s){l.call(rh(t,this,o),e,n,...s)};r.push({path:s,pathInfo:re(s),handler:c,order:1e6+a++}),i.add(s),e.setPathInfo(s,"prop","watch")}r.length>0&&(n.addEntries(e,r),e.addVolumeWatchPaths?.(i),n.start(e))}const r=n[K];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(oh(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[T];"function"==typeof i&&(!function(e,t){let n=ih.get(e);void 0===n&&(n=[],ih.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,injections:o,callback:i}),e.enableUpdatedCallback?.());for(const e of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[e]&&console.warn(`[@wcstack/state] volume "${t}" declares ${e}, which volumes do not support. Declare it on the root state instead.`);he?.volume(t,n,o.length)}function Xp(e,t,n,o=[]){Mc(n),function(e,t,n,o){const s=0===o.length?null:su(n);for(const e of o){const n=e.innerSegments[0],o=s[n];void 0===o||"function"!=typeof o.get&&"function"!=typeof o.set&&"function"!=typeof o.value||ne(`[wcs/mount-path-invalid] Volume "${t}" declares "${n}" as an accessor or a method and also injects it ("${P}.${n}: ${e.outerPathInfo.path}"). Rename one of them.`)}const r=n[V];if(void 0!==r){"object"==typeof r&&null!==r||ne(`${V} must be an object mapping state paths to handler functions.`);const e=yu(t);for(const[t,n]of Object.entries(r))"function"!=typeof n&&ne(`${V} entry "${t}" must be a function.`),e.assertValidPath(t)}const i=n[K];if(void 0!==i){"object"==typeof i&&null!==i||ne(`${K} 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)&&ne(`${K} entry "${n}" must map a list path to a field name or a key function.`);const r=oh(t,o,n,!1);e.listKeys?.has(r)&&ne(`${K} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[q]&&ne(`Volume "${t}" declares ${q}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&ne(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[U]&&ne(`Volume "${t}" declares ${U}, 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 e of Object.keys(su(n)))-1!==e.indexOf(G)&&ne(`Volume "${t}" declares "${e}", which uses "${G}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n,o);const{data:s,accessors:r}=function(e,t){const n={},o=new Map;for(const[s,r]of Object.entries(su(e)))s.startsWith("$")||t.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(e=>e.innerSegments[0]))),i=re(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;ne(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let t=0;t<i.segments.length-1;t++){const o=i.segments[t],s=""===n?o in e:void 0!==e[n+c+o];n=""===n?o:n+c+o,s||(e[n]={})}if(i.segments.length>1&&void 0!==e[t]){if(a)return;ne(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=s}),function(e,t){let n=th.get(e);void 0===n&&(n=new Set,th.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,s]of r){const r=t+c+n,i=s.get,a=s.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(rh(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(rh(t,this,o),e)}),e.defineTreeAccessor(r,l)}Jp(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(rh(t,e,o))}catch(e){return void console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)}n instanceof Promise&&n.catch(e=>{console.error(`[@wcstack/state] volume "${t}" $connectedCallback failed.`,e)})}),{rootStateElement:e,mountPath:t,volumeState:n,injections:o}}function Qp(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=Xp(e,t.mountPath,t.volumeState,t.injections)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let Yp=!1;function Zp(){var e;Yp||(Yp=!0,yp(),Ip||(Ip=!0,tu("scopes",Sp)),Gp(),uh=Qp,e=eg,ql.includes(e)||ql.push(e))}function eg(e,t){(function(e){const t=Yf.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){ch.delete(e);const n=lh.get(e);if(void 0===n||0===n.length||null===uh)return;lh.delete(e);const o=uh;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const tg={name:"scopes",install(){Zp(),Uf||(Uf=!0,tu("dcc",Hf))}},ng=/^@@wcs-(?:for|if|elseif|else):[^-]/,og=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,sg=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,rg=/^@@wcs-text-start:(.+)$/;function ig(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ag(e,t){const n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();){const e=n.currentNode;t(e.data)&&o.push(e)}return o}const lg=e=>ng.test(e),cg=e=>og.test(e),dg=e=>og.test(e)||sg.test(e);function ug(e){return"else"===e.bindingType?"else:":`${e.bindingType}: ${fg(e.statePathName,e.outFilters)}`}function fg(e,t){let n=e;for(const e of t){const t=e.literals??e.args;n+=`|${e.filterName}`,e.args.length>0&&(n+=`(${e.args.map((e,n)=>"string"==typeof t[n]?`'${e.split("'").join("'\"'\"'")}'`:e).join(",")})`)}return n}const hg=/--|-$|[\0\n\r\u2028\u2029]/;function pg(e){const t=e.fragment.cloneNode(!0);for(const n of e.nodeInfos){const o=cc(at(e.fragment,n.nodePath));if(null===o)continue;const s=at(t,n.nodePath);s.parentNode.replaceChild(document.createComment(o),s)}return t}class gg extends ou{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){const e=this.version;if(!e)return!0;const t=e.split("."),n=vu.split(".");return t[0]===n[0]&&t[1]===n[1]}setStateData(e){this._stateData=e}setHydrateProps(e){this._hydrateProps=e}_loadStateData(){const e=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}_loadTemplates(){const e=new Map,t=this.querySelectorAll("template[id]");for(const n of t){const t=n.getAttribute("id");t&&e.set(t,n)}return e}_loadHydrateProps(){const e=this.querySelector("script[data-wcs-ssr-props]");if(!e)return{};try{return JSON.parse(e.textContent||"{}")}catch{return{}}}static find(e){const t=s.tagNames.ssr,n=e instanceof Element?e:e instanceof Document?e.documentElement:null;if(!n)return null;return n.querySelector(t)}static extractStateData(e){const t=e.__state;if(!t||"object"!=typeof t)return{};const n={};for(const e of Object.keys(t)){if(e.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(t,e);if(void 0!==o&&"function"==typeof o.get)continue;const s=t[e];"function"!=typeof s&&(n[e]=s)}return n}static buildContent(e,t,o){const r=o??e.ownerDocument;n.seen&&function(e){const t=new Map;for(const n of ag(e,cg)){if(null===n.parentNode)continue;const[,e,o]=og.exec(n.data),s=o.split(":")[0],r=n.previousSibling?.data,i=`@@wcs-${e}-end:${o}`;if(r!==`@@wcs-${e}:${s}`&&t.get(r)!==s)for(let e=n;null!==e;){const t=e.nextSibling;e.remove(),e=e.data===i?null:t}else"for"===e&&t.set(i,s)}}(r);const i=document.createElement("script");i.setAttribute("type","application/json"),i.textContent=ig(JSON.stringify(t)),e.appendChild(i);for(const[t,n]of function(e){const t=new Map,n=[e];for(;n.length>0;)for(const e of ag(n.shift(),lg)){const o=e.data,s=o.slice(o.indexOf(":")+1);if(t.has(s))continue;const r=Ql(s);null!==r&&(t.set(s,r),n.push(r.fragment))}return t}(r)){const o=document.createElement("template");o.setAttribute("id",t),o.setAttribute(s.bindAttributeName,ug(n.parseBindTextResult)),o.content.appendChild(pg(n)),e.appendChild(o)}const a=e.ownerDocument,l=Array.from(Xa);if(l.length>0){const t={};for(let e=0;e<l.length;e++){const n=l[e];if(!n.isConnected||n.ownerDocument!==a)continue;const o=Ja(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const r={};for(const e of o)r[e.propName]=e.value;t[s]=r}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ig(JSON.stringify(t)),e.appendChild(n)}}Qa()}static removeBlockBoundaryComments(e){for(const t of ag(e,dg))t.remove()}static removeStructuralComments(e){for(const t of ag(e,lg))t.remove()}static restoreTextBindings(e){for(const t of ag(e,e=>rg.test(e))){const e=rg.exec(t.data)[1],n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=e}}}static cleanupDom(e){const t=document.body,n=e.querySelectorAll(s.tagNames.ssr),o=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&o.set(t,e)}}for(const e of ag(t,cg)){const t=og.exec(e.data),n=`@@wcs-${t[1]}-end:${t[2]}`;let o=e.nextSibling;for(;o;){const e=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=e}e.remove()}gg.restoreTextBindings(t);const r=e=>{for(const t of ag(e,lg)){const e=o.get(t.data.split(":")[1]);if(e){const n=document.createElement("template"),o=e.getAttribute(s.bindAttributeName);o&&n.setAttribute(s.bindAttributeName,o);const i=document.importNode(e.content,!0);if(i.childNodes.length>0)n.content.appendChild(i);else for(const t of Array.from(e.childNodes))n.content.appendChild(document.importNode(t,!0));r(n.content),t.parentNode.replaceChild(n,t)}}};r(t);const i=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of i)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const mg={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=s.tagNames.state,n=s.tagNames.ssr,o=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of o){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",vu),gg.buildContent(o,gg.extractStateData(e),e.getRootNode()),e.parentNode?.insertBefore(o,e)}Qa()},reset:function(){Jl.clear(),Qa(),n.seen=!1}};const yg=new Set(["for","if","elseif","else"]);function wg(e){const[,t,n]=og.exec(e),[o,...s]=n.split(":");return"for"===t?{type:t,uuid:o,path:s[0],index:parseInt(s[1],10),nodes:[]}:{type:t,uuid:o,path:s.join(":"),index:null,nodes:[]}}function bg(e){const t=[];for(const n of e)if(n.nodeType===Node.ELEMENT_NODE){const e=n;e.hasAttribute(s.bindAttributeName)&&t.push(e),Array.from(e.children).some(e=>e.localName===s.tagNames.state&&ft(e))||t.push(...gt(e))}else null!==ze(n)&&t.push(n);return t}function vg(e){const[t,n,o]=wt(e),s=new Pr;return{bindingInfos:s.initialize(n,{registerAddress:!1,applyOnReconnect:!1}),subscriberNodes:t,bindingSession:s,deferredSpreads:o}}const $g=/^\s*@@\s*(?:wcs-text)?\s*:/;function xg(e,t){for(const n of t)"event"===n.bindingType||yg.has(n.bindingType)||(n.node.nodeType!==Node.COMMENT_NODE||"text"===n.bindingType&&$g.test(n.node.data))&&e.push(n)}function Sg(e,t){const n=[];for(let o=0;o<e.nodes.length;o++){const s=t.get(e.nodes[o]);s?o+=s.nodes.length+1:n.push(e.nodes[o])}return n}function Ig(e,t,n,o,s,r){t.length>0&&(e.spreads=t);for(const e of t)bt(e.node);Rl(t,n,o,s,r)}function Pg(e,t){const n=Ql(t),o=Vl(e.getRootNode());let s=null;if(n&&o){const{statePathName:e,outFilters:t}=n.parseBindTextResult;o.createState("readonly",n=>{const o=_r(n[e],lt(t,"output"));Array.isArray(o)&&(s=o)})}return s}function kg(e,t){return`@@${{for:s.commentForPrefix,if:s.commentIfPrefix,elseif:s.commentElseIfPrefix,else:s.commentElsePrefix}[e]}:${t}`}function Ng(e,t,n){const o=kg(t,n);return ag(e,e=>e===o)[0]??null}function Ag(e,t){const n=e,o=t.templates,r=new Map;for(const[e,t]of o)for(const n of ag(t.content,lg))r.set(n.data.slice(n.data.indexOf(":")+1),e);const i=new Set(ht(e));if(i.size>0)for(const e of ag(n,lg)){const t=e.data.slice(e.data.indexOf(":")+1);let n=e.parentNode;for(;null!==n&&!i.has(n);)n=n.parentNode;null===n||r.has(t)||r.set(t,n)}const a=new Map,l=[];for(const[e,t]of o){let n=Le(t.getAttribute(s.bindAttributeName)||"")[0];const o=n.bindingType,i=r.get(e),c=a.get(i);"else"===o&&c&&(n={...c,outFilters:[...c.outFilters,ec()],bindingType:"else"}),"if"===o||"elseif"===o?a.set(i,n):"else"===o&&a.set(i,null),l.push([e,t,n])}for(const[e,t,o]of l.reverse()){const s=document.importNode(t.content,!0),r="for"===o.bindingType?o.statePathName:void 0;uc(s),"string"==typeof r&&ic(s,r),mc(n,s,r);Xl(e,n,{fragment:s,parseBindTextResult:o,nodeInfos:dc(s)})}}const _g={hydrate:async function(e){await Wl(e);const t=e.querySelectorAll(s.tagNames.ssr);for(const n of t){const t=n;if(!t.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${t.version}", client="${vu}". Falling back to full render.`),gg.cleanupDom(e),!1}const n=function(e){const t=[];for(const n of ag(e,dg)){if(!cg(n.data)){t.pop();continue}const e=wg(n.data),o=t.at(-1);if("for"===e.type&&o&&o.uuid!==e.uuid)return[e,o];t.push(e)}return null}(document.body);if(null!==n){const[t,o]=n;return console.warn(`[@wcstack/state] SSR: "for: ${t.path}" in "${o.type}: ${o.path}" (known limitation). Falling back to full render.`),gg.cleanupDom(e),!1}for(const n of t)Ag(e,n);gg.restoreTextBindings(document.body);const o=function(e){const t=[];for(const n of ag(e,cg)){const e=wg(n.data);e.start=n;const o=n.data.replace("-start:","-end:");let s=n.nextSibling;for(;s&&(s.nodeType!==Node.COMMENT_NODE||s.data!==o);)e.nodes.push(s),s=s.nextSibling;t.push(e)}return t}(document.body),r=new Map,i=function(e,t,n=new Map){const o=new Map,s=[],r=new Map(t.map(e=>[e.start,e])),i=new Set;for(let e=t.length-1;e>=0;e--){const n=bg(t[e].nodes).filter(e=>!i.has(e));for(const e of n)i.add(e);t[e].subscribers=n}for(const i of t){const t=Sg(i,r);if(0===t.length)continue;const a=t.some(e=>lg(e.data));if(a){const e=document.createComment(`wcs-row-end:${i.uuid}`);i.nodes[i.nodes.length-1].after(e),t.push(e)}const{bindingInfos:l,subscriberNodes:c,bindingSession:u,deferredSpreads:f}=vg(i.subscribers);for(const e of l)if(e.node!==e.replaceNode){const n=t.indexOf(e.node);n>=0&&(t[n]=e.replaceNode)}const h=Ia(t,a);sa(h,u),Tr(h,l),Lr(h,c);const p=l.filter(e=>Sa(e,-1));if(zr(h,p),"for"===i.type&&null!==i.index){const t=Ng(e,"for",i.uuid);if(t){let e=n.get(i.uuid);if(!e){const s=Pg(t,i.uuid)??i.path;e=o.get(s),e||o.set(s,e=[]),n.set(i.uuid,e)}const r=e[i.index]??=Mt(null,i.index);Wa(t,r,h),Da(t,h.lastNode),pa(t,h);const a=Po(re(i.path+"."+d),r);Wr(h,a),u.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),xg(s,l),Ig(h,f,a,u,l,p)}}else{const t=i.start.previousSibling,n=t?.data===kg(i.type,i.uuid)?t:Ng(e,i.type,i.uuid);if(n){pa(n,h);const e=St(n);Wr(h,e),u.initialize(l,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),xg(s,l),Ig(h,f,e,u,l,p)}}}return s}(document.body,o,r);gg.removeBlockBoundaryComments(document.body);const a=[];for(const e of t)e.parentNode&&(a.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());const[,l,c]=function(e,t){return wt(gt(e),t)}(document.body),u=[],f=[],h=kr(document.body),p=h.initialize(l);Rl(c,null,h);for(const e of p)if("event"!==e.bindingType)if(yg.has(e.bindingType))f.push(e);else{if(e.statePathName.includes(d))continue;u.push(e)}for(const e of f)if("for"===e.bindingType){const t=po(e),n=Vl(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=_r(n[e.statePathName],e.outFilters);if(Array.isArray(o)){const n=r.get(e.uuid);n&&mn(o,n),Nn(t,o),s=e.node,i=o,Ra.set(s,wn(i)),jn(t,o)}var s,i})}Tl([...u,...i]);for(const{el:e,parent:t,next:n}of a)t.insertBefore(e,n);const g=new Map;for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))g.set(t.getAttribute("data-wcs-ssr-id"),t);for(const t of e.querySelectorAll(s.tagNames.ssr))for(const[e,n]of Object.entries(t.hydrateProps)){const t=g.get(e);if(t)for(const[e,o]of Object.entries(n))Ar?.isDeclared(t,e)||(t[e]=o)}for(const t of e.querySelectorAll("[data-wcs-ssr-id]"))t.removeAttribute("data-wcs-ssr-id");return!0},textMarker:function(e){const t=e.node.nodeType===Node.COMMENT_NODE,n=t?ze(e.node):null,o=n??(t?e.statePathName:fg(e.statePathName,e.outFilters));if(!hg.test(o))return o;const s=n?.split("|")[0].trim();return s&&!hg.test(s)?s:e.statePathName},loadState(e){const t=e.parentNode;if(!t)return null;const n=gg.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Hl(e.rootNode);const t=gg.extractStateData(e),n=document.createElement(s.tagNames.ssr);n.setAttribute("version",vu),gg.buildContent(n,t,e.rootNode),e.parentNode?.insertBefore(n,e)}};let Cg=!1;function Eg(){Cg||(Cg=!0,al=_g,function(e){if(!du.includes(e)){du.push(e);for(const t of fu())e(t)}}(e=>{e.get(s.tagNames.ssr)||e.define(s.tagNames.ssr,gg)}),function(){const t=globalThis;void 0===t[e]&&(t[e]=mg)}())}const Mg={name:"ssr",install(){Eg()}},Og=new WeakMap,Tg=new Set,Rg=new Set;function jg(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Lg(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function Wg(e){return Og.get(e)}function Dg(e){Bg(e),Og.delete(e)}function Bg(e){Tg.delete(e),Rg.delete(e)}const zg=new WeakSet;let Fg=0;function qg(e){return Wg(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Vg(e){if(0===Rg.size)return;if(t=e.absolutePathInfo.stateElement,!Rg.has(t))return;var t;const n=qg(e);if(void 0!==n)for(const e of n)Hg(e)}function Hg(e){zg.has(e)||(zg.add(e),Fg++)}function Ug(e){return!!zg.delete(e)&&(Fg--,!0)}const Gg=/^(?:0|[1-9]\d*)$/;function Kg(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Jg(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return null;const t=Object.getPrototypeOf(e);if(Array.isArray(e)){return t===Array.prototype&&Reflect.ownKeys(e).every(t=>"length"===t||"string"==typeof t&&Gg.test(t)&&Kg(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Kg(e,t))?"object":null}function Xg(e,t){const n=Jg(e);if(null===n)return e;const o=e,s=t.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(e.length):null===Object.getPrototypeOf(e)?Object.create(null):{},t.set(o,r);for(const e of Object.keys(o))r[e]=Xg(o[e],t);return r}function Qg(e){return Xg(e,new Map)}function Yg(e,t,n){if(Object.is(e,t))return!0;const o=Jg(t);if(null===o||"object"!=typeof e||null===e)return!1;const s=e,r=t;if("array"===o){if(!Array.isArray(e)||e.length!==t.length)return!1}else if(Array.isArray(e)||Object.keys(s).length!==Object.keys(r).length)return!1;if(Jg(e)!==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 t=0;t<e.length;t++)if(!Yg(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&Yg(s[e],r[e],n))}function Zg(e,t){return Yg(e,t,new Map)}const em=new WeakMap;function tm(e,t){if("function"!=typeof t)return;const n=em.get(t);void 0===n?em.set(t,new Set([e])):n.add(e)}function nm(e,t){return"function"==typeof t&&!0===em.get(t)?.has(e)}const om={"read-source":e=>`${H} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-rows":e=>`${H} could not read the rows of "from" for "${e}". Nothing was folded or written.`,"read-output":e=>`${H} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${H} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${H} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${H} could not write the output "${e}".`},sm={"read-source":"evaluate","read-rows":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function rm(e,t,n){null!==Pt&&Pt({type:"state:watch-error",phase:t,path:`${H}.${e}`,error:n})}function im(e,t,n){console.error(`[@wcstack/state] ${om[n](e)}`,t),rm(e,sm[n],t)}function am(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function lm(e,t){t.then(void 0,()=>{}),im(e,new TypeError(`${H} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const cm=new WeakSet;const dm="[wcs/scan-declaration-invalid]",um=Object.freeze([]);function fm(e){return`${H} entry "${e}"`}function hm(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function pm(e,t,n,o){return`[wcs/scan-source-computed] ${e} ${t} "${n}" ${o===n?"is a getter":o.includes(`${d}${d}`)?`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.${ce}`}function gm(e,t,n){0===n.length&&ne(`${dm} ${e} "${t}" must be a non-empty state path.${ce}`),n.startsWith("$")&&ne(`${dm} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ce}`),n.includes("@")&&ne(`${dm} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ce}`),n in Object.prototype&&ne(`${dm} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ce}`);const o=re(n);for(const s of o.segments)0===s.length&&ne(`${dm} ${e} ${t} "${n}" has an empty path segment.${ce}`);return o.wildcardCount>u&&ne(`${dm} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function mm(e,t,n,o){const s=fm(e);0===e.length&&ne(`${dm} ${H} entry name must be a non-empty string.${ce}`),(e.includes(c)||e.includes(d))&&ne(`${dm} ${s} must be a flat property name ("${c}" and "${d}" are not allowed). The output is a property the runtime owns.${ce}`),e.startsWith("$")&&ne(`${dm} ${s} must not start with "$" (reserved namespace).${ce}`),e in Object.prototype&&ne(`${dm} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ce}`),t.has(e)&&ne(`${dm} ${s} conflicts with a getter declared on the state.${ce}`),n.has(e)&&ne(`${dm} ${s} conflicts with a setter declared on the state.${ce}`),o.has(e)&&ne(`${dm} ${s} conflicts with the ${q} entry of the same name — each output has exactly one owner.${ce}`)}function ym(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!nm(e,o)&&ne(`${dm} ${fm(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ce}`)}function wm(e,t,n,o,s,r){const i=fm(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&ne(`${dm} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ce}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||ne(`${dm} ${i} "on" must be a non-empty event-token name.${ce}`),n.has(e)||ne(`${dm} ${i} on "${e}" is not declared in ${z}.${le(e,n)}${ce}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&ne(`${dm} ${i} "from" must be a state path string.${ce}`);const u=gm(i,"from",d),f=hm(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&ne(pm(i,"from",d,f));const h=hm(u,s);return null!==h&&ne(function(e,t,n){return`${dm} ${e} from "${t}" ${n===t?"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.${ce}`}(i,d,h)),(d===e||d.startsWith(e+c))&&ne(`${dm} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ce}`),{kind:"path",path:d,pathInfo:u}}function bm(e,t,n,o){if(void 0===t)return um;const s=fm(e);Array.isArray(t)||ne(`${dm} ${s} "resetOn" must be an array of state paths.${ce}`);const r=[];for(const e of t){"string"!=typeof e&&ne(`${dm} ${s} "resetOn" must contain only state path strings.${ce}`);const t=gm(s,"resetOn",e);t.wildcardCount>0&&ne(`${dm} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${ce}`);const i=hm(t,o);null!==i&&ne(pm(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&ne(`${dm} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ce}`),"path"===n.kind&&e.startsWith(n.path+c)&&ne(`${dm} ${s} resetOn "${e}" 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.${ce}`),r.push(e)}return r}function vm(e,t,n=null){const o=e[H];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&ne(`${dm} ${H} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ce}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(su(e)))"function"==typeof n.get?s.add(t):"function"==typeof n.set&&i.add(t),"function"==typeof n.set&&r.add(t),"function"==typeof n.value&&a.set(t,n.value);const l=function(e){Mc(e);const t=e[q];return"object"!=typeof t||null===t?new Set:new Set(Object.keys(t))}(e),c=[];let d=0;for(const[e,u]of Object.entries(o)){mm(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&ne(`${dm} ${fm(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ce}`);const o=u;ym(e,a,o);const f=wm(e,o,t,s,i,n);"initial"in o||ne(`${dm} ${fm(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ce}`),"function"!=typeof o.fold&&ne(`${dm} ${fm(e)} fold must be a function.${ce}`);const h=bm(e,o.resetOn,f,s);c.push({name:e,source:f,fold:o.fold,initial:o.initial,resetOn:h,order:d++})}return function(e){const t=new Set(e.map(e=>e.name)),n=new Map;for(const o of e){for(const e of o.resetOn){const n=re(e).segments[0];t.has(n)&&ne(`${dm} ${fm(o.name)} resetOn "${e}" reads the ${H} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ce}`)}if("path"===o.source.kind){const e=o.source.pathInfo.segments[0];t.has(e)&&n.set(o.name,e)}}for(const e of n.keys()){const o=[e];let s=n.get(e);for(;void 0!==s&&o.length<=t.size;)s===e&&ne(`${dm} ${H} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ce}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function $m(e){const t=e.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[e.name];i="threw";const a=function(e){return zg.has(e)}(e),l=a&&!Zg(n,e.initial)?Qg(e.initial):n,c=t(l,o,...s);if(am(c))return void lm(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,tm(e.name,c)),a&&Ug(e)}catch(t){im(e.name,t,i)}}}function xm(e,t,n){const o=function(e,t){Dg(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Lg(n,e.source.path,e);for(const t of e.resetOn)Lg(o,t,e),"event"===e.source.kind&&Lg(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Og.set(e,r),r}(e,t);for(const o of t){const t=n.get(o.name);"event"===o.source.kind&&void 0!==t&&(o.resetOn.some(n=>t.includes(n)&&ri().hasQueuedPath(e,n))&&Hg(o))}const s=new Set;for(const t of o.byFromPath.keys())s.add(t),e.setPathInfo(t,"prop","scan");for(const t of o.byResetPath.keys())e.setPathInfo(t,"prop","scan");return s.size>0?s:null}const Sm="scanEntries",Im={order:8,validate(e,t,n){const o=vm(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Sm,o)},applyEarly(e,t,n){const o=n.get(Sm)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=Qg(n.initial);e[n.name]=t,tm(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&zo(e,n.source.tokenName).subscribe($m(n))}(e,o))},register(e,t,n){const o=n.get(Sm)??null,s=function(e){const t=new Map,n=Wg(e);if(void 0!==n)for(const e of n.entries)Ug(e)&&t.set(e.name,e.resetOn);return Dg(e),t}(e);e.setScanPaths?.(null===o?null:xm(e,o,s))}};let Pm=!1;const km=Object.freeze([]),Nm=Object.freeze([]);function Am(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??km,i=e.dynamicDependency.get(n)??km,a=t.byFromPath.get(n)??Nm;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const _m=Symbol("wcs-stream-last-notified-uncertain"),Cm=new WeakMap;function Em(e,t){const n=Cm.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function Mm(e,t){const n=Cm.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:_m,error:Object.is(o.error,null)?null:_m})}const Om=new Set;function Tm(e){Om.delete(e)}const Rm=new WeakMap;function jm(e){return Rm.get(e)??new Map}function Lm(e){Tm(e);const t=Rm.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Mm(e,n.name)}const Wm=(e,t)=>t,Dm=new Set;function Bm(e,t){Mc(t);const n=t[q];if(void 0===n)return void Em(e,Dm);"object"==typeof n&&null!==n||ne(`${q} must be an object mapping stream names to stream definitions.`);const o=new Map,s=su(t);for(const[r,i]of Object.entries(n)){0===r.length&&ne(`${q} entry name must be a non-empty string.`),r.includes(c)&&ne(`${q} entry "${r}" must be a flat property name ("${c}" is not allowed).`),r.includes(d)&&ne(`${q} entry "${r}" must be a flat property name ("${d}" is not allowed).`),r.startsWith("$")&&ne(`${q} entry "${r}" must not start with "$" (reserved namespace).`),r in Object.prototype&&ne(`${q} entry "${r}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(r)&&ne(`${q} entry "${r}" conflicts with a getter declared on the state.`),e.setterPaths.has(r)&&ne(`${q} entry "${r}" conflicts with a setter declared on the state.`),"object"==typeof i&&null!==i||ne(`${q} entry "${r}" must be an object ({ args?, source, fold?, initial? }).`);const n=i,a=s[r]?.value;"function"!=typeof a||a===n.initial||nm(r,a)||ne(`${q} 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&&ne(`${q} entry "${r}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&ne(`${q} entry "${r}" fold must be a function.`),l&&!("initial"in n)&&ne(`${q} entry "${r}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&ne(`${q} entry "${r}" args must be a function.`);const u={name:r,definition:{args:n.args??null,source:n.source,fold:n.fold??Wm,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};r in t||(t[r]=u.definition.initial,tm(r,u.definition.initial)),o.set(r,u)}!function(e,t){Rm.set(e,t)}(e,o),Em(e,new Set(o.keys()))}const zm=new WeakMap,Fm=new WeakMap;function qm(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=jm(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&jm(e).has(n),ownKeys:()=>Array.from(jm(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=jm(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){ne(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){ne(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Vm(e){const t=zm.get(e);if(void 0!==t)return t;const n=qm(e,J,e=>e.status);return zm.set(e,n),n}function Hm(e){const t=Fm.get(e);if(void 0!==t)return t;const n=qm(e,X,e=>e.error);return Fm.set(e,n),n}function Um(e){zm.delete(e),Fm.delete(e)}let Gm=null;function Km(e,t){let n=e;for(let e=1;e<t.length;e++){if(Object(n)!==n)return;n=Reflect.get(n,t[e])}return n}const Jm={read(e,t){!function(e,t){null!==Gm&&Gm.add(eo(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===J?Km(Vm(e),t.pathInfo.segments):n===X?Km(Hm(e),t.pathInfo.segments):Lc},get:(e,t)=>t===J?Vm(e.stateElement):t===X?Hm(e.stateElement):Lc};let Xm=0,Qm=null,Ym=0;const Zm=new WeakMap;function ey(e){Xm=e+1}function ty(){Xm=0}function ny(e){if(Xm>0){const t=Qm??=new Map;Xm>(t.get(e)??0)&&t.set(e,Xm),Ym=Math.max(Ym,Xm)}}function oy(e,t){return Zm.get(e)?.get(t)??0}async function sy(e,t,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 e(t,n);if(s=function(e,t){if("function"==typeof e?.getReader)return async function*(e,t){const n=e.getReader(),o=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",o,{once:!0});try{for(;;){const{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t.removeEventListener("abort",o),n.releaseLock()}}(e,t);if("function"==typeof e?.[Symbol.asyncIterator])return e;throw new TypeError(`[@wcstack/state] ${q}: source must return an AsyncIterable or a ReadableStream (got neither).`)}(i,n)[Symbol.asyncIterator](),n.aborted)return void r();for(;;){const e=await s.next();if(e.done)break;if(n.aborted)return;o.fold(e.value)}if(n.aborted)return;o.done()}catch(e){if(n.aborted)return;o.fail(e)}finally{n.removeEventListener("abort",r)}}function ry(e){fy();const t=jm(e);if(0!==t.size){!function(e){Om.add(e)}(e);for(const n of t.values())iy(e,n)}}function iy(e,t){t.controller?.abort();const n=new AbortController;t.controller=n;const o=function(e,t){const n=t.definition.args;if(null===n)return void t.depAddresses.clear();const o=Gm,s=new Set;let r;Gm=s;try{e.createState("readonly",e=>{r=n(e)})}finally{Gm=o}r instanceof Promise&&ne(`${q} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${J}${c}${t.name}`,a=`${X}${c}${t.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==e||o.path!==t.name&&o.path!==i&&o.path!==a||ne(`${q} entry "${t.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&&ne(`${q} entry "${t.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return t.depAddresses=s,r}(e,t);!function(e,t){const n=Wg(e);if(void 0!==n&&0!==t.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==t.name)continue;const s=Am(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&ne(`[wcs/scan-feedback-loop] ${q} entry "${t.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.`)}}}(e,t),e.createState("writable",e=>{e[t.name]=t.definition.initial}),tm(t.name,t.definition.initial),ay(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{const o=s.fold(e[t.name],n);e[t.name]=o,tm(t.name,o)})},done(){ay(e,t,"done",null)},fail(o){ay(e,t,"error",o),n.abort()}};sy(s.source,o,n.signal,r)}function ay(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return Cm.get(e)?.get(t)??{status:"idle",error:null}}(e,t.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(!function(e,t,n,o){let s=Cm.get(e);void 0===s&&(s=new Map,Cm.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${J}${c}${t.name}`),i&&e.$postUpdate(`${X}${c}${t.name}`)}))}function ly(e){const t=Om;if(0===t.size)return;const n=[];for(const o of t)for(const t of jm(o).values()){let s=-1;for(const n of t.depAddresses)e.has(n)&&(s=Math.max(s,oy(e,n)));s>=0&&s<=32&&n.push({stateElement:o,entry:t,depth:s})}try{for(const{stateElement:e,entry:o,depth:s}of n)if(t.has(e)&&jm(e).get(o.name)===o){ey(s);try{iy(e,o)}catch(n){o.controller?.abort(),t.has(e)&&jm(e).get(o.name)===o&&ay(e,o,"error",n)}}}finally{ty()}}let cy=!1;const dy=new WeakMap,uy={order:20,apply(e,t){var n;Um(e),Lm(n=e),Tm(n),Rm.delete(n),Bm(e,t),void 0!==t[q]&&e.attachAddressHooks?.("streams",q)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return ry(e),void dy.set(e,e.connectGeneration??0)}n===e.connectGeneration&&dy.get(e)!==n&&ry(e)}},deactivate(e){Lm(e),Um(e)}};function fy(){cy||(cy=!0,Bc("streams",Jm),Vc("streams",uy),ti(ly,20))}const hy=new WeakMap;function py(e,t,n){let o=hy.get(e);void 0===o&&(o=new Map,hy.set(e,o)),o.set(t,n)}const gy=new Map;function my(e,t){gy.has(e)||gy.set(e,t)}function yy(e){return gy.get(e)}const wy=new WeakMap,by=new WeakMap,vy=new Set,$y=new Map;function xy(e){return wy.get(e)??$y}function Sy(e){vy.add(e),function(e){const t=Og.get(e);void 0!==t&&(jg(t)&&Tg.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Rg.add(e))}(e)}function Iy(){return vy}function Py(e,t){let n=by.get(e);void 0===n&&(n=new Map,by.set(e,n));for(const e of t){const t=n.get(e.path);void 0===t?n.set(e.path,[e]):t.push(e)}}const ky=new Map;function Ny(e){return by.get(e)??ky}function Ay(e){0===e.length&&ne(`[wcs/watch-declaration-invalid] ${V} entry name must be a non-empty state path.`),e.startsWith("$")&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" must not start with "$" (reserved namespace).${ce}`),e.includes("@")&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ce}`),e in Object.prototype&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=re(e);for(const n of t.segments)0===n.length&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" has an empty path segment.${ce}`);return t.wildcardCount>u&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function _y(e,t){const n=t[V];if(void 0===n)return null;"object"==typeof n&&null!==n||ne(`[wcs/watch-declaration-invalid] ${V} must be an object mapping state paths to handler functions.${ce}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&ne(`[wcs/watch-declaration-invalid] ${V} entry "${t}" must be a function.${ce}`);const n=Ay(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){wy.set(e,t)}(e,o),s.size>0?s:null}const Cy={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||my(n,o)},swapped(e,t,n){var o;o=n,gy.has(o)&&my(t,yy(n))}};function Ey(e){for(let t=e;null!==t;t=t.parentListIndex)if(Xt(t))return!0;return!1}function My(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[zn](Po(t.wildcardParentPathInfos[i],r)),l=fn(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=ao(o,i,t.wildcardCount);if(l!==c&&!Vt(l,c)){if(Xt(c))return"gone";s="replaced"}r=l}return s}function Oy(e,t,n){const o=new Map;for(const s of n){const n=My(e,t,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(),e=>e.row)}const Ty=Object.freeze([]);function Ry(e,t,n,o){let s=e.get(n);return void 0===s&&(s={stateElement:t,entry:n,rows:[],reset:!1,depth:o},e.set(n,s)),s.depth=Math.max(s.depth,o),s}function jy(e,t){let n=0;for(;n<e.indexes.length-1&&e.indexes[n]===t.indexes[n];)n++;return e.indexes[n]-t.indexes[n]}function Ly(e,t){return t.has(e.stateElement)&&!0===Wg(e.stateElement)?.entries.has(e.entry)}function Wy(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Dy(n,e))||Ug(t)}function Dy(e,t){return ri().hasQueuedPath(e,t)}function By(e,t){!function(e,t,n){if(0!==Fg)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=qg(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||Ug(t)}}(e,t,Dy)}function zy(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function Fy(e,t,n){if(!Ly(e,n))return Wy(e),null;const{stateElement:o,entry:s}=e;if(e.reset)return{group:e,next:s.initial};const r=s.source;if(function(e,t){for(const n of t.pathInfo.cumulativePaths)if(e.getterPaths.has(n))return!0;return!1}(o,r))return function(e,t,n){if(cm.has(e))return;cm.add(e);const o=`[wcs/scan-source-computed] ${H} entry "${t}" 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}`),rm(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=jm(e).get(t);if(void 0===o)return!1;for(const e of o.depAddresses)if(n.has(e))return!0;return!1}(o,r.pathInfo.segments[0],t))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",t=>{const n=t[s.name];i.failure="read-rows";const o=0===r.pathInfo.wildcardCount?e.rows:Oy(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(jy)){let n;try{n=zy(t,r,e)}catch(e){im(s.name,e,"read-source");continue}const o=a(l,n,yy(e.absAddress),...e.indexes);if(am(o))return void lm(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){im(s.name,e,i.failure)}return i.plan}function qy(e,t){const{group:n}=e;if(!Ly(n,t))return void Wy(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Ug(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!Zg(o,s.initial):!Object.is(o,e.next)){const o=n.reset?Qg(s.initial):e.next;t[s.name]=o,tm(s.name,o)}})}catch(e){im(s.name,e,"write")}}function Vy(e,t){if(By(e,t),0===Tg.size)return Ty;const n=new Map;for(const o of e){const s=o.absolutePathInfo.stateElement;if(!t.has(s))continue;const r=Wg(s);if(void 0===r)continue;const i=o.absolutePathInfo.pathInfo,a=oy(e,o),l=r.byFromPath.get(i.path);if(void 0!==l){let e=[];if(i.wildcardCount>0){if(null===o.listIndex)continue;e=lo(o.listIndex,i.wildcardCount)}for(const t of l)Ry(n,s,t,a).rows.push({absAddress:o,indexes:e})}const c=r.byResetPath.get(i.path);if(void 0!==c)for(const e of c)Ry(n,s,e,a).reset=!0}if(0===n.size)return Ty;const o=Array.from(n.values()).sort((e,t)=>e.entry.order-t.entry.order),s=[];try{for(const n of o){ey(n.depth);const o=Fy(n,e,t);null!==o&&s.push(o)}}finally{ty()}return s}function Hy(e){ew(),(0!==xy(e).size||0!==Ny(e).size||function(e){const t=Og.get(e);return void 0!==t&&jg(t)}(e))&&(Sy(e),function(e){const t=[];for(const n of xy(e).values())Uy(e,n)&&t.push(n);for(const n of Ny(e).values())for(const o of n)Uy(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{py(e,to(e,o.pathInfo,null),n[o.path])}catch(t){Ky(e,o.path,"prime",t)}})}(e))}function Uy(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Gy={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Ky(e,t,n,o){console.error(`[@wcstack/state] $watch ${Gy[n]} "${t}" threw.`,o),null!==Pt&&Pt({type:"state:watch-error",phase:n,path:t,error:o})}function Jy(e){const t=Iy(),n=function(e){const t=Ym;return t>0&&(Zm.set(e,Qm),Qm=null,Ym=0),t}(e);try{if(n>32){By(e,null);const t=Array.from(e,e=>e.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:t}),void(null!==Pt&&Pt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}if(0===t.size)return void By(e,t);!function(e,t){if(0!==e.length)try{for(const n of e)ey(n.group.depth),qy(n,t)}finally{ty()}}(Vy(e,t),t),function(e,t){const n=[],o=new Set;for(const s of e){const e=s.absolutePathInfo.stateElement;if(!t.has(e))continue;const r=s.absolutePathInfo.pathInfo.path;o.add(r);const i=xy(e).get(r),a=Ny(e).get(r);if(void 0===i&&void 0===a)continue;const l=void 0===i?[]:[i];void 0!==a&&l.push(...a);for(const t of l){let o=[];if(t.pathInfo.wildcardCount>0){if(null===s.listIndex)continue;o=lo(s.listIndex,t.pathInfo.wildcardCount)}n.push({stateElement:e,entry:t,absAddress:s,indexes:o})}}if(0===n.length)return;n.sort(Qy);const s=function(e,t){let n=null;for(let o=0;o<e.length;o++){const s=e[o];if(0===s.entry.pathInfo.wildcardCount)continue;const r=e[o-1];(Ey(s.absAddress.listIndex)||r?.entry===s.entry&&Xy(r.indexes,s.indexes)||s.entry.pathInfo.wildcardParentPaths.some(e=>t.has(e)))&&(n??=new Set).add(s.entry)}if(null===n)return e;const o=new Set;for(const t of n){const n=e.filter(e=>e.entry===t),s=n[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(Oy(e,t.pathInfo,n));for(const e of n)s.has(e)||o.add(e)})}catch(e){Ky(0,t.path,"evaluate",e);for(const e of n)o.add(e)}}return e.filter(e=>!o.has(e))}(n,o);try{for(const n of s){if(!t.has(n.stateElement))continue;const o=xy(n.stateElement).get(n.entry.path)===n.entry,s=!0===Ny(n.stateElement).get(n.entry.path)?.includes(n.entry);(o||s)&&(ey(oy(e,n.absAddress)),Yy(n))}}finally{ty()}}(e,t)}finally{gy.clear()}}function Xy(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Qy(e,t){if(e.entry.order!==t.entry.order)return e.entry.order-t.entry.order;const n=Math.min(e.indexes.length,t.indexes.length);for(let o=0;o<n;o++)if(e.indexes[o]!==t.indexes[o])return e.indexes[o]-t.indexes[o];return e.indexes.length-t.indexes.length}function Yy(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Uy(t,n);try{t.createState("writable",e=>{let i;try{i=function(e,t,n){if(0===t.pathInfo.wildcardCount)return e[t.path];return e.$resolve(t.path,n)}(e,n,s)}catch(e){return void Ky(0,n.path,"evaluate",e)}const a=r?function(e,t){return hy.get(e)?.get(t)}(t,o):yy(o);r&&py(t,o,i),null!==Pt&&Pt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Ky(0,n.path,"handler",e)}}let Zy=!1;function ew(){Zy||(Zy=!0,Bc("watch",Cy),Vc("watch",tw),ti(Jy,10),ei(ny),mu={assertValidPath:Ay,addEntries:Py,start:Hy})}const tw={order:10,register(e,t){var n;n=e,vy.delete(n),Bg(n),wy.delete(n),function(e){hy.delete(e)}(e);const o=_y(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?V:H)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Hy(e)},deactivate(e){var t;t=e,vy.delete(t),Bg(t)}},nw={name:"temporal",install(){ew(),Pm||(Pm=!0,Vc("scan",Im),ei(Vg)),fy()}},ow=new Set,sw=new Set;function rw(e){ow.has(e)||(ow.add(e),console.warn(`[@wcstack/state] [wcs/v4-migration] ${e} See "Preparing for 4.0" in the @wcstack/state README.`))}const iw=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],aw=["formats","diagnostics","temporal","list-keys","scopes","recursion","ssr","devtools"],lw=(e,t,n)=>rw(`${e}: "${t}" is not one of its options, or not ${n}. 4.0 throws on it.`);function cw(e,t){if(sw.has(e))return;sw.add(e);rw(`${"$"===e[0]?"":"filter "}"${e}" is removed in 4.0: write "${t}" (its name since 3.2).`)}const dw={substr:'filter "substr" is removed in 4.0: write slice(start, start + length) — slice takes the end index, not a length.'},uw={$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."},fw=new WeakSet,hw={state(e){const t=e;for(const e of Object.keys(_c))void 0!==t[e]&&cw(e,_c[e]);var n;void 0!==t[H]&&rw(`"${H}" is removed in 4.0: rewrite it with $watch (state paths) or $on (event tokens).`),fw.has(e)||(!function(e){if(null==e)return;if("object"!=typeof e)return void lw("state","$behavior","an object");const t=e;for(const e in t){const n=t[e];iw.includes(e)&&"boolean"==typeof n?n!==s[e]&&rw(`$behavior takes effect in 4.0; 3.x does not read it and runs this state with ${e}: ${!n}. Until you upgrade, pass bootstrapState({ ${e}: ${n} }).`):lw("$behavior",e,"a boolean")}}(t.$behavior),void 0!==(n=t.$features)&&(Array.isArray(n)&&!n.some(e=>!aw.includes(e))||rw(`$features is not an array of add-on names (${aw.join(", ")}). 4.0 throws on it.`)))},volumeLoaded(e){fw.add(e)},renamed:cw,removed(e){rw(dw[e])},volume(e,t,n){n>0&&rw(`volume "${e}" 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(uw))void 0!==t[n]&&rw(`volume "${e}" declares ${n}: 4.0 does not graft a volume that declares it. ${uw[n]}`)}};function pw(e){!function(e){he=e}(hw)}const gw=[rf,nw,Of,tg,Mg,Ou,Vu];await function(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(gw),pw(),gu(e,t)}();
2
2
  //# sourceMappingURL=auto.min.js.map