@wcstack/state 3.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +25 -3
- package/README.md +25 -3
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/manifest.d.ts +2 -0
- package/dist/manifest.esm.js +1 -0
- package/dist/parser.esm.js +25 -0
- package/dist/split/chunks/binder.js +1 -1
- package/dist/split/chunks/binder.js.map +1 -1
- package/dist/split/chunks/checkDependency.js +1 -1
- package/dist/split/chunks/mount.js +1 -1
- package/dist/split/chunks/mount.js.map +1 -1
- package/dist/split/chunks/pathDiagnostics.js +1 -1
- package/dist/split/chunks/pathDiagnostics.js.map +1 -1
- package/dist/split/chunks/registerComponents.js +1 -1
- package/dist/split/chunks/setAll.js +1 -1
- package/dist/split/chunks/version.js +1 -1
- package/dist/split/chunks/watchRuntime.js +1 -1
- package/dist/split/features/devtools.js +1 -1
- package/dist/split/features/diagnostics.js +1 -1
- package/dist/split/features/recursion.js +1 -1
- package/dist/split/features/scopes.js +1 -1
- package/dist/split/features/scopes.js.map +1 -1
- package/dist/split/features/ssr.js +1 -1
- package/dist/wcs-manifest.json +1 -0
- package/package.json +1 -1
package/dist/index.esm.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={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n;function s(){return 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="#",p="|",g="prevent",m="stop",y="ro",w=Object.freeze([g,m,y]),b="init",v="sync",$=Object.freeze([b,v]),x="else",S="...",P="on",I="eventToken",A="command",N="class",k="attr",_="style",T="$",C={};for(let e=0;e<u;e++)C[`${T}${e+1}`]=e;const E=Object.freeze(C),M="$connectedCallback",O="$disconnectedCallback",R="$updatedCallback",j="$errorCallback",L="$stateReadyCallback",W="$bindables",D="$commands",B="$commandTokens",z="$command",F="$eventTokens",q="$on",V="$streams",H="$watch",U="$scan",G="$recursion",K="**",J="$listKeys",X="$streamStatus",Y="$streamError",Q="data-wc-definition",Z=/\{\{\s*(.+?)\s*\}\}/g,ee=new Set(["SCRIPT","STYLE"]);function te(e){if(!o.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&ee.has(e.parentElement.tagName)||ne(e)}(e);const t=Array.from(e.querySelectorAll("template"));for(const e of t)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),te(t.content)}else te(e.content)}function ne(e){const t=e.data;if(Z.lastIndex=0,!Z.test(t))return;Z.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Z.exec(t));){o.index>s&&n.appendChild(document.createTextNode(t.slice(s,o.index)));const e=o[1];n.appendChild(document.createComment(`@@: ${e}`)),s=o.index+o[0].length}s<t.length&&n.appendChild(document.createTextNode(t.slice(s))),e.parentNode.replaceChild(n,e)}function oe(e){throw new Error(`[@wcstack/state] ${e}`)}const se=new Map;let re=0;function ie(e){let t=se.get(e);return void 0!==t||(-1!==e.indexOf(K)&&oe(`[wcs/recursion-unsupported] "${e}" uses "${K}", 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.`),t=Object.freeze(new ae(e)),se.set(e,t)),t}class ae{id=++re;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:ie(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 le(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 ce(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=le(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const de=" Validate statically: npx @wcstack/lint <file>.",ue=new Set(["if","elseif","else","for"]),fe={not:()=>e=>!e},he={input:new Map,output:new Map},pe={input:new Map,output:new Map},ge=new Map;function me(e,t,n){const o=he[e],s=pe[e];for(const e of Object.keys(t)){o.set(e,t[e]);const r=n?.[e];void 0===r?s.delete(e):s.set(e,r)}ge.clear()}function ye(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=ge.get(s);if(void 0!==r)return r;const i=he[n].get(e)??fe[e];void 0===i&&oe(`[wcs/filter-unknown] filter not found: ${e}.${ce(e,function(e){return[...new Set([...Object.keys(fe),...he[e].keys()])]}(n))}${de}`);const a=pe[n].get(e);void 0!==a&&(t.length<a[0]||t.length>a[1])&&oe(t.length<a[0]?`[wcs/filter-arity] filter "${e}" requires at least ${a[0]} argument(s) (${t.length} given).${de}`:`[wcs/filter-arity] filter "${e}" accepts at most ${a[1]} argument(s) (${t.length} given).${de}`);const l=i(t,o);return ge.set(s,l),l}function we(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 be=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function ve(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:be.test(e)?Number(e):e)}function $e(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=we(o,i,a);t.push(e),n.push(ve(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&&oe(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${de}`);const c=we(o,i,a);return(c||r)&&(t.push(c),n.push(ve(c,r))),{args:t,literals:n}}function xe(e,t){return e.map(t=>{const n=t.indexOf("("),o=t.lastIndexOf(")");-1!==n&&-1===o&&oe(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==o&&-1===n&&oe(`Invalid filter format: missing opening parenthesis in "${t}"`);const s=(-1===n?t:t.substring(0,n)).trim();if(0===s.length&&oe(`[wcs/binding-syntax] an empty filter in "${e.join("|")}" — remove the extra "|" or name the filter.${de}`),-1===n)return{filterName:s,args:[],literals:[]};return{filterName:s,...$e(t.substring(n+1,o))}})}const Se=e=>e.trim(),Pe=e=>"'"===e||'"'===e;function Ie(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(Pe(s))n=s;else if(s===t)return o}return-1}function Ae(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):Pe(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const Ne=new Map;function ke(e){const t=Ie(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ne.has(s)?r=Ne.get(s):(o=Ae(s,p).map(Se),r=xe(o),Ne.set(s,r))):n=e.trim();const i=n.split(h).map(Se);i.length>2&&oe(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${h}" — write "${i[0]}${h}${i.slice(1).join(",")}".${de}`);const[a,l]=i,d=a.split(c).map(Se);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(Se):[],inFilters:r}}const _e=new Map;function Te(e){const t=Ie(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),_e.has(s)?r=_e.get(s):(o=Ae(s,p).map(Se),r=xe(o),_e.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&oe(`"${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.`);return{statePathName:n,statePathInfo:ie(n),outFilters:r}}const Ce=new Set([x,"if","elseif","for",S]);function Ee(e){const[...t]=function(e){return Ae(e,";")}(e).map(Se).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&oe(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(h)[0].split(p)[0].trim();if(s!==n&&Ce.has(s)&&oe(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${de}`),n===x){o.length>0&&oe(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${de}`);const t=ie("#else");return{propName:x,propSegments:[x],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===S){const t=Te(o);return t.outFilters.length>0&&oe(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&oe(`Invalid spread binding "${e}": spread target path is required.`),{propName:S,propSegments:[S],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{...ke(n),...e,bindingType:s}}{const e=Te(o),t=ke(n);return t.propSegments[0]===I||t.propSegments[0].startsWith(P)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>ue.has(e.bindingType))&&oe(`[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">).${de}`)}return n}const Me=new WeakMap,Oe=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Re=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function je(e){const t=Me.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=Re.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Oe.has(r)?(Me.set(e,s[2]),s[2]):null}function Le(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Te(e),bindingType:"text"}}const We=new WeakMap,De=new WeakSet;let Be=0;async function ze(e){const t=function(e){let t,n=We.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++Be,promise:o,resolve:t},We.set(e,n),De.has(e)&&n.resolve(),n}(e);await t.promise}function Fe(e){const t=We.get(e);void 0===t?De.add(e):t.resolve()}const qe=new WeakMap;function Ve(e){const t=qe.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{qe.set(e,n)}}function He(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Ue(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return He(t);if(void 0!==n)return He(n)}return He(globalThis.customElements)}function Ge(e,t){e.upgrade?.(t)}function Ke(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=Qe(s.properties,Je);if(null===r)return null;const i=void 0===s.inputs?new Map:Qe(s.inputs,Xe);if(null===i)return null;const a=void 0===s.commands?new Map:Qe(s.commands,Ye);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Je(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 Xe(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 Ye(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 Qe(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 Ze(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ie(n),inFilters:[],outFilters:[],bindingType:"prop"}}function et(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function tt(e,t,n={}){const s=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&&oe("Spread binding requires an element node.");const t=e,o=Ve(t);null===o&&oe(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Ue(t);null===a&&oe(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||oe(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Ge(a,t);const l=Ke(t);null===l&&oe(`Spread binding "${n.statePathName}" requires <${o}> 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=Ze(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=Ze(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=et(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=et(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.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 nt(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 ot(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:ye(s.filterName,s.args,t,s.literals??s.args)})}return n}const st=new WeakMap;function rt(e){return st.get(e)||null}function it(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function at(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!it(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function lt(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 ct(e){const t=[],n=at(e),s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==je(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&<(e,n)||t.push(e)}return t}const dt=new WeakSet;function ut(e,t,n,o){const s=tt(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ve(e):null;return null===n&&oe("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}dt.add(e);const r=function(e,t){const n=[];for(const o of t){const t=ot(o.inFilters,"input"),s=ot(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){st.set(e,t)}(e,r),Fe(e),{bindings:r,deferred:null}}function ft(e,t){const n=ct(e),o=[],s=[];for(const e of n){if(dt.has(e))continue;const n=ut(e,Na(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function ht(e){dt.add(e)}function pt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){dt.delete(e)}(t);return ut(t,n,{allowDeferred:!1},o).bindings}const gt=new WeakMap;let mt=null;function yt(e){let t=e;for(;t;){const e=gt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==mt&&t instanceof ShadowRoot&&(n=mt(t)),t=n}return null}function wt(e,t){null!==t?gt.set(e,t):gt.delete(e)}let bt=null;const vt=new WeakMap;function $t(e){return vt.get(e)??[]}function xt(e,t){vt.set(e,t)}function St(e){return vt.has(e)}const Pt=new WeakMap;let It=null,At=0;function Nt(e){return Pt.get(e)??[]}function kt(e,t){null===It?Pt.set(e,t):It.set(e,t)}function _t(){At++,null===It&&(It=new Map)}function Tt(){if(0!==At&&(At--,!(At>0||null===It))){for(const[e,t]of It)Pt.set(e,t);It=null}}function Ct(e){return(It?.has(e)??!1)||Pt.has(e)}const Et=Symbol("$$setLoopContext"),Mt=Symbol("$$getByAddress"),Ot=Symbol("$$hasByAddress"),Rt=Symbol("$$setByAddress"),jt=Symbol("$$connectedCallback"),Lt=Symbol("$$disconnectedCallback"),Wt=Symbol("$$updatedCallback"),Dt=Symbol("$$errorCallback"),Bt=new WeakMap,zt=new WeakMap;class Ft{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function qt(e,t){if(null===t){let t=zt.get(e);return void 0!==t||(t=new Ft(e,null),zt.set(e,t)),t}{let n=Bt.get(t);void 0===n&&(n=new WeakMap,Bt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Ft(e,t),n.set(e,o)),o}}const Vt=new WeakMap;function Ht(e,t){let n=Vt.get(e);void 0===n&&(n=new Map,Vt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Ut(e,t)),n.set(t,o)),o}class Ut{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Gt(e,t){return qt(Ht(e,t.pathInfo),t.listIndex)}function Kt(e,t,n){return qt(Ht(e,t),n)}const Jt=new WeakMap;function Xt(e,t){null===t?Jt.delete(e):Jt.set(e,t)}function Yt(e){return Jt.get(e)||null}const Qt=new Map;function Zt(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=Qt.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Qt.set(s,r),r}function en(e,t,n){return t<0||t>=n?null:e.at(t-n)}function tn(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const nn=new WeakMap;function on(e){const t=yt(e.node);if(null===t)return null;let n=nn.get(t);if(void 0===n)n=new WeakMap,nn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=Zt(t.pathInfo,e.statePathInfo);return n>0&&(o=en(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const sn=new WeakMap;function rn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Yt(n);null===t?oe(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function an(e,t){let n=null;if(n=sn.get(e)||null,null!==n)return n;const o=rn(e,t),s=on(e),r=ba(o);return null===r&&oe("No state tree found on this root for binding."),n=Kt(r,e.statePathInfo,s),sn.set(e,n),n}function ln(e){sn.delete(e)}const cn=new WeakMap;function dn(e,t){const n=cn.get(e);void 0===n?cn.set(e,t):n instanceof Set?n.add(t):n!==t&&cn.set(e,new Set([n,t])),null!==bt&&bt({type:"state:binding-added",absoluteAddress:e,binding:t})}function un(e,t){const n=cn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&cn.delete(e),null!==bt&&bt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const fn=new WeakMap;function hn(e){const t=cn.get(e);return void 0!==t?t:null!==e.listIndex?fn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const pn=new WeakMap,gn=new WeakMap;class mn{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===d?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=yn(e,t)}}function yn(e,t){if(null===t){let t=gn.get(e);return void 0!==t||(t=new mn(e,null),gn.set(e,t)),t}{let n=pn.get(t);void 0===n&&(n=new WeakMap,pn.set(t,n));let o=n.get(e);return void 0!==o||(o=new mn(e,t),n.set(e,o)),o}}const wn=new WeakMap;function bn(e){let t=null;if(t=wn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=on(e);null===n&&oe(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=yn(e.statePathInfo,n)}else t=yn(e.statePathInfo,null);return wn.set(e,t),t}function vn(e){wn.delete(e)}function $n(){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 xn=new Map,Sn=$n();function Pn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function In(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function An(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=In(e),s=Pn(e,o);let r=xn.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=ba(o.getRootNode());null===i&&oe("No state tree found on this root for two-way binding.");const a=yt(o);i.createState("writable",e=>{e[Et](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]:[]})})},xn.set(s,r)),e.node.addEventListener(o,r),Sn.add(s,e),!0}var t,n;return!1}function Nn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function kn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Nn(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class _n{_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)t.push(n(...e));return t}}class Tn extends _n{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==bt&&bt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Cn=new WeakMap;function En(e,t){let n=Cn.get(e);void 0===n&&(n=new Map,Cn.set(e,n));let o=n.get(t);return void 0===o&&(o=new Tn(t,e),n.set(t,o)),o}const Mn=new WeakMap;function On(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Ve(t),o=Ue(t);if(null!==n&&void 0===o?.get(n))return null===o&&oe(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Mn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||oe('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Ve(e)?null:Ke(e)}(t);null===r&&oe(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&oe(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${ce(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(g)&&e.preventDefault(),c.includes(m)&&e.stopPropagation();const n=ba(t.getRootNode());null===n&&oe("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||oe(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${ce(l,n.eventTokenNames)}${de}`);const o=yt(t);n.createStateAsync("writable",async t=>{kn(t[Et](o,()=>{const s=null!==o?tn(o.listIndex,o.pathInfo.wildcardCount):[];return En(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Mn.set(e,{eventName:a,handler:d}),!0}class Rn extends _n{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==bt&&bt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function jn(e){return e instanceof Rn}const Ln=new Map,Wn=$n();function Dn(e){const t=e.propModifiers.filter(e=>e===g||e===m).sort().join(",");return`${e.statePathName}::${t}`}const Bn=(e,t,n)=>o=>{t.includes(g)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ba(r);null===i&&oe("No state tree found on this root for event handler.");const a=yt(s),l=e.startsWith(z+".");i.createStateAsync("writable",async t=>{const c=t[Et](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?tn(a.listIndex,c):[];if(l){const s=t[Mt](yn(n,null));return jn(s)||oe(`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&&oe(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});kn(c,`"${e}"`)})};function zn(e){if(!e.propName.startsWith(P))return!1;const t=Dn(e);let n=Ln.get(t);void 0===n&&(n=Bn(e.statePathName,e.propModifiers,e.statePathInfo),Ln.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Wn.add(t,e),!0}function Fn(e){if(!e.propName.startsWith(P))return!1;const t=Dn(e),n=Ln.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Wn.countOf(t)&&(Wn.remove(t,e)&&Ln.delete(t),!0)}const qn=new Map,Vn=$n();function Hn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Un(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function Gn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=Un(e),s=Hn(e,o);let r=qn.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=ba(o.getRootNode());null===r&&oe("No state tree found on this root for two-way binding.");const i=yt(o);r.createState("writable",e=>{e[Et](i,()=>{e[t]=s})})},qn.set(s,r)),e.node.addEventListener(o,r),Vn.add(s,e),!0}var t,n;return!1}const Kn=new Set(["radio","checkbox"]),Jn=new Set(["value","valueAsNumber","valueAsDate"]);function Xn(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(Kn.has(e)&&"checked"===t)return!0;if(Jn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ve(n);if(null!==s){const e=Ue(n)?.get(s);void 0===e&&oe(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Ke(n);if(o?.knownProperties.has(t))return!0}return!1}let Yn=1,Qn=1,Zn=1;const eo=new WeakMap;function to(e,t,n){let o=eo.get(e);void 0===o&&(o=new Map,eo.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=Yn++,o.set(s,r)),r}function no(e,t){return"to-element"===t?2*e:2*e+1}const oo=new Set;function so(e){return{transactionId:Qn++,originBindingId:e,visitedEdges:oo,hop:0}}function ro(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 io=null;function ao(){return io}function lo(e,t){const n=io;io=e;try{return t()}finally{io=n}}const co=[];let uo=!1;const fo=new Map,ho=$n(),po=new WeakMap,go=e=>e.detail,mo=new WeakMap;function yo(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function wo(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ve(e.node);if(null!==n){const o=Ue(e.node)?.get(n);void 0===o&&oe(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ke(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function bo(e){if(null!==Ve(e.node)){const t=Ke(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??go}return null}function vo(e){if(null===Ve(e.node))return!1;const t=Ke(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const $o=(e,t,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==go||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=mo.get(e);void 0===r&&(r=new Set,mo.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=po.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=to(a,e,t),s=function(e,t){for(let n=co.length-1;n>=0;n--){const o=co[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==bt&&bt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:no(n,"to-state"),node:a,member:e}));const r=no(n,"to-state"),i=ao();if(null!==i&&i.visitedEdges.has(r))return void(null!==bt&&bt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=ro(i??so(n),r)}const f=ba(a.getRootNode());null===f&&oe("No state tree found on this root for two-way binding.");const h=yt(a),p=()=>{r&&(uo=!0);try{f.createState("writable",e=>{e[Et](h,()=>{e[t]=c})})}finally{r&&(uo=!1)}};null!==u?lo(u,p):p()};const xo=new WeakSet;function So(e){xo.add(e)}function Po(e){return!!xo.has(e)&&(xo.delete(e),!0)}const Io=new WeakMap;function Ao(e,t){const n=Io.get(e);return!(void 0===n||n<t)&&(n===t?Io.delete(e):Io.set(e,n-t),!0)}const No=new WeakSet;function ko(e){No.add(e)}function _o(e){return!!No.has(e)&&(No.delete(e),!0)}let To=0;function Co(){To--}function Eo(){return To>0}class Mo{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 Oo=new WeakMap;function Ro(e){let t=Oo.get(e);return void 0===t&&(t=new Mo(e),Oo.set(e,t)),t}function jo(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&&oe(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&oe(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Lo(e){return e.propModifiers.some(e=>e.includes("="))}const Wo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Do=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Bo(e,t){return"state"===e&&"call"===t?Wo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function zo(e){if(!o.enableDirectionalInitialSync)return Lo(e)&&oe("init=/sync= modifiers require enableDirectionalInitialSync."),Wo;const t=null===(n=jo(e,b))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:oe(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":oe(`Invalid sync modifier value "${e}".`)}(jo(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&oe("Event bindings only allow init=none."),"call"===s?Do:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===A)return Bo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&oe(`Binding type "${e.bindingType}" does not support init=${t}.`),Bo(t??"state",s);const r=Ke(e.node);if(null===r)return Bo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||oe(`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)||oe(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||oe(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Fo(e,t){return"auto"!==t?t:function(e){const t=ba(e.replaceNode.getRootNode());null===t&&oe("No state tree found on this root for binding.");const n=bn(e);let o=!1;return t.createState("readonly",e=>{o=e[Ot](n)}),o}(e)?"state":"element"}let qo=0,Vo=0;const Ho=["active","disposed","failed"],Uo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,Jo=new WeakMap,Xo=new WeakMap;function Yo(e,t){const n=Xo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Xo.set(e,new Set([n,t]))):Xo.set(e,t)}function Qo(e){return Xo.has(e)}function Zo(e,t){const n=Xo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function es(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))es(n,t)}function ts(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class ns{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||!Ao(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)Po(e)||es(e,e=>{Zo(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)_o(e)&&!Eo()||es(e,e=>{Zo(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&ia(o)}}const os=new WeakMap;function ss(e){let t=os.get(e);return void 0===t&&(t=new ns(e),os.set(e,t)),t}function rs(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function is(e,t,n){const o=ba(rn(e,n));null===o&&oe("No state tree found on this root for binding.");const s=Ht(o,e.statePathInfo);return function(e,t,n){let o=fn.get(e);void 0===o&&(o=new WeakMap,fn.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!==bt&&bt({type:"state:binding-added",absoluteAddress:qt(e,t),binding:n})}(s,t,e),s}function as(e,t){const n=an(e,t);return dn(n,e),n}function ls(e,t,n,o){null!==t?un(t,e):function(e,t,n){const o=fn.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!==bt&&bt({type:"state:binding-removed",absoluteAddress:qt(e,t),binding:n}))}(n,o,e),vn(e),ln(e)}function cs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class ds{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;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=Go.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(ts(t)&&ss(t),null===this.rowPlan)for(const n of e){const e=Go.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(!o.enableDirectionalInitialSync)return Lo(e)&&zo(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=Go.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)return{id:64*t.id+n,info:e,generation:t.generation,phase:Ho[t.phases[n]],teardowns:null};const o=Go.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=Go.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(cs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Ue(e);null===s&&oe(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),Yo(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Ro(s).wait(t,()=>{if(a())try{Ge(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.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=Go.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.active=!1,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&&(un(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){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.active=!1,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(){for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(un(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?an(n):null;if(ls(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=an(n);e!==o&&St(o)&&xt(e,$t(o)),e!==o&&Ct(o)&&kt(e,Nt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return ts(t)?t:null}(e);null!==t&&ss(t)}handleMutations(e,t,n){for(const n of t)es(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)es(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&ia(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);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=Go.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Jo.get(t);void 0===e&&(e=rs(t),Jo.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;Yo(n,this);const o=this.knownMapFor(n);let s=Jo.get(e);void 0===s&&(s=rs(e),Jo.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:++qo,session:this,generation:++Vo,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(Yo(r,this),this.addKnownRowBinding(r,o,e),Uo.set(o,s),n[e].isEvent){try{zn(o)}catch(t){throw s.phases[e]=2,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=++Vo,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{zn(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}o.flags[e]|=2}this.registerRowSlot(o,e,n)}}rowOf(e){const t=Uo.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=on(o);null!==s?(e.patternPathInfos[t]=is(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=as(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(ls(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{Fn(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:++qo,info:e,generation:++Vo,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};Go.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;zn(t)?e.eventAttached=!0:t.propSegments[0]!==I?(Gn(t)&&cs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=Un(e),n=Hn(e,t),o=qn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Vn.countOf(n)&&(Vn.remove(n,e)&&qn.delete(n),!0))}return!1}(t)),An(t)&&cs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=In(e),n=Pn(e,t),o=xn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Sn.countOf(n)&&(Sn.remove(n,e)&&xn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Xn(t.node,t.propName)&&-1===t.propModifiers.indexOf(y)){const n=function(e,t,n){let o=po.get(e);void 0===o&&(o=new Map,po.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&&po.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});cs(e,n)}!function(e){const t=Ve(e.node);if(null!==t){const n=Ue(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&oe(`CustomElementRegistry is unavailable for <${t}>.`))}if(Xn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=wo(e),n=bo(e),o=vo(e),s=yo(e,t,null!==n,o);let r=fo.get(s);void 0===r&&(r=$o(e.propName,e.statePathName,e.inFilters,n,o),fo.set(s,r)),e.node.addEventListener(t,r),ho.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{On(t)&&cs(e,()=>function(e){if(e.propSegments[0]!==I)return!1;const t=Mn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Mn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Ve(e.info.node);if(null===n)return void t();const o=Ue(e.info.node);if(null===o&&oe(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=Ro(o).wait(n,()=>{if(this.isAlive(e,s))try{Ge(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});cs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=zo(e.info),n=Fo(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 To++;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,Co()),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=ba(e.node.getRootNode());null===o&&oe("No state tree found on this root for initial binding sync.");const s=yt(e.node);o.createState("writable",t=>{t[Et](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.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=on(n);if(null!==o?(e.patternPathInfo=is(n,o,t),e.patternListIndex=o):e.address=as(n,t),!e.options.registerPathInfo)return;const s=ba(n.replaceNode.getRootNode());null===s&&oe("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&&Go.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,Co());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{ls(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=Ve(e.node);if(null!==t){const n=Ue(e.node),o=n?.get(t);if(void 0===o)return}if(Xn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=wo(e),n=yo(e,t,null!==bo(e),vo(e)),o=fo.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),ho.remove(n,e)&&fo.delete(n)}}(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{Fn(t)}catch{}}}}function us(e){let t=Ko.get(e);return void 0===t&&(t=new ds(e),Ko.set(e,t)),t}function fs(e){return Go.get(e)?.session??Uo.get(e)?.session??null}let hs=null;function ps(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const gs=Object.freeze([]);const ms=new WeakMap;const ys=new WeakMap;function ws(e){return ys.get(e)??[]}function bs(e,t){ys.set(e,t)}const vs=new WeakMap;function $s(e){return vs.get(e)??[]}function xs(e,t){vs.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});let Ss=0;function Ps(){return`u${(Ss++).toString(36)}`}let Is=0,As=0;const Ns=Symbol("wcs.listIndex.noValue");class ks{uuid=Ps();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=Ns,this._index=t,this._version=Is,this._chainGeneration=As}get index(){return this._index}set index(e){this._index=e,this._version=++Is,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}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=Is),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===As||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=As),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Is,As++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function _s(e,t,n=e){return new ks(e,t,n)}function Ts(e,t){e.reparent(t)}function Cs(e){return e.homeParentListIndex}function Es(e,t){e.value=t}function Ms(e,t){const n=e.value;return n!==Ns&&n===t.value}const Os=new WeakMap,Rs=new WeakSet;function js(e){return Rs.has(e)}function Ls(e,t){const n=Cs(e),o=e.parentListIndex;return null===n||n===o||Rs.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Rs.has(e)&&!Rs.has(n)&&n.position===e.position&&Ms(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Rs.has(e)&&!Rs.has(t)}(o,t)?t:null:n}function Ws(e){const t=Os.get(e);return void 0===t?null:t}function Ds(e,t){const n=Os.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Ls(o,t);if(null!==e)for(const t of n)Ts(t,e)}return n}function Bs(e,t){null!==t?Os.set(e,t):Os.delete(e)}const zs=new WeakMap;function Fs(e,t){null===t?zs.delete(e):zs.set(e,t)}function qs(e){const t=zs.get(e);t&&(t.dirty=!0)}const Vs=Symbol.for("wcstack.transition-runner");function Hs(e){const t=globalThis[Vs];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 Us(e,t,n){const o=Hs(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Gs=[],Ks=[];function Js(e){Ks.includes(e)||Ks.push(e)}function Xs(e,t=0){const n=Gs.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Gs.push(o):Gs.splice(n,0,o)}function Ys(e){queueMicrotask(()=>{throw e})}class Qs{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Ks.length;t++)Ks[t](e);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(){_t(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],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=[]){const o=new Map,s=new Set;for(let t=0;t<e.length;t++){const n=e[t],r=o.get(n.absoluteAddress);null!==bt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&bt({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];o.has(t)||o.set(t,null)}const r=[],i=new Map;o.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!==bt&&bt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=hn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(r.push(t),null!==e&&i.set(t,e));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==e&&i.set(n,e))});try{const e=()=>{i.size>0?ia(r,i):ia(r)};if(t()||0===r.length)e();else{const t=Us("state",e);void 0!==t&&t.catch(Ys)}}finally{Tt(),function(e){for(const t of Gs.slice())t.listener(e)}(s)}}}const Zs=new Qs;function er(){return Zs}const tr=new WeakMap,nr=new WeakMap,or=new WeakMap,sr=new WeakMap;let rr=!1;const ir=new WeakMap,ar=new WeakMap,lr=new WeakMap,cr=[];function dr(e,t){const n=ur(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ie(t).cumulativePaths;if(o.length<2)return;let s=lr.get(e);void 0===s&&lr.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 ur(e){let t=tr.get(e);return void 0===t&&tr.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function fr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function hr(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function pr(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=nr.get(o);if(void 0===r&&nr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(hr(s,e,o),r.set(t,n),fr(s,n,o)),!1}return r.set(t,n),fr(s,n,o),!0}function gr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function mr(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&gr(or,o.listIndex,r),null!==r.levelListIndex&&gr(sr,r.levelListIndex,r))}function yr(e,t,n,o,s){rr=!0;const r=ur(e);dr(e,t);mr(r,t,s,o,pr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function wr(e,t){ur(e).tracked.add(t)}function br(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(Gt(e.stateElement,yn(t,o)))}function vr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function $r(e,t,n,o,s){const r=tr.get(e),i=r?.byPath.get(t),a=ir.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return cr;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&&vr(i.get(o),d),f&&vr(i.get(c),d),u&&vr(i.get(s),d)),void 0!==a)for(const e of a)n&&br(e,o,d),f&&br(e,c,d),u&&br(e,s,d);return d}function xr(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Sr(e,t,n){const o=tr.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())vr(e,n);const s=ir.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)br(e,t,n)}function Pr(e){const t=sr.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Ir(e){if(!rr)return;const t=or.get(e);if(void 0!==t){or.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=nr.get(o),r=s.get(n);s.delete(n),hr(tr.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Pr(e)}}}function Ar(e,t,n){if(!rr)return;const o=sr.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=tr.get(e),i=o.byPath.get(s);hr(i,t,r),fr(i,n,r),nr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(qs(r),er().enqueueAbsoluteAddress(r,null))}}const Nr=new WeakMap,kr=Object.freeze([]),_r=new Set;function Tr(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:kr,s=Array.isArray(n)&&n.length>0?n:kr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:kr,o=Array.isArray(t)&&t.length>0?t:kr;let s=Nr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Ds(o,e)||[],a=i.length>0?Cs(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:_r,deleteIndexSet:new Set(i),addIndexSet:_r};let t=Ds(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=_s(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:_r,deleteIndexSet:_r,addIndexSet:new Set(t)}}if(function(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}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:_r,deleteIndexSet:_r,addIndexSet:_r};if(null!==t)return function(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}}(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,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=_s(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=Nr.get(e);o||(o=new WeakMap,Nr.set(e,o)),o.set(t,n)}(o,s,l),Bs(s,l.newIndexes))}}(e,t,n);!function(e,t){for(let n=0;n<e.length;n++){if(e[n].index!==n){const t=e[n].index;e[n].index=n,Ar(e[n],t,n)}Es(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:kr),function(e){for(const t of e)Rs.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)Ir(e);return function(e){for(const t of e)Rs.delete(t)}(o.newIndexes),function(e,t){if(!rr||e===t)return;const n=ar.get(e);if(void 0===n)return;ar.delete(e);const o=ar.get(t);ar.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=ur(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&&!js(e))for(const t of o.getters){const n=Gt(o.stateElement,yn(t,e));qs(n),er().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function Cr(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 Er=new WeakSet;const Mr=new WeakMap;function Or(e){return Mr.get(e)??null}function Rr(e,t){Mr.set(e,t)}const jr=new WeakMap;function Lr(e){return jr.get(e)??[]}function Wr(e,t){jr.set(e,t)}function Dr(e,t){const n=Lr(e);for(const e of n)wt(e,t)}const Br=new WeakMap;const zr=new WeakMap;function Fr(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function qr(e,t,n,o,s){const r=function(e,t,n){let o=zr.get(e);void 0===o&&zr.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;let a,l=!1;for(let e=0;e<t.length;e++){const c=t[e];if(!n.shouldApplyState(c))continue;const d=r[e];if(null===d||Fr(d.prefixes,i)){sa(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[Mt](o),l=!0);const u=d.tail;let f=a;for(let e=0;e<u.length;e++){if(null==f){f=void 0;break}f=f[u[e]]}oa(c,s,f)}}function Vr(e,t,n){Dr(e,t);const o=ws(e),s=Or(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return Br.get(e)??null}(e);if(null!==r)return void qr(r,o,s,t,n)}for(const e of o){if(null===s){dn(an(e),e)}(null===s||s.shouldApplyState(e))&&sa(e,n)}}function Hr(e){if(!e.mounted)return;const t=ws(e),n=Or(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{un(an(o),o)}}!function(e){const t=Lr(e);for(let e=0;e<t.length;e++)wt(t[e],null)}(e)}function Ur(){return Object.freeze(new Set)}const Gr=new WeakMap,Kr=Ur();function Jr(e,t){const n=Gr.get(e);n?n.add(t):Gr.set(e,new Set([t]))}function Xr(e){const t=Gr.get(e);return void 0!==t?t:Kr}function Yr(e,t){const n=Gr.get(e);n&&(n.delete(t),0===n.size&&Gr.delete(e))}function Qr(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:ye(s.filterName,s.args,t,s.literals??s.args)})}return n}function Zr(e){return{...e,inFilters:Qr(e.inFilters,"input"),outFilters:Qr(e.outFilters,"output")}}const ei=new Set(["if","elseif","else","for"]);class ti{_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];ko(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){ko(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=Or(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(ws(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(So(n),n.parentNode.removeChild(n))}const n=ws(this);for(let e=0;e<n.length;e++){const t=n[e];ei.has(t.bindingType)&&Xr(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Or(this);null!==e&&(e.isRowSession?e.disposeBindings(ws(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=ws(this);for(let t=0;t<e.length;t++){const n=e[t];ei.has(n.bindingType)&&Xr(n.node).forEach(e=>{e.unmount()}),vn(n),ln(n)}}unmount(){{const e=Or(this);null!==e&&(e.isRowSession?e.disposeBindings(ws(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(So(e),e.parentNode.removeChild(e));const e=ws(this);for(let t=0;t<e.length;t++){const n=e[t];ei.has(n.bindingType)&&Xr(n.node).forEach(e=>{e.unmount()}),vn(n),ln(n)}this._mounted=!1}}function ni(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.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 oi(e){const t=document.createDocumentFragment(),n=new ti(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function si(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=nt(o,s[e].nodePath);null===t&&oe(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),ht(t),Fe(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=la.get(n);void 0!==o&&o.currentRowPlan===e||(o=new ds,la.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new ti(o);return Rr(d,c),bs(d,a),function(e,t){Br.set(e,t)}(d,n),xs(d,l),Wr(d,r),Jr(e.node,d),d}function ri(e){void 0!==e.uuid&&null!==e.uuid||oe("BindingInfo.uuid is null.");const n=Aa(e.uuid);n||oe(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&ni(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=nt(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===A||s===I)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ve(r))return null;if("prop"===o&&Xn(r,e.propName))return null;const i=Zr(e);let a;try{a=zo({...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{directional:t,slots:n}}(n)),null!==r)return si(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=nt(e,s.nodePath);if(null===t&&oe(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),dt.has(t))continue;const r=ut(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new ds,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new ti(i,s);Rr(l,a.bindingSession),bs(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in E&&c.push(e);return xs(l,c),Wr(l,a.nodes),Jr(e.node,l),l}const ii=new WeakSet,ai=Symbol.for("wcstack.state.view-transition-naming");function li(){const e=Hs("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function ci(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||ii.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[ai]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(ii.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${t}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${t}`))}const di=new WeakMap,ui=new WeakMap,fi=new WeakMap,hi=new WeakMap;function pi(e,t,n){!function(e,t,n){let o=ui.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,ui.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function gi(e,t){di.set(e,t)}function mi(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 yi(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)}function wi(e,t,n){if(o=t,!Er.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const bi=new Set(["if","elseif","else","for"]);function vi(e,t){for(const n of ws(e))if(t.appliedBindingSet.delete(n),bi.has(n.bindingType))for(const e of Xr(n.node))vi(e,t)}function $i(e){for(const t of ws(e)){if(!bi.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Xr(t.node))$i(n),e&&n.mounted&&(Hr(n),n.unmount(),Yr(t.node,n))}}function xi(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Si(e,n,s){const r=Boolean(s);let i;const a=Xr(e.node);i=0===a.size?ri(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${xi(e)}`),Hr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${xi(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);Vr(i,yt(e.node),n);const t=li();null!==t&&ci(i,"branch",t)}}const Pi=new WeakMap;function Ii(e){return Pi.get(e)??[]}const Ai=new Set;const Ni=Symbol.for("wcstack.trustedTypes.policy");function ki(){const e=globalThis[Ni];return null===e||"object"!=typeof e?null:e}function _i(e){globalThis[Ni]=e}let Ti;let Ci=!1;function Ei(e,t){if(Ci)return;if(!function(){if(void 0!==Ti)return Ti;if(!("trustedTypes"in globalThis))return Ti=!1,Ti;try{document.createElement("div").innerHTML="<i></i>",Ti=!1}catch{Ti=!0}return Ti}())return;Ci=!0;const n="function"==typeof ki()?.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 Mi={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")}},Oi=new Set(["textContent","innerText","innerHTML"]);function Ri(e,n,s){if(void 0===s&&1===e.propSegments.length&&Oi.has(e.propSegments[0])&&(s=""),void 0===s)return void(o.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!==s){null!==hs&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Ve(r)&&hs.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=ki(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Ei(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=Ve(e);if(null===n)return null;const o=Ue(e)?.get(n);if(void 0===o)return null;const s=Ke(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,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Xn(r,c)){const t=to(r,c,e.statePathName),o=no(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??ao()??so(t);if(a.visitedEdges.has(o))null!==bt&&bt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=ro(a,o);lo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:Zn++,writtenValue:n};co.push({receipt:i,node:e});try{return r()}finally{co.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=Mi[c];e?e(r,s):(!function(e,t,n){let o=Pi.get(e);o||(o=[],Pi.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,Ai.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!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));null!==hs&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ve(r)&&(u in d?hs.rememberOverwrittenValue(r,c,u,d[u]):hs.recordInjectedKey(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const ji=new WeakSet;function Li(e,t,n){}function Wi(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)}}function Di(e,t,n){const o=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),s=t.length>0?t+c:"";for(const e of n){if(s.length>0&&!e.startsWith(s))continue;const t=e.slice(s.length);t.length>0&&-1===t.indexOf(c)&&o.push(t)}return o}const Bi={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},zi={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Fi(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}.${de}`}function qi(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 Vi(e,t){return`$setAll("${e}") ${t}`}function Hi(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.${de}`}function Ui(e,t){const n=bn(t);if(n.pathInfo.path in E){const e=yt(t.node);return null===e&&oe(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&oe("ListIndex not found for loopContext:");const n=E[t];void 0===n&&oe(`Invalid index name: ${t}`);const o=en(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&oe(Hi(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Mt](n)}const Gi=new WeakSet;function Ki(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Ji=Object.freeze({[N]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&oe("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[k]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[_]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[A]:function(e,t,n){jn(n)||oe("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ms.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||oe('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Ve(e);if(null===t)return null;const n=Ue(e)?.get(t);return void 0===n&&oe(`Custom element <${t}> is not defined for command binding.`),Ke(e)}(r);null===a&&oe(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||oe(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ce(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ms.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 ms.delete(e);const o=n[i];return"function"!=typeof o&&oe(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),ms.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Xi={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!ji.has(e.replaceNode)){ji.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,n,o){const s=e.statePathInfo,r=on(e),i=an(e),a=$t(i),l=a.length>0&&!ui.has(e.node)?[]:a,c=Tr(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=ui.get(e.node);const f=void 0!==u?wi(u,l,c):null,h=Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=hi.get(e.node);if(void 0===t){const n=di.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(mi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(mi(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),hi.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){Io.set(e,(Io.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return fi.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;c.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(Hr(o),$i(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Yr(e.node,o):(Hr(o),o.unmount(),function(e,t){let n=fi.get(e.node);void 0===n&&(n=[],fi.set(e.node,n)),n.length<1e3?n.push(t):Yr(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(ui.delete(e.node),u=void 0)}let g=e.node;const m=ie(s.path+"."+d),y=n.stateElement.loopContextStack,w=Cr(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&g.isConnected&&null===f&&(b=document.createDocumentFragment(),Xt(b,n.rootNode));const v=t(),$=li(),x=e.uuid??"",S=fi.get(e.node);for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const r=yn(m,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=ri(e):vi(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`));else{if(g.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);g.parentNode.insertBefore(e,g.nextSibling),g=e}o.mountAfter(g)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??g;n.parentNode.insertBefore(e,n.nextSibling)}}Vr(o,r,n),null!==$&&ci(o,"row",$)}),void 0===o&&oe(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)){const e=n.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](n.stateElement,o)}}}else{if(o=void 0!==u?u.get(t)??null:null,c.changeIndexSet.has(t)){const e=$s(o);for(const t of e)sa(t,n)}null===o&&oe(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&yi(g,o.firstNode)||g.nextSibling===o.firstNode||o.mountAfter(g),e){const e=o,s=yn(m,t);y.createLoopContext(s,t=>{Vr(e,t,n)})}}g=o.lastNode||g,void 0===u&&(u=new WeakMap,ui.set(e.node,u)),u.set(t,o)}di.set(e.node,g),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Xt(b,null))},if:Si,else:Si,elseif:Si,radio:function(e,t,n){const o=e.node,s=ps(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=ps(o.value,e.inFilters),r=Array.isArray(n)?n:gs;o.checked=r.includes(s)}},Yi=new WeakMap,Qi=new WeakMap,Zi=new WeakMap;function ea(){}function ta(e){const t=hs;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Li;if(t.isDeclared(n,o))return ea}return Ri}function na(e,t){oa(e,t,Ui(t.state,e))}function oa(e,t,n){const o=ps(n,e.outFilters);if(!0===Qi.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=Yi.get(e);if(void 0===s){if(Yi.has(e))return s=ta(e),s===Li&&Yi.set(e,s),void s(e,t,o);if(s=Xi[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Ji[t],Yi.set(e,s),void 0===s){Ve(e.replaceNode)?(s=ta(e),s===Li&&Yi.set(e,s)):(s=Ri,Yi.set(e,s))}}if(s===Ri){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 Qi.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function sa(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=an(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=fs(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==Zi.get(e)){const t=Ve(e.replaceNode);if(t&&void 0===Ue(e.replaceNode)?.get(t))return void function(e,t){if(Gi.has(e))return;Gi.add(e);const n=()=>{Gi.delete(e);const t=fs(e);(null===t||t.shouldApplyState(e))&&ia([e])},o=n=>{Gi.delete(e),Ki(t,n)},s=fs(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Gi.delete(e),r()})||(Gi.delete(e),r()))}const r=Ue(e.replaceNode);if(null===r)return Gi.delete(e),void Ki(t,new Error("CustomElementRegistry is unavailable."));Ro(r).wait(t,()=>{e.replaceNode.isConnected?n():Gi.delete(e)},o)}(e,t);Zi.set(e,!0)}if(!0===t.sameRootVerified)return void na(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Yt(o),null===o&&oe("Root node for fragment not found for binding.")),o!==t.rootNode){const n=ba(o);null===n&&oe("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};na(e,r)})}else na(e,t)}function ra(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!==bt&&bt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function ia(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Yt(d),null===d&&oe("Root node for fragment not found for binding."));const u=ba(d);null===u&&oe("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{sa(n,f)}catch(e){ra(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{Ri(e,{propagationContextByBinding:t},n)}catch(t){ra(e,t,o??null,c)}for(const[e,t]of i.entries())xt(e,t),kt(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Wt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Dt](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 aa(e,t,n){const[o,s,r]=ft(e,n),i=us(e);for(const e of o)wt(e,t);ia(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=pt(o);0!==e.length&&(wt(o.node,t),ia(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const la=new WeakMap;async function ca(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Ue(e);null===s&&oe(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(it(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function da(e){if(e===document)await ca(document),te(document),qa(document,document),aa(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await ze(t.host),await ca(t),te(t),qa(t,t),aa(t,null)}}const ua={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function fa(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${ua[e]??e}" before the state is defined.`}let ha=null;function pa(e){return null===ha&&oe(fa("ssr",e)),ha}const ga=new WeakMap,ma=new WeakMap,ya=new Set,wa=[];function ba(e){return ga.get(e)??null}function va(e){return ma.get(e)??Promise.resolve()}const $a=new WeakSet;function xa(e){$a.add(e)}function Sa(e,n){const s=ga.get(e);if(null===n){if(void 0===s)return;ga.delete(e),ya.delete(s),null!==bt&&bt({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){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 pa('the "enable-ssr" attribute').hydrate(e)||await da(e)}else await da(e);xa(e),Ja(),t()}catch(e){n(e)}})});ma.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await da(e),xa(e),Ja(),t()}catch(e){n(e)}})});ma.set(e,t)}}void 0!==s&&oe('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="...">.'),ga.set(e,n),ya.add(n);for(let t=0;t<wa.length;t++)wa[t](e,n);null!==bt&&bt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Pa=new Map;function Ia(e,t,n){if(null===n)Pa.delete(e);else{Pa.set(e,n);const o=ba(t);null===o&&oe("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 Aa(e){return Pa.get(e)||null}function Na(e){if(e.nodeType===Node.ELEMENT_NODE){return Ee(e.getAttribute(o.bindAttributeName)||"")}if(e.nodeType===Node.COMMENT_NODE){const t=je(e);null===t&&oe("Comment node binding text not found.");const n=Aa(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Le(t),s=null):s=t,[{...o,uuid:s}]}return[]}let ka;function _a(){return ka??={filterName:"not",args:[]}}const Ta=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Ca(e,t){const n=t+c+d,o=e.indexOf("|");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 Ea(e,t){const n=Ta.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Ca(s,t)+r}function Ma(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Ca(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function Oa(e,t){return Ma(e,t)}function Ra(e,t){const n=o.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Ea(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Ma(r,t);e!==r&&o.setAttribute(n,e)}}}function ja(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}function La(e){const t=[],n=ct(e);for(const e of n){const n=Na(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:ja(o),parseBindTextResults:n})}return t}function Wa(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 Da=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Ba=_a();function za(e,t){const n=t.outFilters;return{...t,outFilters:[...n,Ba],bindingType:e}}function Fa(e,t,n,o,s,r=!0){Wa(t),"string"==typeof o&&Ra(t,o),qa(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:La(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 qa(e,t,n,s){const r=o.commentElsePrefix,i=at(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(o.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(o.bindAttributeName)||"";"string"==typeof n&&(i=Oa(i,n));let a=Ee(i)[0];const d=Da.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Ps();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&oe("'else' binding found without preceding 'if' or 'elseif' binding."),a=za("else",l.parseBindTextResult),p=Fa(e,f,a,g,s,!1),Ia(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:ja(o),parseBindTextResults:Na(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&oe("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Fa(e,f,a,g,s),Ia(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=Ps(),i={fragment:document.createDocumentFragment(),parseBindTextResult:za("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ja(n),parseBindTextResults:Na(n)}),Ia(o,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:ja(m),parseBindTextResults:Na(m)})):t.replaceWith(m)}else{p=Fa(e,f,a,g,s),Ia(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 Va=()=>`[${o.bindAttributeName}]`;function Ha(e){if(Qo(e))return!0;if(!Ua(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(Va());return null!==t&&Qo(t)}function Ua(e){return 1===e.nodeType}function Ga(e){if(Ha(e))return;te(e),qa(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);aa(t&&s?n:e,null)}const Ka=[];function Ja(){const e=Ka.splice(0,Ka.length);for(const t of e)Ga(t);l()}const Xa={protocol:"wcs-binder",version:1,bind:function(e){var t;Ua(e)&&!Ha(e)&&(t=e.getRootNode(),$a.has(t)?Ga(e):Ka.push(e))}};const Ya="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Qa=0;async function Za(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++Qa}\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 new Error(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, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${Ya}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Ya}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function el(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){oe(`Failed to load script file: ${e}`)}}class tl{_loopContextStack=Array(f).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&oe("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=f&&oe("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&&oe("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&&oe("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&&oe(`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 nl=new WeakMap;function ol(e,t){let n=nl.get(e);void 0===n&&(n=new Map,nl.set(e,n));let o=n.get(t);return void 0===o&&(o=new Rn(t,e),n.set(t,o)),o}const sl=new WeakMap;function rl(e){const t=sl.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 ol(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:ol(e,n)}},set(){oe("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){oe("$command namespace is read-only; deleting from it is not allowed.")}});return sl.set(e,n),n}const il=Symbol("wcs.notHandled"),al=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],ll=new Map;function cl(e,t){ll.set(e,t)}const dl=new Map;let ul=[],fl=[];function hl(e,t){dl.set(e,t),ul=Array.from(dl.values()).sort((e,t)=>e.order-t.order),fl=ul.slice().reverse()}function pl(e,t){for(let n=0;n<ul.length;n++)ul[n].activate?.(e,t)}function gl(e){"readonly"===e.mutability&&oe("This state is readonly.")}const ml=new Map;class yl{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=ie(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 wl(e){let t;return ml.get(e)??(ml.set(e,t=new yl(e)),t)}function bl(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:en(n.listIndex,o,n.pathInfo.wildcardCount)}function vl(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=Zt(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?en(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?en(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function $l(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function xl(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!==il)return a}}return il}function Sl(e,t,n,o,s){if(t.pathInfo.segments[0]===z)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}(rl(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=xl(s,t,null,n,o);if(r!==il)return r;oe(function(e,t,n){return`[${Bi.binding}] Path "${e}" does not exist on the state tree.${ce(e,Di(t,"",n))}${de}`}(t.pathInfo.path,e,s.getterPaths))}const r=Il(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=xl(s,t,Object(r),n,o);if(e!==il)return e}if(i===d){const e=t.listIndex?.index??oe(Hi(`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 Pl(e,t,n,o,s){const r=Gt(s,t),i=function(e){return zs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Sl(e,t,n,o,s);return Fs(r,{value:l,dirty:!1,generation:a}),l}function Il(e,t,n,o){vl(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!==il)return i}}return $l(s,t)?Pl(e,t,n,o,s):Sl(e,t,n,o,s)}function Al(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=yn(f,r),p=Gt(n.stateElement,h),g=Nt(p),m=Il(e,h,t,n),y=Tr(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]??oe(`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())kt(e,Array.isArray(t)?t:[]);return l}function Nl(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Ds(Il(e,yn(a,r),t,n),r);null==l&&oe(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??oe(`ListIndex not found at index ${c} of ${a.path}`)}return r}function kl(e,t,n,o){"object"==typeof e&&null!==e||oe(`${J} 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&&oe(`${J} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function _l(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&oe(`${J} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function Tl(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];kl(a,n,o,i);const l=_l(a,t,n,o,i);r.has(l)&&oe(`${J} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Cl(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 El(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=Il(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 Ml=new WeakMap;function Ol(e,t){null===t?Ml.delete(e):Ml.set(e,t)}function Rl(e,t,n){const s=yn(ie(e.wildcardParentPaths[t]),n),r=Gt(e.stateElement,s),i=Nt(r),a=e.stateProxy[Mt](s),l=Tr(s.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 o.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)Rl(e,t+1,n)}const jl=[];function Ll(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:jl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:jl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Wl=[];function Dl(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Wl;let s=null;const r=t+c;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ie(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Wl}function Bl(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=ie(r);if(e.listPathSet.has(o)&&s.lastSegment===d){const i=e.stateProxy[Mt](t),a=Gt(e.stateElement,t),l=Nt(a),c=Tr(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Ll(e,o,0,0,c);for(const t of d.fullRows){const o=yn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=Dl(e,r,s);if(null===t)for(const t of d.movedRows){const o=yn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=yn(s,o);e.result.add(t),n.push(t)}}}else{const o=yn(s,t.listIndex);e.result.add(o),n.push(o)}}const r=e.dynamicMap.get(o);if(r)for(const o of r){const s=ie(o),r=[];if(s.wildcardCount>0){const n=Zt(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&oe(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=en(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Rl(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&oe(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=en(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=yn(s,t);e.result.add(o),n.push(o)}}}function zl(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&&oe(`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};!function(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),n(a),i.length=0,Bl(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}(u,t,a);for(const[e,t]of u.observedListValueByAbsAddress)kt(e,t);return Array.from(u.result)}function Fl(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 ql(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 Vl(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 Hl(e,t,n,s,r,i){const a=function(e,t){return!0===tr.get(e)?.byPath.has(t)||!0===ir.get(e)?.has(t)}(e,t),l=function(e,t){return!0===lr.get(e)?.has(t)}(e,t);if(!a&&!l)return;const c=er(),u=o.enablePropagationContext?ao()??null:null,f=e=>{qs(e),c.enqueueAbsoluteAddress(e,u)};a&&$r(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=ie(t).segments.length,r=[];for(const i of lr.get(e).get(t)){const t=ie(i).segments.slice(s);if(t.includes(d))Sr(e,i,r);else for(const s of $r(e,i,!0,xr(n,t),xr(o,t)))r.push(s)}return r}(e,t,n?s:i(),r).forEach(f)}function Ul(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?ao()??so(-1):null,c=er();c.enqueueAbsoluteAddress(t,l),i&&qs(t),zl(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Gt(s.stateElement,t);qs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Gl(e,t,n,o,s){s&&(e.getterPaths.has(t)?qs(n):Fs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function Kl(e,t,n,o,s,r,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=Il(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??oe(Hi(`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{Ul(t,n,s,r,i,a)}}function Jl(e,t,n,o,s,r,i,a){const l=t.parentAddress??oe(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=Il(e,l,s,r)??[];let f=(h=u,Ml.get(h)??null);var h;if(null===f){const e=Ws(u)??[];f={value:[...u],listIndexes:[...e]},Ol(u,f)}try{return Kl(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=Il(e,l,s,r)??[],a=Array.isArray(i)?Ws(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:_s(l.listIndex,-1);a[h]=p;if(new Set(i).size===f.value.length){for(let e=0;e<a.length;e++)a[e].index=e;Ol(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=er(),l=Gt(i,e);$t(l)===n&&(Bs(t.value,t.listIndexes),xt(l,t.value),function(e){Er.add(e)}(t.value));a.enqueueRenderOnlyAddress(l);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=ie(e.pathInfo.path+c+d);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=yn(f,n),d=Gt(i,c);if(void 0===l){const n=Kt(i,f,t.listIndexes[e]??null);Vl(i,d,n),Ul(c,d,s,r,null,$l(i,c),"full");continue}zl(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Gt(i,e);qs(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(l,f,i,a,s,r)}}}function Xl(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=Il(e,t,o,s),a=function(e,t,n,o){const s=Tl(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Tl(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===Ws(o)&&Tr(a,null,o);const l=Tr(a,o,n.list),u=Yl(e,t,n.list,s,r,i),f=ie(i+c+d);for(const t of n.matched){const n=Cl(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?Xl(e,yn(ie(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 Yl(e,t,n,o,s,null)}function Yl(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==il)return i}}const u=!!uo&&(uo=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=Il(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===d?t.listIndex?.index:e;let p,g=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in f,t=void 0!==h?f[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}Hl(a,l,g,p,n,()=>f[h]);const m=$l(a,t),y=Gt(a,t);null!==bt&&bt({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:g}),Fl(a,l,y,p,g);let w=!1;try{if(void 0===h&&oe(Hi(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==d&&!(h in f)){const e=c.writeMissing;for(let o=0;o<e.length;o++){w=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==il)return i;w=!1}}return Reflect.set(f,h,n)}finally{Ul(t,y,s,r,i,m),w?qs(y):Gl(a,l,y,n,m),ql(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Il(e,t,s,r);if(El(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Hl(a,l,h,f,n,()=>Il(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),g=$l(a,t),m=Gt(a,t);null!==bt&&bt({type:"state:write",absoluteAddress:m,value:n,oldValue:f,hasOldValue:h}),Fl(a,l,m,f,h);try{return p?Jl(e,t,m,n,s,r,i,g):Kl(e,t,m,n,s,r,i,g)}finally{p||Gl(a,l,m,n,g),ql(a,t.pathInfo,{value:n})}}function Ql(e,t,n,o){return(t,s,...r)=>{const i=ie(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&&oe(Fi("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=yn(i,Nl(e,n,o,i,s));if(0===r.length)return Il(e,a,n,o);gl(o),Xl(e,a,r[0],n,o)}}function Zl(e,t,n,o){const s=Ql(e,0,n,o);return(t,r)=>{const i=ie(t);if(void 0===r||Array.isArray(r)||oe(`$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&&oe(Fi("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=bl(o,i.wildcardPaths[e]);if(t){r=tn(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&&oe(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=Al(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 ec(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return bl(o,s.wildcardPaths.at(-1)??oe(`lastWildcardPath is null: ${t.pathInfo.path}`))??oe(`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]??oe(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=Ds(Il(e,yn(i,s),n,o),s)??oe(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??oe(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??oe(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":oe(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function tc(e,t,n,o){return(t,s,r,i)=>{gl(o);const a=ie(t);Array.isArray(s)||oe(Vi(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&oe(Fi("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&oe(Vi(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&oe(Vi(t,"requires an array as the value when { spread: true } is set."));const d=Al(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&oe(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,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=Nl(e,n,o,a,d[t]);u.push(yn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(Il(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(Xl(e,s,i,n,o),f++)}return f}}function nc(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of ie(t).cumulativePaths)if(n.has(e))return!0;return!1}const oc=/^\$\d+$/,sc=`${X}${c}`,rc=`${Y}${c}`,ic=new WeakMap;function ac(e,t,n,o){const s=E[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&oc.test(t)&&oe(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${T}1 to ${T}128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&oe(`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&&oe(`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=en(r,i,a.wildcardCount);return c?.index??oe(`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!==il)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>Zl(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>tc(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=wl(t),i=ec(e,r,n,o),a=yn(r.pathInfo,i),l=Gt(s,a),c=er();c.enqueueAbsoluteAddress(l),zl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Gt(s,e);qs(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)}}}(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>Ql(e,0,n,o)(t,s,...r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(K)&&oe(`[wcs/recursion-unsupported] $trackDependency("${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&&oe(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??oe("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(t.path)&&t.path!==e&&n.addDynamicDependency(e,t.path)}}(0,0,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(nc(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&wr(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)&&yr(o.stateElement,e,t,Gt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=nc(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?wr(o.stateElement,e):yr(o.stateElement,e,i,Gt(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||oe(`$eqIndex("${e}") needs a list row scope.`);const r=en(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&oe(`$eqIndex("${e}", ${t}): no list index at that level.`),nc(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&wr(o.stateElement,e),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?Ws(l):null;null!==t?function(e,t,n,o,s){rr=!0,ur(e).lastValue.set(t,s),dr(e,t);let r=ir.get(e);void 0===r&&ir.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=ar.get(o);void 0===l?ar.set(o,l=[]):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)),a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){rr=!0;const r=ur(e);dr(e,t),mr(r,t,s,o,pr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Gt(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case z:return rl(o.stateElement)}if(!t.startsWith(sc)&&!t.startsWith(rc))return}const r=wl(t),i=ec(e,r,n,o),a=yn(r.pathInfo,i);return Il(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=ic.get(e);return void 0===t&&(t=new Map,ic.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Et:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&oe("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 Mt:i=t=>Il(e,t,n,o);break;case Ot:i=t=>El(e,t,n,o);break;case Rt:i=(t,s)=>Xl(e,t,s,n,o);break;case jt:i=()=>async function(e,t,n){const o=Reflect.get(e,M);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Lt:i=()=>function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&o.call(n)}(e,0,n);break;case Wt:i=t=>function(e,t,n,o){const s=Reflect.get(e,R);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=tn(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}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 Dt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,j);"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 lc{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=ba(e);null===n&&oe("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&&oe("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()&&oe(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),oe(`[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&&oe(`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 ac(e,t,n,this)}set(e,t,n,o){return gl(this),function(e,t,n,o,s){if("string"==typeof t){const r=wl(t),i=ec(e,r,o,s);return Xl(e,yn(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)}}const cc=Promise.resolve(),dc=new Map;let uc=[];function fc(e,t){dc.set(e,t),uc=Array.from(dc.values()).sort((e,t)=>e.order-t.order)}function hc(e,t){return oe(fa(e,t))}const pc="undefined"==typeof HTMLElement?class{}:HTMLElement;function gc(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 mc=null;const yc=new Set(["for","if","elseif","else"]);function wc(e,n,o){const s=new Map;for(const e of o){const t=ie(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=Gt(e,t);if(i.has(n))return;i.add(n);const o=hn(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(yn(n,t.listIndex))}};_t();try{if(e.createState("readonly",t=>{for(const o of n){const n=yn(ie(o),null);a(n);try{zl(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)yc.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=()=>{ia(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Us("state",s);void 0!==i&&i.catch(Ys)}finally{Tt()}}class bc extends pc{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return va(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 tl}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(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&&oe(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(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<ul.length;o++)ul[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[B];if(void 0===n)return t;Array.isArray(n)||oe(`${B} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||oe(`${B} entries must be non-empty strings.`),e===z&&oe(`${B} entry "${e}" conflicts with the reserved namespace name "${z}".`),t.has(e)&&oe(`${B} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[F];if(void 0===n)return t;Array.isArray(n)||oe(`${F} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||oe(`${F} entries must be non-empty strings.`),t.has(e)&&oe(`${F} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[J];if(void 0===t)return null;"object"==typeof t&&null!==t||oe(`${J} 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&&oe(`${J} entry path must be a non-empty string.`);const t=e.split(c);t.some(e=>0===e.length)&&oe(`${J} entry "${e}" must not contain empty path segments.`),t[t.length-1]===d&&oe(`${J} entry "${e}" must be the list path itself, not the element path (drop the trailing "${c}${d}").`),-1!==e.indexOf(K)&&oe(`[wcs/recursion-unsupported] ${J} entry "${e}" uses "${K}", which ${J} 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&&oe(`${J} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&oe(`${J} entry "${e}" key field name must be a non-empty string.`),(o.includes(c)||o.includes(d))&&oe(`${J} entry "${e}" key field name "${o}" must be a flat property name ("${c}" / "${d}" are not allowed).`),o in Object.prototype&&oe(`${J} 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<ul.length;o++)ul[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<ul.length;o++)ul[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&mc?.reset(this),this._hasUpdatedCallback=R in e,this._hasErrorCallback=j in e,i=this,Cn.delete(i),function(e,t,n){for(let o=0;o<ul.length;o++)ul[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[q];if(void 0!==o){"object"==typeof o&&null!==o||oe(`${q} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||oe(`${q} entry "${t}" is not declared in $eventTokens.${ce(t,n)}`),"function"!=typeof s&&oe(`${q} entry "${t}" must be a function.`),En(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=gc(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<ul.length;o++)ul[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<ul.length;o++)ul[o].register?.(e,t,n)}(this,e,n),pl(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 <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?pa('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){oe("Failed to parse JSON from script element:"+e)}return{}}(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 Za(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.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){try{const t=await fetch(e);return t.ok||oe(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e);if(e&&e.endsWith(".js"))return await el(e);oe(`Unsupported src file type: ${e}`)}}catch(e){oe(`Failed to initialize state: ${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&&(Sa(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),oe(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===ba(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),ma.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<uc.length;o++)uc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{M in e&&await e[jt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{O in e&&e[Lt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<uc.length;t++)if(!0===uc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||ba(this._rootNode)===this||Sa(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const e=function(e){for(let t=0;t<uc.length;t++){const n=uc[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(Q))try{hc("dcc",`a <${o.tagNames.state}> inside a [${Q}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{hc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<uc.length;t++){const n=uc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&hc("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let s=!1;try{s=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!s)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 pa('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}pl(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<uc.length;t++)if(!0===uc[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<uc.length;n++)uc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Sa(this.rootNode,null),e=this,sl.delete(e),function(e){for(let t=0;t<fl.length;t++)fl[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()}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",H)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&oe(`$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 Wi(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&&oe("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=ll.get(e);return void 0===n&&oe(fa(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<al.length;n++){const o=al[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",W)}_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){return this._addDependency(this._dynamicDependency,e,t)}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=ie(e);if(this._pathSet.add(e),mc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ie(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 lc(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&&oe(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);!function(e){for(let t=0;t<uc.length;t++)uc[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&oe("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(gc(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){wc(this,e,this._pathRegistrations.keys())}}const vc=[];function $c(e=customElements){for(let t=0;t<vc.length;t++)vc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,bc)}function xc(e){if("string"==typeof e?.locale)return 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 Sc(e,t){const o=xc(e);var s;o&&((s=o).tagNames&&Object.assign(n.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(n.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(n.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(n.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(n.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(n.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(n.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(n.locale=s.locale),"boolean"==typeof s.debug&&(n.debug=s.debug),"boolean"==typeof s.enableMustache&&(n.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(n.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(n.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(n.sameValueGuard=s.sameValueGuard)),$c(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=Xa)}()}let Pc=0;const Ic=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Ac=new Set;function Nc(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);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 kc(e,t,n,o,s,r=new Set){0===n.length&&oe(`Cannot build a mount record without host bindings for "${t}".`);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)&&oe("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(y)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++Pc,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(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)e.innerSegments.length>0&&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,privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function _c(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function Tc(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 Cc(e,t){for(const n of e.entries)if(Tc(t,n.innerSegments)){const e=t.slice(n.innerSegments.length);return 0===e.length?n.outerPathInfo.path:n.outerPathInfo.path+c+e.join(c)}return null}function Ec(e,t){return e.markerBasePath+c+t}function Mc(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:ie(r).wildcardCount-ie(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function Oc(e,t){return!e.injectedKeys.has(t)&&!e.mappedKeys.has(t)&&("function"==typeof e.stateObject[t]&&!e.getterKeys.has(t)||Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t))}function Rc(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}.${_c(t)}: path") or declare the key on the component state.`}const jc=/^\$(\d+)$/;function Lc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=_c(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||Oc(e,o))return null;const s=function(e,t){for(const n of e.entries)if(Tc(t,n.innerSegments))return n;return null}(e,t.split(c));return null!==s&&s.readonly?s:null}function Wc(e,t){const n=Lc(e,t);if(null!==n){const o=0===n.innerSegments.length?"":c+n.innerSegments.join(c);oe(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${y}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${y} from the mount.`)}return Dc(e,t)}function Dc(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 Mc(e,e.markerBasePath,t,t),Ec(e,t);if(Oc(e,n[0]))return Mc(e,e.markerBasePath,t,t),Ec(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Cc(e,s);null===i&&oe(Rc(e,t)),0===r.length&&oe(`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 Mc(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=_c(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return Ec(e,t);if(Oc(e,o))return Ec(e,t);const s=Cc(e,t.split(c));if(null!==s)return s;oe(Rc(e,t))}function Bc(e,t,n){let o;const s=jc.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ie(Dc(e,t)).wildcardCount-ie(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Dc(e,t.statePathName),"for"===t.bindingType){const n=ie(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+c+d,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(y)&&null!==Lc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ie(o),...i?{propModifiers:[...r,y]}:{}}:t}function zc(e,t,n,o,s){if(void 0===o)return;const r=ie(n).wildcardCount-ie(t).wildcardCount;return 0===r?o:(s.length<r&&oe(`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])}const Fc=new WeakMap,qc=new WeakMap;const Vc=new WeakMap;const Hc=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)}),Uc=new WeakMap;function Gc(e){return Uc.get(e)??null}let Kc=!1;function Jc(){Kc||(Kc=!0,mt=e=>Fc.has(e)?e.host:null)}function Xc(e){const t=Vc.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 Yc(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Vc.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 Qc="3.0.0",Zc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function ed(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 td(e){const t=function(e){const t=tr.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:ir.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 nd="__WCSTACK_DEVTOOLS_HOOK__";function od(){const e=globalThis,t=e[nd];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[nd]=n,n}const sd=e=>{null!==bt&&bt({type:"state:update-batch",addresses:e})};function rd(e){const t=null!==bt;!function(e){bt=e}(e);const n=null!==e;n&&!t?Xs(sd,0):!n&&t&&function(e){const t=Gs.findIndex(t=>t.listener===e);-1!==t&&Gs.splice(t,1)}(sd)}function id(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 ad(e){return ba(e)??oe("devtools: no state tree on this root")}let ld=null;function cd(){if(t())return;if(null!==ld)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Qc,getStateElements(){const e=[];for(const t of ya)e.push(id(t));return e},overlays:e=>Xc(ad(e)).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join("."),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]})),keyedSubscriptions:e=>td(ad(e)),keys(e){const t=ad(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 ad(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){ad(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>function(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=[...e.inFilters,...e.outFilters].map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=Aa(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(ed(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(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=tt(t,Ee(n));for(const o of e)r(ed(t,o,"attribute",n))}catch{}continue}const t=Zc.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=Aa(s);if(null===a){if(n===o.commentTextPrefix)try{r(ed(e,Le(s),"comment",s))}catch{}}else r(ed(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:rd};ld=e,od().register(e)}const dd={name:"devtools",install(){cd()}},ud=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),fd=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const hd=new WeakMap;const pd=new WeakMap,gd=new WeakSet,md=new WeakMap;function yd(e,t,n,o){console.warn(`[@wcstack/state] [${Bi[n]}] ${zi[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ce(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${de}`),null!==bt&&bt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const wd={check:function(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=e.addressHooks;if(s){const t=s.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const r=ie(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=hd.get(e);return void 0===n&&(n=new Set,hd.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const i=function(e,t,n){if(void 0!==Wi(e,t))return fd;const o=ie(t).segments;let s=e,r="";for(let t=0;t<o.length;t++){const i=o[t],a=r;if(r=0===t?i:r+c+i,t>0&&t<o.length-1&&void 0!==Wi(e,r))return ud;if(Object(s)!==s)return ud;if(i===d){if(!Array.isArray(s)||0===s.length)return ud;s=s[0];continue}const l=Wi(s,i);if(void 0===l)return{existence:"missing",missingSegment:i,candidates:Di(s,a,n)};if("function"==typeof l.get)return t===o.length-1?fd:ud;s=l.value}return fd}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===md.get(e)?.has(t)}(e,n)||("binding"!==o?yd(e,n,o,i):function(e,t,n){let o=pd.get(e);void 0===o&&(o=new Map,pd.set(e,o));if(o.set(t,n),gd.has(e))return;gd.add(e),setTimeout(()=>function(e){gd.delete(e);const t=pd.get(e);if(void 0===t)return;pd.delete(e);for(const[n,o]of t)yd(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){hd.delete(e),pd.delete(e)},markExported:function(e,t){let n=md.get(e);void 0===n&&(n=new Set,md.set(e,n)),n.add(t),pd.get(e)?.delete(t)}};let bd=!1;function vd(){bd||(bd=!0,function(e){mc=e}(wd))}const $d={name:"diagnostics",install(){vd()}};function xd(e){oe(`filter ${e} requires at least one option`)}function Sd(e){oe(`filter ${e} requires a number as option`)}function Pd(e){oe(`filter ${e} requires a number value`)}function Id(e){oe(`filter ${e} requires a date value`)}function Ad(e){return!(!e||isNaN(Number(e)))}const Nd={eq:(e,t)=>{const n=e?.[0]??xd("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Ad(n)||Sd("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??xd("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Ad(n)||Sd("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>("boolean"!=typeof e&&oe(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??xd("lt");return Ad(t)||Sd("lt"),e=>("number"!=typeof e&&Pd("lt"),e<Number(t))},le:e=>{const t=e?.[0]??xd("le");return Ad(t)||Sd("le"),e=>("number"!=typeof e&&Pd("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??xd("gt");return Ad(t)||Sd("gt"),e=>("number"!=typeof e&&Pd("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??xd("ge");return Ad(t)||Sd("ge"),e=>("number"!=typeof e&&Pd("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??xd("inc");return Ad(t)||Sd("inc"),e=>("number"!=typeof e&&Pd("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??xd("dec");return Ad(t)||Sd("dec"),e=>("number"!=typeof e&&Pd("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??xd("mul");return Ad(t)||Sd("mul"),e=>("number"!=typeof e&&Pd("mul"),e*Number(t))},div:e=>{const t=e?.[0]??xd("div");return Ad(t)||Sd("div"),e=>("number"!=typeof e&&Pd("div"),e/Number(t))},mod:e=>{const t=e?.[0]??xd("mod");return Ad(t)||Sd("mod"),e=>("number"!=typeof e&&Pd("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&Pd("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??xd("clamp");Ad(t)||Sd("clamp");const n=e?.[1]??xd("clamp");Ad(n)||Sd("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&Pd("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return Ad(t)||Sd("fix"),e=>("number"!=typeof e&&Pd("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Pd("locale"),e.toLocaleString(t??o.locale))},uc:e=>e=>String(e).toUpperCase(),lc:e=>e=>String(e).toLowerCase(),cap:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??xd("slice");Ad(n)||Sd("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Ad(o)||Sd("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??xd("substr");Ad(t)||Sd("substr");const n=e?.[1]??xd("substr");return Ad(n)||Sd("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??xd("pad");Ad(t)||Sd("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??xd("rep");return Ad(t)||Sd("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??xd("truncate");Ad(t)||Sd("truncate");const n=Number(t),o=e?.[1]??"…";return e=>{const t=String(e);return t.length<=n?t:t.slice(0,n)+o}},join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||oe(`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=e?.[0]??"0";return Ad(t)||Sd("round"),e=>{"number"!=typeof e&&Pd("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Ad(t)||Sd("floor"),e=>{"number"!=typeof e&&Pd("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Ad(t)||Sd("ceil"),e=>{"number"!=typeof e&&Pd("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Ad(t)||Sd("percent"),e=>("number"!=typeof e&&Pd("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??xd("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Id("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Id("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Id("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Id("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||Id("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]??xd("defaults"),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),null:e=>e=>""===e?null:e},kd={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],inc:[0,1],dec:[0,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],fix:[0,1],locale:[0,1],uc:[0,0],lc:[0,0],cap:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],pad:[1,2],rep:[1,1],rev:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],boolean:[0,0],number:[0,0],string:[0,0],null:[0,0]},_d=Nd,Td=Nd;let Cd=!1;const Ed={name:"formats",install(){Cd||(Cd=!0,me("input",Td,kd),me("output",_d,kd))}};function Md(e){return-1!==e.indexOf(K)}function Od(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(Md(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function Rd(e){return 0===e.length?e:c+Wd(e.slice(1))}function jd(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 Ld(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(jd(e,t,n.slice(0,o)))return!0;return!1}function Wd(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 Dd(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 Bd(e,t,n){n<0&&oe(`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&&oe(`[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 zd(e,t){return Bd(e,"",t)}function Fd(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 qd(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 Vd(e,t,n){const o=e.recursionRegistry,s=Od(o.spec,n);null===s&&oe(qi(n,o.spec.recursiveAnchor));const r=qd(t,o);return null===r&&oe(`[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 Hd(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(yn(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=yn(o,s),c=Gt(n.stateElement,l),u=Il(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)&&oe(`[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)&&oe(`[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=Tr(s,Nt(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:ie(n),childListPathInfo:ie(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(yn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,ie(u),null);for(const[e,t]of a)kt(e,t);return i}function Ud(e,t,n,o,s,r,i){gl(n);const a=n.stateElement.recursionRegistry,l=Od(a.spec,o);null===l&&oe(qi(o,a.spec.recursiveAnchor));const c=Rd(l);Array.isArray(s)||oe(Vi(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&oe(`[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&&oe(Vi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&oe(Vi(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){Dd(e,n)&&oe(`[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&&oe(`[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=Hd(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Xl(e,u[o],r,t,n),f++);return f}const Gd={write(e,t){if(!0!==e.hasRecursion)return il;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&oe(`[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.`),il},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return il;if("$getAll"===t)return(t,s)=>{if(Md(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Od(r.spec,o);null===i&&oe(qi(o,r.spec.recursiveAnchor)),Array.isArray(s)||oe(`[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&&oe(`[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=Hd(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Il(e,a[o],t,n));return l}(o,n,e,t,s);t=Vd(e.stateElement,e,t)}return Zl(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>Md(t)?Ud(o,n,e,t,s,r,i):tc(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&Md(t)){const s=wl(Vd(e.stateElement,e,t)),r=ec(o,s,n,e);return Il(o,yn(s.pathInfo,r),n,e)}return il}};let Kd=!1;function Jd(e,t){"string"==typeof t&&0!==t.length||oe(`[wcs/recursion-declaration-invalid] ${G} ${e} must be a non-empty string.`);const n=t.split(c);n.some(e=>0===e.length)&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not contain empty path segments.`),n.length<2&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must name a list element: a property path ending with "${c}${d}" (for example "nodes${c}${d}").`),n[n.length-1]!==d&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must end with "${c}${d}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===d&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must have exactly one "${d}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===K&&oe(`[wcs/recursion-declaration-invalid] ${G} ${e} "${t}" must not contain "${K}" — the declaration is what gives "${K}" its meaning.`),isNaN(Number(n[o]))||oe(`[wcs/recursion-declaration-invalid] ${G} ${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 Xd=new WeakSet;function Yd(e){return"function"==typeof e.get&&Xd.has(e.get)}function Qd(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&Yd(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))}}!function(e,t,n){for(const o of n){const n=ie(o),s=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void Fs(Kt(e,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=t;for(const e of s[i].segments.slice(a))l=l?.[e];if(!Array.isArray(l))return;const c=Ws(l);if(null===c)return;const d=Math.min(c.length,l.length);for(let e=0;e<d;e++)r(l[e],c[e],i+1)};r(t,null,0)}}(e,t,n)}}const Zd="[wcs/recursion-declaration-invalid]";class eu{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=gc(t);for(const[t,o]of Object.entries(n)){if(!Md(t))continue;"function"==typeof o.set&&oe(`${Zd} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&oe(`${Zd} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Od(e,t);null===n&&oe(qi(t,e.recursiveAnchor)),0===n.length&&oe(`${Zd} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),Dd(e,Rd(n))&&oe(`${Zd} "${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(Md(t)||Yd(n))continue;const e=this._matchExpansion(t);null!==e&&oe(`${Zd} "${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++)jd(this.spec,e[t].suffix,e[n].suffix)&&oe(`${Zd} "${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(Ld(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=Wd(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!==Fd(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=Fd(this.spec,e.suffix,t);null!==n&&(null!==o&&oe(`"${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||Yd(s)||oe(`"${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,Xd.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(zd(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 Qd(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=Bd(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 tu="recursionSpec",nu="recursionRegistry",ou={order:5,validateEarly(e,t,n){const o=function(e){const t=e[G];if(void 0===t)return null;"object"==typeof t&&null!==t||oe(`[wcs/recursion-declaration-invalid] ${G} 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&&oe(`[wcs/recursion-declaration-invalid] ${G} must declare exactly one anchor; it is empty.`),n.length>1&&oe(`[wcs/recursion-declaration-invalid] ${G} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Jd("anchor",o),"string"!=typeof s&&oe(`[wcs/recursion-declaration-invalid] ${G} entry "${o}" must map to the repeating sub-path as a string (for example "children${c}${d}").`),Jd("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(c)),i=s.slice(0,s.lastIndexOf(c)),a=r+c+K;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(tu,o),n.set(nu,null===o?null:new eu(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(nu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",G)},apply(e,t,n){const o=n.get(tu)??null;null!==o&&e.addListPath(o.anchorList)}};let su=!1;function ru(){su||(su=!0,Kd||(Kd=!0,cl("recursion",Gd)),hl("recursion",ou))}const iu={name:"recursion",install(){ru()}};const au={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?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 lu=!1;function cu(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 du(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 uu(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 fu(e){return e.startsWith("$")}function hu(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 pu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||oe(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||oe(`${t} entries must be non-empty strings.`),e.startsWith("$")&&oe(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&oe(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function gu(e){const t=pu(e,W)??[],n=pu(e,D)??[],o=gc(e),s=function(e){const t=e[V];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}oe(`${W} entry "${e}" is not declared on the state.${ce(e,hu(o,"value"))}`)}"function"==typeof t.value&&oe(`${W} entry "${e}" is a method. Declare it in ${D} instead.`)}for(const e of n){const t=o[e];void 0===t&&oe(`${D} entry "${e}" is not declared on the state.${ce(e,hu(o,"method"))}`),"function"!=typeof t.value&&oe(`${D} entry "${e}" is not a method. Declare it in ${W} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function mu(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||oe(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Ue(e);null!==r&&"function"==typeof r.define||oe(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&oe(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=gu(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}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.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=Ue(this._shadow);return null!==e&&Ge(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?(lu||(lu=!0,cl("dcc",au)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${W} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=gc(n);for(const[e,t]of Object.entries(m)){if(fu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=uu(e,o)}else n.get=cu(e),n.set=du(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:cu(e),set:du(e)});r.define(s,g)}async function yu(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&oe(`"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){try{if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await el(t);oe(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await Za(n,t.tagName.toLowerCase());oe(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){oe(`DCC: Failed to load state: ${e}`)}}(o,t);mu(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const wu={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Q)?yu(e,t.host,t):null}};let bu=!1;const vu=new WeakMap;function $u(e,t,n){let o=vu.get(e);void 0===o&&(o=new Map,vu.set(e,o));const s=o.get(t);null!=s&&oe(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function xu(e,t){if(null===e)return!1;const n=vu.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 Su=new WeakMap;function Pu(e,t){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{t.$postUpdate(e+c+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...s)=>t[n](e+c+o,...s)}return t[o]}return t[e+c+o]}},set:(n,o,s)=>("string"!=typeof o||(t[e+c+o]=s),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Iu=new WeakMap,Au=[];const Nu=new WeakMap,ku=new WeakSet;function _u(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 Tu=null;const Cu=new WeakMap,Eu=new Set;function Mu(e,t,n,o){let s=Cu.get(e);if(void 0===s){if(!o)return null;s=new Map,Cu.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 Ou(e,t){if(!e.component.isConnected)return!1;const n=yt(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 Ru(e,t,n,o){const s=Mu(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&&Ou(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?Ou(r,o)&&(null!==a&&oe(`[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 ju(e){const t=e.parentStateElement,n=yt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Et](n,()=>{e.$postUpdate(o.exportedPath)})})}const Lu=new WeakMap;class Wu{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return yn(ie(this.markerParentPath+c+e),this.listIndex)}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(Dc(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Wc(e,t):Dc(e,t),a=zc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Wc(e,t):Dc(e,t),l=zc(0,t,a,r,n);return o[s](a,l,...i)}}return 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 vl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[Dc(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)||oe(`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,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(e,t)?(e[t]=n,!0):(this.receiver[Wc(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 Dc(this.record,t),!0}catch{return!1}}}function Du(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Lu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Lu.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 Wu(e,s,t.listIndex,r,n,o))}function Bu(e){const t=e.parentStateElement,n=(t,n)=>{const o=yt(e.component);let s;return t[Et](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(Dc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Wc(e,n):Dc(e,n),l=yt(e.component)?.listIndex.indexes??[],c=zc(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:Dc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Wc(e,s)]=r})}),!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 Dc(e,n),!0}catch{return!1}}})}function zu(e,t){const n=function(e){return Fc.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&oe(`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&&us(t).dispose(),function(e,t){Jc(),Fc.set(e,t),Uc.set(t,e);let n=Vc.get(t.parentStateElement);void 0===n&&(n=new Map,Vc.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=qc.get(t.component);void 0===o&&(o=new Map,qc.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Hc.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=ga.get(e);if(void 0!==n){if(n===t)return;oe("A state tree is already registered on this root.")}ga.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Bc(e,t,n);te(t);const o=yt(e.component);qa(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),aa(t,o,n)}(e,t),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=Dc(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=ie(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Mu(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),mc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=yt(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(Eu.has(s))continue;const r=ie(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Et](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Eu.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),ju(e),o=t,s=Promise.resolve(),ma.set(o,s),s.then(()=>xa(o),()=>{})}function Fu(e,t){const n=us(t),o=yt(e.component);n.forEachActiveBindingNode(e=>wt(e,o));ia(n.rebindAddresses()),ju(e)}function qu(e,t){if(function(e){const t=Vc.get(e);return void 0!==t&&t.size>0}(t))for(const n of Xc(t)){if(!Vu(n.component,e))continue;const t=Gc(n);null!==t&&Fu(n,t)}}function Vu(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 Hu={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=Yc(e,t.pathInfo.path);if(null!==s)return Du(s,t,n,o)}return il},readMissing(e,t,n,o,s){if(null===n){if(xu(e.rootNode??null,t.pathInfo.path))return;return il}if(!0===e.hasMounts){const n=Ru(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Du(e,yn(ie(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return il},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=Su.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&&oe(`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 il},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Ru(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Du(e,yn(ie(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return il},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=Yc(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=Fc.get(n);if(void 0!==e)return e;n=n.parentNode}return Fc.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 Iu.get(e)??Au}(e);for(const s of o){const o=s.mountPath+c,r=new Set,i={};for(const n of t){if(n.absolutePathInfo.stateElement!==e)continue;const t=n.absolutePathInfo.pathInfo.path;if(t!==s.mountPath&&!t.startsWith(o))continue;if(-1!==t.indexOf("#"))continue;const a=t===s.mountPath?"":t.slice(o.length);if(""===a)continue;r.add(a);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const e=tn(n.listIndex,l);(i[a]??=[]).push(e)}}if(r.size>0)try{s.callback.call(Pu(s.mountPath,n),Array.from(r),i)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>xu(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){qu(t,e)}};let Uu=!1;const Gu=new WeakMap;function Ku(e){let t=Gu.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Gu.set(e,t)),t}function Ju(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=vu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function Xu(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{$u(n,s,e)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return ba(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function Yu(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");try{!function(e){0===e.length&&oe('"mount" requires a non-empty tree path.');const t=ie(e);for(const n of t.segments)0===n.length&&oe(`"mount" path "${e}" has an empty segment.`),n===d&&oe(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&oe(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),n.hasAttribute("bind-component")&&oe('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),$u(s,r,e),ba(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===ba(s)&&function(e,t){const n=()=>{if(null!==ba(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const i=n=>{t.graftInfo=n,e.markInitialized(),null===n&&Ju(e,t),e.settleInitialization()};let a;try{a=await e.loadStateFromSource()}catch(e){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,e),void i(null)}const l=e.connectedRootNode??null;null!==l&&Xu(e,t,l)?function(e,t,n,o,s,r){const i={mountPath:n,volumeState:o,onGrafted:s,acquireSlot:r};if(null!==t)return void sp(t,i);ip(),function(e,t){if(ku.has(e))return void _u(t);let n=Nu.get(e);void 0===n&&(n=[],Nu.set(e,n)),n.push(t)}(e,i)}(l,ba(l),r,a,i,()=>Xu(e,t,l)):i(null)}const Qu={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=Ku(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{$u(n,t.mountPath,e),ba(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,cc}return Yu(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Ku(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&ba(n)===t.graftInfo.rootStateElement&&tp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==Gu.get(e)?.initializing)return;const t=e.getAttribute("mount");oe(`Cannot replace the state of <${o.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){ku.add(e);const t=Nu.get(e);if(void 0!==t){Nu.delete(e);for(const e of t)_u(e)}}(t)},initializeFailureCleared(e,t){!function(e){ku.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=Ku(e);return null!==t.graftInfo&&tp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,Ju(e,t)),e.clearConnectedRootNode(),!0}};let Zu=!1;const ef=new WeakMap;function tf(e,t){let n=ef.get(e);n||(n=new Set,ef.set(e,n)),n.add(t)}const nf=new WeakMap;const of=new WeakMap,sf=new WeakMap;const rf=new WeakMap;const af={isComplete:function(e,t){return!0===ef.get(e)?.has(t)},isDeclared:function(e,t){return!0===nf.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=of.get(e);o||(o=new Map,of.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=sf.get(e);o||(o=new Map,sf.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=rf.get(e);s||(s=new Map,rf.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function lf(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 cf=new WeakMap;class df{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=cf.get(e);return n?n.get(t)??null:null}(e,t)??oe("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 uf=e=>()=>e;function ff(e,t,n,o){!function(e,t,n){let o=cf.get(e);o||(o=new Map,cf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(lf(o));const s=function(e,t){const n=new df(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:uf(s),enumerable:!0,configurable:!0}),tf(t,n),hf(t,n)}function hf(e,t){if(L in e){const n=e[L];"function"==typeof n?n.call(e,t).catch(e=>{oe(`Error in ${L}: ${e instanceof Error?e.message:String(e)}`)}):oe(`${L} is not a function.`)}}const pf=new Set;function gf(e,t){pf.has(e)||(pf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function mf(e){const t=e.rootEntry,n=yt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Et](n,()=>{o=e[t.outerPathInfo.path]})}),o}const yf=new WeakMap;function wf(e,t){e.landInitialization(),oe(t)}async function bf(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?Ve(a):null;null!==a&&null!==l||oe(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||wf(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&&oe(`"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=nf.get(e);n||(n=new Set,nf.set(e,n)),n.add(t)}(a,d);const u=Ue(a);null===u&&oe(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await ze(a),d in a||oe(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||oe(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=of.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==h&&function(e,t){if(!e.hasAttribute(o.bindAttributeName))return!1;const n=rt(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]=h,f=h),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(rt(a)??[]).some(e=>e.propSegments[0]===d)||wf(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(o.bindAttributeName)){const o=(rt(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=ba(a.getRootNode())??wf(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,qc.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(function(e,t,n){const o=rf.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;rf.get(e).delete(t)}}(a,d,f),u=kc(a,d,o,c,f,function(e,t){return sf.get(e)?.get(t)}(a,d)),function(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=mf(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;gf(`${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.`)}}(u)),t.mountRecord=u,n.parentNode!==i)return;try{zu(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Bu(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),tf(a,d)}return hf(a,d),function(e){const t=Ic.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(K)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;Ac.has(n)||(Ac.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),void Nc(u,"$connectedCallback")}}ff(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const vf={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=yf.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},yf.set(e,t)),t}(e);return bf(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=yf.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&Fu(n,o)}),Nc(n,"$connectedCallback"),!0},disconnecting(e){const t=yf.get(e);return void 0!==t&&null!==t.mountRecord&&(Nc(t.mountRecord,"$disconnectedCallback"),ju(t.mountRecord),e.clearConnectedRootNode(),!0)}};let $f=!1;function xf(){$f||($f=!0,fc("bindComponent",vf),hs=af)}const Sf=new WeakMap,Pf=new Set,If=new Set;function Af(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Nf(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function kf(e){return Sf.get(e)}function _f(e){Tf(e),Sf.delete(e)}function Tf(e){Pf.delete(e),If.delete(e)}const Cf=new WeakMap,Ef=new WeakMap,Mf=new Set,Of=new Map;function Rf(e){return Cf.get(e)??Of}function jf(e){Mf.add(e),function(e){const t=Sf.get(e);void 0!==t&&(Af(t)&&Pf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&If.add(e))}(e)}const Lf=new Map;function Wf(e){return Ef.get(e)??Lf}function Df(e){0===e.length&&oe(`[wcs/watch-declaration-invalid] ${H} entry name must be a non-empty state path.`),e.startsWith("$")&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" must not start with "$" (reserved namespace).${de}`),e.includes("@")&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${de}`),e in Object.prototype&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ie(e);for(const n of t.segments)0===n.length&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" has an empty path segment.${de}`);return t.wildcardCount>u&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Bf(e,t){const n=t[H];if(void 0===n)return null;"object"==typeof n&&null!==n||oe(`[wcs/watch-declaration-invalid] ${H} must be an object mapping state paths to handler functions.${de}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&oe(`[wcs/watch-declaration-invalid] ${H} entry "${t}" must be a function.${de}`);const n=Df(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Cf.set(e,t)}(e,o),s.size>0?s:null}let zf=0,Ff=0;function qf(e){zf=e+1}function Vf(){zf=0}function Hf(){zf>Ff&&(Ff=zf)}const Uf=new WeakMap;function Gf(e,t,n){let o=Uf.get(e);void 0===o&&(o=new Map,Uf.set(e,o)),o.set(t,n)}const Kf=new Map;function Jf(e,t){Kf.has(e)||Kf.set(e,t)}function Xf(e){return Kf.get(e)}const Yf={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||Jf(n,o)},swapped(e,t,n){var o;o=n,Kf.has(o)&&Jf(t,Xf(n))}};function Qf(e){for(let t=e;null!==t;t=t.parentListIndex)if(js(t))return!0;return!1}function Zf(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[Mt](yn(t.wildcardParentPathInfos[i],r)),l=Ws(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=en(o,i,t.wildcardCount);if(l!==c&&!Ms(l,c)){if(js(c))return"gone";s="replaced"}r=l}return s}function eh(e,t,n){const o=new Map;for(const s of n){const n=Zf(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 th=new Set;function nh(e){th.delete(e)}function oh(){return th}const sh=Symbol("wcs-stream-last-notified-uncertain"),rh=new WeakMap;function ih(e,t){const n=rh.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function ah(e,t){const n=rh.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:sh,error:Object.is(o.error,null)?null:sh})}const lh=new WeakMap;function ch(e){return lh.get(e)??new Map}function dh(e){nh(e);const t=lh.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,ah(e,n.name)}const uh=new WeakSet;let fh=0;function hh(e){return kf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function ph(e){if(0===If.size)return;if(t=e.absolutePathInfo.stateElement,!If.has(t))return;var t;const n=hh(e);if(void 0!==n)for(const e of n)gh(e)}function gh(e){uh.has(e)||(uh.add(e),fh++)}function mh(e){return!!uh.delete(e)&&(fh--,!0)}const yh=/^(?:0|[1-9]\d*)$/;function wh(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function bh(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&&yh.test(t)&&wh(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&wh(e,t))?"object":null}function vh(e,t){const n=bh(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]=vh(o[e],t);return r}function $h(e){return vh(e,new Map)}function xh(e,t,n){if(Object.is(e,t))return!0;const o=bh(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(bh(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(!xh(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&xh(s[e],r[e],n))}function Sh(e,t){return xh(e,t,new Map)}const Ph=new WeakMap;function Ih(e,t){if("function"!=typeof t)return;const n=Ph.get(t);void 0===n?Ph.set(t,new Set([e])):n.add(e)}const Ah={"read-source":e=>`${U} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${U} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${U} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${U} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${U} could not write the output "${e}".`},Nh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function kh(e,t,n){null!==bt&&bt({type:"state:watch-error",phase:t,path:`${U}.${e}`,error:n})}function _h(e,t,n){console.error(`[@wcstack/state] ${Ah[n](e)}`,t),kh(e,Nh[n],t)}function Th(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Ch(e,t){t.then(void 0,()=>{}),_h(e,new TypeError(`${U} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Eh=new WeakSet;const Mh=Object.freeze([]);function Oh(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function Rh(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 jh(e,t){return t.has(e.stateElement)&&!0===kf(e.stateElement)?.entries.has(e.entry)}function Lh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Wh(n,e))||mh(t)}function Wh(e,t){return er().hasQueuedPath(e,t)}function Dh(e,t){!function(e,t,n){if(0!==fh)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=hh(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||mh(t)}}(e,t,Wh)}function Bh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function zh(e,t,n){if(!jh(e,n))return Lh(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(Eh.has(e))return;Eh.add(e);const o=`[wcs/scan-source-computed] ${U} 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}`),kh(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=ch(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],o=0===r.pathInfo.wildcardCount?e.rows:eh(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Rh)){let n;try{n=Bh(t,r,e)}catch(e){_h(s.name,e,"read-source");continue}const o=a(l,n,Xf(e.absAddress),...e.indexes);if(Th(o))return void Ch(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){_h(s.name,e,i.failure)}return i.plan}function Fh(e,t){const{group:n}=e;if(!jh(n,t))return void Lh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||mh(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!Sh(o,s.initial):!Object.is(o,e.next)){const o=n.reset?$h(s.initial):e.next;t[s.name]=o,Ih(s.name,o)}})}catch(e){_h(s.name,e,"write")}}function qh(e,t,n){if(Dh(e,t),0===Pf.size)return Mh;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=kf(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=tn(n.listIndex,r.wildcardCount)}for(const s of i)Oh(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)Oh(o,e,t).reset=!0}if(0===o.size)return Mh;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];qf(n);try{for(const n of s){const o=zh(n,e,t);null!==o&&r.push(o)}}finally{Vf()}return r}function Vh(e){Zh(),(0!==Rf(e).size||0!==Wf(e).size||function(e){const t=Sf.get(e);return void 0!==t&&Af(t)}(e))&&(jf(e),function(e){const t=[];for(const n of Rf(e).values())Hh(e,n)&&t.push(n);for(const n of Wf(e).values())for(const o of n)Hh(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{Gf(e,Kt(e,o.pathInfo,null),n[o.path])}catch(t){Gh(e,o.path,"prime",t)}})}(e))}function Hh(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Uh={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Gh(e,t,n,o){console.error(`[@wcstack/state] $watch ${Uh[n]} "${t}" threw.`,o),null!==bt&&bt({type:"state:watch-error",phase:n,path:t,error:o})}function Kh(e){const t=Mf;try{if(0===t.size)return void Dh(e,t);const n=function(){const e=Ff;return Ff=0,e}();if(n>32){Dh(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!==bt&&bt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){qf(n);try{for(const n of e)Fh(n,t)}finally{Vf()}}}(qh(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Rf(e).get(s),i=Wf(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=tn(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Xh);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(Qf(o.absAddress.listIndex)||s?.entry===o.entry&&Jh(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(eh(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){Gh(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);qf(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Rf(e.stateElement).get(e.entry.path)===e.entry,o=!0===Wf(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&Yh(e)}}finally{Vf()}}(e,t,n)}finally{Kf.clear()}}function Jh(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Xh(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 Yh(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Hh(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 Gh(0,n.path,"evaluate",e)}const a=r?function(e,t){return Uf.get(e)?.get(t)}(t,o):Xf(o);r&&Gf(t,o,i),null!==bt&&bt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){Gh(0,n.path,"handler",e)}}let Qh=!1;function Zh(){Qh||(Qh=!0,cl("watch",Yf),hl("watch",ep),Xs(Kh,10),Js(Hf))}const ep={order:10,register(e,t){var n;n=e,Mf.delete(n),Tf(n),Cf.delete(n),function(e){Uf.delete(e)}(e);const o=Bf(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?H:U)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Vh(e)},deactivate(e){var t;t=e,Mf.delete(t),Tf(t)}};function tp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Pu(e.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function np(e,t,n){const o=n[H];if(void 0!==o){const n=[],s=new Set;let r=0;for(const[i,a]of Object.entries(o)){const o=t+c+i,l=function(e,n,...o){a.call(Pu(t,this),e,n,...o)};n.push({path:o,pathInfo:ie(o),handler:l,order:1e6+r++}),s.add(o),e.setPathInfo(o,"prop","watch")}n.length>0&&(!function(e,t){let n=Ef.get(e);void 0===n&&(n=new Map,Ef.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)}}(e,n),e.addVolumeWatchPaths?.(s),Vh(e))}const s=n[J];if(void 0!==s){const n=new Map;for(const[e,o]of Object.entries(s))n.set(t+c+e,o);e.mergeVolumeListKeys?.(n)}const r=n[R];"function"==typeof r&&(!function(e,t){let n=Iu.get(e);void 0===n&&(n=[],Iu.set(e,n)),n.push(t),e.markHasVolume?.()}(e,{mountPath:t,callback:r}),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.`)}function op(e,t,n){!function(e,t,n){const o=n[H];if(void 0!==o){"object"==typeof o&&null!==o||oe(`${H} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(o))"function"!=typeof t&&oe(`${H} entry "${e}" must be a function.`),Df(e)}const s=n[J];if(void 0!==s){"object"==typeof s&&null!==s||oe(`${J} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(s))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&oe(`${J} entry "${n}" must map a list path to a field name or a key function.`),e.listKeys?.has(t+c+n)&&oe(`${J} entry "${t+c+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&oe(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&oe(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[G]&&oe(`Volume "${t}" declares ${G}, 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(gc(n)))-1!==e.indexOf(K)&&oe(`Volume "${t}" declares "${e}", which uses "${K}". Volumes do not support recursive getters yet — declare them on the root state.`)}(e,t,n);const{data:o,accessors:s}=function(e){const t={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(e)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(t[o]=s.value):n.set(o,s));return{data:t,accessors:n}}(n),r=ie(t),i=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===r.segments.length&&t in e){if(i)return;oe(`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<r.segments.length-1;t++){const o=r.segments[t],s=""===n?o in e:void 0!==e[n+c+o];n=""===n?o:n+c+o,s||(e[n]={})}if(r.segments.length>1&&void 0!==e[t]){if(i)return;oe(`Volume mount "${t}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}e[t]=o}),function(e,t){let n=Su.get(e);void 0===n&&(n=new Set,Su.set(e,n)),n.add(t)}(e,t),e.markHasGraftedVolumes?.();for(const[n,o]of s){const s=t+c+n,r=o.get,i=o.set,a={enumerable:!1,configurable:!0};"function"==typeof r&&(a.get=function(){return r.call(Pu(t,this))}),"function"==typeof i&&(a.set=function(e){i.call(Pu(t,this),e)}),e.defineTreeAccessor(s,a)}np(e,t,n);const a=n.$connectedCallback;return"function"==typeof a&&e.createState("writable",e=>{let n;try{n=a.call(Pu(t,e))}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}}function sp(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=op(e,t.mountPath,t.volumeState)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" failed to graft.`,e)}finally{t.onGrafted(n)}}let rp=!1;function ip(){var e;rp||(rp=!0,Uu||(Uu=!0,cl("scopes",Hu)),Zu||(Zu=!0,fc("scopes",Qu)),xf(),Tu=sp,e=ap,wa.includes(e)||wa.push(e))}function ap(e,t){(function(e){const t=vu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){ku.delete(e);const n=Nu.get(e);if(void 0===n||0===n.length||null===Tu)return;Nu.delete(e);const o=Tu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const lp={name:"scopes",install(){ip(),bu||(bu=!0,fc("dcc",wu))}},cp=/^@@wcs-(?:for|if|elseif|else):[^-]/,dp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,up=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,fp=/^@@wcs-text-start:(.+)$/;function hp(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class pp extends pc{_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=Qc.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=o.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){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=hp(JSON.stringify(t)),e.appendChild(n);const s=Array.from(Pa.keys());for(const t of s){const n=Aa(t);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",t);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),e.appendChild(s)}const r=Array.from(Ai);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=Ii(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=hp(JSON.stringify(t)),e.appendChild(n)}}Ai.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(dp.test(e.data)||up.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;cp.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=fp.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;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(o.tagNames.ssr),s=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;dp.test(e.data)&&i.push(e)}for(const e of i){const t=dp.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()}pp.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(cp.test(e.data)){const t=e.data.split(":")[1];l.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of l){const n=s.get(t);if(n){const t=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&t.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const c=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of c)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const gp={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Qc),pp.buildContent(o,pp.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const mp=new Set(["for","if","elseif","else"]);function yp(e){const t=new ds;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=ft(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function wp(e,t,n){for(const o of t)"event"===o.bindingType||mp.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in E||ie(o.statePathName).wildcardCount>n||e.push(o)}function bp(e,t,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function vp(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Ee(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,_a()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;Wa(a),"string"==typeof l&&Ra(a,l),qa(n,a,l);Ia(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:La(a)})}}const $p={hydrate:async function(e){await ca(e);const t=e.querySelectorAll(o.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="${Qc}". Falling back to full render.`),pp.cleanupDom(e),!1}for(const n of t)vp(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=dp.exec(e.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let d=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:l,nodes:c})}return t}(document.body),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=oi(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=yp(s.nodes);Rr(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");bs(t,r),Wr(t,i);const l=[];for(const e of r)e.statePathName in E&&l.push(e);if(xs(t,l),"for"===s.type&&null!==s.index){const i=bp(e,"for",s.uuid);if(i){const e=_s(null,s.index);pi(i,e,t),gi(i,s.nodes[s.nodes.length-1]),Jr(i,t);const l=ie(s.path+"."+d);Dr(t,yn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),wp(o,r,l.wildcardCount);let c=n.get(s.uuid);c||(c=[],n.set(s.uuid,c)),c.push(e)}}else{const n=bp(e,s.type,s.uuid);n&&(Jr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),wp(o,r,0))}}for(const[t,o]of n){const n=bp(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=Aa(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ba(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&Bs(t,o)})}return o}(document.body,n);pp.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());pp.restoreTextBindings(document.body);const[i,a]=ft(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(wt(e,null),t.setAttribute("data-wcs-completed",""))}else wt(e,null);const l=[],c=[],u=us(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(mp.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(d))continue;l.push(e)}for(const e of c)if("for"===e.bindingType){const t=an(e),n=ba(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(xt(t,o),kt(t,o))})}ia([...l,...s]);for(const{el:e,parent:t,next:n}of r)t.insertBefore(e,n);const f=e.querySelectorAll(o.tagNames.ssr);for(const t of f){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=pp.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await va(e.rootNode);const t=pp.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",Qc),pp.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let xp=!1;function Sp(){var t;xp||(xp=!0,ha=$p,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,pp)},vc.includes(t)||vc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=gp)}())}const Pp={name:"ssr",install(){Sp()}},Ip="[wcs/scan-declaration-invalid]",Ap=Object.freeze([]);function Np(e){return`${U} entry "${e}"`}function kp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function _p(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.${de}`}function Tp(e,t,n){0===n.length&&oe(`${Ip} ${e} "${t}" must be a non-empty state path.${de}`),n.startsWith("$")&&oe(`${Ip} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${de}`),n.includes("@")&&oe(`${Ip} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${de}`),n in Object.prototype&&oe(`${Ip} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${de}`);const o=ie(n);for(const s of o.segments)0===s.length&&oe(`${Ip} ${e} ${t} "${n}" has an empty path segment.${de}`);return o.wildcardCount>u&&oe(`${Ip} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Cp(e,t,n,o){const s=Np(e);0===e.length&&oe(`${Ip} ${U} entry name must be a non-empty string.${de}`),(e.includes(c)||e.includes(d))&&oe(`${Ip} ${s} must be a flat property name ("${c}" and "${d}" are not allowed). The output is a property the runtime owns.${de}`),e.startsWith("$")&&oe(`${Ip} ${s} must not start with "$" (reserved namespace).${de}`),e in Object.prototype&&oe(`${Ip} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${de}`),t.has(e)&&oe(`${Ip} ${s} conflicts with a getter declared on the state.${de}`),n.has(e)&&oe(`${Ip} ${s} conflicts with a setter declared on the state.${de}`),o.has(e)&&oe(`${Ip} ${s} conflicts with the ${V} entry of the same name — each output has exactly one owner.${de}`)}function Ep(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Ph.get(t)?.has(e)}(e,o)&&oe(`${Ip} ${Np(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${de}`)}function Mp(e,t,n,o,s,r){const i=Np(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&oe(`${Ip} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${de}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||oe(`${Ip} ${i} "on" must be a non-empty event-token name.${de}`),n.has(e)||oe(`${Ip} ${i} on "${e}" is not declared in ${F}.${ce(e,n)}${de}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&oe(`${Ip} ${i} "from" must be a state path string.${de}`);const u=Tp(i,"from",d),f=kp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&oe(_p(i,"from",d,f));const h=kp(u,s);return null!==h&&oe(function(e,t,n){return`${Ip} ${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.${de}`}(i,d,h)),(d===e||d.startsWith(e+c))&&oe(`${Ip} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${de}`),{kind:"path",path:d,pathInfo:u}}function Op(e,t,n,o){if(void 0===t)return Ap;const s=Np(e);Array.isArray(t)||oe(`${Ip} ${s} "resetOn" must be an array of state paths.${de}`);const r=[];for(const e of t){"string"!=typeof e&&oe(`${Ip} ${s} "resetOn" must contain only state path strings.${de}`);const t=Tp(s,"resetOn",e);t.wildcardCount>0&&oe(`${Ip} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${de}`);const i=kp(t,o);null!==i&&oe(_p(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&oe(`${Ip} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${de}`),"path"===n.kind&&e.startsWith(n.path+c)&&oe(`${Ip} ${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.${de}`),r.push(e)}return r}function Rp(e,t,n=null){const o=e[U];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&oe(`${Ip} ${U} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${de}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(gc(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){const t=e[V];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)){Cp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&oe(`${Ip} ${Np(e)} must be an object ({ from | on, initial, fold, resetOn? }).${de}`);const o=u;Ep(e,a,o);const f=Mp(e,o,t,s,i,n);"initial"in o||oe(`${Ip} ${Np(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${de}`),"function"!=typeof o.fold&&oe(`${Ip} ${Np(e)} fold must be a function.${de}`);const h=Op(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=ie(e).segments[0];t.has(n)&&oe(`${Ip} ${Np(o.name)} resetOn "${e}" reads the ${U} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${de}`)}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&&oe(`${Ip} ${U} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${de}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function jp(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 uh.has(e)}(e),l=a&&!Sh(n,e.initial)?$h(e.initial):n,c=t(l,o,...s);if(Th(c))return void Ch(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Ih(e.name,c)),a&&mh(e)}catch(t){_h(e.name,t,i)}}}function Lp(e,t,n){const o=function(e,t){_f(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Nf(n,e.source.path,e);for(const t of e.resetOn)Nf(o,t,e),"event"===e.source.kind&&Nf(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Sf.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)&&er().hasQueuedPath(e,n))&&gh(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 Wp="scanEntries",Dp={order:8,validate(e,t,n){const o=Rp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Wp,o)},applyEarly(e,t,n){const o=n.get(Wp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=$h(n.initial);e[n.name]=t,Ih(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&En(e,n.source.tokenName).subscribe(jp(n))}(e,o))},register(e,t,n){const o=n.get(Wp)??null,s=function(e){const t=new Map,n=kf(e);if(void 0!==n)for(const e of n.entries)mh(e)&&t.set(e.name,e.resetOn);return _f(e),t}(e);e.setScanPaths?.(null===o?null:Lp(e,o,s))}};let Bp=!1;const zp=Object.freeze([]),Fp=Object.freeze([]);function qp(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??zp,i=e.dynamicDependency.get(n)??zp,a=t.byFromPath.get(n)??Fp;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Vp=(e,t)=>t,Hp=new Set;function Up(e,t){const n=t[V];if(void 0===n)return void ih(e,Hp);"object"==typeof n&&null!==n||oe(`${V} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&oe(`${V} entry name must be a non-empty string.`),s.includes(c)&&oe(`${V} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.includes(d)&&oe(`${V} entry "${s}" must be a flat property name ("${d}" is not allowed).`),s.startsWith("$")&&oe(`${V} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&oe(`${V} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&oe(`${V} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&oe(`${V} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||oe(`${V} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&oe(`${V} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&oe(`${V} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&oe(`${V} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&oe(`${V} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??Vp,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in t||(t[s]=a.definition.initial),o.set(s,a)}!function(e,t){lh.set(e,t)}(e,o),ih(e,new Set(o.keys()))}const Gp=new WeakMap,Kp=new WeakMap;function Jp(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=ch(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&ch(e).has(n),ownKeys:()=>Array.from(ch(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=ch(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){oe(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){oe(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function Xp(e){const t=Gp.get(e);if(void 0!==t)return t;const n=Jp(e,X,e=>e.status);return Gp.set(e,n),n}function Yp(e){const t=Kp.get(e);if(void 0!==t)return t;const n=Jp(e,Y,e=>e.error);return Kp.set(e,n),n}function Qp(e){Gp.delete(e),Kp.delete(e)}let Zp=null;function eg(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 tg={read(e,t){!function(e,t){null!==Zp&&Zp.add(Gt(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===X?eg(Xp(e),t.pathInfo.segments):n===Y?eg(Yp(e),t.pathInfo.segments):il},get:(e,t)=>t===X?Xp(e.stateElement):t===Y?Yp(e.stateElement):il};async function ng(e,t,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await 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] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();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",i)}}function og(e){dg();const t=ch(e);if(0!==t.size){!function(e){th.add(e)}(e);for(const n of t.values())sg(e,n)}}function sg(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=Zp,s=new Set;let r;Zp=s;try{e.createState("readonly",e=>{r=n(e)})}finally{Zp=o}r instanceof Promise&&oe(`${V} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${X}${c}${t.name}`,a=`${Y}${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||oe(`${V} 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&&oe(`${V} 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=kf(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=qp(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&oe(`[wcs/scan-feedback-loop] ${V} entry "${t.name}" args read "${n}", which is derived from the ${U} 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}),rg(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{e[t.name]=s.fold(e[t.name],n)})},done(){rg(e,t,"done",null)},fail(o){rg(e,t,"error",o),n.abort()}};ng(s.source,o,n.signal,r)}function rg(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return rh.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=rh.get(e);void 0===s&&(s=new Map,rh.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${X}${c}${t.name}`),i&&e.$postUpdate(`${Y}${c}${t.name}`)}))}function ig(e){const t=oh();if(0===t.size)return;const n=[];for(const o of t)for(const t of ch(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&ch(e).get(o.name)===o)try{sg(e,o)}catch(n){o.controller?.abort(),t.has(e)&&ch(e).get(o.name)===o&&rg(e,o,"error",n)}}let ag=!1;const lg=new WeakMap,cg={order:20,apply(e,t){var n;Qp(e),dh(n=e),nh(n),lh.delete(n),Up(e,t),void 0!==t[V]&&e.attachAddressHooks?.("streams",V)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return og(e),void lg.set(e,e.connectGeneration??0)}n===e.connectGeneration&&lg.get(e)!==n&&og(e)}},deactivate(e){dh(e),Qp(e)}};function dg(){ag||(ag=!0,cl("streams",tg),hl("streams",cg),Xs(ig,20))}const ug=[Ed,{name:"temporal",install(){Zh(),Bp||(Bp=!0,hl("scan",Dp),Js(ph)),dg()}},iu,lp,Pp,dd,$d];function fg(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(ug),Sc(e,t)}function hg(e){return e}const pg={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"ブール値を反転",hasArgs:!1,resultType:"boolean",acceptTypes:["boolean"],minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},inc:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},dec:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},fix:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},uc:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lc:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},cap:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},pad:{description:"パディング (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},rep:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},rev:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator])",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},time:{description:"ロケール形式の時刻",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},datetime:{description:"ロケール形式の日時",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},ymd:{description:"YYYY-MM-DD 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},null:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},gg=1;function mg(){return{version:1,syntax:{bindAttribute:o.bindAttributeName,tagName:o.tagNames.state,pathDelimiter:c,wildcard:d,delimiters:{binding:";",propValue:":",modifier:h,filter:p},structuralDirectives:Array.from(ue),modifiers:{flags:w,keyValue:$,eventNamePrefix:P},indexParam:{prefix:T,maxDepth:u},bindingTypes:{elseKeyword:x,spread:S,eventPropertyPrefix:P,propNamespaces:{eventToken:I,command:A,class:N,attr:k,style:_}}},filters:Object.keys(_d),filterMeta:pg,reservedLifecycle:[M,O,R,j,L],reservedStateApi:[W,D,B,z,F,q,V,H,U,J,G,X,Y]}}const yg=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),wg=Object.freeze([]);function bg(e){if(!o.enableContractAnalyzer)return wg;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))yg.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?vg(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,$g,e=>{t.push(e),null!==bt&&bt(e)}),t}function vg(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function $g(e){const t=Ue(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{pp as Ssr,Ni as TRUSTED_TYPES_POLICY_SLOT,Qc as VERSION,gg as WCS_MANIFEST_VERSION,bg as analyzeContract,fg as bootstrapState,da as buildBindings,pg as builtinFilterMeta,hg as defineState,va as getBindingsReady,s as getConfig,ki as getTrustedTypesPolicy,mg as getWcsManifest,_i as setTrustedTypesPolicy};
|
|
1
|
+
const e=Symbol.for("wcstack.ssr.snapshotBuilder");function t(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n;function s(){return 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="#",p="|",g="prevent",m="stop",y="ro",w=Object.freeze([g,m,y]),b="init",v="sync",$=Object.freeze([b,v]),x="else",S="...",P="on",I="eventToken",A="state",N="command",k="class",_="attr",T="style",C="$",E={};for(let e=0;e<u;e++)E[`${C}${e+1}`]=e;const M=Object.freeze(E),O="$connectedCallback",R="$disconnectedCallback",j="$updatedCallback",L="$errorCallback",W="$stateReadyCallback",D="$bindables",B="$commands",z="$commandTokens",F="$command",q="$eventTokens",V="$on",H="$streams",U="$watch",G="$scan",K="$recursion",J="**",X="$listKeys",Y="$streamStatus",Q="$streamError",Z="data-wc-definition",ee=/\{\{\s*(.+?)\s*\}\}/g,te=new Set(["SCRIPT","STYLE"]);function ne(e){if(!o.enableMustache)return;!function(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(;t.nextNode();)n.push(t.currentNode);for(const e of n)e.parentElement&&te.has(e.parentElement.tagName)||oe(e)}(e);const t=Array.from(e.querySelectorAll("template"));for(const e of t)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),ne(t.content)}else ne(e.content)}function oe(e){const t=e.data;if(ee.lastIndex=0,!ee.test(t))return;ee.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=ee.exec(t));){o.index>s&&n.appendChild(document.createTextNode(t.slice(s,o.index)));const e=o[1];n.appendChild(document.createComment(`@@: ${e}`)),s=o.index+o[0].length}s<t.length&&n.appendChild(document.createTextNode(t.slice(s))),e.parentNode.replaceChild(n,e)}function se(e){throw new Error(`[@wcstack/state] ${e}`)}const re=new Map;let ie=0;function ae(e){let t=re.get(e);return void 0!==t||(-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] "${e}" uses "${J}", 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.`),t=Object.freeze(new le(e)),re.set(e,t)),t}class le{id=++ie;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:ae(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 ce(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 de(e,t){if(0===e.length)return"";const n=e.toLowerCase();let o=null,s=3;for(const e of t){const t=ce(n,e.toLowerCase(),2);t<s&&(o=e,s=t)}return null!==o?` Did you mean "${o}"?`:""}const ue=" Validate statically: npx @wcstack/lint <file>.",fe=new Set(["if","elseif","else","for"]),he={not:()=>e=>!e},pe={input:new Map,output:new Map},ge={input:new Map,output:new Map},me=new Map;function ye(e,t,n){const o=pe[e],s=ge[e];for(const e of Object.keys(t)){o.set(e,t[e]);const r=n?.[e];void 0===r?s.delete(e):s.set(e,r)}me.clear()}function we(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=me.get(s);if(void 0!==r)return r;const i=pe[n].get(e)??he[e];void 0===i&&se(`[wcs/filter-unknown] filter not found: ${e}.${de(e,function(e){return[...new Set([...Object.keys(he),...pe[e].keys()])]}(n))}${ue}`);const a=ge[n].get(e);void 0!==a&&(t.length<a[0]||t.length>a[1])&&se(t.length<a[0]?`[wcs/filter-arity] filter "${e}" requires at least ${a[0]} argument(s) (${t.length} given).${ue}`:`[wcs/filter-arity] filter "${e}" accepts at most ${a[1]} argument(s) (${t.length} given).${ue}`);const l=i(t,o);return me.set(s,l),l}function be(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 ve=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function $e(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:ve.test(e)?Number(e):e)}function xe(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=be(o,i,a);t.push(e),n.push($e(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&&se(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${e})". Close the quote.${ue}`);const c=be(o,i,a);return(c||r)&&(t.push(c),n.push($e(c,r))),{args:t,literals:n}}function Se(e,t){return e.map(t=>{const n=t.indexOf("("),o=t.lastIndexOf(")");-1!==n&&-1===o&&se(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==o&&-1===n&&se(`Invalid filter format: missing opening parenthesis in "${t}"`);const s=(-1===n?t:t.substring(0,n)).trim();if(0===s.length&&se(`[wcs/binding-syntax] an empty filter in "${e.join("|")}" — remove the extra "|" or name the filter.${ue}`),-1===n)return{filterName:s,args:[],literals:[]};return{filterName:s,...xe(t.substring(n+1,o))}})}const Pe=e=>e.trim(),Ie=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(Ie(s))n=s;else if(s===t)return o}return-1}function Ne(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):Ie(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const ke=new Map;function _e(e){const t=Ae(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),ke.has(s)?r=ke.get(s):(o=Ne(s,p).map(Pe),r=Se(o),ke.set(s,r))):n=e.trim();const i=n.split(h).map(Pe);i.length>2&&se(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${h}" — write "${i[0]}${h}${i.slice(1).join(",")}".${ue}`);const[a,l]=i,d=a.split(c).map(Pe);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(Pe):[],inFilters:r}}const Te=new Map;function Ce(e){const t=Ae(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Te.has(s)?r=Te.get(s):(o=Ne(s,p).map(Pe),r=Se(o),Te.set(s,r))):n=e.trim(),-1!==n.indexOf("@")&&se(`"${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.`);return{statePathName:n,statePathInfo:ae(n),outFilters:r}}const Ee=new Set([x,"if","elseif","for",S]),Me=new Set([k,_,T,N,I]);function Oe(e){const[...t]=function(e){return Ne(e,";")}(e).map(Pe).filter(e=>e.length>0),n=t.map(e=>{const t=e.indexOf(":");-1===t&&se(`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`);const n=e.slice(0,t).trim(),o=e.slice(t+1).trim(),s=n.split(h)[0].split(p)[0].trim();if(s!==n&&Ee.has(s)&&se(`[wcs/binding-syntax] "${e}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${ue}`),n===x){o.length>0&&se(`[wcs/binding-syntax] "${e}": "else" takes no value — write "else:".${ue}`);const t=ae("#else");return{propName:x,propSegments:[x],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===S){const t=Ce(o);return t.outFilters.length>0&&se(`Invalid spread binding "${e}": filters are not allowed on spread targets.`),0===t.statePathName.length&&se(`Invalid spread binding "${e}": spread target path is required.`),{propName:S,propSegments:[S],propModifiers:[],inFilters:[],...t,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n){return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Ce(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Ce(o);return{..._e(n),...e,bindingType:s}}{const e=Ce(o),t=_e(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Me.has(o[0]))&&se(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...Me].join(", ")}).${ue}`),{...t,propName:o.join(c),propSegments:o,...e,bindingType:"prop"}}return t.propSegments[0]===I||t.propSegments[0].startsWith(P)?{...t,...e,bindingType:"event"}:{...t,...e,bindingType:"prop"}}});if(n.length>1){n.some(e=>fe.has(e.bindingType))&&se(`[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">).${ue}`)}return n}const Re=new WeakMap,je=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Le=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function We(e){const t=Re.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=Le.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return je.has(r)?(Re.set(e,s[2]),s[2]):null}function De(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ce(e),bindingType:"text"}}const Be=new WeakMap,ze=new WeakSet;let Fe=0;async function qe(e){const t=function(e){let t,n=Be.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++Fe,promise:o,resolve:t},Be.set(e,n),ze.has(e)&&n.resolve(),n}(e);await t.promise}function Ve(e){const t=Be.get(e);void 0===t?ze.add(e):t.resolve()}const He=new WeakMap;function Ue(e){const t=He.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{He.set(e,n)}}function Ge(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Ke(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Ge(t);if(void 0!==n)return Ge(n)}return Ge(globalThis.customElements)}function Je(e,t){e.upgrade?.(t)}function Xe(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=et(s.properties,Ye);if(null===r)return null;const i=void 0===s.inputs?new Map:et(s.inputs,Qe);if(null===i)return null;const a=void 0===s.commands?new Map:et(s.commands,Ze);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Ye(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 Qe(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 Ze(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 et(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 tt(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ae(n),inFilters:[],outFilters:[],bindingType:"prop"}}function nt(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function ot(e,t,n={}){const s=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&&se("Spread binding requires an element node.");const t=e,o=Ue(t);null===o&&se(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${t.tagName.toLowerCase()}> is not a custom element.`);const a=Ke(t);null===a&&se(`CustomElementRegistry is unavailable for <${o}>.`);if(void 0===a.get(o)){s||se(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Je(a,t);const l=Xe(t);null===l&&se(`Spread binding "${n.statePathName}" requires <${o}> 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=tt(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=tt(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=nt(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=nt(r[t]);if(null!==n){if(a.get(n)===t)l.push(r[t]);else if(o.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 st(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 rt(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:we(s.filterName,s.args,t,s.literals??s.args)})}return n}const it=new WeakMap;function at(e){return it.get(e)||null}function lt(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function ct(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!lt(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function dt(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 ut(e){const t=[],n=ct(e),s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode(e){if(e.nodeType===Node.ELEMENT_NODE){return e.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}return null!==We(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&dt(e,n)||t.push(e)}return t}const ft=new WeakSet;function ht(e,t,n,o){const s=ot(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ue(e):null;return null===n&&se("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:e,tagName:n,parseResults:t,transform:o}}}ft.add(e);const r=function(e,t){const n=[];for(const o of t){const t=rt(o.inFilters,"input"),s=rt(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){it.set(e,t)}(e,r),Ve(e),{bindings:r,deferred:null}}function pt(e,t){const n=ut(e),o=[],s=[];for(const e of n){if(ft.has(e))continue;const n=ht(e,_a(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function gt(e){ft.add(e)}function mt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){ft.delete(e)}(t);return ht(t,n,{allowDeferred:!1},o).bindings}const yt=new WeakMap;let wt=null;function bt(e){let t=e;for(;t;){const e=yt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==wt&&t instanceof ShadowRoot&&(n=wt(t)),t=n}return null}function vt(e,t){null!==t?yt.set(e,t):yt.delete(e)}let $t=null;const xt=new WeakMap;function St(e){return xt.get(e)??[]}function Pt(e,t){xt.set(e,t)}function It(e){return xt.has(e)}const At=new WeakMap;let Nt=null,kt=0;function _t(e){return At.get(e)??[]}function Tt(e,t){null===Nt?At.set(e,t):Nt.set(e,t)}function Ct(){kt++,null===Nt&&(Nt=new Map)}function Et(){if(0!==kt&&(kt--,!(kt>0||null===Nt))){for(const[e,t]of Nt)At.set(e,t);Nt=null}}function Mt(e){return(Nt?.has(e)??!1)||At.has(e)}const Ot=Symbol("$$setLoopContext"),Rt=Symbol("$$getByAddress"),jt=Symbol("$$hasByAddress"),Lt=Symbol("$$setByAddress"),Wt=Symbol("$$connectedCallback"),Dt=Symbol("$$disconnectedCallback"),Bt=Symbol("$$updatedCallback"),zt=Symbol("$$errorCallback"),Ft=new WeakMap,qt=new WeakMap;class Vt{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Ht(e,t){if(null===t){let t=qt.get(e);return void 0!==t||(t=new Vt(e,null),qt.set(e,t)),t}{let n=Ft.get(t);void 0===n&&(n=new WeakMap,Ft.set(t,n));let o=n.get(e);return void 0!==o||(o=new Vt(e,t),n.set(e,o)),o}}const Ut=new WeakMap;function Gt(e,t){let n=Ut.get(e);void 0===n&&(n=new Map,Ut.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Kt(e,t)),n.set(t,o)),o}class Kt{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Jt(e,t){return Ht(Gt(e,t.pathInfo),t.listIndex)}function Xt(e,t,n){return Ht(Gt(e,t),n)}const Yt=new WeakMap;function Qt(e,t){null===t?Yt.delete(e):Yt.set(e,t)}function Zt(e){return Yt.get(e)||null}const en=new Map;function tn(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=en.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,en.set(s,r),r}function nn(e,t,n){return t<0||t>=n?null:e.at(t-n)}function on(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const sn=new WeakMap;function rn(e){const t=bt(e.node);if(null===t)return null;let n=sn.get(t);if(void 0===n)n=new WeakMap,sn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=tn(t.pathInfo,e.statePathInfo);return n>0&&(o=nn(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const an=new WeakMap;function ln(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=Zt(n);null===t?se(`Cannot get absolute state address for disconnected binding: ${e.bindingType} ${e.statePathName} on ${e.node.nodeName}`):n=t}return n}function cn(e,t){let n=null;if(n=an.get(e)||null,null!==n)return n;const o=ln(e,t),s=rn(e),r=$a(o);return null===r&&se("No state tree found on this root for binding."),n=Xt(r,e.statePathInfo,s),an.set(e,n),n}function dn(e){an.delete(e)}const un=new WeakMap;function fn(e,t){const n=un.get(e);void 0===n?un.set(e,t):n instanceof Set?n.add(t):n!==t&&un.set(e,new Set([n,t])),null!==$t&&$t({type:"state:binding-added",absoluteAddress:e,binding:t})}function hn(e,t){const n=un.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&un.delete(e),null!==$t&&$t({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const pn=new WeakMap;function gn(e){const t=un.get(e);return void 0!==t?t:null!==e.listIndex?pn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const mn=new WeakMap,yn=new WeakMap;class wn{pathInfo;listIndex;_parentAddress;constructor(e,t){this.pathInfo=e,this.listIndex=t}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const e=this.pathInfo.parentPathInfo;if(null===e)return null;let t=null;return t=this.pathInfo.segments[this.pathInfo.segments.length-1]===d?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=bn(e,t)}}function bn(e,t){if(null===t){let t=yn.get(e);return void 0!==t||(t=new wn(e,null),yn.set(e,t)),t}{let n=mn.get(t);void 0===n&&(n=new WeakMap,mn.set(t,n));let o=n.get(e);return void 0!==o||(o=new wn(e,t),n.set(e,o)),o}}const vn=new WeakMap;function $n(e){let t=null;if(t=vn.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=rn(e);null===n&&se(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=bn(e.statePathInfo,n)}else t=bn(e.statePathInfo,null);return vn.set(e,t),t}function xn(e){vn.delete(e)}function Sn(){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 Pn=new Map,In=Sn();function An(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Nn(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function kn(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=Nn(e),s=An(e,o);let r=Pn.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=$a(o.getRootNode());null===i&&se("No state tree found on this root for two-way binding.");const a=bt(o);i.createState("writable",e=>{e[Ot](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]:[]})})},Pn.set(s,r)),e.node.addEventListener(o,r),In.add(s,e),!0}var t,n;return!1}function _n(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Tn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)_n(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class Cn{_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)t.push(n(...e));return t}}class En extends Cn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==$t&&$t({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const Mn=new WeakMap;function On(e,t){let n=Mn.get(e);void 0===n&&(n=new Map,Mn.set(e,n));let o=n.get(t);return void 0===o&&(o=new En(t,e),n.set(t,o)),o}const Rn=new WeakMap;function jn(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Ue(t),o=Ke(t);if(null!==n&&void 0===o?.get(n))return null===o&&se(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Rn.has(e))return!0;const s=e.propSegments[1];"string"==typeof s&&0!==s.length||se('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(e){return null===Ue(e)?null:Xe(e)}(t);null===r&&se(`eventToken binding requires a wc-bindable custom element. <${t.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&se(`Property "${s}" is not declared in wcBindable.properties of <${t.tagName.toLowerCase()}>.${de(s,r.knownProperties.keys())}`);const a=i.event,l=e.statePathName,c=e.propModifiers,d=e=>{c.includes(g)&&e.preventDefault(),c.includes(m)&&e.stopPropagation();const n=$a(t.getRootNode());null===n&&se("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||se(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${de(l,n.eventTokenNames)}${ue}`);const o=bt(t);n.createStateAsync("writable",async t=>{Tn(t[Ot](o,()=>{const s=null!==o?on(o.listIndex,o.pathInfo.wildcardCount):[];return On(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),Rn.set(e,{eventName:a,handler:d}),!0}class Ln extends Cn{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==$t&&$t({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Wn(e){return e instanceof Ln}const Dn=new Map,Bn=Sn();function zn(e){const t=e.propModifiers.filter(e=>e===g||e===m).sort().join(",");return`${e.statePathName}::${t}`}const Fn=(e,t,n)=>o=>{t.includes(g)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=$a(r);null===i&&se("No state tree found on this root for event handler.");const a=bt(s),l=e.startsWith(F+".");i.createStateAsync("writable",async t=>{const c=t[Ot](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?on(a.listIndex,c):[];if(l){const s=t[Rt](bn(n,null));return Wn(s)||se(`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&&se(`Handler "${e}" is not a function on the state tree.`),Reflect.apply(u,t,[o,...d])});Tn(c,`"${e}"`)})};function qn(e){if(!e.propName.startsWith(P))return!1;const t=zn(e);let n=Dn.get(t);void 0===n&&(n=Fn(e.statePathName,e.propModifiers,e.statePathInfo),Dn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),Bn.add(t,e),!0}function Vn(e){if(!e.propName.startsWith(P))return!1;const t=zn(e),n=Dn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==Bn.countOf(t)&&(Bn.remove(t,e)&&Dn.delete(t),!0)}const Hn=new Map,Un=Sn();function Gn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Kn(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function Jn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=Kn(e),s=Gn(e,o);let r=Hn.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=$a(o.getRootNode());null===r&&se("No state tree found on this root for two-way binding.");const i=bt(o);r.createState("writable",e=>{e[Ot](i,()=>{e[t]=s})})},Hn.set(s,r)),e.node.addEventListener(o,r),Un.add(s,e),!0}var t,n;return!1}const Xn=new Set(["radio","checkbox"]),Yn=new Set(["value","valueAsNumber","valueAsDate"]);function Qn(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(Xn.has(e)&&"checked"===t)return!0;if(Yn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ue(n);if(null!==s){const e=Ke(n)?.get(s);void 0===e&&se(`Custom element <${s}> is not defined. Cannot determine if property "${t}" is suitable for two-way binding.`);const o=Xe(n);if(o?.knownProperties.has(t))return!0}return!1}let Zn=1,eo=1,to=1;const no=new WeakMap;function oo(e,t,n){let o=no.get(e);void 0===o&&(o=new Map,no.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=Zn++,o.set(s,r)),r}function so(e,t){return"to-element"===t?2*e:2*e+1}const ro=new Set;function io(e){return{transactionId:eo++,originBindingId:e,visitedEdges:ro,hop:0}}function ao(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 lo=null;function co(){return lo}function uo(e,t){const n=lo;lo=e;try{return t()}finally{lo=n}}const fo=[];let ho=!1;const po=new Map,go=Sn(),mo=new WeakMap,yo=e=>e.detail,wo=new WeakMap;function bo(e,t,n,o){const s=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.propName}::${e.statePathName}::${t}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function vo(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ue(e.node);if(null!==n){const o=Ke(e.node)?.get(n);void 0===o&&se(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Xe(e.node)?.knownProperties.get(e.propName);s&&(t=s.event)}for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function $o(e){if(null!==Ue(e.node)){const t=Xe(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??yo}return null}function xo(e){if(null===Ue(e.node))return!1;const t=Xe(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const So=(e,t,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==yo||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=wo.get(e);void 0===r&&(r=new Set,wo.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=mo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=oo(a,e,t),s=function(e,t){for(let n=fo.length-1;n>=0;n--){const o=fo[n];if(o.node===e&&o.receipt.member===t)return o.receipt}return null}(a,e);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:e,statePathName:t,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==$t&&$t({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:so(n,"to-state"),node:a,member:e}));const r=so(n,"to-state"),i=co();if(null!==i&&i.visitedEdges.has(r))return void(null!==$t&&$t({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=ao(i??io(n),r)}const f=$a(a.getRootNode());null===f&&se("No state tree found on this root for two-way binding.");const h=bt(a),p=()=>{r&&(ho=!0);try{f.createState("writable",e=>{e[Ot](h,()=>{e[t]=c})})}finally{r&&(ho=!1)}};null!==u?uo(u,p):p()};const Po=new WeakSet;function Io(e){Po.add(e)}function Ao(e){return!!Po.has(e)&&(Po.delete(e),!0)}const No=new WeakMap;function ko(e,t){const n=No.get(e);return!(void 0===n||n<t)&&(n===t?No.delete(e):No.set(e,n-t),!0)}const _o=new WeakSet;function To(e){_o.add(e)}function Co(e){return!!_o.has(e)&&(_o.delete(e),!0)}let Eo=0;function Mo(){Eo--}function Oo(){return Eo>0}class Ro{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 jo=new WeakMap;function Lo(e){let t=jo.get(e);return void 0===t&&(t=new Ro(e),jo.set(e,t)),t}function Wo(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&&se(`Unknown binding modifier "${s}" in "${o}".`),s===t&&(null!==n&&se(`Binding modifier "${t}" may only be specified once.`),n=r)}return n}function Do(e){return e.propModifiers.some(e=>e.includes("="))}const Bo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),zo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Fo(e,t){return"state"===e&&"call"===t?Bo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function qo(e){if(!o.enableDirectionalInitialSync)return Do(e)&&se("init=/sync= modifiers require enableDirectionalInitialSync."),Bo;const t=null===(n=Wo(e,b))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:se(`Invalid init modifier value "${n}".`);var n;const s=function(e){return null===e||"call"===e?"call":"connect"===e?"connect":se(`Invalid sync modifier value "${e}".`)}(Wo(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&se("Event bindings only allow init=none."),"call"===s?zo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===N)return Fo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&se(`Binding type "${e.bindingType}" does not support init=${t}.`),Fo(t??"state",s);const r=Xe(e.node);if(null===r)return Fo(t??"state",s);const i=r.knownProperties.has(e.propName),a=r.declaredInputs.has(e.propName);i||a||se(`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)||se(`init=${l} is incompatible with wcBindable member "${e.propName}".`),"connect"!==s||i||se(`sync=connect requires observable property "${e.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}function Vo(e,t){return"auto"!==t?t:function(e){const t=$a(e.replaceNode.getRootNode());null===t&&se("No state tree found on this root for binding.");const n=$n(e);let o=!1;return t.createState("readonly",e=>{o=e[jt](n)}),o}(e)?"state":"element"}let Ho=0,Uo=0;const Go=["active","disposed","failed"],Ko=new WeakMap,Jo=new WeakMap,Xo=new WeakMap,Yo=new WeakMap,Qo=new WeakMap;function Zo(e,t){const n=Qo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Qo.set(e,new Set([n,t]))):Qo.set(e,t)}function es(e){return Qo.has(e)}function ts(e,t){const n=Qo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function ns(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))ns(n,t)}function os(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class ss{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||!ko(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)Ao(e)||ns(e,e=>{ts(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Co(e)&&!Oo()||ns(e,e=>{ts(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&la(o)}}const rs=new WeakMap;function is(e){let t=rs.get(e);return void 0===t&&(t=new ss(e),rs.set(e,t)),t}function as(e){const t=e.inFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|"),n=e.outFilters.map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.bindingType,e.propName,e.propModifiers.join(","),e.statePathName,t,n,e.uuid??""].join("\0")}function ls(e,t,n){const o=$a(ln(e,n));null===o&&se("No state tree found on this root for binding.");const s=Gt(o,e.statePathInfo);return function(e,t,n){let o=pn.get(e);void 0===o&&(o=new WeakMap,pn.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!==$t&&$t({type:"state:binding-added",absoluteAddress:Ht(e,t),binding:n})}(s,t,e),s}function cs(e,t){const n=cn(e,t);return fn(n,e),n}function ds(e,t,n,o){null!==t?hn(t,e):function(e,t,n){const o=pn.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!==$t&&$t({type:"state:binding-removed",absoluteAddress:Ht(e,t),binding:n}))}(n,o,e),xn(e),dn(e)}function us(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class fs{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;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=Jo.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(os(t)&&is(t),null===this.rowPlan)for(const n of e){const e=Jo.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(!o.enableDirectionalInitialSync)return Do(e)&&qo(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=Jo.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)return{id:64*t.id+n,info:e,generation:t.generation,phase:Go[t.phases[n]],teardowns:null};const o=Jo.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=Jo.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(us(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Ke(e);null===s&&se(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),Zo(e,this);const r={node:e,active:!0,cancel:null};let i=this.deferredByNode.get(e);void 0===i&&(i=new Set,this.deferredByNode.set(e,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Lo(s).wait(t,()=>{if(a())try{Je(s,e),n()}catch(e){o(e)}},e=>{a()&&o(e)}),()=>{a()&&r.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=Jo.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.active=!1,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&&(hn(n,e.bindings[t]),e.addresses[t]=null),e.phases[t]=1}}dispose(){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.active=!1,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(){for(const e of this.rows)this.destroyRowRecord(e);this.rows.clear();for(const e of this.records)null!==e.address&&(hn(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?cn(n):null;if(ds(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=cn(n);e!==o&&It(o)&&Pt(e,St(o)),e!==o&&Mt(o)&&Tt(e,_t(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return os(t)?t:null}(e);null!==t&&is(t)}handleMutations(e,t,n){for(const n of t)ns(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)ns(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&la(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);const n=this.deferredByNode.get(e);if(void 0!==n)for(const e of Array.from(n))e.active=!1,e.cancel?.(),n.delete(e),this.deferred.delete(e)}handleAddedNode(e,t){const n=this.knownBindingsByNode.get(e);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const e of o){const n=Jo.get(e);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(e);if(void 0!==o)try{this.start(e,o),o.applyOnReconnect&&this.shouldApplyState(e)&&t.push(e)}catch{}}}knownMapFor(e){const t=this.knownBindingsByNode.get(e);if(t instanceof Map)return t;const n=new Map;if(void 0!==t){let e=Yo.get(t);void 0===e&&(e=as(t),Yo.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;Zo(n,this);const o=this.knownMapFor(n);let s=Yo.get(e);void 0===s&&(s=as(e),Yo.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:++Ho,session:this,generation:++Uo,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(Zo(r,this),this.addKnownRowBinding(r,o,e),Ko.set(o,s),n[e].isEvent){try{qn(o)}catch(t){throw s.phases[e]=2,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=++Uo,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{qn(t[e])}catch(t){throw o.phases[e]=2,this.runRowSlotTeardowns(o,e),t}o.flags[e]|=2}this.registerRowSlot(o,e,n)}}rowOf(e){const t=Ko.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=rn(o);null!==s?(e.patternPathInfos[t]=ls(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=cs(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(ds(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{Vn(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:++Ho,info:e,generation:++Uo,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};Jo.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;qn(t)?e.eventAttached=!0:t.propSegments[0]!==I?(Jn(t)&&us(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=Kn(e),n=Gn(e,t),o=Hn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Un.countOf(n)&&(Un.remove(n,e)&&Hn.delete(n),!0))}return!1}(t)),kn(t)&&us(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=Nn(e),n=An(e,t),o=Pn.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==In.countOf(n)&&(In.remove(n,e)&&Pn.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Qn(t.node,t.propName)&&-1===t.propModifiers.indexOf(y)){const n=function(e,t,n){let o=mo.get(e);void 0===o&&(o=new Map,mo.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&&mo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});us(e,n)}!function(e){const t=Ue(e.node);if(null!==t){const n=Ke(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&se(`CustomElementRegistry is unavailable for <${t}>.`))}if(Qn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=vo(e),n=$o(e),o=xo(e),s=bo(e,t,null!==n,o);let r=po.get(s);void 0===r&&(r=So(e.propName,e.statePathName,e.inFilters,n,o),po.set(s,r)),e.node.addEventListener(t,r),go.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{jn(t)&&us(e,()=>function(e){if(e.propSegments[0]!==I)return!1;const t=Rn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),Rn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Ue(e.info.node);if(null===n)return void t();const o=Ke(e.info.node);if(null===o&&se(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void t();e.phase="waiting-definition",e.pendingDefinitions+=1;const s=e.generation,r=Lo(o).wait(n,()=>{if(this.isAlive(e,s))try{Je(o,e.info.node),t(),e.pendingDefinitions-=1,0===e.pendingDefinitions&&(e.phase="active",this.settleInitialRecord(e))}catch{e.phase="failed",this.runTeardowns(e),this.records.delete(e)}},()=>{this.isAlive(e,s)&&(e.phase="failed",this.runTeardowns(e),this.records.delete(e))});us(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=qo(e.info),n=Vo(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 Eo++;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,Mo()),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=$a(e.node.getRootNode());null===o&&se("No state tree found on this root for initial binding sync.");const s=bt(e.node);o.createState("writable",t=>{t[Ot](s,()=>{t[e.statePathName]=n})})}(e.info,r))}settleConnectedSnapshot(e){if(o.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=rn(n);if(null!==o?(e.patternPathInfo=ls(n,o,t),e.patternListIndex=o):e.address=cs(n,t),!e.options.registerPathInfo)return;const s=$a(n.replaceNode.getRootNode());null===s&&se("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&&Jo.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,Mo());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{ds(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=Ue(e.node);if(null!==t){const n=Ke(e.node),o=n?.get(t);if(void 0===o)return}if(Qn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=vo(e),n=bo(e,t,null!==$o(e),xo(e)),o=po.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),go.remove(n,e)&&po.delete(n)}}(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{Vn(t)}catch{}}}}function hs(e){let t=Xo.get(e);return void 0===t&&(t=new fs(e),Xo.set(e,t)),t}function ps(e){return Jo.get(e)?.session??Ko.get(e)?.session??null}let gs=null;function ms(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ys=Object.freeze([]);const ws=new WeakMap;const bs=new WeakMap;function vs(e){return bs.get(e)??[]}function $s(e,t){bs.set(e,t)}const xs=new WeakMap;function Ss(e){return xs.get(e)??[]}function Ps(e,t){xs.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});let Is=0;function As(){return`u${(Is++).toString(36)}`}let Ns=0,ks=0;const _s=Symbol("wcs.listIndex.noValue");class Ts{uuid=As();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(e,t,n){this.parentListIndex=e,this.position=e?e.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=_s,this._index=t,this._version=Ns,this._chainGeneration=ks}get index(){return this._index}set index(e){this._index=e,this._version=++Ns,this.indexes[this.position]=e}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}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=Ns),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===ks||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=ks),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++Ns,ks++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Cs(e,t,n=e){return new Ts(e,t,n)}function Es(e,t){e.reparent(t)}function Ms(e){return e.homeParentListIndex}function Os(e,t){e.value=t}function Rs(e,t){const n=e.value;return n!==_s&&n===t.value}const js=new WeakMap,Ls=new WeakSet;function Ws(e){return Ls.has(e)}function Ds(e,t){const n=Ms(e),o=e.parentListIndex;return null===n||n===o||Ls.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Ls.has(e)&&!Ls.has(n)&&n.position===e.position&&Rs(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Ls.has(e)&&!Ls.has(t)}(o,t)?t:null:n}function Bs(e){const t=js.get(e);return void 0===t?null:t}function zs(e,t){const n=js.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Ds(o,t);if(null!==e)for(const t of n)Es(t,e)}return n}function Fs(e,t){null!==t?js.set(e,t):js.delete(e)}const qs=new WeakMap;function Vs(e,t){null===t?qs.delete(e):qs.set(e,t)}function Hs(e){const t=qs.get(e);t&&(t.dirty=!0)}const Us=Symbol.for("wcstack.transition-runner");function Gs(e){const t=globalThis[Us];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 Ks(e,t,n){const o=Gs(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Js=[],Xs=[];function Ys(e){Xs.includes(e)||Xs.push(e)}function Qs(e,t=0){const n=Js.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Js.push(o):Js.splice(n,0,o)}function Zs(e){queueMicrotask(()=>{throw e})}class er{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Xs.length;t++)Xs[t](e);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(){Ct(),queueMicrotask(()=>{const e=this._queueUpdateRecords,t=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],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=[]){const o=new Map,s=new Set;for(let t=0;t<e.length;t++){const n=e[t],r=o.get(n.absoluteAddress);null!==$t&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&$t({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let e=0;e<n.length;e++){const t=n[e];o.has(t)||o.set(t,null)}const r=[],i=new Map;o.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!==$t&&$t({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=gn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(r.push(t),null!==e&&i.set(t,e));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==e&&i.set(n,e))});try{const e=()=>{i.size>0?la(r,i):la(r)};if(t()||0===r.length)e();else{const t=Ks("state",e);void 0!==t&&t.catch(Zs)}}finally{Et(),function(e){for(const t of Js.slice())t.listener(e)}(s)}}}const tr=new er;function nr(){return tr}const or=new WeakMap,sr=new WeakMap,rr=new WeakMap,ir=new WeakMap;let ar=!1;const lr=new WeakMap,cr=new WeakMap,dr=new WeakMap,ur=[];function fr(e,t){const n=hr(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ae(t).cumulativePaths;if(o.length<2)return;let s=dr.get(e);void 0===s&&dr.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 hr(e){let t=or.get(e);return void 0===t&&or.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function pr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function gr(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function mr(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=sr.get(o);if(void 0===r&&sr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(gr(s,e,o),r.set(t,n),pr(s,n,o)),!1}return r.set(t,n),pr(s,n,o),!0}function yr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function wr(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&yr(rr,o.listIndex,r),null!==r.levelListIndex&&yr(ir,r.levelListIndex,r))}function br(e,t,n,o,s){ar=!0;const r=hr(e);fr(e,t);wr(r,t,s,o,mr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function vr(e,t){hr(e).tracked.add(t)}function $r(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(Jt(e.stateElement,bn(t,o)))}function xr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Sr(e,t,n,o,s){const r=or.get(e),i=r?.byPath.get(t),a=lr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return ur;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&&xr(i.get(o),d),f&&xr(i.get(c),d),u&&xr(i.get(s),d)),void 0!==a)for(const e of a)n&&$r(e,o,d),f&&$r(e,c,d),u&&$r(e,s,d);return d}function Pr(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Ir(e,t,n){const o=or.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())xr(e,n);const s=lr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)$r(e,t,n)}function Ar(e){const t=ir.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function Nr(e){if(!ar)return;const t=rr.get(e);if(void 0!==t){rr.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=sr.get(o),r=s.get(n);s.delete(n),gr(or.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Ar(e)}}}function kr(e,t,n){if(!ar)return;const o=ir.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=or.get(e),i=o.byPath.get(s);gr(i,t,r),pr(i,n,r),sr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Hs(r),nr().enqueueAbsoluteAddress(r,null))}}const _r=new WeakMap,Tr=Object.freeze([]),Cr=new Set;function Er(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Tr,s=Array.isArray(n)&&n.length>0?n:Tr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Tr,o=Array.isArray(t)&&t.length>0?t:Tr;let s=_r.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=zs(o,e)||[],a=i.length>0?Ms(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Cr,deleteIndexSet:new Set(i),addIndexSet:Cr};let t=zs(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Cs(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:Cr,deleteIndexSet:Cr,addIndexSet:new Set(t)}}if(function(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}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:Cr,deleteIndexSet:Cr,addIndexSet:Cr};if(null!==t)return function(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}}(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,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],d=n.get(l),u=d&&d.length>0?d.shift():void 0;if(void 0===u){const n=Cs(e,o,a);t.push(n),c.add(n)}else{const e=i[u];u!==o&&r.add(e),t.push(e)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(t)),addIndexSet:c}}finally{void 0!==l&&(!function(e,t,n){let o=_r.get(e);o||(o=new WeakMap,_r.set(e,o)),o.set(t,n)}(o,s,l),Fs(s,l.newIndexes))}}(e,t,n);!function(e,t){for(let n=0;n<e.length;n++){if(e[n].index!==n){const t=e[n].index;e[n].index=n,kr(e[n],t,n)}Os(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Tr),function(e){for(const t of e)Ls.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)Nr(e);return function(e){for(const t of e)Ls.delete(t)}(o.newIndexes),function(e,t){if(!ar||e===t)return;const n=cr.get(e);if(void 0===n)return;cr.delete(e);const o=cr.get(t);cr.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=hr(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&&!Ws(e))for(const t of o.getters){const n=Jt(o.stateElement,bn(t,e));Hs(n),nr().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function Mr(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 Or=new WeakSet;const Rr=new WeakMap;function jr(e){return Rr.get(e)??null}function Lr(e,t){Rr.set(e,t)}const Wr=new WeakMap;function Dr(e){return Wr.get(e)??[]}function Br(e,t){Wr.set(e,t)}function zr(e,t){const n=Dr(e);for(const e of n)vt(e,t)}const Fr=new WeakMap;const qr=new WeakMap;function Vr(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function Hr(e,t,n,o,s){const r=function(e,t,n){let o=qr.get(e);void 0===o&&qr.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;let a,l=!1;for(let e=0;e<t.length;e++){const c=t[e];if(!n.shouldApplyState(c))continue;const d=r[e];if(null===d||Vr(d.prefixes,i)){ia(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[Rt](o),l=!0);const u=d.tail;let f=a;for(let e=0;e<u.length;e++){if(null==f){f=void 0;break}f=f[u[e]]}ra(c,s,f)}}function Ur(e,t,n){zr(e,t);const o=vs(e),s=jr(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return Fr.get(e)??null}(e);if(null!==r)return void Hr(r,o,s,t,n)}for(const e of o){if(null===s){fn(cn(e),e)}(null===s||s.shouldApplyState(e))&&ia(e,n)}}function Gr(e){if(!e.mounted)return;const t=vs(e),n=jr(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{hn(cn(o),o)}}!function(e){const t=Dr(e);for(let e=0;e<t.length;e++)vt(t[e],null)}(e)}function Kr(){return Object.freeze(new Set)}const Jr=new WeakMap,Xr=Kr();function Yr(e,t){const n=Jr.get(e);n?n.add(t):Jr.set(e,new Set([t]))}function Qr(e){const t=Jr.get(e);return void 0!==t?t:Xr}function Zr(e,t){const n=Jr.get(e);n&&(n.delete(t),0===n.size&&Jr.delete(e))}function ei(e,t){if(0===e.length)return e;const n=[];for(let o=0;o<e.length;o++){const s=e[o];n.push({filterName:s.filterName,args:s.args,filterFn:we(s.filterName,s.args,t,s.literals??s.args)})}return n}function ti(e){return{...e,inFilters:ei(e.inFilters,"input"),outFilters:ei(e.outFilters,"output")}}const ni=new Set(["if","elseif","else","for"]);class oi{_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];To(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){To(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=jr(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow(vs(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Io(n),n.parentNode.removeChild(n))}const n=vs(this);for(let e=0;e<n.length;e++){const t=n[e];ni.has(t.bindingType)&&Qr(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=jr(this);null!==e&&(e.isRowSession?e.disposeBindings(vs(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=vs(this);for(let t=0;t<e.length;t++){const n=e[t];ni.has(n.bindingType)&&Qr(n.node).forEach(e=>{e.unmount()}),xn(n),dn(n)}}unmount(){{const e=jr(this);null!==e&&(e.isRowSession?e.disposeBindings(vs(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Io(e),e.parentNode.removeChild(e));const e=vs(this);for(let t=0;t<e.length;t++){const n=e[t];ni.has(n.bindingType)&&Qr(n.node).forEach(e=>{e.unmount()}),xn(n),dn(n)}this._mounted=!1}}function si(e){let t=e.topLevelStructural;return void 0===t&&(t=e.topLevelStructural=function(e){const t=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.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 ri(e){const t=document.createDocumentFragment(),n=new oi(t);return n._childNodeArray=e,n._firstNode=e.length>0?e[0]:null,n._lastNode=e.length>0?e[e.length-1]:null,n._mounted=!0,n}function ii(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=st(o,s[e].nodePath);null===t&&se(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),gt(t),Ve(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=da.get(n);void 0!==o&&o.currentRowPlan===e||(o=new fs,da.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new oi(o);return Lr(d,c),$s(d,a),function(e,t){Fr.set(e,t)}(d,n),Ps(d,l),Br(d,r),Yr(e.node,d),d}function ai(e){void 0!==e.uuid&&null!==e.uuid||se("BindingInfo.uuid is null.");const n=ka(e.uuid);n||se(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&si(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(e){const t=o.enableDirectionalInitialSync,n=[],s=e.nodeInfos;for(let t=0;t<s.length;t++){const o=s[t],r=st(e.fragment,o.nodePath);if(null===r)return null;for(const e of o.parseBindTextResults){const o=e.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=e.propSegments[0];if(s===N||s===I)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ue(r))return null;if("prop"===o&&Qn(r,e.propName))return null;const i=ti(e);let a;try{a=qo({...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 M,policy:a,authority:a.authority})}}return{directional:t,slots:n}}(n)),null!==r)return ii(e,n,r);const i=document.importNode(n.fragment,!0),a=function(e,t){const[n,o]=function(e,t){const n=[],o=[];for(const s of t){const t=st(e,s.nodePath);if(null===t&&se(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),ft.has(t))continue;const r=ht(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new fs,r=s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null);return{nodes:n,bindingInfos:r,bindingSession:s}}(i,n.nodeInfos);s&&function(e,t){e.appendChild(document.createComment(`wcs-row-end:${t}`))}(i,e.uuid);const l=new oi(i,s);Lr(l,a.bindingSession),$s(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in M&&c.push(e);return Ps(l,c),Br(l,a.nodes),Yr(e.node,l),l}const li=new WeakSet,ci=Symbol.for("wcstack.state.view-transition-naming");function di(){const e=Gs("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function ui(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||li.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[ci]??={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.`)):(li.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 fi=new WeakMap,hi=new WeakMap,pi=new WeakMap,gi=new WeakMap;function mi(e,t,n){!function(e,t,n){let o=hi.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,hi.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function yi(e,t){fi.set(e,t)}function wi(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 bi(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)}function vi(e,t,n){if(o=t,!Or.has(o))return null;var o;let s=null;for(let t=0;t<n.newIndexes.length;t++){const o=n.newIndexes[t],r=n.oldIndexes[t],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?e.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}const $i=new Set(["if","elseif","else","for"]);function xi(e,t){for(const n of vs(e))if(t.appliedBindingSet.delete(n),$i.has(n.bindingType))for(const e of Qr(n.node))xi(e,t)}function Si(e){for(const t of vs(e)){if(!$i.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Qr(t.node))Si(n),e&&n.mounted&&(Gr(n),n.unmount(),Zr(t.node,n))}}function Pi(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ii(e,n,s){const r=Boolean(s);let i;const a=Qr(e.node);i=0===a.size?ai(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Pi(e)}`),Gr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Pi(e)}`),l){const t=document.createComment(`@@wcs-${d}-start:${c}:${e.statePathName}`);e.node.parentNode.insertBefore(t,e.node.nextSibling),i.mountAfter(t);const n=document.createComment(`@@wcs-${d}-end:${c}:${e.statePathName}`),o=i.lastNode??t;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(e.node);Ur(i,bt(e.node),n);const t=di();null!==t&&ui(i,"branch",t)}}const Ai=new WeakMap;function Ni(e){return Ai.get(e)??[]}const ki=new Set;const _i=Symbol.for("wcstack.trustedTypes.policy");function Ti(){const e=globalThis[_i];return null===e||"object"!=typeof e?null:e}function Ci(e){globalThis[_i]=e}let Ei;let Mi=!1;function Oi(e,t){if(Mi)return;if(!function(){if(void 0!==Ei)return Ei;if(!("trustedTypes"in globalThis))return Ei=!1,Ei;try{document.createElement("div").innerHTML="<i></i>",Ei=!1}catch{Ei=!0}return Ei}())return;Mi=!0;const n="function"==typeof Ti()?.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 Ri={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")}},ji=new Set(["textContent","innerText","innerHTML"]);function Li(e,n,s){if(void 0===s&&1===e.propSegments.length&&ji.has(e.propSegments[0])&&(s=""),void 0===s)return void(o.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!==s){null!==gs&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Ue(r)&&gs.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=Ti(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Oi(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:e})}if(e){const e=function(e,t){const n=Ue(e);if(null===n)return null;const o=Ke(e)?.get(n);if(void 0===o)return null;const s=Xe(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,s)}catch(t){o.debug&&console.warn(`Failed to mirror attribute '${e}' on element.`,{element:r,newValue:s,error:t})}}};if(o.enablePropagationContext&&Qn(r,c)){const t=oo(r,c,e.statePathName),o=so(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??co()??io(t);if(a.visitedEdges.has(o))null!==$t&&$t({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=ao(a,o);uo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:to++,writtenValue:n};fo.push({receipt:i,node:e});try{return r()}finally{fo.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=Ri[c];e?e(r,s):(!function(e,t,n){let o=Ai.get(e);o||(o=[],Ai.set(e,o));const s=o.find(e=>e.propName===t);s?s.value=n:o.push({propName:t,value:n})}(r,c,s),a=r,ki.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!==s){if(Object.isFrozen(d))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:f,newValue:s}));null!==gs&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ue(r)&&(u in d?gs.rememberOverwrittenValue(r,c,u,d[u]):gs.recordInjectedKey(r,c,u));try{d[u]=s}catch(e){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:f,newValue:s,error:e})}}}const Wi=new WeakSet;function Di(e,t,n){}function Bi(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)}}function zi(e,t,n){const o=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),s=t.length>0?t+c:"";for(const e of n){if(s.length>0&&!e.startsWith(s))continue;const t=e.slice(s.length);t.length>0&&-1===t.indexOf(c)&&o.push(t)}return o}const Fi={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},qi={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Vi(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}.${ue}`}function Hi(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 Ui(e,t){return`$setAll("${e}") ${t}`}function Gi(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.${ue}`}function Ki(e,t){const n=$n(t);if(n.pathInfo.path in M){const e=bt(t.node);return null===e&&se(`ListIndex not found for binding: ${t.statePathName}`),function(e,t){null===e.listIndex&&se("ListIndex not found for loopContext:");const n=M[t];void 0===n&&se(`Invalid index name: ${t}`);const o=nn(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&se(Gi(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[Rt](n)}const Ji=new WeakSet;function Xi(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Yi=Object.freeze({[k]:function(e,t,n){const o=e.node,s=e.propSegments[1];"boolean"!=typeof n&&se("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[_]:function(e,t,n){const o=e.node,s=e.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[T]:function(e,t,n){const o=e.propSegments[1],s=e.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[N]:function(e,t,n){Wn(n)||se("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ws.get(e);if(s&&s.token===o)return;const r=e.node,i=e.propSegments[1];"string"==typeof i&&0!==i.length||se('command binding requires a method name (e.g., "command.fetch").');const a=function(e){const t=Ue(e);if(null===t)return null;const n=Ke(e)?.get(t);return void 0===n&&se(`Custom element <${t}> is not defined for command binding.`),Xe(e)}(r);null===a&&se(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||se(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${de(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ws.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 ws.delete(e);const o=n[i];return"function"!=typeof o&&se(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,t)}),ws.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Qi={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Wi.has(e.replaceNode)){Wi.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,n,o){const s=e.statePathInfo,r=rn(e),i=cn(e),a=St(i),l=a.length>0&&!hi.has(e.node)?[]:a,c=Er(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=hi.get(e.node);const f=void 0!==u?vi(u,l,c):null,h=Array.isArray(l)&&l.length===c.deleteIndexSet.size&&c.deleteIndexSet.size>0;if(h&&null===f&&null!==e.node.parentNode){let t=gi.get(e.node);if(void 0===t){const n=fi.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(wi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(wi(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),gi.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){No.set(e,(No.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return pi.get(e.node)||[]}(e).length:Number.POSITIVE_INFINITY;if(void 0!==u){const t=u;c.deleteIndexSet.forEach(n=>{const o=t.get(n);void 0!==o&&(null!==f&&f.reused.has(o)?(Gr(o),Si(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Zr(e.node,o):(Gr(o),o.unmount(),function(e,t){let n=pi.get(e.node);void 0===n&&(n=[],pi.set(e.node,n)),n.length<1e3?n.push(t):Zr(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(hi.delete(e.node),u=void 0)}let g=e.node;const m=ae(s.path+"."+d),y=n.stateElement.loopContextStack,w=Mr(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&g.isConnected&&null===f&&(b=document.createDocumentFragment(),Qt(b,n.rootNode));const v=t(),$=di(),x=e.uuid??"",S=pi.get(e.node);for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const r=bn(m,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=ai(e):xi(o,n),null!==b)v&&b.appendChild(document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`)),o.appendTo(b),v&&b.appendChild(document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`));else{if(g.nextSibling!==o.firstNode){if(v){const e=document.createComment(`@@wcs-for-start:${x}:${s.path}:${t.index}`);g.parentNode.insertBefore(e,g.nextSibling),g=e}o.mountAfter(g)}if(v){const e=document.createComment(`@@wcs-for-end:${x}:${s.path}:${t.index}`),n=o.lastNode??g;n.parentNode.insertBefore(e,n.nextSibling)}}Ur(o,r,n),null!==$&&ui(o,"row",$)}),void 0===o&&se(`Content not found for ListIndex: ${t.index} at path "${s.path}"`),null!==f&&f.reused.has(o)){const e=n.stateElement.addressHooks;if(e){const t=e.rowReused;for(let e=0;e<t.length;e++)t[e](n.stateElement,o)}}}else{if(o=void 0!==u?u.get(t)??null:null,c.changeIndexSet.has(t)){const e=Ss(o);for(const t of e)ia(t,n)}null===o&&se(`Content not found for ListIndex: ${t.index} at path "${s.path}"`);const e=!o.mounted;if(null!==w&&w.has(t)&&bi(g,o.firstNode)||g.nextSibling===o.firstNode||o.mountAfter(g),e){const e=o,s=bn(m,t);y.createLoopContext(s,t=>{Ur(e,t,n)})}}g=o.lastNode||g,void 0===u&&(u=new WeakMap,hi.set(e.node,u)),u.set(t,o)}fi.set(e.node,g),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Qt(b,null))},if:Ii,else:Ii,elseif:Ii,radio:function(e,t,n){const o=e.node,s=ms(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=ms(o.value,e.inFilters),r=Array.isArray(n)?n:ys;o.checked=r.includes(s)}},Zi=new WeakMap,ea=new WeakMap,ta=new WeakMap;function na(){}function oa(e){const t=gs;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Di;if(t.isDeclared(n,o))return na}return Li}function sa(e,t){ra(e,t,Ki(t.state,e))}function ra(e,t,n){const o=ms(n,e.outFilters);if(!0===ea.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=Zi.get(e);if(void 0===s){if(Zi.has(e))return s=oa(e),s===Di&&Zi.set(e,s),void s(e,t,o);if(s=Qi[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Yi[t],Zi.set(e,s),void 0===s){Ue(e.replaceNode)?(s=oa(e),s===Di&&Zi.set(e,s)):(s=Li,Zi.set(e,s))}}if(s===Li){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 ea.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function ia(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=cn(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=ps(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==ta.get(e)){const t=Ue(e.replaceNode);if(t&&void 0===Ke(e.replaceNode)?.get(t))return void function(e,t){if(Ji.has(e))return;Ji.add(e);const n=()=>{Ji.delete(e);const t=ps(e);(null===t||t.shouldApplyState(e))&&la([e])},o=n=>{Ji.delete(e),Xi(t,n)},s=ps(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Ji.delete(e),r()})||(Ji.delete(e),r()))}const r=Ke(e.replaceNode);if(null===r)return Ji.delete(e),void Xi(t,new Error("CustomElementRegistry is unavailable."));Lo(r).wait(t,()=>{e.replaceNode.isConnected?n():Ji.delete(e)},o)}(e,t);ta.set(e,!0)}if(!0===t.sameRootVerified)return void sa(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Zt(o),null===o&&se("Root node for fragment not found for binding.")),o!==t.rootNode){const n=$a(o);null===n&&se("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};sa(e,r)})}else sa(e,t)}function aa(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!==$t&&$t({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function la(e,t,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<e.length;){let n=e[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let d=n.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Zt(d),null===d&&se("Root node for fragment not found for binding."));const u=$a(d);null===u&&se("No state tree found on this root for binding."),u.createState("readonly",o=>{const f={rootNode:d,stateElement:u,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:t};for(;;){try{ia(n,f)}catch(e){aa(n,e,u,c)}s++;const t=e[s];if(!t)break;if(t.replaceNode.getRootNode()!==f.rootNode)break;n=t}})}for(const{binding:e,value:n,stateElement:o}of l)try{Li(e,{propagationContextByBinding:t},n)}catch(t){aa(e,t,o??null,c)}for(const[e,t]of i.entries())Pt(e,t),Tt(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[Bt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[zt](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 ca(e,t,n){const[o,s,r]=pt(e,n),i=hs(e);for(const e of o)vt(e,t);la(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=mt(o);0!==e.length&&(vt(o.node,t),la(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const da=new WeakMap;async function ua(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Ke(e);null===s&&se(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(lt(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function fa(e){if(e===document)await ua(document),ne(document),Ha(document,document),ca(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await qe(t.host),await ua(t),ne(t),Ha(t,t),ca(t,null)}}const ha={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function pa(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${ha[e]??e}" before the state is defined.`}let ga=null;function ma(e){return null===ga&&se(pa("ssr",e)),ga}const ya=new WeakMap,wa=new WeakMap,ba=new Set,va=[];function $a(e){return ya.get(e)??null}function xa(e){return wa.get(e)??Promise.resolve()}const Sa=new WeakSet;function Pa(e){Sa.add(e)}function Ia(e,n){const s=ya.get(e);if(null===n){if(void 0===s)return;ya.delete(e),ba.delete(s),null!==$t&&$t({type:"state:element-unregistered",rootNode:e,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){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 ma('the "enable-ssr" attribute').hydrate(e)||await fa(e)}else await fa(e);Pa(e),Ya(),t()}catch(e){n(e)}})});wa.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await fa(e),Pa(e),Ya(),t()}catch(e){n(e)}})});wa.set(e,t)}}void 0!==s&&se('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="...">.'),ya.set(e,n),ba.add(n);for(let t=0;t<va.length;t++)va[t](e,n);null!==$t&&$t({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Aa=new Map;function Na(e,t,n){if(null===n)Aa.delete(e);else{Aa.set(e,n);const o=$a(t);null===o&&se("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 ka(e){return Aa.get(e)||null}function _a(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Oe(t.getAttribute(o.bindAttributeName)||"");return t.localName===o.tagNames.state&&t.hasAttribute("mount")?n.filter(e=>e.propSegments[0]!==A):n}if(e.nodeType===Node.COMMENT_NODE){const t=We(e);null===t&&se("Comment node binding text not found.");const n=ka(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=De(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Ta;function Ca(){return Ta??={filterName:"not",args:[]}}const Ea=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Ma(e,t){const n=t+c+d,o=e.indexOf("|");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 Oa(e,t){const n=Ea.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Ma(s,t)+r}function Ra(e,t){const n=e.split(";");let o=!1;const s=n.map(e=>{const n=e.trim();if(0===n.length)return e;const s=n.indexOf(":");if(-1===s)return e;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=Ma(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function ja(e,t){return Ra(e,t)}function La(e,t){const n=o.bindAttributeName,s=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const e=s.currentNode;if(e.nodeType===Node.COMMENT_NODE){const n=e;n.data=Oa(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=Ra(r,t);e!==r&&o.setAttribute(n,e)}}}function Wa(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}function Da(e){const t=[],n=ut(e);for(const e of n){const n=_a(e);let o=e;if(e.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==e.parentNode){const t=document.createTextNode("");e.parentNode.replaceChild(t,e),o=t}t.push({nodePath:Wa(o),parseBindTextResults:n})}return t}function Ba(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 za=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Fa=Ca();function qa(e,t){const n=t.outFilters;return{...t,outFilters:[...n,Fa],bindingType:e}}function Va(e,t,n,o,s,r=!0){Ba(t),"string"==typeof o&&La(t,o),Ha(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Da(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 Ha(e,t,n,s){const r=o.commentElsePrefix,i=ct(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(o.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(o.bindAttributeName)||"";"string"==typeof n&&(i=ja(i,n));let a=Oe(i)[0];const d=za.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=As();let p=null;const g="for"===u?a.statePathName:n;if("else"===u){null===l&&se("'else' binding found without preceding 'if' or 'elseif' binding."),a=qa("else",l.parseBindTextResult),p=Va(e,f,a,g,s,!1),Na(h,e,p);const n=c.at(-1),o=document.createComment(`@@${d}:${h}`);void 0!==n?(t.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Wa(o),parseBindTextResults:_a(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&se("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Va(e,f,a,g,s),Na(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=As(),i={fragment:document.createDocumentFragment(),parseBindTextResult:qa("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Wa(n),parseBindTextResults:_a(n)}),Na(o,e,i);const u=c.at(-1);c.push(i);const m=document.createComment(`@@${r}:${o}`);void 0!==u?(t.remove(),u.fragment.appendChild(m),u.nodeInfos.push({nodePath:Wa(m),parseBindTextResults:_a(m)})):t.replaceWith(m)}else{p=Va(e,f,a,g,s),Na(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 Ua=()=>`[${o.bindAttributeName}]`;function Ga(e){if(es(e))return!0;if(!Ka(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(Ua());return null!==t&&es(t)}function Ka(e){return 1===e.nodeType}function Ja(e){if(Ga(e))return;ne(e),Ha(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);ca(t&&s?n:e,null)}const Xa=[];function Ya(){const e=Xa.splice(0,Xa.length);for(const t of e)Ja(t);l()}const Qa={protocol:"wcs-binder",version:1,bind:function(e){var t;Ka(e)&&!Ga(e)&&(t=e.getRootNode(),Sa.has(t)?Ja(e):Xa.push(e))}};const Za="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let el=0;async function tl(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++el}\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 new Error(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, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${Za}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${Za}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function nl(e){try{const t=await import(function(e){return new URL(e,document.baseURI).href}(e));return t.default||{}}catch(e){se(`Failed to load script file: ${e}`)}}class ol{_loopContextStack=Array(f).fill(void 0);_length=0;createLoopContext(e,t){null===e.listIndex&&se("Cannot create loop context for a state address that does not have a list index.");const n=e;this._length>=f&&se("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&&se("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&&se("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&&se(`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 sl=new WeakMap;function rl(e,t){let n=sl.get(e);void 0===n&&(n=new Map,sl.set(e,n));let o=n.get(t);return void 0===o&&(o=new Ln(t,e),n.set(t,o)),o}const il=new WeakMap;function al(e){const t=il.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 rl(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:rl(e,n)}},set(){se("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){se("$command namespace is read-only; deleting from it is not allowed.")}});return il.set(e,n),n}const ll=Symbol("wcs.notHandled"),cl=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],dl=new Map;function ul(e,t){dl.set(e,t)}const fl=new Map;let hl=[],pl=[];function gl(e,t){fl.set(e,t),hl=Array.from(fl.values()).sort((e,t)=>e.order-t.order),pl=hl.slice().reverse()}function ml(e,t){for(let n=0;n<hl.length;n++)hl[n].activate?.(e,t)}function yl(e){"readonly"===e.mutability&&se("This state is readonly.")}const wl=new Map;class bl{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=ae(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 vl(e){let t;return wl.get(e)??(wl.set(e,t=new bl(e)),t)}function $l(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:nn(n.listIndex,o,n.pathInfo.wildcardCount)}function xl(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=tn(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?nn(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?nn(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function Sl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function Pl(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!==ll)return a}}return ll}function Il(e,t,n,o,s){if(t.pathInfo.segments[0]===F)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}(al(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=Pl(s,t,null,n,o);if(r!==ll)return r;se(function(e,t,n){return`[${Fi.binding}] Path "${e}" does not exist on the state tree.${de(e,zi(t,"",n))}${ue}`}(t.pathInfo.path,e,s.getterPaths))}const r=Nl(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=Pl(s,t,Object(r),n,o);if(e!==ll)return e}if(i===d){const e=t.listIndex?.index??se(Gi(`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 Al(e,t,n,o,s){const r=Jt(s,t),i=function(e){return qs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Il(e,t,n,o,s);return Vs(r,{value:l,dirty:!1,generation:a}),l}function Nl(e,t,n,o){xl(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!==ll)return i}}return Sl(s,t)?Al(e,t,n,o,s):Il(e,t,n,o,s)}function kl(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=bn(f,r),p=Jt(n.stateElement,h),g=_t(p),m=Nl(e,h,t,n),y=Er(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]??se(`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())Tt(e,Array.isArray(t)?t:[]);return l}function _l(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=zs(Nl(e,bn(a,r),t,n),r);null==l&&se(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??se(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Tl(e,t,n,o){"object"==typeof e&&null!==e||se(`${X} 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&&se(`${X} list "${t}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Cl(e,t,n,o,s){const r="function"==typeof t?t(e):e[t];return null==r&&se(`${X} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof t?"key function":`field "${t}"`} returned ${String(r)}).`),r}function El(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];Tl(a,n,o,i);const l=Cl(a,t,n,o,i);r.has(l)&&se(`${X} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Ml(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 Ol(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=Nl(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 Rl=new WeakMap;function jl(e,t){null===t?Rl.delete(e):Rl.set(e,t)}function Ll(e,t,n){const s=bn(ae(e.wildcardParentPaths[t]),n),r=Jt(e.stateElement,s),i=_t(r),a=e.stateProxy[Rt](s),l=Er(s.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 o.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)Ll(e,t+1,n)}const Wl=[];function Dl(e,t,n,o,s){return"full"===e.listExpansion||e.stateElement.crossRowListPaths?.has(t)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?e.keyedMergePath===t?{fullRows:Wl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Wl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Bl=[];function zl(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Bl;let s=null;const r=t+c;for(const e of o){if(e!==t&&!e.startsWith(r))continue;const o=ae(e);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??Bl}function Fl(e,t,n){const o=t.pathInfo.path,s=e.staticMap.get(o);if(s)for(const r of s){const s=ae(r);if(e.listPathSet.has(o)&&s.lastSegment===d){const i=e.stateProxy[Rt](t),a=Jt(e.stateElement,t),l=_t(a),c=Er(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Dl(e,o,0,0,c);for(const t of d.fullRows){const o=bn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=zl(e,r,s);if(null===t)for(const t of d.movedRows){const o=bn(s,t);e.result.add(o),n.push(o)}else if(t.length>0)for(const o of d.movedRows)for(const s of t){const t=bn(s,o);e.result.add(t),n.push(t)}}}else{const o=bn(s,t.listIndex);e.result.add(o),n.push(o)}}const r=e.dynamicMap.get(o);if(r)for(const o of r){const s=ae(o),r=[];if(s.wildcardCount>0){const n=tn(t.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===t.listIndex&&se(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`),o=nn(t.listIndex,n-1,t.pathInfo.wildcardCount)):o=null;const i={stateElement:e.stateElement,observedListValueByAbsAddress:e.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:e.stateProxy,searchType:e.searchType};Ll(i,n,o),r.push(...i.targetListIndexes)}else{null===t.listIndex&&se(`Cannot expand dynamic dependency with wildcard for non-list address: ${t.pathInfo.path}`);const e=nn(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=bn(s,t);e.result.add(o),n.push(o)}}}function ql(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&&se(`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};!function(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),n(a),i.length=0,Fl(e,a,i);for(let e=0;e<i.length;e++)r(i[e],t+1)}}}}(u,t,a);for(const[e,t]of u.observedListValueByAbsAddress)Tt(e,t);return Array.from(u.result)}function Vl(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 Hl(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 Ul(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 Gl(e,t,n,s,r,i){const a=function(e,t){return!0===or.get(e)?.byPath.has(t)||!0===lr.get(e)?.has(t)}(e,t),l=function(e,t){return!0===dr.get(e)?.has(t)}(e,t);if(!a&&!l)return;const c=nr(),u=o.enablePropagationContext?co()??null:null,f=e=>{Hs(e),c.enqueueAbsoluteAddress(e,u)};a&&Sr(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=ae(t).segments.length,r=[];for(const i of dr.get(e).get(t)){const t=ae(i).segments.slice(s);if(t.includes(d))Ir(e,i,r);else for(const s of Sr(e,i,!0,Pr(n,t),Pr(o,t)))r.push(s)}return r}(e,t,n?s:i(),r).forEach(f)}function Kl(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?co()??io(-1):null,c=nr();c.enqueueAbsoluteAddress(t,l),i&&Hs(t),ql(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Jt(s.stateElement,t);Hs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Jl(e,t,n,o,s){s&&(e.getterPaths.has(t)?Hs(n):Vs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function Xl(e,t,n,o,s,r,i,a){try{if(!(t.pathInfo.path in e)){const n=t.parentAddress;if(null===n)return Reflect.set(e,t.pathInfo.path,o);const i=Nl(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??se(Gi(`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{Kl(t,n,s,r,i,a)}}function Yl(e,t,n,o,s,r,i,a){const l=t.parentAddress??se(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=Nl(e,l,s,r)??[];let f=(h=u,Rl.get(h)??null);var h;if(null===f){const e=Bs(u)??[];f={value:[...u],listIndexes:[...e]},jl(u,f)}try{return Xl(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=Nl(e,l,s,r)??[],a=Array.isArray(i)?Bs(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:Cs(l.listIndex,-1);a[h]=p;if(new Set(i).size===f.value.length){for(let e=0;e<a.length;e++)a[e].index=e;jl(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=nr(),l=Jt(i,e);St(l)===n&&(Fs(t.value,t.listIndexes),Pt(l,t.value),function(e){Or.add(e)}(t.value));a.enqueueRenderOnlyAddress(l);const u=new Map;t.listIndexes.forEach((e,t)=>u.set(e,t));const f=ae(e.pathInfo.path+c+d);for(let e=0;e<o.length;e++){const n=o[e],l=u.get(n);if(l===e)continue;const c=bn(f,n),d=Jt(i,c);if(void 0===l){const n=Xt(i,f,t.listIndexes[e]??null);Ul(i,d,n),Kl(c,d,s,r,null,Sl(i,c),"full");continue}ql(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Jt(i,e);Hs(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(l,f,i,a,s,r)}}}function Ql(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=Nl(e,t,o,s),a=function(e,t,n,o){const s=El(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=El(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===Bs(o)&&Er(a,null,o);const l=Er(a,o,n.list),u=Zl(e,t,n.list,s,r,i),f=ae(i+c+d);for(const t of n.matched){const n=Ml(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?Ql(e,bn(ae(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 Zl(e,t,n,o,s,null)}function Zl(e,t,n,s,r,i){const a=r.stateElement,l=t.pathInfo.path,c=a.addressHooks;if(c){const e=c.write;for(let o=0;o<e.length;o++){const i=e[o](a,t,n,s,r);if(i!==ll)return i}}const u=!!ho&&(ho=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=Nl(e,t.parentAddress,s,r);if("object"==typeof f&&null!==f){const e=t.pathInfo.lastSegment,h=e===d?t.listIndex?.index:e;let p,g=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const e=void 0!==h&&h in f,t=void 0!==h?f[h]:void 0;if(e&&Object.is(t,n))return!0;p=t,g=!0}Gl(a,l,g,p,n,()=>f[h]);const m=Sl(a,t),y=Jt(a,t);null!==$t&&$t({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:g}),Vl(a,l,y,p,g);let w=!1;try{if(void 0===h&&se(Gi(`path "${l}"`,t.pathInfo.wildcardCount,t.listIndex?.length??0)),c&&0!==c.writeMissing.length&&e!==d&&!(h in f)){const e=c.writeMissing;for(let o=0;o<e.length;o++){w=!0;const i=e[o](a,t,f,h,n,s,r);if(i!==ll)return i;w=!1}}return Reflect.set(f,h,n)}finally{Kl(t,y,s,r,i,m),w?Hs(y):Jl(a,l,y,n,m),Hl(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Nl(e,t,s,r);if(Ol(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Gl(a,l,h,f,n,()=>Nl(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),g=Sl(a,t),m=Jt(a,t);null!==$t&&$t({type:"state:write",absoluteAddress:m,value:n,oldValue:f,hasOldValue:h}),Vl(a,l,m,f,h);try{return p?Yl(e,t,m,n,s,r,i,g):Xl(e,t,m,n,s,r,i,g)}finally{p||Jl(a,l,m,n,g),Hl(a,t.pathInfo,{value:n})}}function ec(e,t,n,o){return(t,s,...r)=>{const i=ae(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&&se(Vi("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=bn(i,_l(e,n,o,i,s));if(0===r.length)return Nl(e,a,n,o);yl(o),Ql(e,a,r[0],n,o)}}function tc(e,t,n,o){const s=ec(e,0,n,o);return(t,r)=>{const i=ae(t);if(void 0===r||Array.isArray(r)||se(`$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&&se(Vi("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=$l(o,i.wildcardPaths[e]);if(t){r=on(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&&se(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=kl(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 nc(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return $l(o,s.wildcardPaths.at(-1)??se(`lastWildcardPath is null: ${t.pathInfo.path}`))??se(`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]??se(`wildcardParentPathInfo is null: ${t.pathInfo.path}`),a=zs(Nl(e,bn(i,s),n,o),s)??se(`ListIndex not found: ${i.path}`),l=t.wildcardIndexes[r]??se(`wildcardIndex is null: ${t.pathInfo.path}`);s=a[l]??se(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":se(`Partial wildcard type is not supported yet: ${t.pathInfo.path}`)}}function oc(e,t,n,o){return(t,s,r,i)=>{yl(o);const a=ae(t);Array.isArray(s)||se(Ui(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&se(Vi("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&se(Ui(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&se(Ui(t,"requires an array as the value when { spread: true } is set."));const d=kl(e,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&se(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,d.length,r.length));const u=[];for(let t=0;t<d.length;t++){const s=_l(e,n,o,a,d[t]);u.push(bn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(Nl(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(Ql(e,s,i,n,o),f++)}return f}}function sc(e,t){const n=e.getterPaths;if(0===n.size)return!1;for(const e of ae(t).cumulativePaths)if(n.has(e))return!0;return!1}const rc=/^\$\d+$/,ic=`${Y}${c}`,ac=`${Q}${c}`,lc=new WeakMap;function cc(e,t,n,o){const s=M[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&rc.test(t)&&se(`[wcs/index-param-range] "${t}" is not a valid list index parameter: they run from ${C}1 to ${C}128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&se(`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&&se(`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=nn(r,i,a.wildcardCount);return c?.index??se(`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!==ll)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>tc(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>oc(e,0,n,o)(t,s,r,i);case"$postUpdate":return t=>function(e,t,n,o){const s=o.stateElement;return t=>{const r=vl(t),i=nc(e,r,n,o),a=bn(r.pathInfo,i),l=Jt(s,a),c=nr();c.enqueueAbsoluteAddress(l),ql(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Jt(s,e);Hs(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)}}}(e,0,n,o)(t);case"$resolve":return(t,s,...r)=>ec(e,0,n,o)(t,s,...r);case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] $trackDependency("${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&&se(`No active state reference to track dependency for path "${e}".`);const t=o.lastAddressStack?.pathInfo??se("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(t.path)&&t.path!==e&&n.addDynamicDependency(e,t.path)}}(0,0,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(sc(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&vr(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)&&br(o.stateElement,e,t,Jt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=sc(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?vr(o.stateElement,e):br(o.stateElement,e,i,Jt(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||se(`$eqIndex("${e}") needs a list row scope.`);const r=nn(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&se(`$eqIndex("${e}", ${t}): no list index at that level.`),sc(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&vr(o.stateElement,e),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?Bs(l):null;null!==t?function(e,t,n,o,s){ar=!0,hr(e).lastValue.set(t,s),fr(e,t);let r=lr.get(e);void 0===r&&lr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=cr.get(o);void 0===l?cr.set(o,l=[]):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)),a.getters.add(n)}(o.stateElement,e,s.pathInfo,t,a):function(e,t,n,o,s){ar=!0;const r=hr(e);fr(e,t),wr(r,t,s,o,mr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Jt(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":return e=>function(e,t,n,o){return e=>{o.beginUntrack();try{return e()}finally{o.endUntrack()}}}(0,0,0,o)(e);case F:return al(o.stateElement)}if(!t.startsWith(ic)&&!t.startsWith(ac))return}const r=vl(t),i=nc(e,r,n,o),a=bn(r.pathInfo,i);return Nl(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=lc.get(e);return void 0===t&&(t=new Map,lc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Ot:i=(e,t=()=>{})=>function(e,t,n){void 0!==e.loopContext&&se("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 Rt:i=t=>Nl(e,t,n,o);break;case jt:i=t=>Ol(e,t,n,o);break;case Lt:i=(t,s)=>Ql(e,t,s,n,o);break;case Wt:i=()=>async function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Dt:i=()=>function(e,t,n){const o=Reflect.get(e,R);"function"==typeof o&&o.call(n)}(e,0,n);break;case Bt:i=t=>function(e,t,n,o){const s=Reflect.get(e,j);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=on(n.listIndex,t.wildcardCount),o=i[s];void 0===o?i[s]=[e]:o.push(e)}}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 zt:i=(t,o)=>function(e,t,n,o){const s=Reflect.get(e,L);"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 dc{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=$a(e);null===n&&se("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&&se("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()&&se(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),se(`[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&&se(`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 cc(e,t,n,this)}set(e,t,n,o){return yl(this),function(e,t,n,o,s){if("string"==typeof t){const r=vl(t),i=nc(e,r,o,s);return Ql(e,bn(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)}}const uc=Promise.resolve(),fc=new Map;let hc=[];function pc(e,t){fc.set(e,t),hc=Array.from(fc.values()).sort((e,t)=>e.order-t.order)}function gc(e,t){return se(pa(e,t))}const mc="undefined"==typeof HTMLElement?class{}:HTMLElement;function yc(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 wc=null;const bc=new Set(["for","if","elseif","else"]);function vc(e,n,o){const s=new Map;for(const e of o){const t=ae(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=Jt(e,t);if(i.has(n))return;i.add(n);const o=gn(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(bn(n,t.listIndex))}};Ct();try{if(e.createState("readonly",t=>{for(const o of n){const n=bn(ae(o),null);a(n);try{ql(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)bc.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=()=>{la(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Ks("state",s);void 0!==i&&i.catch(Zs)}finally{Et()}}class $c extends mc{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return xa(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 ol}();_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&&se(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(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<hl.length;o++)hl[o].validateEarly?.(e,t,n)}(this,e,n);const o=function(e){const t=new Set,n=e[z];if(void 0===n)return t;Array.isArray(n)||se(`${z} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||se(`${z} entries must be non-empty strings.`),e===F&&se(`${z} entry "${e}" conflicts with the reserved namespace name "${F}".`),t.has(e)&&se(`${z} entry "${e}" is duplicated.`),t.add(e);return t}(e),s=function(e){const t=new Set,n=e[q];if(void 0===n)return t;Array.isArray(n)||se(`${q} must be an array of strings.`);for(const e of n)"string"==typeof e&&0!==e.length||se(`${q} entries must be non-empty strings.`),t.has(e)&&se(`${q} entry "${e}" is duplicated.`),t.add(e);return t}(e),r=function(e){const t=e[X];if(void 0===t)return null;"object"==typeof t&&null!==t||se(`${X} 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&&se(`${X} entry path must be a non-empty string.`);const t=e.split(c);t.some(e=>0===e.length)&&se(`${X} entry "${e}" must not contain empty path segments.`),t[t.length-1]===d&&se(`${X} entry "${e}" must be the list path itself, not the element path (drop the trailing "${c}${d}").`),-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] ${X} entry "${e}" uses "${J}", which ${X} 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&&se(`${X} entry "${e}" key spec must be a field name (string) or a function.`),0===o.length&&se(`${X} entry "${e}" key field name must be a non-empty string.`),(o.includes(c)||o.includes(d))&&se(`${X} entry "${e}" key field name "${o}" must be a flat property name ("${c}" / "${d}" are not allowed).`),o in Object.prototype&&se(`${X} 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<hl.length;o++)hl[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<hl.length;o++)hl[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&wc?.reset(this),this._hasUpdatedCallback=j in e,this._hasErrorCallback=L in e,i=this,Mn.delete(i),function(e,t,n){for(let o=0;o<hl.length;o++)hl[o].applyEarly?.(e,t,n)}(this,e,n),function(e,t,n){const o=t[V];if(void 0!==o){"object"==typeof o&&null!==o||se(`${V} must be an object mapping event-token names to handler functions.`);for(const[t,s]of Object.entries(o))n.has(t)||se(`${V} entry "${t}" is not declared in $eventTokens.${de(t,n)}`),"function"!=typeof s&&se(`${V} entry "${t}" must be a function.`),On(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=yc(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<hl.length;o++)hl[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<hl.length;o++)hl[o].register?.(e,t,n)}(this,e,n),ml(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 <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?ma('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state")){return function(e){const t=document.getElementById(e);if(t&&"application/json"===t.type)try{return JSON.parse(t.textContent||"{}")}catch(e){se("Failed to parse JSON from script element:"+e)}return{}}(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 tl(e,o.tagNames.state);{const e=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.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){try{const t=await fetch(e);return t.ok||se(`Failed to fetch JSON file: ${t.statusText}`),await t.json()}catch(e){return console.error("Failed to load JSON file:",e),{}}}(e);if(e&&e.endsWith(".js"))return await nl(e);se(`Unsupported src file type: ${e}`)}}catch(e){se(`Failed to initialize state: ${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&&(Ia(this._rootNode,this),!0)}_failInitialization(e){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),se(e)}_failInitializeLoudly(e,t=!0){if(this._initializationLanded)throw e;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,e),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(e),t&&null!==this._rootNode&&null===$a(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),wa.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<hc.length;o++)hc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{O in e&&await e[Wt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{R in e&&e[Dt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<hc.length;t++)if(!0===hc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||$a(this._rootNode)===this||Ia(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<hc.length;t++){const n=hc[t].connecting?.(e);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(Z))try{gc("dcc",`a <${o.tagNames.state}> inside a [${Z}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{gc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<hc.length;t++){const n=hc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&gc("scopes",'the "bind-component" attribute'),n=await(e??!1)}catch(e){this._failInitializeLoudly(e)}if(n)return;let s=!1;try{s=await this._initialize()}catch(e){this._failInitializeLoudly(e)}if(!s)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 ma('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}ml(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<hc.length;t++)if(!0===hc[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<hc.length;n++)hc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Ia(this.rootNode,null),e=this,il.delete(e),function(e){for(let t=0;t<pl.length;t++)pl[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()}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",U)}mergeVolumeListKeys(e){if(0===e.size)return;const t=new Map(this._listKeys??[]);for(const[n,o]of e)t.has(n)&&se(`$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 Bi(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&&se("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=dl.get(e);return void 0===n&&se(pa(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<cl.length;n++){const o=cl[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",D)}_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){return this._addDependency(this._dynamicDependency,e,t)}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=ae(e);if(this._pathSet.add(e),wc?.check(this,this.__state,e,n),null!==t.parentPath){let e=t;for(;null!==e.parentPath&&this.addStaticDependency(e.parentPath,e.path);)e=ae(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 dc(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&&se(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(e);!function(e){for(let t=0;t<hc.length;t++)hc[t].replacingState?.(e)}(this),(this._hasGraftedVolumes||this._hasMounts)&&se("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(yc(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){vc(this,e,this._pathRegistrations.keys())}}const xc=[];function Sc(e=customElements){for(let t=0;t<xc.length;t++)xc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,$c)}function Pc(e){if("string"==typeof e?.locale)return 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 Ic(e,t){const o=Pc(e);var s;o&&((s=o).tagNames&&Object.assign(n.tagNames,s.tagNames),"string"==typeof s.bindAttributeName&&(n.bindAttributeName=s.bindAttributeName),"string"==typeof s.commentTextPrefix&&(n.commentTextPrefix=s.commentTextPrefix),"string"==typeof s.commentForPrefix&&(n.commentForPrefix=s.commentForPrefix),"string"==typeof s.commentIfPrefix&&(n.commentIfPrefix=s.commentIfPrefix),"string"==typeof s.commentElseIfPrefix&&(n.commentElseIfPrefix=s.commentElseIfPrefix),"string"==typeof s.commentElsePrefix&&(n.commentElsePrefix=s.commentElsePrefix),"string"==typeof s.locale&&(n.locale=s.locale),"boolean"==typeof s.debug&&(n.debug=s.debug),"boolean"==typeof s.enableMustache&&(n.enableMustache=s.enableMustache),"boolean"==typeof s.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=s.enableDirectionalInitialSync),"boolean"==typeof s.enablePropagationContext&&(n.enablePropagationContext=s.enablePropagationContext),"boolean"==typeof s.enableContractAnalyzer&&(n.enableContractAnalyzer=s.enableContractAnalyzer),"boolean"==typeof s.sameValueGuard&&(n.sameValueGuard=s.sameValueGuard)),Sc(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=Qa)}()}function Ac(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 Nc(e,t){for(const n of e)if(Ac(t,n.innerSegments))return n;return null}function kc(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+c+n.join(c)}let _c=0;const Tc=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Cc=new Set;function Ec(e,t){const n=e.stateObject[t];if("function"==typeof n)try{const o=e.component[e.stateProp],s=n.call(o);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 Mc(e,t,n,o,s,r=new Set){0===n.length&&se(`Cannot build a mount record without host bindings for "${t}".`);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)&&se("Duplicate mapping rule for web component."),a.add(n);const o={innerSegments:t,outerPathInfo:e.statePathInfo,readonly:!0===e.propModifiers?.includes(y)};i.push(o),0===t.length&&(l=o)}i.sort((e,t)=>t.innerSegments.length-e.innerSegments.length);const d=++_c,u=`#m${d}`,{getterKeys:f,setterKeys:h}=function(e){const t=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(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)e.innerSegments.length>0&&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,privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}function Oc(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function Rc(e,t){const n=Nc(e.entries,t);return null===n?null:kc(n,t)}function jc(e,t){return e.markerBasePath+c+t}function Lc(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:ae(r).wildcardCount-ae(o).wildcardCount}),e.getterKeys.has(o)&&(e.parentStateElement.getterPaths?.add(r),e.addedGetterPaths.add(r))}function Wc(e,t){return!e.injectedKeys.has(t)&&!e.mappedKeys.has(t)&&("function"==typeof e.stateObject[t]&&!e.getterKeys.has(t)||Object.prototype.hasOwnProperty.call(e.stateObject,t)&&!e.getterKeys.has(t)&&!e.setterKeys.has(t))}function Dc(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}.${Oc(t)}: path") or declare the key on the component state.`}const Bc=/^\$(\d+)$/;function zc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=Oc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||Wc(e,o))return null;const s=function(e,t){return Nc(e.entries,t)}(e,t.split(c));return null!==s&&s.readonly?s:null}function Fc(e,t){const n=zc(e,t);if(null!==n){const o=0===n.innerSegments.length?"":c+n.innerSegments.join(c);se(`[wcs/mount-readonly] <${e.component.tagName.toLowerCase()}> cannot write "${t}": it is mounted read-only ("${e.stateProp}${o}#${y}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${y} from the mount.`)}return qc(e,t)}function qc(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 Lc(e,e.markerBasePath,t,t),jc(e,t);if(Wc(e,n[0]))return Lc(e,e.markerBasePath,t,t),jc(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Rc(e,s);null===i&&se(Dc(e,t)),0===r.length&&se(`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 Lc(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=Oc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return jc(e,t);if(Wc(e,o))return jc(e,t);const s=Rc(e,t.split(c));if(null!==s)return s;se(Dc(e,t))}function Vc(e,t,n){let o;const s=Bc.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ae(qc(e,t)).wildcardCount-ae(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=qc(e,t.statePathName),"for"===t.bindingType){const n=ae(o).wildcardCount-t.statePathInfo.wildcardCount;e.indexShiftByLoopElementPath.set(o+c+d,n)}const r=t.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(y)&&null!==zc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ae(o),...i?{propModifiers:[...r,y]}:{}}:t}function Hc(e,t,n,o,s){if(void 0===o)return;const r=ae(n).wildcardCount-ae(t).wildcardCount;return 0===r?o:(s.length<r&&se(`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])}const Uc=new WeakMap,Gc=new WeakMap;const Kc=new WeakMap;const Jc=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)}),Xc=new WeakMap;function Yc(e){return Xc.get(e)??null}let Qc=!1;function Zc(){Qc||(Qc=!0,wt=e=>Uc.has(e)?e.host:null)}function ed(e){const t=Kc.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 td(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Kc.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 nd="3.1.0",od=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function sd(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 rd(e){const t=function(e){const t=or.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:lr.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 id="__WCSTACK_DEVTOOLS_HOOK__";function ad(){const e=globalThis,t=e[id];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[id]=n,n}const ld=e=>{null!==$t&&$t({type:"state:update-batch",addresses:e})};function cd(e){const t=null!==$t;!function(e){$t=e}(e);const n=null!==e;n&&!t?Qs(ld,0):!n&&t&&function(e){const t=Js.findIndex(t=>t.listener===e);-1!==t&&Js.splice(t,1)}(ld)}function dd(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 ud(e){return $a(e)??se("devtools: no state tree on this root")}let fd=null;function hd(){if(t())return;if(null!==fd)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:nd,getStateElements(){const e=[];for(const t of ba)e.push(dd(t));return e},overlays:e=>ed(ud(e)).map(e=>({marker:e.marker,componentTag:e.component.tagName.toLowerCase(),stateProp:e.stateProp,mountTable:e.entries.map(e=>({inner:e.innerSegments.join("."),outer:e.outerPathInfo.path})),delta:e.delta,privateKeys:Object.keys(e.privateSnapshot),getterKeys:[...e.getterKeys],exports:[...e.exports.keys()]})),keyedSubscriptions:e=>rd(ud(e)),keys(e){const t=ud(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 ud(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){ud(e).createState("writable",e=>{void 0!==o&&o.length>0?e.$resolve(t,o,n):e[t]=n})},getDeclaredBindings:e=>function(e){const t=[],n=new Set,s=new Set,r=e=>{const o=function(e){const t=[...e.inFilters,...e.outFilters].map(e=>`${e.filterName}(${e.args.join(",")})`).join("|");return[e.statePathName,e.propName,e.bindingType,t].join("\0")}(e);n.has(o)||(n.add(o),t.push(e))},i=e=>{if(s.has(e))return;s.add(e);const t=ka(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(sd(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(o.bindAttributeName);if(null===n||0===n.length)continue;try{const e=ot(t,Oe(n));for(const o of e)r(sd(t,o,"attribute",n))}catch{}continue}const t=od.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=ka(s);if(null===a){if(n===o.commentTextPrefix)try{r(sd(e,De(s),"comment",s))}catch{}}else r(sd(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:cd};fd=e,ad().register(e)}const pd={name:"devtools",install(){hd()}},gd=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),md=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const yd=new WeakMap;const wd=new WeakMap,bd=new WeakSet,vd=new WeakMap;function $d(e,t,n,o){console.warn(`[@wcstack/state] [${Fi[n]}] ${qi[n]} "${t}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${de(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${ue}`),null!==$t&&$t({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const xd={check:function(e,t,n,o){if("internal"===o||void 0===t)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=e.addressHooks;if(s){const t=s.suppressPathDiagnostic;for(let o=0;o<t.length;o++)if(t[o](e,n))return}const r=ae(n).segments;if("binding"===o&&r.length<2)return;if(function(e,t){let n=yd.get(e);return void 0===n&&(n=new Set,yd.set(e,n)),!!n.has(t)||(n.add(t),!1)}(e,n))return;if(!0===e.hasRecursion&&null!==e.recursionRegistry.recursiveGetterOwning(n))return;const i=function(e,t,n){if(void 0!==Bi(e,t))return md;const o=ae(t).segments;let s=e,r="";for(let t=0;t<o.length;t++){const i=o[t],a=r;if(r=0===t?i:r+c+i,t>0&&t<o.length-1&&void 0!==Bi(e,r))return gd;if(Object(s)!==s)return gd;if(i===d){if(!Array.isArray(s)||0===s.length)return gd;s=s[0];continue}const l=Bi(s,i);if(void 0===l)return{existence:"missing",missingSegment:i,candidates:zi(s,a,n)};if("function"==typeof l.get)return t===o.length-1?md:gd;s=l.value}return md}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===vd.get(e)?.has(t)}(e,n)||("binding"!==o?$d(e,n,o,i):function(e,t,n){let o=wd.get(e);void 0===o&&(o=new Map,wd.set(e,o));if(o.set(t,n),bd.has(e))return;bd.add(e),setTimeout(()=>function(e){bd.delete(e);const t=wd.get(e);if(void 0===t)return;wd.delete(e);for(const[n,o]of t)$d(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){yd.delete(e),wd.delete(e)},markExported:function(e,t){let n=vd.get(e);void 0===n&&(n=new Set,vd.set(e,n)),n.add(t),wd.get(e)?.delete(t)}};let Sd=!1;function Pd(){Sd||(Sd=!0,function(e){wc=e}(xd))}const Id={name:"diagnostics",install(){Pd()}};function Ad(e){se(`filter ${e} requires at least one option`)}function Nd(e){se(`filter ${e} requires a number as option`)}function kd(e){se(`filter ${e} requires a number value`)}function _d(e){se(`filter ${e} requires a date value`)}function Td(e){return!(!e||isNaN(Number(e)))}const Cd={eq:(e,t)=>{const n=e?.[0]??Ad("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Td(n)||Nd("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Ad("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(Td(n)||Nd("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==o},not:e=>e=>("boolean"!=typeof e&&se(`filter ${"not"} requires a boolean value`),!e),lt:e=>{const t=e?.[0]??Ad("lt");return Td(t)||Nd("lt"),e=>("number"!=typeof e&&kd("lt"),e<Number(t))},le:e=>{const t=e?.[0]??Ad("le");return Td(t)||Nd("le"),e=>("number"!=typeof e&&kd("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??Ad("gt");return Td(t)||Nd("gt"),e=>("number"!=typeof e&&kd("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??Ad("ge");return Td(t)||Nd("ge"),e=>("number"!=typeof e&&kd("ge"),e>=Number(t))},inc:e=>{const t=e?.[0]??Ad("inc");return Td(t)||Nd("inc"),e=>("number"!=typeof e&&kd("inc"),e+Number(t))},dec:e=>{const t=e?.[0]??Ad("dec");return Td(t)||Nd("dec"),e=>("number"!=typeof e&&kd("dec"),e-Number(t))},mul:e=>{const t=e?.[0]??Ad("mul");return Td(t)||Nd("mul"),e=>("number"!=typeof e&&kd("mul"),e*Number(t))},div:e=>{const t=e?.[0]??Ad("div");return Td(t)||Nd("div"),e=>("number"!=typeof e&&kd("div"),e/Number(t))},mod:e=>{const t=e?.[0]??Ad("mod");return Td(t)||Nd("mod"),e=>("number"!=typeof e&&kd("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&kd("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??Ad("clamp");Td(t)||Nd("clamp");const n=e?.[1]??Ad("clamp");Td(n)||Nd("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&kd("clamp"),Math.min(Math.max(e,o),s))},fix:e=>{const t=e?.[0]??"0";return Td(t)||Nd("fix"),e=>("number"!=typeof e&&kd("fix"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&kd("locale"),e.toLocaleString(t??o.locale))},uc:e=>e=>String(e).toUpperCase(),lc:e=>e=>String(e).toLowerCase(),cap:e=>e=>{const t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)},trim:e=>e=>String(e).trim(),slice:e=>{const t=[],n=e?.[0]??Ad("slice");Td(n)||Nd("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(Td(o)||Nd("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??Ad("substr");Td(t)||Nd("substr");const n=e?.[1]??Ad("substr");return Td(n)||Nd("substr"),e=>String(e).substr(Number(t),Number(n))},pad:e=>{const t=e?.[0]??Ad("pad");Td(t)||Nd("pad");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},rep:e=>{const t=e?.[0]??Ad("rep");return Td(t)||Nd("rep"),e=>String(e).repeat(Number(t))},rev:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??Ad("truncate");Td(t)||Nd("truncate");const n=Number(t),o=e?.[1]??"…";return e=>{const t=String(e);return t.length<=n?t:t.slice(0,n)+o}},join:e=>{const t=e?.[0]??", ";return e=>(Array.isArray(e)||se(`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=e?.[0]??"0";return Td(t)||Nd("round"),e=>{"number"!=typeof e&&kd("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return Td(t)||Nd("floor"),e=>{"number"!=typeof e&&kd("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return Td(t)||Nd("ceil"),e=>{"number"!=typeof e&&kd("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return Td(t)||Nd("percent"),e=>("number"!=typeof e&&kd("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??Ad("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||_d("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||_d("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||_d("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||_d("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||_d("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]??Ad("defaults"),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),null:e=>e=>""===e?null:e},Ed={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],inc:[0,1],dec:[0,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],fix:[0,1],locale:[0,1],uc:[0,0],lc:[0,0],cap:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],pad:[1,2],rep:[1,1],rev:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],boolean:[0,0],number:[0,0],string:[0,0],null:[0,0]},Md=Cd,Od=Cd;let Rd=!1;const jd={name:"formats",install(){Rd||(Rd=!0,ye("input",Od,Ed),ye("output",Md,Ed))}};function Ld(e){return-1!==e.indexOf(J)}function Wd(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(Ld(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function Dd(e){return 0===e.length?e:c+Fd(e.slice(1))}function Bd(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 zd(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(Bd(e,t,n.slice(0,o)))return!0;return!1}function Fd(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 qd(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 Vd(e,t,n){n<0&&se(`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&&se(`[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 Hd(e,t){return Vd(e,"",t)}function Ud(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 Gd(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 Kd(e,t,n){const o=e.recursionRegistry,s=Wd(o.spec,n);null===s&&se(Hi(n,o.spec.recursiveAnchor));const r=Gd(t,o);return null===r&&se(`[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 Jd(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(bn(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=bn(o,s),c=Jt(n.stateElement,l),u=Nl(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)&&se(`[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)&&se(`[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=Er(s,_t(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:ae(n),childListPathInfo:ae(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(bn(u.concretePathInfo,n)):p(u.concretePathInfo,e+1,n),m(e+1,u.childListPathInfo,n)}f.delete(y)};m(0,ae(u),null);for(const[e,t]of a)Tt(e,t);return i}function Xd(e,t,n,o,s,r,i){yl(n);const a=n.stateElement.recursionRegistry,l=Wd(a.spec,o);null===l&&se(Hi(o,a.spec.recursiveAnchor));const c=Dd(l);Array.isArray(s)||se(Ui(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&se(`[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&&se(Ui(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&se(Ui(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){qd(e,n)&&se(`[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&&se(`[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=Jd(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(Ql(e,u[o],r,t,n),f++);return f}const Yd={write(e,t){if(!0!==e.hasRecursion)return ll;const n=e.recursionRegistry.recursiveGetterOwningPath(t.pathInfo);return null!==n&&se(`[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.`),ll},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return ll;if("$getAll"===t)return(t,s)=>{if(Ld(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Wd(r.spec,o);null===i&&se(Hi(o,r.spec.recursiveAnchor)),Array.isArray(s)||se(`[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&&se(`[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=Jd(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Nl(e,a[o],t,n));return l}(o,n,e,t,s);t=Kd(e.stateElement,e,t)}return tc(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>Ld(t)?Xd(o,n,e,t,s,r,i):oc(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&Ld(t)){const s=vl(Kd(e.stateElement,e,t)),r=nc(o,s,n,e);return Nl(o,bn(s.pathInfo,r),n,e)}return ll}};let Qd=!1;function Zd(e,t){"string"==typeof t&&0!==t.length||se(`[wcs/recursion-declaration-invalid] ${K} ${e} must be a non-empty string.`);const n=t.split(c);n.some(e=>0===e.length)&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain empty path segments.`),n.length<2&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must name a list element: a property path ending with "${c}${d}" (for example "nodes${c}${d}").`),n[n.length-1]!==d&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must end with "${c}${d}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===d&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must have exactly one "${d}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===J&&se(`[wcs/recursion-declaration-invalid] ${K} ${e} "${t}" must not contain "${J}" — the declaration is what gives "${J}" its meaning.`),isNaN(Number(n[o]))||se(`[wcs/recursion-declaration-invalid] ${K} ${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 eu=new WeakSet;function tu(e){return"function"==typeof e.get&&eu.has(e.get)}function nu(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&tu(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))}}!function(e,t,n){for(const o of n){const n=ae(o),s=n.wildcardParentPathInfos,r=(t,o,i)=>{if(i===s.length)return void Vs(Xt(e,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=t;for(const e of s[i].segments.slice(a))l=l?.[e];if(!Array.isArray(l))return;const c=Bs(l);if(null===c)return;const d=Math.min(c.length,l.length);for(let e=0;e<d;e++)r(l[e],c[e],i+1)};r(t,null,0)}}(e,t,n)}}const ou="[wcs/recursion-declaration-invalid]";class su{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=yc(t);for(const[t,o]of Object.entries(n)){if(!Ld(t))continue;"function"==typeof o.set&&se(`${ou} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&se(`${ou} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Wd(e,t);null===n&&se(Hi(t,e.recursiveAnchor)),0===n.length&&se(`${ou} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),qd(e,Dd(n))&&se(`${ou} "${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(Ld(t)||tu(n))continue;const e=this._matchExpansion(t);null!==e&&se(`${ou} "${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++)Bd(this.spec,e[t].suffix,e[n].suffix)&&se(`${ou} "${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(zd(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=Fd(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!==Ud(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=Ud(this.spec,e.suffix,t);null!==n&&(null!==o&&se(`"${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||tu(s)||se(`"${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,eu.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(Hd(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 nu(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=Vd(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 ru="recursionSpec",iu="recursionRegistry",au={order:5,validateEarly(e,t,n){const o=function(e){const t=e[K];if(void 0===t)return null;"object"==typeof t&&null!==t||se(`[wcs/recursion-declaration-invalid] ${K} 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&&se(`[wcs/recursion-declaration-invalid] ${K} must declare exactly one anchor; it is empty.`),n.length>1&&se(`[wcs/recursion-declaration-invalid] ${K} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Zd("anchor",o),"string"!=typeof s&&se(`[wcs/recursion-declaration-invalid] ${K} entry "${o}" must map to the repeating sub-path as a string (for example "children${c}${d}").`),Zd("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(c)),i=s.slice(0,s.lastIndexOf(c)),a=r+c+J;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:a,anchorList:r,repeatList:i})}(t);n.set(ru,o),n.set(iu,null===o?null:new su(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(iu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",K)},apply(e,t,n){const o=n.get(ru)??null;null!==o&&e.addListPath(o.anchorList)}};let lu=!1;function cu(){lu||(lu=!0,Qd||(Qd=!0,ul("recursion",Yd)),gl("recursion",au))}const du={name:"recursion",install(){cu()}};const uu={written:function(e,t,n){const o=e.bindableEventMap,s=o[t.path],r="string"==typeof s,i=r?s:t.segments.length>1?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 fu=!1;function hu(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 pu(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 gu(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 mu(e){return e.startsWith("$")}function yu(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 wu(e,t){const n=e[t];if(void 0===n)return null;Array.isArray(n)||se(`${t} must be an array of strings.`);const o=[],s=new Set;for(const e of n)"string"==typeof e&&0!==e.length||se(`${t} entries must be non-empty strings.`),e.startsWith("$")&&se(`${t} entry "${e}" must not start with "$" (internal properties are not exposed on the component).`),s.has(e)&&se(`${t} entry "${e}" is duplicated.`),s.add(e),o.push(e);return o}function bu(e){const t=wu(e,D)??[],n=wu(e,B)??[],o=yc(e),s=function(e){const t=e[H];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}se(`${D} entry "${e}" is not declared on the state.${de(e,yu(o,"value"))}`)}"function"==typeof t.value&&se(`${D} entry "${e}" is a method. Declare it in ${B} instead.`)}for(const e of n){const t=o[e];void 0===t&&se(`${B} entry "${e}" is not declared on the state.${de(e,yu(o,"method"))}`),"function"!=typeof t.value&&se(`${B} entry "${e}" is not a method. Declare it in ${D} instead.`)}return{bindables:t,commands:n,streamBackedBindables:r}}function vu(e,t,n){const s=e.tagName.toLowerCase();s.includes("-")||se(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Ke(e);null!==r&&"function"==typeof r.define||se(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&se(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const e of Array.from(t.childNodes))i.content.appendChild(a.importNode(e,!0));const l=t.mode,{bindables:c,commands:d,streamBackedBindables:u}=bu(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}}(s,c,d):null,h=c.length>0?function(e,t){const n={};for(const o of t)n[o]=`${e}:${o}-changed`;return n}(s,c):{},p=o.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(Z))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const e=Ke(this._shadow);return null!==e&&Je(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?(fu||(fu=!0,ul("dcc",uu)),t.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${D} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},m=yc(n);for(const[e,t]of Object.entries(m)){if(mu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=gu(e,o)}else n.get=hu(e),n.set=pu(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:hu(e),set:pu(e)});r.define(s,g)}async function $u(e,t,n){const o=e;try{o.hasAttribute("bind-component")&&se(`"bind-component" cannot be used inside a [${Z}] host. DCC state comes from the template, not from a component property.`);const s=await async function(e,t){try{if(e.hasAttribute("src")){const t=e.getAttribute("src");if(t.endsWith(".js"))return await nl(t);se(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await tl(n,t.tagName.toLowerCase());se(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}catch(e){se(`DCC: Failed to load state: ${e}`)}}(o,t);vu(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const xu={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Z)?$u(e,t.host,t):null}};let Su=!1;const Pu=new WeakMap;function Iu(e,t,n){let o=Pu.get(e);void 0===o&&(o=new Map,Pu.set(e,o));const s=o.get(t);null!=s&&se(`Volume slot "${t}" is already mounted on this tree.`),o.set(t,n)}function Au(e,t){if(null===e)return!1;const n=Pu.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 Nu=new WeakMap;const ku=[];function _u(e,t,n,o){if(t.length>0){const s=n.split(c),r=Nc(t,s);if(null!==r)return o&&r.readonly&&se(`[wcs/mount-readonly] volume "${e}" cannot write "${n}": it is injected read-only ("${A}.${r.innerSegments.join(c)}#${y}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${y} from the injection.`),kc(r,s)}return e+c+n}function Tu(e,t,n){for(const e of t){const t=e.outerPathInfo.path;if(n===t)return e.innerSegments.join(c);if(n.startsWith(t+c))return e.innerSegments.join(c)+n.slice(t.length)}return n===e?"":n.startsWith(e+c)?n.slice(e.length+1):null}function Cu(e,t,n=ku){return new Proxy({},{get(o,s){if("string"==typeof s&&"then"!==s){if("$"===s[0]){if("$postUpdate"===s||"$getAll"===s){const o=s;return(s,...r)=>t[o](_u(e,n,s,!1),...r)}return"$setAll"===s?(o,...s)=>t.$setAll(_u(e,n,o,!0),...s):"$resolve"===s?(o,...s)=>t.$resolve(_u(e,n,o,s.length>1),...s):t[s]}return t[_u(e,n,s,!1)]}},set:(o,s,r)=>("string"!=typeof s||(t[_u(e,n,s,!0)]=r),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Eu=new WeakMap,Mu=[];const Ou=new WeakMap,Ru=new WeakSet;function ju(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 Lu=null;const Wu=new WeakMap,Du=new Set;function Bu(e,t,n,o){let s=Wu.get(e);if(void 0===s){if(!o)return null;s=new Map,Wu.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 zu(e,t){if(!e.component.isConnected)return!1;const n=bt(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 Fu(e,t,n,o){const s=Bu(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&&zu(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?zu(r,o)&&(null!==a&&se(`[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 qu(e){const t=e.parentStateElement,n=bt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Ot](n,()=>{e.$postUpdate(o.exportedPath)})})}const Vu=new WeakMap;class Hu{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(e,t,n,o,s,r){this.record=e,this.markerParentPath=t,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(e){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(e)?.accessorName}accessorAddress(e){return bn(ae(this.markerParentPath+c+e),this.listIndex)}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(qc(this.record,e))};if("$getAll"===t||"$setAll"===t||"$resolve"===t){const e=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===t)return(t,s,...r)=>{const i=r.length>0?Fc(e,t):qc(e,t),a=Hc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Fc(e,t):qc(e,t),l=Hc(0,t,a,r,n);return o[s](a,l,...i)}}return 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 xl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[qc(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)||se(`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,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(e,t)?(e[t]=n,!0):(this.receiver[Fc(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 qc(this.record,t),!0}catch{return!1}}}function Uu(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Vu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Vu.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 Hu(e,s,t.listIndex,r,n,o))}function Gu(e){const t=e.parentStateElement,n=(t,n)=>{const o=bt(e.component);let s;return t[Ot](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(e,t,n){const o=e.parentStateElement,s=(e,t)=>{let s;return o.createState(e,e=>{s=n(e,()=>t(e))}),s};return"$postUpdate"===t?t=>s("readonly",n=>n.$postUpdate(qc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Fc(e,n):qc(e,n),l=bt(e.component)?.listIndex.indexes??[],c=Hc(0,n,a,"$resolve"===t?o??[]:o,l);return s(i?"writable":"readonly",e=>e[t](a,c,...r))}}(e,s,n);let r;return t.createState("readonly",t=>{r=n(t,()=>t["$"===s[0]?s:qc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Fc(e,s)]=r})}),!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 qc(e,n),!0}catch{return!1}}})}function Ku(e,t){const n=function(e){return Uc.get(e)??null}(t);var o,s;null!==n&&n.stateProp!==e.stateProp&&se(`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&&hs(t).dispose(),function(e,t){Zc(),Uc.set(e,t),Xc.set(t,e);let n=Kc.get(t.parentStateElement);void 0===n&&(n=new Map,Kc.set(t.parentStateElement,n)),n.set(t.marker,new WeakRef(t));let o=Gc.get(t.component);void 0===o&&(o=new Map,Gc.set(t.component,o));const s=o.get(t.stateProp)!==t;o.set(t.stateProp,t),s&&Jc.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=ya.get(e);if(void 0!==n){if(n===t)return;se("A state tree is already registered on this root.")}ya.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Vc(e,t,n);ne(t);const o=bt(e.component);Ha(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),ca(t,o,n)}(e,t),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=qc(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=ae(i);if(a.wildcardCount!==e.delta)continue;const l={markerTerminalPath:s,suffix:r,markerPath:t,exportedPath:i};e.exports.set(i,l),Bu(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),wc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=bt(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(Du.has(s))continue;const r=ae(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Ot](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Du.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),qu(e),o=t,s=Promise.resolve(),wa.set(o,s),s.then(()=>Pa(o),()=>{})}function Ju(e,t){const n=hs(t),o=bt(e.component);n.forEachActiveBindingNode(e=>vt(e,o));la(n.rebindAddresses()),qu(e)}function Xu(e,t){if(function(e){const t=Kc.get(e);return void 0!==t&&t.size>0}(t))for(const n of ed(t)){if(!Yu(n.component,e))continue;const t=Yc(n);null!==t&&Ju(n,t)}}function Yu(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 Qu={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=td(e,t.pathInfo.path);if(null!==s)return Uu(s,t,n,o)}return ll},readMissing(e,t,n,o,s){if(null===n){if(Au(e.rootNode??null,t.pathInfo.path))return;return ll}if(!0===e.hasMounts){const n=Fu(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Uu(e,bn(ae(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return ll},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=Nu.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&&se(`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 ll},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Fu(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Uu(e,bn(ae(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return ll},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=td(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=Uc.get(n);if(void 0!==e)return e;n=n.parentNode}return Uc.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 Eu.get(e)??Mu}(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=Tu(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=on(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(Cu(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>Au(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){Xu(t,e)}};let Zu=!1;const ef=new WeakMap;function tf(e){let t=ef.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},ef.set(e,t)),t}function nf(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Pu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function of(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{Iu(n,s,e)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return $a(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function sf(e,t){const n=e,s=e.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(e){0===e.length&&se('"mount" requires a non-empty tree path.');const t=ae(e);for(const n of t.segments)0===n.length&&se(`"mount" path "${e}" has an empty segment.`),n===d&&se(`"mount" path "${e}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&se(`"mount" path "${e}" must not use reserved characters ($, #, @).`)}(r),i=function(e,t){const n=[],s=new Set;for(const r of Oe(e)){if(r.propSegments[0]!==A)continue;const e=r.propSegments.slice(1),i=r.statePathInfo,a=e=>se(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${t}"> "${r.propName}: ${r.statePathName}": ${e}`);1===e.length&&e[0]&&e[0]!==d&&"$"!==e[0][0]&&"#"!==e[0][0]||a(`inject one key at a time ("${A}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(r.inFilters.length>0||r.outFilters.length>0)&&a("an injection takes no filters."),r.propModifiers.some(e=>e!==y)&&a(`an injection accepts only #${y}.`),s.has(e[0])&&a(`"${e[0]}" is injected twice.`),s.add(e[0]),n.push({innerSegments:e,outerPathInfo:i,readonly:r.propModifiers.includes(y)})}return n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&se('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),Iu(s,r,e),$a(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===$a(s)&&function(e,t){const n=()=>{if(null!==$a(e))return;const n=e.querySelectorAll(o.tagNames.state);for(const e of n)if(!e.hasAttribute("mount")&&!e.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${t}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=e.ownerDocument??e;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{t.graftInfo=n,e.markInitialized(),null===n&&nf(e,t),e.settleInitialization()};let l;try{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&&of(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 up(t,a);hp(),function(e,t){if(Ru.has(e))return void ju(t);let n=Ou.get(e);void 0===n&&(n=[],Ou.set(e,n)),n.push(t)}(e,a)}(c,$a(c),r,l,a,()=>of(e,t,c),i):a(null)}const rf={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=tf(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{Iu(n,t.mountPath,e),$a(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,uc}return sf(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=tf(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&$a(n)===t.graftInfo.rootStateElement&&lp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==ef.get(e)?.initializing)return;const t=e.getAttribute("mount");se(`Cannot replace the state of <${o.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){Ru.add(e);const t=Ou.get(e);if(void 0!==t){Ou.delete(e);for(const e of t)ju(e)}}(t)},initializeFailureCleared(e,t){!function(e){Ru.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=tf(e);return null!==t.graftInfo&&lp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,nf(e,t)),e.clearConnectedRootNode(),!0}};let af=!1;const lf=new WeakMap;function cf(e,t){let n=lf.get(e);n||(n=new Set,lf.set(e,n)),n.add(t)}const df=new WeakMap;const uf=new WeakMap,ff=new WeakMap;const hf=new WeakMap;const pf={isComplete:function(e,t){return!0===lf.get(e)?.has(t)},isDeclared:function(e,t){return!0===df.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=uf.get(e);o||(o=new Map,uf.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=ff.get(e);o||(o=new Map,ff.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=hf.get(e);s||(s=new Map,hf.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function gf(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 mf=new WeakMap;class yf{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=mf.get(e);return n?n.get(t)??null:null}(e,t)??se("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 wf=e=>()=>e;function bf(e,t,n,o){!function(e,t,n){let o=mf.get(e);o||(o=new Map,mf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState(gf(o));const s=function(e,t){const n=new yf(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:wf(s),enumerable:!0,configurable:!0}),cf(t,n),vf(t,n)}function vf(e,t){if(W in e){const n=e[W];"function"==typeof n?n.call(e,t).catch(e=>{se(`Error in ${W}: ${e instanceof Error?e.message:String(e)}`)}):se(`${W} is not a function.`)}}const $f=new Set;function xf(e,t){$f.has(e)||($f.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function Sf(e){const t=e.rootEntry,n=bt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Ot](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Pf=new WeakMap;function If(e,t){e.landInitialization(),se(t)}async function Af(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?Ue(a):null;null!==a&&null!==l||se(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||If(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&&se(`"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=df.get(e);n||(n=new Set,df.set(e,n)),n.add(t)}(a,d);const u=Ke(a);null===u&&se(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await qe(a),d in a||se(`Component does not have property "${d}" for state binding.`);let f=a[d];"object"==typeof f&&null!==f||se(`Component property "${d}" is not an object for state binding.`);const h=function(e,t){const n=uf.get(e);if(!n)return;const o=n.get(t);return n.delete(t),o}(a,d);if(void 0!==h&&function(e,t){if(!e.hasAttribute(o.bindAttributeName))return!1;const n=at(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]=h,f=h),t.boundComponent=a,t.boundComponentStateProp=d,e.setBoundComponent(a,d),i instanceof ShadowRoot||(at(a)??[]).some(e=>e.propSegments[0]===d)||If(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(o.bindAttributeName)){const o=(at(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=$a(a.getRootNode())??If(e,`No state tree found on this root for mount host <${l}>.`);let u=(s=a,r=d,Gc.get(s)?.get(r)??null);const h=null!==u;if(null===u&&(function(e,t,n){const o=hf.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;hf.get(e).delete(t)}}(a,d,f),u=Mc(a,d,o,c,f,function(e,t){return ff.get(e)?.get(t)}(a,d)),function(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=Sf(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;xf(`${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.`)}}(u)),t.mountRecord=u,n.parentNode!==i)return;try{Ku(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Gu(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),cf(a,d)}return vf(a,d),function(e){const t=Tc.filter(t=>void 0!==e.stateObject[t]);for(const n of e.getterKeys)-1!==n.indexOf(J)&&t.push(`"${n}"`);if(0===t.length)return;const n=`${e.component.tagName.toLowerCase()}|${e.stateProp}`;Cc.has(n)||(Cc.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),void Ec(u,"$connectedCallback")}}bf(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const Nf={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=Pf.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Pf.set(e,t)),t}(e);return Af(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Pf.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&Ju(n,o)}),Ec(n,"$connectedCallback"),!0},disconnecting(e){const t=Pf.get(e);return void 0!==t&&null!==t.mountRecord&&(Ec(t.mountRecord,"$disconnectedCallback"),qu(t.mountRecord),e.clearConnectedRootNode(),!0)}};let kf=!1;function _f(){kf||(kf=!0,pc("bindComponent",Nf),gs=pf)}const Tf=new WeakMap,Cf=new Set,Ef=new Set;function Mf(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Of(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function Rf(e){return Tf.get(e)}function jf(e){Lf(e),Tf.delete(e)}function Lf(e){Cf.delete(e),Ef.delete(e)}const Wf=new WeakMap,Df=new WeakMap,Bf=new Set,zf=new Map;function Ff(e){return Wf.get(e)??zf}function qf(e){Bf.add(e),function(e){const t=Tf.get(e);void 0!==t&&(Mf(t)&&Cf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Ef.add(e))}(e)}const Vf=new Map;function Hf(e){return Df.get(e)??Vf}function Uf(e){0===e.length&&se(`[wcs/watch-declaration-invalid] ${U} entry name must be a non-empty state path.`),e.startsWith("$")&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not start with "$" (reserved namespace).${ue}`),e.includes("@")&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${ue}`),e in Object.prototype&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const t=ae(e);for(const n of t.segments)0===n.length&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" has an empty path segment.${ue}`);return t.wildcardCount>u&&se(`[wcs/watch-declaration-invalid] ${U} entry "${e}" exceeds the maximum wildcard depth (128).`),t}function Gf(e,t){const n=t[U];if(void 0===n)return null;"object"==typeof n&&null!==n||se(`[wcs/watch-declaration-invalid] ${U} must be an object mapping state paths to handler functions.${ue}`);const o=new Map,s=new Set;let r=0;for(const[t,i]of Object.entries(n)){"function"!=typeof i&&se(`[wcs/watch-declaration-invalid] ${U} entry "${t}" must be a function.${ue}`);const n=Uf(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Wf.set(e,t)}(e,o),s.size>0?s:null}let Kf=0,Jf=0;function Xf(e){Kf=e+1}function Yf(){Kf=0}function Qf(){Kf>Jf&&(Jf=Kf)}const Zf=new WeakMap;function eh(e,t,n){let o=Zf.get(e);void 0===o&&(o=new Map,Zf.set(e,o)),o.set(t,n)}const th=new Map;function nh(e,t){th.has(e)||th.set(e,t)}function oh(e){return th.get(e)}const sh={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||nh(n,o)},swapped(e,t,n){var o;o=n,th.has(o)&&nh(t,oh(n))}};function rh(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ws(t))return!0;return!1}function ih(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[Rt](bn(t.wildcardParentPathInfos[i],r)),l=Bs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=nn(o,i,t.wildcardCount);if(l!==c&&!Rs(l,c)){if(Ws(c))return"gone";s="replaced"}r=l}return s}function ah(e,t,n){const o=new Map;for(const s of n){const n=ih(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 lh=new Set;function ch(e){lh.delete(e)}function dh(){return lh}const uh=Symbol("wcs-stream-last-notified-uncertain"),fh=new WeakMap;function hh(e,t){const n=fh.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function ph(e,t){const n=fh.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:uh,error:Object.is(o.error,null)?null:uh})}const gh=new WeakMap;function mh(e){return gh.get(e)??new Map}function yh(e){ch(e);const t=gh.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,ph(e,n.name)}const wh=new WeakSet;let bh=0;function vh(e){return Rf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function $h(e){if(0===Ef.size)return;if(t=e.absolutePathInfo.stateElement,!Ef.has(t))return;var t;const n=vh(e);if(void 0!==n)for(const e of n)xh(e)}function xh(e){wh.has(e)||(wh.add(e),bh++)}function Sh(e){return!!wh.delete(e)&&(bh--,!0)}const Ph=/^(?:0|[1-9]\d*)$/;function Ih(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Ah(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&&Ph.test(t)&&Ih(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Ih(e,t))?"object":null}function Nh(e,t){const n=Ah(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]=Nh(o[e],t);return r}function kh(e){return Nh(e,new Map)}function _h(e,t,n){if(Object.is(e,t))return!0;const o=Ah(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(Ah(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(!_h(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&_h(s[e],r[e],n))}function Th(e,t){return _h(e,t,new Map)}const Ch=new WeakMap;function Eh(e,t){if("function"!=typeof t)return;const n=Ch.get(t);void 0===n?Ch.set(t,new Set([e])):n.add(e)}const Mh={"read-source":e=>`${G} could not read a "from" value for "${e}". That landing was not folded; the other landings of the batch still were.`,"read-output":e=>`${G} could not read the output "${e}". Nothing was folded or written.`,threw:e=>`${G} fold for "${e}" threw. The output was not written.`,"returned-promise":e=>`${G} fold for "${e}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:e=>`${G} could not write the output "${e}".`},Oh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Rh(e,t,n){null!==$t&&$t({type:"state:watch-error",phase:t,path:`${G}.${e}`,error:n})}function jh(e,t,n){console.error(`[@wcstack/state] ${Mh[n](e)}`,t),Rh(e,Oh[n],t)}function Lh(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Wh(e,t){t.then(void 0,()=>{}),jh(e,new TypeError(`${G} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Dh=new WeakSet;const Bh=Object.freeze([]);function zh(e,t,n){let o=e.get(n);return void 0===o&&(o={stateElement:t,entry:n,rows:[],reset:!1},e.set(n,o)),o}function Fh(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 qh(e,t){return t.has(e.stateElement)&&!0===Rf(e.stateElement)?.entries.has(e.entry)}function Vh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Hh(n,e))||Sh(t)}function Hh(e,t){return nr().hasQueuedPath(e,t)}function Uh(e,t){!function(e,t,n){if(0!==bh)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=vh(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||Sh(t)}}(e,t,Hh)}function Gh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function Kh(e,t,n){if(!qh(e,n))return Vh(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(Dh.has(e))return;Dh.add(e);const o=`[wcs/scan-source-computed] ${G} 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}`),Rh(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=mh(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],o=0===r.pathInfo.wildcardCount?e.rows:ah(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Fh)){let n;try{n=Gh(t,r,e)}catch(e){jh(s.name,e,"read-source");continue}const o=a(l,n,oh(e.absAddress),...e.indexes);if(Lh(o))return void Wh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){jh(s.name,e,i.failure)}return i.plan}function Jh(e,t){const{group:n}=e;if(!qh(n,t))return void Vh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Sh(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!Th(o,s.initial):!Object.is(o,e.next)){const o=n.reset?kh(s.initial):e.next;t[s.name]=o,Eh(s.name,o)}})}catch(e){jh(s.name,e,"write")}}function Xh(e,t,n){if(Uh(e,t),0===Cf.size)return Bh;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=Rf(e);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let t=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;t=on(n.listIndex,r.wildcardCount)}for(const s of i)zh(o,e,s).rows.push({absAddress:n,indexes:t})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const t of a)zh(o,e,t).reset=!0}if(0===o.size)return Bh;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];Xf(n);try{for(const n of s){const o=Kh(n,e,t);null!==o&&r.push(o)}}finally{Yf()}return r}function Yh(e){ip(),(0!==Ff(e).size||0!==Hf(e).size||function(e){const t=Tf.get(e);return void 0!==t&&Mf(t)}(e))&&(qf(e),function(e){const t=[];for(const n of Ff(e).values())Qh(e,n)&&t.push(n);for(const n of Hf(e).values())for(const o of n)Qh(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{eh(e,Xt(e,o.pathInfo,null),n[o.path])}catch(t){ep(e,o.path,"prime",t)}})}(e))}function Qh(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const Zh={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function ep(e,t,n,o){console.error(`[@wcstack/state] $watch ${Zh[n]} "${t}" threw.`,o),null!==$t&&$t({type:"state:watch-error",phase:n,path:t,error:o})}function tp(e){const t=Bf;try{if(0===t.size)return void Uh(e,t);const n=function(){const e=Jf;return Jf=0,e}();if(n>32){Uh(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!==$t&&$t({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){Xf(n);try{for(const n of e)Jh(n,t)}finally{Yf()}}}(Xh(e,t,n),t,n),function(e,t,n){const o=[];for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=n.absolutePathInfo.pathInfo.path,r=Ff(e).get(s),i=Hf(e).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const t of a){let s=[];if(t.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=on(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(op);const s=function(e){let t=null;for(let n=0;n<e.length;n++){const o=e[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=e[n-1];(rh(o.absAddress.listIndex)||s?.entry===o.entry&&np(s.indexes,o.indexes))&&(t??=new Set).add(o.entry)}if(null===t)return e;const n=new Set;for(const o of t){const t=e.filter(e=>e.entry===o),s=t[0].stateElement;try{s.createState("readonly",e=>{const s=new Set(ah(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){ep(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);Xf(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Ff(e.stateElement).get(e.entry.path)===e.entry,o=!0===Hf(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&sp(e)}}finally{Yf()}}(e,t,n)}finally{th.clear()}}function np(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function op(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 sp(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=Qh(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 ep(0,n.path,"evaluate",e)}const a=r?function(e,t){return Zf.get(e)?.get(t)}(t,o):oh(o);r&&eh(t,o,i),null!==$t&&$t({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){ep(0,n.path,"handler",e)}}let rp=!1;function ip(){rp||(rp=!0,ul("watch",sh),gl("watch",ap),Qs(tp,10),Ys(Qf))}const ap={order:10,register(e,t){var n;n=e,Bf.delete(n),Lf(n),Wf.delete(n),function(e){Zf.delete(e)}(e);const o=Gf(e,t);e.setWatchPaths?.(o),null===o&&null==e.scanPaths||e.attachAddressHooks?.("watch",null!==o?U:G)},activate(e,n){t()||null==e.connectedRootNode||(null===n?!0===e.initialized:n===e.connectGeneration)&&Yh(e)},deactivate(e){var t;t=e,Bf.delete(t),Lf(t)}};function lp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Cu(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function cp(e,t,n,o){const s=n[U];if(void 0!==s){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(s)){const s=_u(t,o,a,!1),c=function(e,n,...s){l.call(Cu(t,this,o),e,n,...s)};n.push({path:s,pathInfo:ae(s),handler:c,order:1e6+i++}),r.add(s),e.setPathInfo(s,"prop","watch")}n.length>0&&(!function(e,t){let n=Df.get(e);void 0===n&&(n=new Map,Df.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)}}(e,n),e.addVolumeWatchPaths?.(r),Yh(e))}const r=n[X];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(_u(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[j];"function"==typeof i&&(!function(e,t){let n=Eu.get(e);void 0===n&&(n=[],Eu.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.`)}function dp(e,t,n,o=[]){!function(e,t,n,o){for(const e of o){const o=e.innerSegments[0],s=Object.getOwnPropertyDescriptor(n,o);void 0===s||"function"!=typeof s.get&&"function"!=typeof s.set&&"function"!=typeof s.value||se(`Volume "${t}" declares "${o}" as an accessor or a method and also injects it ("${A}.${o}: ${e.outerPathInfo.path}"). Rename one of them.`)}const s=n[U];if(void 0!==s){"object"==typeof s&&null!==s||se(`${U} must be an object mapping state paths to handler functions.`);for(const[e,t]of Object.entries(s))"function"!=typeof t&&se(`${U} entry "${e}" must be a function.`),Uf(e)}const r=n[X];if(void 0!==r){"object"==typeof r&&null!==r||se(`${X} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(r)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&se(`${X} entry "${n}" must map a list path to a field name or a key function.`);const r=_u(t,o,n,!1);e.listKeys?.has(r)&&se(`${X} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n.$streams&&se(`Volume "${t}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&se(`Volume "${t}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[K]&&se(`Volume "${t}" declares ${K}, 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(yc(n)))-1!==e.indexOf(J)&&se(`Volume "${t}" declares "${e}", which uses "${J}". 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(Object.getOwnPropertyDescriptors(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=ae(t),a=!0===e.hydratedFromSsr;e.createState("writable",e=>{if(1===i.segments.length&&t in e){if(a)return;se(`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;se(`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=Nu.get(e);void 0===n&&(n=new Set,Nu.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(Cu(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(Cu(t,this,o),e)}),e.defineTreeAccessor(r,l)}cp(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(Cu(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 up(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=dp(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 fp=!1;function hp(){var e;fp||(fp=!0,Zu||(Zu=!0,ul("scopes",Qu)),af||(af=!0,pc("scopes",rf)),_f(),Lu=up,e=pp,va.includes(e)||va.push(e))}function pp(e,t){(function(e){const t=Pu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){Ru.delete(e);const n=Ou.get(e);if(void 0===n||0===n.length||null===Lu)return;Ou.delete(e);const o=Lu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const gp={name:"scopes",install(){hp(),Su||(Su=!0,pc("dcc",xu))}},mp=/^@@wcs-(?:for|if|elseif|else):[^-]/,yp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,wp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,bp=/^@@wcs-text-start:(.+)$/;function vp(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class $p extends mc{_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=nd.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=o.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){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=vp(JSON.stringify(t)),e.appendChild(n);const s=Array.from(Aa.keys());for(const t of s){const n=ka(t);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",t);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),e.appendChild(s)}const r=Array.from(ki);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=Ni(n);if(0===o.length)continue;const s=`wcs-ssr-${e}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const e of o)i[e.propName]=e.value;t[s]=i}if(Object.keys(t).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=vp(JSON.stringify(t)),e.appendChild(n)}}ki.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(yp.test(e.data)||wp.test(e.data))&&n.push(e)}for(const e of n)e.remove()}static removeStructuralComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;mp.test(e.data)&&n.push(e)}for(const e of n)e.remove()}static restoreTextBindings(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode,o=bp.exec(e.data);o&&n.push({comment:e,path:o[1]})}for(const{comment:e,path:t}of n){const n=document.createComment(`@@: ${t}`);e.parentNode.insertBefore(n,e);let o=e.nextSibling;e.remove();const s=`@@wcs-text-end:${t}`;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(o.tagNames.ssr),s=new Map;for(const e of n){const t=e.querySelectorAll("template[id]");for(const e of t){const t=e.getAttribute("id");t&&s.set(t,e)}}const r=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const e=r.currentNode;yp.test(e.data)&&i.push(e)}for(const e of i){const t=yp.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()}$p.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(mp.test(e.data)){const t=e.data.split(":")[1];l.push({comment:e,uuid:t})}}for(const{comment:e,uuid:t}of l){const n=s.get(t);if(n){const t=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&t.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)t.content.appendChild(r);else for(const e of Array.from(n.childNodes))t.content.appendChild(document.importNode(e,!0));e.parentNode.replaceChild(t,e)}}const c=e.querySelectorAll("[data-wcs-ssr-id]");for(const e of c)e.removeAttribute("data-wcs-ssr-id");for(const e of n)e.remove()}}const xp={protocol:"wcs-ssr-snapshot",version:1,build:function(e){const t=o.tagNames.state,n=o.tagNames.ssr,s=e.querySelectorAll(`${t}[enable-ssr]:not([mount]):not([bind-component])`);for(const e of s){const t=e.previousElementSibling;if(null!==t&&t.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",nd),$p.buildContent(o,$p.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const Sp=new Set(["for","if","elseif","else"]);function Pp(e){const t=new fs;if(0===e.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:t};const n=e[0].parentNode,o=e[e.length-1].nextSibling,s=document.createElement("div");for(const t of e)s.appendChild(t);const[r,i]=pt(s),a=t.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:t}}function Ip(e,t,n){for(const o of t)"event"===o.bindingType||Sp.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in M||ae(o.statePathName).wildcardCount>n||e.push(o)}function Ap(e,t,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[t];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const e=i.currentNode;if(e.data===r)return e}return null}function Np(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Oe(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,Ca()],bindingType:"else"}),"if"===i||"elseif"===i?s=t:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?t.statePathName:void 0;Ba(a),"string"==typeof l&&La(a,l),Ha(n,a,l);Na(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Da(a)})}}const kp={hydrate:async function(e){await ua(e);const t=e.querySelectorAll(o.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="${nd}". Falling back to full render.`),$p.cleanupDom(e),!1}for(const n of t)Np(e,n);const n=function(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const e of o){const n=yp.exec(e.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let d=e.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.nextSibling;t.push({type:o,uuid:i,path:a,index:l,nodes:c})}return t}(document.body),s=function(e,t){const n=new Map,o=[];for(const s of t){if(0===s.nodes.length)continue;const t=ri(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=Pp(s.nodes);Lr(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");$s(t,r),Br(t,i);const l=[];for(const e of r)e.statePathName in M&&l.push(e);if(Ps(t,l),"for"===s.type&&null!==s.index){const i=Ap(e,"for",s.uuid);if(i){const e=Cs(null,s.index);mi(i,e,t),yi(i,s.nodes[s.nodes.length-1]),Yr(i,t);const l=ae(s.path+"."+d);zr(t,bn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ip(o,r,l.wildcardCount);let c=n.get(s.uuid);c||(c=[],n.set(s.uuid,c)),c.push(e)}}else{const n=Ap(e,s.type,s.uuid);n&&(Yr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Ip(o,r,0))}}for(const[t,o]of n){const n=Ap(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=ka(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=$a(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&Fs(t,o)})}return o}(document.body,n);$p.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());$p.restoreTextBindings(document.body);const[i,a]=pt(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||(vt(e,null),t.setAttribute("data-wcs-completed",""))}else vt(e,null);const l=[],c=[],u=hs(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(Sp.has(e.bindingType))c.push(e);else{if(e.statePathName.includes(d))continue;l.push(e)}for(const e of c)if("for"===e.bindingType){const t=cn(e),n=$a(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(Pt(t,o),Tt(t,o))})}la([...l,...s]);for(const{el:e,parent:t,next:n}of r)t.insertBefore(e,n);const f=e.querySelectorAll(o.tagNames.ssr);for(const t of f){const n=t.hydrateProps;for(const[t,o]of Object.entries(n)){const n=e.querySelector(`[data-wcs-ssr-id="${t}"]`);if(n)for(const[e,t]of Object.entries(o))n[e]=t}}const h=e.querySelectorAll("[data-wcs-completed]");for(const e of h)e.removeAttribute("data-wcs-completed");return!0},loadState(e){const t=e.parentNode;if(!t)return null;const n=$p.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await xa(e.rootNode);const t=$p.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",nd),$p.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let _p=!1;function Tp(){var t;_p||(_p=!0,ga=kp,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,$p)},xc.includes(t)||xc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=xp)}())}const Cp={name:"ssr",install(){Tp()}},Ep="[wcs/scan-declaration-invalid]",Mp=Object.freeze([]);function Op(e){return`${G} entry "${e}"`}function Rp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function jp(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.${ue}`}function Lp(e,t,n){0===n.length&&se(`${Ep} ${e} "${t}" must be a non-empty state path.${ue}`),n.startsWith("$")&&se(`${Ep} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ue}`),n.includes("@")&&se(`${Ep} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ue}`),n in Object.prototype&&se(`${Ep} ${e} ${t} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ue}`);const o=ae(n);for(const s of o.segments)0===s.length&&se(`${Ep} ${e} ${t} "${n}" has an empty path segment.${ue}`);return o.wildcardCount>u&&se(`${Ep} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Wp(e,t,n,o){const s=Op(e);0===e.length&&se(`${Ep} ${G} entry name must be a non-empty string.${ue}`),(e.includes(c)||e.includes(d))&&se(`${Ep} ${s} must be a flat property name ("${c}" and "${d}" are not allowed). The output is a property the runtime owns.${ue}`),e.startsWith("$")&&se(`${Ep} ${s} must not start with "$" (reserved namespace).${ue}`),e in Object.prototype&&se(`${Ep} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ue}`),t.has(e)&&se(`${Ep} ${s} conflicts with a getter declared on the state.${ue}`),n.has(e)&&se(`${Ep} ${s} conflicts with a setter declared on the state.${ue}`),o.has(e)&&se(`${Ep} ${s} conflicts with the ${H} entry of the same name — each output has exactly one owner.${ue}`)}function Dp(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Ch.get(t)?.has(e)}(e,o)&&se(`${Ep} ${Op(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ue}`)}function Bp(e,t,n,o,s,r){const i=Op(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&se(`${Ep} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${ue}`),l){const e=t.on;return"string"==typeof e&&0!==e.length||se(`${Ep} ${i} "on" must be a non-empty event-token name.${ue}`),n.has(e)||se(`${Ep} ${i} on "${e}" is not declared in ${q}.${de(e,n)}${ue}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&se(`${Ep} ${i} "from" must be a state path string.${ue}`);const u=Lp(i,"from",d),f=Rp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&se(jp(i,"from",d,f));const h=Rp(u,s);return null!==h&&se(function(e,t,n){return`${Ep} ${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.${ue}`}(i,d,h)),(d===e||d.startsWith(e+c))&&se(`${Ep} ${i} from "${d}" reads the entry's own output — the scan would fold its own writes forever.${ue}`),{kind:"path",path:d,pathInfo:u}}function zp(e,t,n,o){if(void 0===t)return Mp;const s=Op(e);Array.isArray(t)||se(`${Ep} ${s} "resetOn" must be an array of state paths.${ue}`);const r=[];for(const e of t){"string"!=typeof e&&se(`${Ep} ${s} "resetOn" must contain only state path strings.${ue}`);const t=Lp(s,"resetOn",e);t.wildcardCount>0&&se(`${Ep} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${ue}`);const i=Rp(t,o);null!==i&&se(jp(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&se(`${Ep} ${s} resetOn "${e}" is the entry's own "from" — every change would reset instead of fold.${ue}`),"path"===n.kind&&e.startsWith(n.path+c)&&se(`${Ep} ${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.${ue}`),r.push(e)}return r}function Fp(e,t,n=null){const o=e[G];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&se(`${Ep} ${G} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${ue}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[t,n]of Object.entries(yc(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){const t=e[H];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)){Wp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&se(`${Ep} ${Op(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ue}`);const o=u;Dp(e,a,o);const f=Bp(e,o,t,s,i,n);"initial"in o||se(`${Ep} ${Op(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ue}`),"function"!=typeof o.fold&&se(`${Ep} ${Op(e)} fold must be a function.${ue}`);const h=zp(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=ae(e).segments[0];t.has(n)&&se(`${Ep} ${Op(o.name)} resetOn "${e}" reads the ${G} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${ue}`)}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&&se(`${Ep} ${G} entries ${[...o,e].map(e=>`"${e}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${ue}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}function qp(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 wh.has(e)}(e),l=a&&!Th(n,e.initial)?kh(e.initial):n,c=t(l,o,...s);if(Lh(c))return void Wh(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Eh(e.name,c)),a&&Sh(e)}catch(t){jh(e.name,t,i)}}}function Vp(e,t,n){const o=function(e,t){jf(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Of(n,e.source.path,e);for(const t of e.resetOn)Of(o,t,e),"event"===e.source.kind&&Of(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return Tf.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)&&nr().hasQueuedPath(e,n))&&xh(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 Hp="scanEntries",Up={order:8,validate(e,t,n){const o=Fp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Hp,o)},applyEarly(e,t,n){const o=n.get(Hp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=kh(n.initial);e[n.name]=t,Eh(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&On(e,n.source.tokenName).subscribe(qp(n))}(e,o))},register(e,t,n){const o=n.get(Hp)??null,s=function(e){const t=new Map,n=Rf(e);if(void 0!==n)for(const e of n.entries)Sh(e)&&t.set(e.name,e.resetOn);return jf(e),t}(e);e.setScanPaths?.(null===o?null:Vp(e,o,s))}};let Gp=!1;const Kp=Object.freeze([]),Jp=Object.freeze([]);function Xp(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??Kp,i=e.dynamicDependency.get(n)??Kp,a=t.byFromPath.get(n)??Jp;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const Yp=(e,t)=>t,Qp=new Set;function Zp(e,t){const n=t[H];if(void 0===n)return void hh(e,Qp);"object"==typeof n&&null!==n||se(`${H} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&se(`${H} entry name must be a non-empty string.`),s.includes(c)&&se(`${H} entry "${s}" must be a flat property name ("${c}" is not allowed).`),s.includes(d)&&se(`${H} entry "${s}" must be a flat property name ("${d}" is not allowed).`),s.startsWith("$")&&se(`${H} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&se(`${H} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),e.getterPaths.has(s)&&se(`${H} entry "${s}" conflicts with a getter declared on the state.`),e.setterPaths.has(s)&&se(`${H} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||se(`${H} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&se(`${H} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&se(`${H} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&se(`${H} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`);void 0!==n.args&&"function"!=typeof n.args&&se(`${H} entry "${s}" args must be a function.`);const a={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??Yp,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in t||(t[s]=a.definition.initial),o.set(s,a)}!function(e,t){gh.set(e,t)}(e,o),hh(e,new Set(o.keys()))}const eg=new WeakMap,tg=new WeakMap;function ng(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=mh(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&mh(e).has(n),ownKeys:()=>Array.from(mh(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=mh(e).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){se(`${t} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){se(`${t} namespace is read-only; deleting from it is not allowed.`)}})}function og(e){const t=eg.get(e);if(void 0!==t)return t;const n=ng(e,Y,e=>e.status);return eg.set(e,n),n}function sg(e){const t=tg.get(e);if(void 0!==t)return t;const n=ng(e,Q,e=>e.error);return tg.set(e,n),n}function rg(e){eg.delete(e),tg.delete(e)}let ig=null;function ag(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 lg={read(e,t){!function(e,t){null!==ig&&ig.add(Jt(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===Y?ag(og(e),t.pathInfo.segments):n===Q?ag(sg(e),t.pathInfo.segments):ll},get:(e,t)=>t===Y?og(e.stateElement):t===Q?sg(e.stateElement):ll};async function cg(e,t,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await 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] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();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",i)}}function dg(e){yg();const t=mh(e);if(0!==t.size){!function(e){lh.add(e)}(e);for(const n of t.values())ug(e,n)}}function ug(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=ig,s=new Set;let r;ig=s;try{e.createState("readonly",e=>{r=n(e)})}finally{ig=o}r instanceof Promise&&se(`${H} entry "${t.name}" args must be synchronous (it returned a Promise).`);const i=`${Y}${c}${t.name}`,a=`${Q}${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||se(`${H} 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&&se(`${H} 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=Rf(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=Xp(e,n,o.name);for(const e of t.depAddresses){const n=e.absolutePathInfo.pathInfo.path;s.has(n)&&se(`[wcs/scan-feedback-loop] ${H} entry "${t.name}" args read "${n}", which is derived from the ${G} 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}),fg(e,t,"active",null);const s=t.definition,r={fold(n){e.createState("writable",e=>{e[t.name]=s.fold(e[t.name],n)})},done(){fg(e,t,"done",null)},fail(o){fg(e,t,"error",o),n.abort()}};cg(s.source,o,n.signal,r)}function fg(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return fh.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=fh.get(e);void 0===s&&(s=new Map,fh.set(e,s)),s.set(t,{status:n,error:o})}(e,t.name,n,o),e.createState("writable",e=>{r&&e.$postUpdate(`${Y}${c}${t.name}`),i&&e.$postUpdate(`${Q}${c}${t.name}`)}))}function hg(e){const t=dh();if(0===t.size)return;const n=[];for(const o of t)for(const t of mh(o).values())for(const s of t.depAddresses)if(e.has(s)){n.push({stateElement:o,entry:t});break}for(const{stateElement:e,entry:o}of n)if(t.has(e)&&mh(e).get(o.name)===o)try{ug(e,o)}catch(n){o.controller?.abort(),t.has(e)&&mh(e).get(o.name)===o&&fg(e,o,"error",n)}}let pg=!1;const gg=new WeakMap,mg={order:20,apply(e,t){var n;rg(e),yh(n=e),ch(n),gh.delete(n),Zp(e,t),void 0!==t[H]&&e.attachAddressHooks?.("streams",H)},activate(e,n){if(!t()&&null!=e.connectedRootNode){if(null===n){if(!0!==e.initialized)return;return dg(e),void gg.set(e,e.connectGeneration??0)}n===e.connectGeneration&&gg.get(e)!==n&&dg(e)}},deactivate(e){yh(e),rg(e)}};function yg(){pg||(pg=!0,ul("streams",lg),gl("streams",mg),Qs(hg,20))}const wg=[jd,{name:"temporal",install(){ip(),Gp||(Gp=!0,gl("scan",Up),Ys($h)),yg()}},du,gp,Cp,pd,Id];function bg(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(wg),Ic(e,t)}function vg(e){return e}const $g={eq:{description:"等しいか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},ne:{description:"異なるか比較",hasArgs:!0,resultType:"boolean",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},not:{description:"ブール値を反転",hasArgs:!1,resultType:"boolean",acceptTypes:["boolean"],minArgs:0,maxArgs:0},lt:{description:"より小さいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},le:{description:"以下か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},gt:{description:"より大きいか",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},ge:{description:"以上か",hasArgs:!0,resultType:"boolean",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["number"]},inc:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},dec:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},mul:{description:"乗算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},div:{description:"除算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},mod:{description:"剰余",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},abs:{description:"絶対値",hasArgs:!1,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:0},clamp:{description:"範囲内に丸める (min,max)",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:2,maxArgs:2,argTypes:["number","number"]},fix:{description:"固定小数点表記",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},locale:{description:"ロケール形式で数値フォーマット",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["string"]},uc:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lc:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},cap:{description:"先頭文字を大文字に",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},trim:{description:"前後の空白を削除",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},slice:{description:"部分文字列 (start[,end])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},substr:{description:"部分文字列 (pos,len)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","number"]},pad:{description:"パディング (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},rep:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},rev:{description:"文字順を反転",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},truncate:{description:"切り詰めて省略記号 (length[,suffix])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},join:{description:"配列を連結 ([separator])",hasArgs:!0,resultType:"string",acceptTypes:["array"],minArgs:0,maxArgs:1,argTypes:["string"]},int:{description:"整数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},float:{description:"浮動小数点数にパース",hasArgs:!1,resultType:"number",acceptTypes:["string","number"],minArgs:0,maxArgs:0},round:{description:"四捨五入",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},floor:{description:"切り下げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},ceil:{description:"切り上げ",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},percent:{description:"パーセンテージ形式",hasArgs:!0,resultType:"string",acceptTypes:["number"],minArgs:0,maxArgs:1,argTypes:["number"]},unit:{description:"単位(接尾辞)を付加",hasArgs:!0,resultType:"string",acceptTypes:["number","string"],minArgs:1,maxArgs:1,argTypes:["string"]},date:{description:"ロケール形式の日付",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},time:{description:"ロケール形式の時刻",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},datetime:{description:"ロケール形式の日時",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},ymd:{description:"YYYY-MM-DD 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},hms:{description:"HH:MM:SS 形式",hasArgs:!0,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:1,argTypes:["string"]},falsy:{description:"偽値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},truthy:{description:"真値か判定",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},defaults:{description:"偽値の場合デフォルト値",hasArgs:!0,resultType:"passthrough",acceptTypes:"any",minArgs:1,maxArgs:1,argTypes:["any"]},boolean:{description:"ブール値に変換",hasArgs:!1,resultType:"boolean",acceptTypes:"any",minArgs:0,maxArgs:0},number:{description:"数値に変換",hasArgs:!1,resultType:"number",acceptTypes:"any",minArgs:0,maxArgs:0},string:{description:"文字列に変換",hasArgs:!1,resultType:"string",acceptTypes:"any",minArgs:0,maxArgs:0},null:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},xg=1;function Sg(){return{version:1,syntax:{bindAttribute:o.bindAttributeName,tagName:o.tagNames.state,pathDelimiter:c,wildcard:d,delimiters:{binding:";",propValue:":",modifier:h,filter:p},structuralDirectives:Array.from(fe),modifiers:{flags:w,keyValue:$,eventNamePrefix:P},indexParam:{prefix:C,maxDepth:u},bindingTypes:{elseKeyword:x,spread:S,eventPropertyPrefix:P,explicitPropertyPrefix:c,propNamespaces:{eventToken:I,command:N,class:k,attr:_,style:T}}},filters:Object.keys(Md),filterMeta:$g,reservedLifecycle:[O,R,j,L,W],reservedStateApi:[D,B,z,F,q,V,H,U,G,X,K,Y,Q]}}const Pg=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),Ig=Object.freeze([]);function Ag(e){if(!o.enableContractAnalyzer)return Ig;const t=[];return function(e,t,n){const o=e.manifestExtensions;if(null===o||"object"!=typeof o)return;for(const e of Object.keys(o))Pg.has(e)||n({type:"contract:unsupported-extension",namespace:e});const s=o["wcstack.types"]?.components;if(null==s)return;for(const[e,o]of Object.entries(s)){const s=t(e);n({type:"contract:manifest-read",tag:e,loaded:null!==s}),null!==s?Ng(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,kg,e=>{t.push(e),null!==$t&&$t(e)}),t}function Ng(e,t,n,o){const s=null!==t&&"object"==typeof t?t:{};for(const[t,r]of Object.entries(s.observables??{})){if(!n.propertyEvents.has(t)){o({type:"contract:drift",reason:"missing-member",tag:e,member:t});continue}const s=n.propertyEvents.get(t),i=r?.event;"string"==typeof i&&i!==s&&o({type:"contract:drift",reason:"event-mismatch",tag:e,member:t,sidecarEvent:i,liveEvent:s})}for(const t of Object.keys(s.inputs??{}))n.inputs.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t});for(const t of Object.keys(s.commands??{}))n.commands.has(t)||o({type:"contract:drift",reason:"missing-member",tag:e,member:t})}function kg(e){const t=Ke(),n=t?.get(e);if(void 0===n)return null;const o=n.wcBindable;if(null===o||"object"!=typeof o||"wc-bindable"!==o.protocol)return null;const s=o,r=new Map;for(const e of Array.isArray(s.properties)?s.properties:[])"string"==typeof e?.name&&"string"==typeof e.event&&r.set(e.name,e.event);const i=new Set;for(const e of Array.isArray(s.inputs)?s.inputs:[])"string"==typeof e?.name&&i.add(e.name);const a=new Set;for(const e of Array.isArray(s.commands)?s.commands:[])"string"==typeof e?.name&&a.add(e.name);return{propertyEvents:r,inputs:i,commands:a}}export{$p as Ssr,_i as TRUSTED_TYPES_POLICY_SLOT,nd as VERSION,xg as WCS_MANIFEST_VERSION,Ag as analyzeContract,bg as bootstrapState,fa as buildBindings,$g as builtinFilterMeta,vg as defineState,xa as getBindingsReady,s as getConfig,Ti as getTrustedTypesPolicy,Sg as getWcsManifest,Ci as setTrustedTypesPolicy};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|