@wcstack/state 3.1.0 → 3.2.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 -17
- package/README.md +25 -17
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/define.d.ts +11 -7
- package/dist/index.d.ts +13 -7
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/manifest.d.ts +12 -1
- package/dist/manifest.esm.js +90 -35
- package/dist/split/chunks/declarationAliases.js +2 -0
- package/dist/split/chunks/declarationAliases.js.map +1 -0
- package/dist/split/chunks/filterRegistry.js +1 -1
- package/dist/split/chunks/filterRegistry.js.map +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/registerComponents.js.map +1 -1
- package/dist/split/chunks/version.js +1 -1
- package/dist/split/core.d.ts +11 -7
- package/dist/split/core.js +1 -1
- package/dist/split/core.js.map +1 -1
- package/dist/split/features/devtools.js +1 -1
- package/dist/split/features/devtools.js.map +1 -1
- package/dist/split/features/formats.js +1 -1
- package/dist/split/features/formats.js.map +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/split/features/ssr.js.map +1 -1
- package/dist/split/features/temporal.js +1 -1
- package/dist/split/features/temporal.js.map +1 -1
- package/dist/wcs-manifest.json +64 -25
- 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="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};
|
|
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="$renderedCallback",L="$errorCallback",W="$stateReadyCallback",D="$bindables",B="$commands",z="$commandTokens",F="$command",q="$eventTokens",V="$on",H="$stream",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={input:new Map,output:new Map},ye=new Map;function we(e,t,n,o){const s=pe[e],r=ge[e];for(const e of Object.keys(t)){s.set(e,t[e]);const o=n?.[e];void 0===o?r.delete(e):r.set(e,o)}for(const t of Object.keys(o??{}))me[e].set(t,o[t]);ye.clear()}function be(e,t,n,o=t){const s=`${e}${JSON.stringify(o)}:${n}`,r=ye.get(s);if(void 0!==r)return r;const i=me[n].get(e)??e,a=pe[n].get(i)??he[i];void 0===a&&se(`[wcs/filter-unknown] filter not found: ${e}.${de(e,function(e){return[...new Set([...Object.keys(he),...pe[e].keys()])]}(n))}${ue}`);const l=ge[n].get(i);void 0!==l&&(t.length<l[0]||t.length>l[1])&&se(t.length<l[0]?`[wcs/filter-arity] filter "${e}" requires at least ${l[0]} argument(s) (${t.length} given).${ue}`:`[wcs/filter-arity] filter "${e}" accepts at most ${l[1]} argument(s) (${t.length} given).${ue}`);const c=a(t,o);return ye.set(s,c),c}function ve(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 $e=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function xe(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:$e.test(e)?Number(e):e)}function Se(e){const t=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const e=ve(o,i,a);t.push(e),n.push(xe(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=ve(o,i,a);return(c||r)&&(t.push(c),n.push(xe(c,r))),{args:t,literals:n}}function Pe(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,...Se(t.substring(n+1,o))}})}const Ie=e=>e.trim(),Ae=e=>"'"===e||'"'===e;function Ne(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(Ae(s))n=s;else if(s===t)return o}return-1}function ke(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):Ae(i)?o=i:i===t&&(n.push(e.slice(s,r)),s=r+1)}return n.push(e.slice(s)),n}const _e=new Map;function Te(e){const t=Ne(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=ke(s,p).map(Ie),r=Pe(o),_e.set(s,r))):n=e.trim();const i=n.split(h).map(Ie);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(Ie);return{propName:a,propSegments:d,propModifiers:l?l.split(",").map(Ie):[],inFilters:r}}const Ce=new Map;function Ee(e){const t=Ne(e,p);let n="",o=[],s="",r=[];-1!==t?(n=e.slice(0,t).trim(),s=e.slice(t+1).trim(),Ce.has(s)?r=Ce.get(s):(o=ke(s,p).map(Ie),r=Pe(o),Ce.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 Me=new Set([x,"if","elseif","for",S]),Oe=new Set([k,_,T,N,I]);function Re(e){const[...t]=function(e){return ke(e,";")}(e).map(Ie).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&&Me.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=Ee(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:[],...Ee(o),bindingType:n}}if("radio"===s||"checkbox"===s){const e=Ee(o);return{...Te(n),...e,bindingType:s}}{const e=Ee(o),t=Te(n);if(""===t.propSegments[0]&&t.propSegments.length>1){const o=t.propSegments.slice(1);return(o.includes("")||Oe.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 (${[...Oe].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 je=new WeakMap,Le=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),We=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function De(e){const t=je.get(e);if("string"==typeof t)return t;if(e.nodeType!==Node.COMMENT_NODE)return null;const n=e.data.trim(),s=We.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Le.has(r)?(je.set(e,s[2]),s[2]):null}function Be(e){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Ee(e),bindingType:"text"}}const ze=new WeakMap,Fe=new WeakSet;let qe=0;async function Ve(e){const t=function(e){let t,n=ze.get(e)||null;if(null!==n)return n;const o=new Promise(e=>{t=e});return n={id:++qe,promise:o,resolve:t},ze.set(e,n),Fe.has(e)&&n.resolve(),n}(e);await t.promise}function He(e){const t=ze.get(e);void 0===t?Fe.add(e):t.resolve()}const Ue=new WeakMap;function Ge(e){const t=Ue.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{Ue.set(e,n)}}function Ke(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined?null:t}function Je(e=null){if(null!=e){const{customElementRegistry:t,customElements:n}=e;if(null===t)return null;if(void 0!==t)return Ke(t);if(void 0!==n)return Ke(n)}return Ke(globalThis.customElements)}function Xe(e,t){e.upgrade?.(t)}function Ye(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=tt(s.properties,Qe);if(null===r)return null;const i=void 0===s.inputs?new Map:tt(s.inputs,Ze);if(null===i)return null;const a=void 0===s.commands?new Map:tt(s.commands,et);return null===a?null:{target:e,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Qe(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 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.attribute||"string"==typeof t.attribute)}function et(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 tt(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 nt(e,t){const n="."===t?`.${e}`:`${t}.${e}`;return{propName:e,propSegments:[e],propModifiers:[],statePathName:n,statePathInfo:ae(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ot(e){switch(e.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${e.bindingType}::${e.propName}`;default:return null}}function st(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=Ge(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=Je(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}Xe(a,t);const l=Ye(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=nt(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=nt(e,c);i.add(t),r.push(t)}}const a=new Map;for(let e=0;e<r.length;e++){const t=ot(r[e]);null!==t&&a.set(t,e)}const l=[];for(let t=0;t<r.length;t++){const n=ot(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 rt(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 it(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:be(s.filterName,s.args,t,s.literals??s.args)})}return n}const at=new WeakMap;function lt(e){return at.get(e)||null}function ct(e){if(!e.hasAttribute("bind-component"))return!1;const t=e.parentNode;return t instanceof Element&&t.hasAttribute(o.bindAttributeName)}function dt(e){const t=[],n=e.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!ct(o))continue;const n=o.parentNode;n!==e&&t.push(n)}return t}function ut(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 ft(e){const t=[],n=dt(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!==De(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();){const e=s.currentNode;n.length>0&&ut(e,n)||t.push(e)}return t}const ht=new WeakSet;function pt(e,t,n,o){const s=st(e,t,{allowDeferred:n.allowDeferred});if(s.some(e=>"spread"===e.bindingType)){const n=e.nodeType===Node.ELEMENT_NODE?Ge(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}}}ht.add(e);const r=function(e,t){const n=[];for(const o of t){const t=it(o.inFilters,"input"),s=it(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){at.set(e,t)}(e,r),He(e),{bindings:r,deferred:null}}function gt(e,t){const n=ft(e),o=[],s=[];for(const e of n){if(ht.has(e))continue;const n=pt(e,Ta(e),{allowDeferred:!0},t);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function mt(e){ht.add(e)}function yt(e){const{node:t,parseResults:n,transform:o}=e;!function(e){ht.delete(e)}(t);return pt(t,n,{allowDeferred:!1},o).bindings}const wt=new WeakMap;let bt=null;function vt(e){let t=e;for(;t;){const e=wt.get(t);if(e)return e;let n=t.parentNode;null===n&&null!==bt&&t instanceof ShadowRoot&&(n=bt(t)),t=n}return null}function $t(e,t){null!==t?wt.set(e,t):wt.delete(e)}let xt=null;const St=new WeakMap;function Pt(e){return St.get(e)??[]}function It(e,t){St.set(e,t)}function At(e){return St.has(e)}const Nt=new WeakMap;let kt=null,_t=0;function Tt(e){return Nt.get(e)??[]}function Ct(e,t){null===kt?Nt.set(e,t):kt.set(e,t)}function Et(){_t++,null===kt&&(kt=new Map)}function Mt(){if(0!==_t&&(_t--,!(_t>0||null===kt))){for(const[e,t]of kt)Nt.set(e,t);kt=null}}function Ot(e){return(kt?.has(e)??!1)||Nt.has(e)}const Rt=Symbol("$$setLoopContext"),jt=Symbol("$$getByAddress"),Lt=Symbol("$$hasByAddress"),Wt=Symbol("$$setByAddress"),Dt=Symbol("$$connectedCallback"),Bt=Symbol("$$disconnectedCallback"),zt=Symbol("$$updatedCallback"),Ft=Symbol("$$errorCallback"),qt=new WeakMap,Vt=new WeakMap;class Ht{absolutePathInfo;listIndex;constructor(e,t){this.absolutePathInfo=e,this.listIndex=t}}function Ut(e,t){if(null===t){let t=Vt.get(e);return void 0!==t||(t=new Ht(e,null),Vt.set(e,t)),t}{let n=qt.get(t);void 0===n&&(n=new WeakMap,qt.set(t,n));let o=n.get(e);return void 0!==o||(o=new Ht(e,t),n.set(e,o)),o}}const Gt=new WeakMap;function Kt(e,t){let n=Gt.get(e);void 0===n&&(n=new Map,Gt.set(e,n));let o=n.get(t);return void 0===o&&(o=Object.freeze(new Jt(e,t)),n.set(t,o)),o}class Jt{pathInfo;stateElement;constructor(e,t){this.pathInfo=t,this.stateElement=e}}function Xt(e,t){return Ut(Kt(e,t.pathInfo),t.listIndex)}function Yt(e,t,n){return Ut(Kt(e,t),n)}const Qt=new WeakMap;function Zt(e,t){null===t?Qt.delete(e):Qt.set(e,t)}function en(e){return Qt.get(e)||null}const tn=new Map;function nn(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=tn.get(s);if(void 0!==r)return r;return r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,tn.set(s,r),r}function on(e,t,n){return t<0||t>=n?null:e.at(t-n)}function sn(e,t){const n=e.indexes??[];return n.length===t?n:n.slice(n.length-t)}const rn=new WeakMap;function an(e){const t=vt(e.node);if(null===t)return null;let n=rn.get(t);if(void 0===n)n=new WeakMap,rn.set(t,n);else{const t=n.get(e);if(void 0!==t)return t}let o=null;try{const n=nn(t.pathInfo,e.statePathInfo);return n>0&&(o=on(t.listIndex,n-1,t.pathInfo.wildcardCount)),o}finally{n.set(e,o)}}const ln=new WeakMap;function cn(e,t){if(null!=t)return t;let n=e.replaceNode.getRootNode();if(!1===e.replaceNode.isConnected){const t=en(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 dn(e,t){let n=null;if(n=ln.get(e)||null,null!==n)return n;const o=cn(e,t),s=an(e),r=xa(o);return null===r&&se("No state tree found on this root for binding."),n=Yt(r,e.statePathInfo,s),ln.set(e,n),n}function un(e){ln.delete(e)}const fn=new WeakMap;function hn(e,t){const n=fn.get(e);void 0===n?fn.set(e,t):n instanceof Set?n.add(t):n!==t&&fn.set(e,new Set([n,t])),null!==xt&&xt({type:"state:binding-added",absoluteAddress:e,binding:t})}function pn(e,t){const n=fn.get(e);void 0!==n&&(n instanceof Set?n.delete(t):n===t&&fn.delete(e),null!==xt&&xt({type:"state:binding-removed",absoluteAddress:e,binding:t}))}const gn=new WeakMap;function mn(e){const t=fn.get(e);return void 0!==t?t:null!==e.listIndex?gn.get(e.absolutePathInfo)?.get(e.listIndex):void 0}const yn=new WeakMap,wn=new WeakMap;class bn{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=vn(e,t)}}function vn(e,t){if(null===t){let t=wn.get(e);return void 0!==t||(t=new bn(e,null),wn.set(e,t)),t}{let n=yn.get(t);void 0===n&&(n=new WeakMap,yn.set(t,n));let o=n.get(e);return void 0!==o||(o=new bn(e,t),n.set(e,o)),o}}const $n=new WeakMap;function xn(e){let t=null;if(t=$n.get(e)||null,null!==t)return t;if(e.statePathInfo.wildcardCount>0){const n=an(e);null===n&&se(`Cannot resolve state address for binding with wildcard statePathName "${e.statePathName}" because list index is null.`),t=vn(e.statePathInfo,n)}else t=vn(e.statePathInfo,null);return $n.set(e,t),t}function Sn(e){$n.delete(e)}function Pn(){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 In=new Map,An=Pn();function Nn(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 _n(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=kn(e),s=Nn(e,o);let r=In.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=xa(o.getRootNode());null===i&&se("No state tree found on this root for two-way binding.");const a=vt(o);i.createState("writable",e=>{e[Rt](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]:[]})})},In.set(s,r)),e.node.addEventListener(o,r),An.add(s,e),!0}var t,n;return!1}function Tn(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e.then}function Cn(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)Tn(e)&&Promise.resolve(e).catch(e=>{console.error(`[wcstack/state] ${t} rejected.`,e)})}class En{_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 Mn extends En{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==xt&&xt({type:"state:token-emit",kind:"event",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}const On=new WeakMap;function Rn(e,t){let n=On.get(e);void 0===n&&(n=new Map,On.set(e,n));let o=n.get(t);return void 0===o&&(o=new Mn(t,e),n.set(t,o)),o}const jn=new WeakMap;function Ln(e){if(e.propSegments[0]!==I)return!1;const t=e.node,n=Ge(t),o=Je(t);if(null!==n&&void 0===o?.get(n))return null===o&&se(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(jn.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===Ge(e)?null:Ye(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=xa(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=vt(t);n.createStateAsync("writable",async t=>{Cn(t[Rt](o,()=>{const s=null!==o?sn(o.listIndex,o.pathInfo.wildcardCount):[];return Rn(n,l).emit(t,e,...s)}),`$on."${l}"`)})};return t.addEventListener(a,d),jn.set(e,{eventName:a,handler:d}),!0}class Wn extends En{_stateElement;constructor(e,t){super(e),this._stateElement=t}emit(...e){return null!==xt&&xt({type:"state:token-emit",kind:"command",tokenName:this.name,args:e,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...e)}}function Dn(e){return e instanceof Wn}const Bn=new Map,zn=Pn();function Fn(e){const t=e.propModifiers.filter(e=>e===g||e===m).sort().join(",");return`${e.statePathName}::${t}`}const qn=(e,t,n)=>o=>{t.includes(g)&&o.preventDefault(),t.includes(m)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=xa(r);null===i&&se("No state tree found on this root for event handler.");const a=vt(s),l=e.startsWith(F+".");i.createStateAsync("writable",async t=>{const c=t[Rt](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?sn(a.listIndex,c):[];if(l){const s=t[jt](vn(n,null));return Dn(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])});Cn(c,`"${e}"`)})};function Vn(e){if(!e.propName.startsWith(P))return!1;const t=Fn(e);let n=Bn.get(t);void 0===n&&(n=qn(e.statePathName,e.propModifiers,e.statePathInfo),Bn.set(t,n));const o=e.propName.slice(2);return e.node.addEventListener(o,n),zn.add(t,e),!0}function Hn(e){if(!e.propName.startsWith(P))return!1;const t=Fn(e),n=Bn.get(t);if(void 0===n)return!1;const o=e.propName.slice(2);return e.node.removeEventListener(o,n),0!==zn.countOf(t)&&(zn.remove(t,e)&&Bn.delete(t),!0)}const Un=new Map,Gn=Pn();function Kn(e,t){const n=e.inFilters.map(e=>e.filterName+"("+e.args.join(",")+")").join("|");return`${e.statePathName}::${t}::${n}`}function Jn(e){let t="input";for(const n of e.propModifiers)n.startsWith(P)&&(t=n.slice(2));return t}function Xn(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const o=Jn(e),s=Kn(e,o);let r=Un.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=xa(o.getRootNode());null===r&&se("No state tree found on this root for two-way binding.");const i=vt(o);r.createState("writable",e=>{e[Rt](i,()=>{e[t]=s})})},Un.set(s,r)),e.node.addEventListener(o,r),Gn.add(s,e),!0}var t,n;return!1}const Yn=new Set(["radio","checkbox"]),Qn=new Set(["value","valueAsNumber","valueAsDate"]);function Zn(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(Yn.has(e)&&"checked"===t)return!0;if(Qn.has(t))return!0}if("select"===o&&"value"===t)return!0;if("textarea"===o&&"value"===t)return!0;const s=Ge(n);if(null!==s){const e=Je(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=Ye(n);if(o?.knownProperties.has(t))return!0}return!1}let eo=1,to=1,no=1;const oo=new WeakMap;function so(e,t,n){let o=oo.get(e);void 0===o&&(o=new Map,oo.set(e,o));const s=function(e,t){return`${t}::${e}`}(t,n);let r=o.get(s);return void 0===r&&(r=eo++,o.set(s,r)),r}function ro(e,t){return"to-element"===t?2*e:2*e+1}const io=new Set;function ao(e){return{transactionId:to++,originBindingId:e,visitedEdges:io,hop:0}}function lo(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 co=null;function uo(){return co}function fo(e,t){const n=co;co=e;try{return t()}finally{co=n}}const ho=[];let po=!1;const go=new Map,mo=Pn(),yo=new WeakMap,wo=e=>e.detail,bo=new WeakMap;function vo(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 $o(e){let t="select"===e.node.tagName.toLowerCase()?"change":"input";const n=Ge(e.node);if(null!==n){const o=Je(e.node)?.get(n);void 0===o&&se(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ye(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 xo(e){if(null!==Ge(e.node)){const t=Ye(e.node)?.knownProperties.get(e.propName);if(t)return t.getter??wo}return null}function So(e){if(null===Ge(e.node))return!1;const t=Ye(e.node)?.knownProperties.get(e.propName);return"event"===t?.semantics}const Po=(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!==wo||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=bo.get(e);void 0===r&&(r=new Set,bo.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=yo.get(a)?.get(e);if(void 0!==d)for(const e of d)e(c);let u=null;if(o.enablePropagationContext){const n=so(a,e,t),s=function(e,t){for(let n=ho.length-1;n>=0;n--){const o=ho[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!==xt&&xt({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:ro(n,"to-state"),node:a,member:e}));const r=ro(n,"to-state"),i=uo();if(null!==i&&i.visitedEdges.has(r))return void(null!==xt&&xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:e}));u=lo(i??ao(n),r)}const f=xa(a.getRootNode());null===f&&se("No state tree found on this root for two-way binding.");const h=vt(a),p=()=>{r&&(po=!0);try{f.createState("writable",e=>{e[Rt](h,()=>{e[t]=c})})}finally{r&&(po=!1)}};null!==u?fo(u,p):p()};const Io=new WeakSet;function Ao(e){Io.add(e)}function No(e){return!!Io.has(e)&&(Io.delete(e),!0)}const ko=new WeakMap;function _o(e,t){const n=ko.get(e);return!(void 0===n||n<t)&&(n===t?ko.delete(e):ko.set(e,n-t),!0)}const To=new WeakSet;function Co(e){To.add(e)}function Eo(e){return!!To.has(e)&&(To.delete(e),!0)}let Mo=0;function Oo(){Mo--}function Ro(){return Mo>0}class jo{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 Lo=new WeakMap;function Wo(e){let t=Lo.get(e);return void 0===t&&(t=new jo(e),Lo.set(e,t)),t}function Do(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 Bo(e){return e.propModifiers.some(e=>e.includes("="))}const zo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Fo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function qo(e,t){return"state"===e&&"call"===t?zo:{authority:e,syncOn:t,observable:!1,outputOnly:!1}}function Vo(e){if(!o.enableDirectionalInitialSync)return Bo(e)&&se("init=/sync= modifiers require enableDirectionalInitialSync."),zo;const t=null===(n=Do(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}".`)}(Do(e,v));if("event"===e.bindingType)return null!==t&&"none"!==t&&se("Event bindings only allow init=none."),"call"===s?Fo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(e.propSegments[0]===N)return qo("state",s);if("prop"!==e.bindingType)return null!==t&&"state"!==t&&"none"!==t&&se(`Binding type "${e.bindingType}" does not support init=${t}.`),qo(t??"state",s);const r=Ye(e.node);if(null===r)return qo(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 Ho(e,t){return"auto"!==t?t:function(e){const t=xa(e.replaceNode.getRootNode());null===t&&se("No state tree found on this root for binding.");const n=xn(e);let o=!1;return t.createState("readonly",e=>{o=e[Lt](n)}),o}(e)?"state":"element"}let Uo=0,Go=0;const Ko=["active","disposed","failed"],Jo=new WeakMap,Xo=new WeakMap,Yo=new WeakMap,Qo=new WeakMap,Zo=new WeakMap;function es(e,t){const n=Zo.get(e);void 0!==n?n!==t&&(n instanceof Set?n.add(t):Zo.set(e,new Set([n,t]))):Zo.set(e,t)}function ts(e){return Zo.has(e)}function ns(e,t){const n=Zo.get(e);if(void 0!==n)if(n instanceof Set)for(const e of Array.from(n))t(e);else t(n)}function os(e,t){if(t(e),null!==e.firstChild)for(const n of Array.from(e.childNodes))os(n,t)}function ss(e){if("object"!=typeof e||null===e)return!1;const t=e;return 9===t.nodeType||11===t.nodeType&&"host"in t}class rs{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||!_o(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)No(e)||os(e,e=>{ns(e,t=>{this.root.contains(e)||t.handleRemovedNode(e)})});for(const e of n)Eo(e)&&!Ro()||os(e,e=>{ns(e,t=>{this.root.contains(e)&&t.handleAddedNode(e,o)})});o.length>0&&ca(o)}}const is=new WeakMap;function as(e){let t=is.get(e);return void 0===t&&(t=new rs(e),is.set(e,t)),t}function ls(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 cs(e,t,n){const o=xa(cn(e,n));null===o&&se("No state tree found on this root for binding.");const s=Kt(o,e.statePathInfo);return function(e,t,n){let o=gn.get(e);void 0===o&&(o=new WeakMap,gn.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!==xt&&xt({type:"state:binding-added",absoluteAddress:Ut(e,t),binding:n})}(s,t,e),s}function ds(e,t){const n=dn(e,t);return hn(n,e),n}function us(e,t,n,o){null!==t?pn(t,e):function(e,t,n){const o=gn.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!==xt&&xt({type:"state:binding-removed",absoluteAddress:Ut(e,t),binding:n}))}(n,o,e),Sn(e),un(e)}function fs(e,t){null===e.teardowns&&(e.teardowns=new Set),e.teardowns.add(t)}class hs{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=Xo.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(ss(t)&&as(t),null===this.rowPlan)for(const n of e){const e=Xo.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 Bo(e)&&Vo(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=Xo.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:Ko[t.phases[n]],teardowns:null};const o=Xo.get(e);return o?.session===this?o:null}addTeardown(e,t){const n=Xo.get(e);return!(void 0===n||!this.isAlive(n,n.generation))&&(fs(n,t),!0)}deferUntilDefined(e,t,n,o=()=>{}){const s=Je(e);null===s&&se(`CustomElementRegistry is unavailable for <${t}>.`),this.observe(e),es(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=Wo(s).wait(t,()=>{if(a())try{Xe(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=Xo.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&&(pn(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&&(pn(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?dn(n):null;if(us(n,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null,this.registerAddress(t),null!==o){const e=dn(n);e!==o&&At(o)&&It(e,Pt(o)),e!==o&&Ot(o)&&Ct(e,Tt(o))}this.shouldApplyState(n)&&e.push(n)}return e}observe(e){const t=function(e){const t=e.getRootNode();return ss(t)?t:null}(e);null!==t&&as(t)}handleMutations(e,t,n){for(const n of t)os(n,t=>{e.contains(t)||this.handleRemovedNode(t)});const o=[];for(const t of n)os(t,t=>{e.contains(t)&&this.handleAddedNode(t,o)});o.length>0&&ca(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=Xo.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=Qo.get(t);void 0===e&&(e=ls(t),Qo.set(t,e)),n.set(e,t)}return this.knownBindingsByNode.set(e,n),n}remember(e,t){const n=e.replaceNode;es(n,this);const o=this.knownMapFor(n);let s=Qo.get(e);void 0===s&&(s=ls(e),Qo.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:++Uo,session:this,generation:++Go,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(es(r,this),this.addKnownRowBinding(r,o,e),Jo.set(o,s),n[e].isEvent){try{Vn(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=++Go,r=!0,this.rows.add(o)),o.phases[e]=0,o.flags[e]=0,s[e].isEvent){try{Vn(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=Jo.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=an(o);null!==s?(e.patternPathInfos[t]=cs(o,s,n),e.patternListIndexes[t]=s):e.addresses[t]=ds(o,n)}unregisterRowSlot(e,t){const n=e.addresses[t],o=e.patternPathInfos[t];null===n&&null===o||(us(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{Hn(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:++Uo,info:e,generation:++Go,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};Xo.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;Vn(t)?e.eventAttached=!0:t.propSegments[0]!==I?(Xn(t)&&fs(e,()=>function(e){if("radio"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=Jn(e),n=Kn(e,t),o=Un.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==Gn.countOf(n)&&(Gn.remove(n,e)&&Un.delete(n),!0))}return!1}(t)),_n(t)&&fs(e,()=>function(e){if("checkbox"===e.bindingType&&-1===e.propModifiers.indexOf(y)){const t=kn(e),n=Nn(e,t),o=In.get(n);return void 0!==o&&(e.node.removeEventListener(t,o),0!==An.countOf(n)&&(An.remove(n,e)&&In.delete(n),!0))}return!1}(t)),this.attachAfterDefinition(e,()=>{if(o.enableDirectionalInitialSync&&Zn(t.node,t.propName)&&-1===t.propModifiers.indexOf(y)){const n=function(e,t,n){let o=yo.get(e);void 0===o&&(o=new Map,yo.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&&yo.delete(e)}}(t.node,t.propName,t=>{this.isAlive(e,e.generation)&&(e.eventSequence+=1,e.hasProducerValue=!0,e.producerValue=t)});fs(e,n)}!function(e){const t=Ge(e.node);if(null!==t){const n=Je(e.node),o=n?.get(t);if(void 0===o)return void(null===n&&se(`CustomElementRegistry is unavailable for <${t}>.`))}if(Zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=$o(e),n=xo(e),o=So(e),s=vo(e,t,null!==n,o);let r=go.get(s);void 0===r&&(r=Po(e.propName,e.statePathName,e.inFilters,n,o),go.set(s,r)),e.node.addEventListener(t,r),mo.add(s,e)}}(t),e.twowayAttached=!0})):this.attachAfterDefinition(e,()=>{Ln(t)&&fs(e,()=>function(e){if(e.propSegments[0]!==I)return!1;const t=jn.get(e);return void 0!==t&&(e.node.removeEventListener(t.eventName,t.handler),jn.delete(e),!0)}(t))})}attachAfterDefinition(e,t){const n=Ge(e.info.node);if(null===n)return void t();const o=Je(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=Wo(o).wait(n,()=>{if(this.isAlive(e,s))try{Xe(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))});fs(e,r)}settleInitialRecord(e){if(o.enableDirectionalInitialSync&&!e.initialSettled&&e.options.registerAddress){e.phase="synchronizing";try{const t=Vo(e.info),n=Ho(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 Mo++;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,Oo()),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=xa(e.node.getRootNode());null===o&&se("No state tree found on this root for initial binding sync.");const s=vt(e.node);o.createState("writable",t=>{t[Rt](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=an(n);if(null!==o?(e.patternPathInfo=cs(n,o,t),e.patternListIndex=o):e.address=ds(n,t),!e.options.registerPathInfo)return;const s=xa(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&&Xo.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,Oo());const t=e.info;if(null!==e.address||null!==e.patternListIndex)try{us(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=Ge(e.node);if(null!==t){const n=Je(e.node),o=n?.get(t);if(void 0===o)return}if(Zn(e.node,e.propName)&&-1===e.propModifiers.indexOf(y)){const t=$o(e),n=vo(e,t,null!==xo(e),So(e)),o=go.get(n);if(void 0===o)return;e.node.removeEventListener(t,o),mo.remove(n,e)&&go.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{Hn(t)}catch{}}}}function ps(e){let t=Yo.get(e);return void 0===t&&(t=new hs(e),Yo.set(e,t)),t}function gs(e){return Xo.get(e)?.session??Jo.get(e)?.session??null}let ms=null;function ys(e,t){let n=e;for(const e of t)n=e.filterFn(n);return n}const ws=Object.freeze([]);const bs=new WeakMap;const vs=new WeakMap;function $s(e){return vs.get(e)??[]}function xs(e,t){vs.set(e,t)}const Ss=new WeakMap;function Ps(e){return Ss.get(e)??[]}function Is(e,t){Ss.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 As=0;function Ns(){return`u${(As++).toString(36)}`}let ks=0,_s=0;const Ts=Symbol("wcs.listIndex.noValue");class Cs{uuid=Ns();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=Ts,this._index=t,this._version=ks,this._chainGeneration=_s}get index(){return this._index}set index(e){this._index=e,this._version=++ks,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=ks),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===_s||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=_s),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(e){this.parentListIndex=e,this._indexes=void 0,this._listIndexes=void 0,this._version=++ks,_s++}at(e){return e>=0?this.listIndexes[e]?.deref()||null:this.listIndexes[this.listIndexes.length+e]?.deref()||null}}function Es(e,t,n=e){return new Cs(e,t,n)}function Ms(e,t){e.reparent(t)}function Os(e){return e.homeParentListIndex}function Rs(e,t){e.value=t}function js(e,t){const n=e.value;return n!==Ts&&n===t.value}const Ls=new WeakMap,Ws=new WeakSet;function Ds(e){return Ws.has(e)}function Bs(e,t){const n=Os(e),o=e.parentListIndex;return null===n||n===o||Ws.has(n)?function(e,t,n){return null!==e&&null!==n&&n!==t&&!!Ws.has(e)&&!Ws.has(n)&&n.position===e.position&&js(n,e)}(n,o,t)||function(e,t){return e!==t&&null!==e&&null!==t&&e.position===t.position&&Ws.has(e)&&!Ws.has(t)}(o,t)?t:null:n}function zs(e){const t=Ls.get(e);return void 0===t?null:t}function Fs(e,t){const n=Ls.get(e);if(void 0===n)return null;const o=n[0];if(void 0!==o){const e=Bs(o,t);if(null!==e)for(const t of n)Ms(t,e)}return n}function qs(e,t){null!==t?Ls.set(e,t):Ls.delete(e)}const Vs=new WeakMap;function Hs(e,t){null===t?Vs.delete(e):Vs.set(e,t)}function Us(e){const t=Vs.get(e);t&&(t.dirty=!0)}const Gs=Symbol.for("wcstack.transition-runner");function Ks(e){const t=globalThis[Gs];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 Js(e,t,n){const o=Ks(e);if(null!==o)return o.run(t,{source:e,types:n});t()}const Xs=[],Ys=[];function Qs(e){Ys.includes(e)||Ys.push(e)}function Zs(e,t=0){const n=Xs.findIndex(e=>e.priority>t),o={listener:e,priority:t};-1===n?Xs.push(o):Xs.splice(n,0,o)}function er(e){queueMicrotask(()=>{throw e})}class tr{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(e,t=null){for(let t=0;t<Ys.length;t++)Ys[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(){Et(),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!==xt&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&xt({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!==xt&&xt({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop}));const n=mn(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?ca(r,i):ca(r)};if(t()||0===r.length)e();else{const t=Js("state",e);void 0!==t&&t.catch(er)}}finally{Mt(),function(e){for(const t of Xs.slice())t.listener(e)}(s)}}}const nr=new tr;function or(){return nr}const sr=new WeakMap,rr=new WeakMap,ir=new WeakMap,ar=new WeakMap;let lr=!1;const cr=new WeakMap,dr=new WeakMap,ur=new WeakMap,fr=[];function hr(e,t){const n=pr(e);if(n.recorded.has(t))return;n.recorded.add(t);const o=ae(t).cumulativePaths;if(o.length<2)return;let s=ur.get(e);void 0===s&&ur.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 pr(e){let t=sr.get(e);return void 0===t&&sr.set(e,t={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),t}function gr(e,t,n){let o=e.get(t);void 0===o&&e.set(t,o=new Set),o.add(n)}function mr(e,t,n){const o=e.get(t);o.delete(n),0===o.size&&e.delete(t)}function yr(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=rr.get(o);if(void 0===r&&rr.set(o,r=new Map),r.has(t)){const e=r.get(t);return Object.is(e,n)||(mr(s,e,o),r.set(t,n),gr(s,n,o)),!1}return r.set(t,n),gr(s,n,o),!0}function wr(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function br(e,t,n,o,s,r){e.lastValue.set(t,n),s&&(null!==o.listIndex&&wr(ir,o.listIndex,r),null!==r.levelListIndex&&wr(ar,r.levelListIndex,r))}function vr(e,t,n,o,s){lr=!0;const r=pr(e);hr(e,t);br(r,t,s,o,yr(r,t,n,o),{stateElement:e,path:t,absAddress:o,levelListIndex:null})}function $r(e,t){pr(e).tracked.add(t)}function xr(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(Xt(e.stateElement,vn(t,o)))}function Sr(e,t){if(void 0!==e)for(const n of e)t.push(n)}function Pr(e,t,n,o,s){const r=sr.get(e),i=r?.byPath.get(t),a=cr.get(e)?.get(t);if(void 0===r||void 0===i&&void 0===a)return fr;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&&Sr(i.get(o),d),f&&Sr(i.get(c),d),u&&Sr(i.get(s),d)),void 0!==a)for(const e of a)n&&xr(e,o,d),f&&xr(e,c,d),u&&xr(e,s,d);return d}function Ir(e,t){let n=e;for(const e of t){if("object"!=typeof n||null===n)return;n=n[e]}return n}function Ar(e,t,n){const o=sr.get(e).byPath.get(t);if(void 0!==o)for(const e of o.values())Sr(e,n);const s=cr.get(e)?.get(t);if(void 0!==s)for(const e of s)for(let t=0;t<e.indexes.length;t++)xr(e,t,n)}function Nr(e){const t=ar.get(e.levelListIndex),n=t.indexOf(e);t.splice(n,1)}function kr(e){if(!lr)return;const t=ir.get(e);if(void 0!==t){ir.delete(e);for(const e of t){const{stateElement:t,path:n,absAddress:o}=e,s=rr.get(o),r=s.get(n);s.delete(n),mr(sr.get(t).byPath.get(n),r,o),null!==e.levelListIndex&&Nr(e)}}}function _r(e,t,n){if(!lr)return;const o=ar.get(e);if(void 0!==o)for(const{stateElement:e,path:s,absAddress:r}of o){const o=sr.get(e),i=o.byPath.get(s);mr(i,t,r),gr(i,n,r),rr.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,t)||Object.is(a,n))&&(Us(r),or().enqueueAbsoluteAddress(r,null))}}const Tr=new WeakMap,Cr=Object.freeze([]),Er=new Set;function Mr(e,t,n){const o=function(e,t,n){const o=Array.isArray(t)&&t.length>0?t:Cr,s=Array.isArray(n)&&n.length>0?n:Cr,r=function(e,t){const n=Array.isArray(e)&&e.length>0?e:Cr,o=Array.isArray(t)&&t.length>0?t:Cr;let s=Tr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Fs(o,e)||[],a=i.length>0?Os(i[0]):e;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:Er,deleteIndexSet:new Set(i),addIndexSet:Er};let t=Fs(s,e);if(0===o.length){if(null===t){t=[];for(let n=0;n<s.length;n++){const o=Es(e,n,a);t.push(o)}}return l={oldIndexes:i,newIndexes:t,changeIndexSet:Er,deleteIndexSet:Er,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:Er,deleteIndexSet:Er,addIndexSet:Er};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=Es(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=Tr.get(e);o||(o=new WeakMap,Tr.set(e,o)),o.set(t,n)}(o,s,l),qs(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,_r(e[n],t,n)}Rs(e[n],t[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Cr),function(e){for(const t of e)Ws.add(t)}(o.deleteIndexSet);for(const e of o.deleteIndexSet)kr(e);return function(e){for(const t of e)Ws.delete(t)}(o.newIndexes),function(e,t){if(!lr||e===t)return;const n=dr.get(e);if(void 0===n)return;dr.delete(e);const o=dr.get(t);dr.set(t,void 0===o?n:o.concat(n));for(const o of n){o.indexes=t;const n=pr(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&&!Ds(e))for(const t of o.getters){const n=Xt(o.stateElement,vn(t,e));Us(n),or().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}function Or(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 Rr=new WeakSet;const jr=new WeakMap;function Lr(e){return jr.get(e)??null}function Wr(e,t){jr.set(e,t)}const Dr=new WeakMap;function Br(e){return Dr.get(e)??[]}function zr(e,t){Dr.set(e,t)}function Fr(e,t){const n=Br(e);for(const e of n)$t(e,t)}const qr=new WeakMap;const Vr=new WeakMap;function Hr(e,t){for(let n=0;n<e.length;n++)if(t.has(e[n]))return!0;return!1}function Ur(e,t,n,o,s){const r=function(e,t,n){let o=Vr.get(e);void 0===o&&Vr.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||Hr(d.prefixes,i)){aa(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[jt](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]]}ia(c,s,f)}}function Gr(e,t,n){Fr(e,t);const o=$s(e),s=Lr(e);if(null!==s&&(s.activate(o,n.rootNode),null!==t&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(e){return qr.get(e)??null}(e);if(null!==r)return void Ur(r,o,s,t,n)}for(const e of o){if(null===s){hn(dn(e),e)}(null===s||s.shouldApplyState(e))&&aa(e,n)}}function Kr(e){if(!e.mounted)return;const t=$s(e),n=Lr(e);for(let e=0;e<t.length;e++){const o=t[e];if(null!==n)n.disposeBinding(o);else{pn(dn(o),o)}}!function(e){const t=Br(e);for(let e=0;e<t.length;e++)$t(t[e],null)}(e)}function Jr(){return Object.freeze(new Set)}const Xr=new WeakMap,Yr=Jr();function Qr(e,t){const n=Xr.get(e);n?n.add(t):Xr.set(e,new Set([t]))}function Zr(e){const t=Xr.get(e);return void 0!==t?t:Yr}function ei(e,t){const n=Xr.get(e);n&&(n.delete(t),0===n.size&&Xr.delete(e))}function ti(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:be(s.filterName,s.args,t,s.literals??s.args)})}return n}function ni(e){return{...e,inFilters:ti(e.inFilters,"input"),outFilters:ti(e.outFilters,"output")}}const oi=new Set(["if","elseif","else","for"]);class si{_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];Co(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){Co(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=Lr(this);if(null===e||!e.canWholesaleDestroy())return!1;e.destroyRow($s(this));const t=this._childNodeArray;for(let e=0;e<t.length;e++){const n=t[e];null!==n.parentNode&&(Ao(n),n.parentNode.removeChild(n))}const n=$s(this);for(let e=0;e<n.length;e++){const t=n[e];oi.has(t.bindingType)&&Zr(t.node).forEach(e=>{e.tryDestroy()||e.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const e=Lr(this);null!==e&&(e.isRowSession?e.disposeBindings($s(this)):e.dispose())}this._teardownBindings()}_teardownBindings(){const e=$s(this);for(let t=0;t<e.length;t++){const n=e[t];oi.has(n.bindingType)&&Zr(n.node).forEach(e=>{e.unmount()}),Sn(n),un(n)}}unmount(){{const e=Lr(this);null!==e&&(e.isRowSession?e.disposeBindings($s(this)):e.dispose())}for(const e of this._childNodeArray)null!==e.parentNode&&(Ao(e),e.parentNode.removeChild(e));const e=$s(this);for(let t=0;t<e.length;t++){const n=e[t];oi.has(n.bindingType)&&Zr(n.node).forEach(e=>{e.unmount()}),Sn(n),un(n)}this._mounted=!1}}function ri(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 ii(e){const t=document.createDocumentFragment(),n=new si(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 ai(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=rt(o,s[e].nodePath);null===t&&se(`Node not found by path [${s[e].nodePath.join(", ")}] in fragment.`),mt(t),He(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=ua.get(n);void 0!==o&&o.currentRowPlan===e||(o=new hs,ua.set(n,o));return o.initializeRow(e,t),o}(n,a,e.node),d=new si(o);return Wr(d,c),xs(d,a),function(e,t){qr.set(e,t)}(d,n),Is(d,l),zr(d,r),Qr(e.node,d),d}function li(e){void 0!==e.uuid&&null!==e.uuid||se("BindingInfo.uuid is null.");const n=_a(e.uuid);n||se(`Fragment with UUID "${e.uuid}" not found.`);const s=!t()&&ri(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=rt(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!==Ge(r))return null;if("prop"===o&&Zn(r,e.propName))return null;const i=ni(e);let a;try{a=Vo({...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 ai(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=rt(e,s.nodePath);if(null===t&&se(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),ht.has(t))continue;const r=pt(t,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(t)}return[n,o]}(e,t),s=new hs,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 si(i,s);Wr(l,a.bindingSession),xs(l,a.bindingInfos);const c=[];for(const e of a.bindingInfos)e.statePathName in M&&c.push(e);return Is(l,c),zr(l,a.nodes),Qr(e.node,l),l}const ci=new WeakSet,di=Symbol.for("wcstack.state.view-transition-naming");function ui(){const e=Ks("state");return null===e||"auto"!==e.naming?null:{limit:e.namingLimit}}function fi(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||ci.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const e=globalThis;return e[di]??={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.`)):(ci.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 hi=new WeakMap,pi=new WeakMap,gi=new WeakMap,mi=new WeakMap;function yi(e,t,n){!function(e,t,n){let o=pi.get(e);if(void 0===o){if(null===n)return;o=new WeakMap,pi.set(e,o)}null===n?o.delete(t):o.set(t,n)}(e,t,n)}function wi(e,t){hi.set(e,t)}function bi(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 vi(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 $i(e,t,n){if(o=t,!Rr.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 xi=new Set(["if","elseif","else","for"]);function Si(e,t){for(const n of $s(e))if(t.appliedBindingSet.delete(n),xi.has(n.bindingType))for(const e of Zr(n.node))Si(e,t)}function Pi(e){for(const t of $s(e)){if(!xi.has(t.bindingType))continue;const e="for"===t.bindingType;for(const n of Zr(t.node))Pi(n),e&&n.mounted&&(Kr(n),n.unmount(),ei(t.node,n))}}function Ii(e){return`${e.bindingType} ${e.statePathName} ${e.outFilters.map(e=>e.filterName).join("|")} ${e.node.isConnected?"(connected)":"(disconnected)"}`}function Ai(e,n,s){const r=Boolean(s);let i;const a=Zr(e.node);i=0===a.size?li(e):a.values().next().value;const l=t(),c=e.uuid??"",d=e.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Ii(e)}`),Kr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Ii(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);Gr(i,vt(e.node),n);const t=ui();null!==t&&fi(i,"branch",t)}}const Ni=new WeakMap;function ki(e){return Ni.get(e)??[]}const _i=new Set;const Ti=Symbol.for("wcstack.trustedTypes.policy");function Ci(){const e=globalThis[Ti];return null===e||"object"!=typeof e?null:e}function Ei(e){globalThis[Ti]=e}let Mi;let Oi=!1;function Ri(e,t){if(Oi)return;if(!function(){if(void 0!==Mi)return Mi;if(!("trustedTypes"in globalThis))return Mi=!1,Mi;try{document.createElement("div").innerHTML="<i></i>",Mi=!1}catch{Mi=!0}return Mi}())return;Oi=!0;const n="function"==typeof Ci()?.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 ji={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")}},Li=new Set(["textContent","innerText","innerHTML"]);function Wi(e,n,s){if(void 0===s&&1===e.propSegments.length&&Li.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!==ms&&null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Ge(r)&&ms.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=Ci(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(s):s,e=!0}catch(e){t&&Ri(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=Ge(e);if(null===n)return null;const o=Je(e)?.get(n);if(void 0===o)return null;const s=Ye(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&&Zn(r,c)){const t=so(r,c,e.statePathName),o=ro(t,"to-element"),a=n?.propagationContextByBinding?.get(e)??uo()??ao(t);if(a.visitedEdges.has(o))null!==xt&&xt({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const e=lo(a,o);fo(e,()=>function(e,t,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:t,transactionId:s,synchronousScopeId:no++,writtenValue:n};ho.push({receipt:i,node:e});try{return r()}finally{ho.pop()}}(r,c,s,t,e.transactionId,i))}}else i()}if(t()){const e=ji[c];e?e(r,s):(!function(e,t,n){let o=Ni.get(e);o||(o=[],Ni.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,_i.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!==ms&&2===i.length&&"object"==typeof d&&null!==d&&null!==Ge(r)&&(u in d?ms.rememberOverwrittenValue(r,c,u,d[u]):ms.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 Di=new WeakSet;function Bi(e,t,n){}function zi(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 Fi(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 qi={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Vi={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Hi(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 Ui(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 Gi(e,t){return`$setAll("${e}") ${t}`}function Ki(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 Ji(e,t){const n=xn(t);if(n.pathInfo.path in M){const e=vt(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=on(e.listIndex,n,e.pathInfo.wildcardCount);return null===o&&se(Ki(`"${t}"`,n+1,e.pathInfo.wildcardCount)),o.index}(e,n.pathInfo.path)}return e[jt](n)}const Xi=new WeakSet;function Yi(e,t){console.error(`[@wcstack/state] deferred apply failed for <${e}>.`,t)}const Qi=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){Dn(n)||se("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=bs.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=Ge(e);if(null===t)return null;const n=Je(e)?.get(t);return void 0===n&&se(`Custom element <${t}> is not defined for command binding.`),Ye(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(),bs.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 bs.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)}),bs.set(e,{token:o,unsubscribe:c,elementRef:l})}}),Zi={text:function(e,n,o){const s=null==o?"":String(o);if(e.replaceNode.nodeValue!==s&&(e.replaceNode.nodeValue=s),t()&&!Di.has(e.replaceNode)){Di.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=an(e),i=dn(e),a=Pt(i),l=a.length>0&&!pi.has(e.node)?[]:a,c=Mr(r,l,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let u=pi.get(e.node);const f=void 0!==u?$i(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=mi.get(e.node);if(void 0===t){const n=hi.get(e.node)||e.node;t=function(e,t){let n=e.previousSibling,o=t.nextSibling,s=!0;for(;null!==n;){if(bi(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(bi(o)){s=!1;break}o=o.nextSibling}return s}(e.node,n),mi.set(e.node,t)}if(t){const t=e.node.parentNode;!function(e,t){ko.set(e,(ko.get(e)??0)+t)}(t,t.childNodes.length),t.textContent="",t.appendChild(e.node)}}let p=h?1e3-function(e){return gi.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)?(Kr(o),Pi(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?ei(e.node,o):(Kr(o),o.unmount(),function(e,t){let n=gi.get(e.node);void 0===n&&(n=[],gi.set(e.node,n)),n.length<1e3?n.push(t):ei(e.node,t)}(e,o),p-=1),h||t.delete(n))}),h&&(pi.delete(e.node),u=void 0)}let g=e.node;const m=ae(s.path+"."+d),y=n.stateElement.loopContextStack,w=Or(c);let b=null;c.newIndexes.length==c.addIndexSet.size&&c.newIndexes.length>0&&g.isConnected&&null===f&&(b=document.createDocumentFragment(),Zt(b,n.rootNode));const v=t(),$=ui(),x=e.uuid??"",S=gi.get(e.node);for(const t of c.newIndexes){let o;if(c.addIndexSet.has(t)){const r=vn(m,t);if(y.createLoopContext(r,r=>{if(o=f?.byAddedIndex.get(t)??(void 0!==S?S.pop():void 0),void 0===o?o=li(e):Si(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)}}Gr(o,r,n),null!==$&&fi(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=Ps(o);for(const t of e)aa(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)&&vi(g,o.firstNode)||g.nextSibling===o.firstNode||o.mountAfter(g),e){const e=o,s=vn(m,t);y.createLoopContext(s,t=>{Gr(e,t,n)})}}g=o.lastNode||g,void 0===u&&(u=new WeakMap,pi.set(e.node,u)),u.set(t,o)}hi.set(e.node,g),null!==b&&(e.node.parentNode.insertBefore(b,e.node.nextSibling),Zt(b,null))},if:Ai,else:Ai,elseif:Ai,radio:function(e,t,n){const o=e.node,s=ys(o.value,e.inFilters);o.checked=n===s},checkbox:function(e,t,n){const o=e.node,s=ys(o.value,e.inFilters),r=Array.isArray(n)?n:ws;o.checked=r.includes(s)}},ea=new WeakMap,ta=new WeakMap,na=new WeakMap;function oa(){}function sa(e){const t=ms;if(null!==t){const n=e.replaceNode,o=e.propSegments[0];if(t.isComplete(n,o))return Bi;if(t.isDeclared(n,o))return oa}return Wi}function ra(e,t){ia(e,t,Ji(t.state,e))}function ia(e,t,n){const o=ys(n,e.outFilters);if(!0===ta.get(e))return void t.deferredSelectBindings.push({binding:e,value:o,stateElement:t.stateElement});let s=ea.get(e);if(void 0===s){if(ea.has(e))return s=sa(e),s===Bi&&ea.set(e,s),void s(e,t,o);if(s=Zi[e.bindingType],void 0===s){const t=e.propSegments[0];if(s=Qi[t],ea.set(e,s),void 0===s){Ge(e.replaceNode)?(s=sa(e),s===Bi&&ea.set(e,s)):(s=Wi,ea.set(e,s))}}if(s===Wi){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 ta.set(e,!0)}}s(e,t,o)}else s(e,t,o)}function aa(e,t){if(t.appliedBindingSet.has(e))return;if(t.appliedBindingSet.add(e),!1!==t.stateElement.hasUpdatedCallback){const n=dn(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=gs(e);if(null!==n&&!n.shouldApplyState(e))return;if("event"===e.bindingType)return;if(!0!==na.get(e)){const t=Ge(e.replaceNode);if(t&&void 0===Je(e.replaceNode)?.get(t))return void function(e,t){if(Xi.has(e))return;Xi.add(e);const n=()=>{Xi.delete(e);const t=gs(e);(null===t||t.shouldApplyState(e))&&ca([e])},o=n=>{Xi.delete(e),Yi(t,n)},s=gs(e);if(null!==s){const r=s.deferUntilDefined(e.replaceNode,t,n,o);return void(s.addTeardown(e,()=>{Xi.delete(e),r()})||(Xi.delete(e),r()))}const r=Je(e.replaceNode);if(null===r)return Xi.delete(e),void Yi(t,new Error("CustomElementRegistry is unavailable."));Wo(r).wait(t,()=>{e.replaceNode.isConnected?n():Xi.delete(e)},o)}(e,t);na.set(e,!0)}if(!0===t.sameRootVerified)return void ra(e,t);let o=e.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=en(o),null===o&&se("Root node for fragment not found for binding.")),o!==t.rootNode){const n=xa(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};ra(e,r)})}else ra(e,t)}function la(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!==xt&&xt({type:"state:binding-apply-error",path:e.statePathName,bindingType:e.bindingType,error:t})}function ca(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=en(d),null===d&&se("Root node for fragment not found for binding."));const u=xa(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{aa(n,f)}catch(e){la(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{Wi(e,{propagationContextByBinding:t},n)}catch(t){la(e,t,o??null,c)}for(const[e,t]of i.entries())It(e,t),Ct(e,t);if(!1!==n?.updatedCallback)for(const[e,t]of a.entries())e.createState("writable",e=>{e[zt](Array.from(t))});for(const[e,t]of c.entries())e.createState("writable",e=>{for(const{error:n,info:o}of t)try{e[Ft](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 da(e,t,n){const[o,s,r]=gt(e,n),i=ps(e);for(const e of o)$t(e,t);ca(i.initialize(s)),function(e,t,n){for(const o of e)n.deferUntilDefined(o.node,o.tagName,()=>{const e=yt(o);0!==e.length&&($t(o.node,t),ca(n.initialize(e)))},e=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,e)})}(r,t,i)}const ua=new WeakMap;async function fa(e){const t=e.querySelectorAll(o.tagNames.state),n=[],s=Je(e);null===s&&se(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const e of t){if(ct(e))continue;const t=e;n.push(t.initializePromise)}await Promise.all(n)}async function ha(e){if(e===document)await fa(document),ne(document),Ua(document,document),da(document.body,null);else{const t=e;t.host.hasAttribute(o.bindAttributeName)&&await Ve(t.host),await fa(t),ne(t),Ua(t,t),da(t,null)}}const pa={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function ga(e,t){return`[wcs/feature-not-installed] ${t} needs the "${e}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${pa[e]??e}" before the state is defined.`}let ma=null;function ya(e){return null===ma&&se(ga("ssr",e)),ma}const wa=new WeakMap,ba=new WeakMap,va=new Set,$a=[];function xa(e){return wa.get(e)??null}function Sa(e){return ba.get(e)??Promise.resolve()}const Pa=new WeakSet;function Ia(e){Pa.add(e)}function Aa(e,n){const s=wa.get(e);if(null===n){if(void 0===s)return;wa.delete(e),va.delete(s),null!==xt&&xt({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 ya('the "enable-ssr" attribute').hydrate(e)||await ha(e)}else await ha(e);Ia(e),Qa(),t()}catch(e){n(e)}})});ba.set(e,t)}else if("ShadowRoot"===e.constructor.name){const t=new Promise((t,n)=>{queueMicrotask(async()=>{try{await ha(e),Ia(e),Qa(),t()}catch(e){n(e)}})});ba.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="...">.'),wa.set(e,n),va.add(n);for(let t=0;t<$a.length;t++)$a[t](e,n);null!==xt&&xt({type:"state:element-registered",rootNode:e,element:n}),o.debug&&console.debug("State element registered",n)}}const Na=new Map;function ka(e,t,n){if(null===n)Na.delete(e);else{Na.set(e,n);const o=xa(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 _a(e){return Na.get(e)||null}function Ta(e){if(e.nodeType===Node.ELEMENT_NODE){const t=e,n=Re(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=De(e);null===t&&se("Comment node binding text not found.");const n=_a(t);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Be(t),s=null):s=t,[{...o,uuid:s}]}return[]}let Ca;function Ea(){return Ca??={filterName:"not",args:[]}}const Ma=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function Oa(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 Ra(e,t){const n=Ma.exec(e);if(null===n)return e;const o=n[1],s=n[2],r=n[3];return o+Oa(s,t)+r}function ja(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=Oa(i,t);return a!==i?(o=!0,`${r}: ${a}`):e});return o?s.join(";"):e}function La(e,t){return ja(e,t)}function Wa(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=Ra(n.data,t);continue}const o=e;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const e=ja(r,t);e!==r&&o.setAttribute(n,e)}}}function Da(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 Ba(e){const t=[],n=ft(e);for(const e of n){const n=Ta(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:Da(o),parseBindTextResults:n})}return t}function za(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 Fa=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),qa=Ea();function Va(e,t){const n=t.outFilters;return{...t,outFilters:[...n,qa],bindingType:e}}function Ha(e,t,n,o,s,r=!0){za(t),"string"==typeof o&&Wa(t,o),Ua(e,t,o,s);const i={fragment:t,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ba(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 Ua(e,t,n,s){const r=o.commentElsePrefix,i=dt(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=La(i,n));let a=Re(i)[0];const d=Fa.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,f=t.content,h=Ns();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=Va("else",l.parseBindTextResult),p=Ha(e,f,a,g,s,!1),ka(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:Da(o),parseBindTextResults:Ta(o)})):t.replaceWith(o)}else if("elseif"===u){null===l&&se("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ha(e,f,a,g,s),ka(h,e,p);const n=document.createComment(`@@${d}:${h}`),o=Ns(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Va("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Da(n),parseBindTextResults:Ta(n)}),ka(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:Da(m),parseBindTextResults:Ta(m)})):t.replaceWith(m)}else{p=Ha(e,f,a,g,s),ka(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 Ga=()=>`[${o.bindAttributeName}]`;function Ka(e){if(ts(e))return!0;if(!Ja(e))return!1;if(e.hasAttribute(o.bindAttributeName))return!1;const t=e.querySelector(Ga());return null!==t&&ts(t)}function Ja(e){return 1===e.nodeType}function Xa(e){if(Ka(e))return;ne(e),Ua(e.getRootNode(),e);const t=e.hasAttribute(o.bindAttributeName),n=e.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);da(t&&s?n:e,null)}const Ya=[];function Qa(){const e=Ya.splice(0,Ya.length);for(const t of e)Xa(t);l()}const Za={protocol:"wcs-binder",version:1,bind:function(e){var t;Ja(e)&&!Ka(e)&&(t=e.getRootNode(),Pa.has(t)?Xa(e):Ya.push(e))}};const el="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let tl=0;async function nl(e,t){let n=null;const o=`\n//# sourceURL=${t}#${++tl}\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 ${el}`:`Failed to evaluate the inline <script> of state "${e}": ${o}. If this page sets a Content-Security-Policy, see ${el}`}(t,e,s),{cause:e})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function ol(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 sl{_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 rl={$updatedCallback:j,$streams:H},il=new WeakSet;function al(e,t){let n=e;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,t);)n=Object.getPrototypeOf(n);return n}function ll(e){if(!il.has(e)){for(const t of Object.keys(rl)){if(!(t in e))continue;const n=rl[t];n in e&&se(`[wcs/declaration-alias] The state declares both "${t}" and "${n}". "${t}" is the old name of "${n}" (it works through 3.x) — keep "${n}".`);const o=al(e,t),s=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,n,{...s,configurable:!0}),o===e&&delete e[t]}il.add(e)}}const cl=new WeakMap;function dl(e,t){let n=cl.get(e);void 0===n&&(n=new Map,cl.set(e,n));let o=n.get(t);return void 0===o&&(o=new Wn(t,e),n.set(t,o)),o}const ul=new WeakMap;function fl(e){const t=ul.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 dl(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:dl(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 ul.set(e,n),n}const hl=Symbol("wcs.notHandled"),pl=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],gl=new Map;function ml(e,t){gl.set(e,t)}const yl=new Map;let wl=[],bl=[];function vl(e,t){yl.set(e,t),wl=Array.from(yl.values()).sort((e,t)=>e.order-t.order),bl=wl.slice().reverse()}function $l(e,t){for(let n=0;n<wl.length;n++)wl[n].activate?.(e,t)}function xl(e){"readonly"===e.mutability&&se("This state is readonly.")}const Sl=new Map;class Pl{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 Il(e){let t;return Sl.get(e)??(Sl.set(e,t=new Pl(e)),t)}function Al(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:on(n.listIndex,o,n.pathInfo.wildcardCount)}function Nl(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=nn(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?on(i,n,t.pathInfo.wildcardCount):null)!==(null!==a?on(a,n,o.wildcardCount):null)){r=!0;break}}if(r)for(let n=0;n<e;n++)s.addCrossRowListPath?.(t.pathInfo.wildcardParentPaths[n])}}}}function kl(e,t){return(!0!==e.hasMounts||35!==t.pathInfo.lastSegment.charCodeAt(0))&&(t.pathInfo.wildcardCount>0||e.getterPaths.has(t.pathInfo.path))}function _l(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!==hl)return a}}return hl}function Tl(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}(fl(s),t.pathInfo.segments);if(!(t.pathInfo.path in e)){if(null===t.parentAddress){const r=_l(s,t,null,n,o);if(r!==hl)return r;se(function(e,t,n){return`[${qi.binding}] Path "${e}" does not exist on the state tree.${de(e,Fi(t,"",n))}${ue}`}(t.pathInfo.path,e,s.getterPaths))}const r=El(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=_l(s,t,Object(r),n,o);if(e!==hl)return e}if(i===d){const e=t.listIndex?.index??se(Ki(`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 Cl(e,t,n,o,s){const r=Xt(s,t),i=function(e){return Vs.get(e)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Tl(e,t,n,o,s);return Hs(r,{value:l,dirty:!1,generation:a}),l}function El(e,t,n,o){Nl(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!==hl)return i}}return kl(s,t)?Cl(e,t,n,o,s):Tl(e,t,n,o,s)}function Ml(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=vn(f,r),p=Xt(n.stateElement,h),g=Tt(p),m=El(e,h,t,n),y=Mr(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())Ct(e,Array.isArray(t)?t:[]);return l}function Ol(e,t,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Fs(El(e,vn(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 Rl(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 jl(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 Ll(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];Rl(a,n,o,i);const l=jl(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 Wl(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 Dl(e,t,n,o){if(t.pathInfo.path in e)return!0;const s=t.parentAddress;if(null===s)return!1;const r=El(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 Bl=new WeakMap;function zl(e,t){null===t?Bl.delete(e):Bl.set(e,t)}function Fl(e,t,n){const s=vn(ae(e.wildcardParentPaths[t]),n),r=Xt(e.stateElement,s),i=Tt(r),a=e.stateProxy[jt](s),l=Mr(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)Fl(e,t+1,n)}const ql=[];function Vl(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:ql,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:ql,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Hl=[];function Ul(e,t,n){const o=e.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Hl;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??Hl}function Gl(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[jt](t),a=Xt(e.stateElement,t),l=Tt(a),c=Mr(t.listIndex,l,i);e.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const d=Vl(e,o,0,0,c);for(const t of d.fullRows){const o=vn(s,t);e.result.add(o),n.push(o)}if(null!==d.movedRows){const t=Ul(e,r,s);if(null===t)for(const t of d.movedRows){const o=vn(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=vn(s,o);e.result.add(t),n.push(t)}}}else{const o=vn(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=nn(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=on(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};Fl(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=on(t.listIndex,n-1,t.pathInfo.wildcardCount);r.push(e)}}else r.push(null);for(const t of r){const o=vn(s,t);e.result.add(o),n.push(o)}}}function Kl(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,Gl(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)Ct(e,t);return Array.from(u.result)}function Jl(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 Xl(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 Yl(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 Ql(e,t,n,s,r,i){const a=function(e,t){return!0===sr.get(e)?.byPath.has(t)||!0===cr.get(e)?.has(t)}(e,t),l=function(e,t){return!0===ur.get(e)?.has(t)}(e,t);if(!a&&!l)return;const c=or(),u=o.enablePropagationContext?uo()??null:null,f=e=>{Us(e),c.enqueueAbsoluteAddress(e,u)};a&&Pr(e,t,n,s,r).forEach(f),l&&function(e,t,n,o){const s=ae(t).segments.length,r=[];for(const i of ur.get(e).get(t)){const t=ae(i).segments.slice(s);if(t.includes(d))Ar(e,i,r);else for(const s of Pr(e,i,!0,Ir(n,t),Ir(o,t)))r.push(s)}return r}(e,t,n?s:i(),r).forEach(f)}function Zl(e,t,n,s,r,i,a="diff"){const l=o.enablePropagationContext?uo()??ao(-1):null,c=or();c.enqueueAbsoluteAddress(t,l),i&&Us(t),Kl(s.stateElement,e,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",t=>{if(t===e)return;const n=Xt(s.stateElement,t);Us(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function ec(e,t,n,o,s){s&&(e.getterPaths.has(t)?Us(n):Hs(n,{value:o,dirty:!1,generation:e.stateGeneration}))}function tc(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=El(e,n,s,r),a=t.pathInfo.segments[t.pathInfo.segments.length-1];if(a===d){const e=t.listIndex?.index??se(Ki(`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{Zl(t,n,s,r,i,a)}}function nc(e,t,n,o,s,r,i,a){const l=t.parentAddress??se(`address.parentAddress is undefined path: ${t.pathInfo.path}`),u=El(e,l,s,r)??[];let f=(h=u,Bl.get(h)??null);var h;if(null===f){const e=zs(u)??[];f={value:[...u],listIndexes:[...e]},zl(u,f)}try{return tc(e,t,n,o,s,r,i,a)}finally{const n=f.value.indexOf(o),i=El(e,l,s,r)??[],a=Array.isArray(i)?zs(i)??[]:[],h=t.listIndex.index,p=-1!==n?f.listIndexes[n]:Es(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;zl(u,null),function(e,t,n,o,s,r){const i=r.stateElement,a=or(),l=Xt(i,e);Pt(l)===n&&(qs(t.value,t.listIndexes),It(l,t.value),function(e){Rr.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=vn(f,n),d=Xt(i,c);if(void 0===l){const n=Yt(i,f,t.listIndexes[e]??null);Yl(i,d,n),Zl(c,d,s,r,null,kl(i,c),"full");continue}Kl(i,c,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",e=>{const t=Xt(i,e);Us(t),a.enqueueRenderOnlyAddress(t)},{listExpansion:"diff"})}}(l,f,i,a,s,r)}}}function oc(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=El(e,t,o,s),a=function(e,t,n,o){const s=Ll(o,t,e,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Ll(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===zs(o)&&Mr(a,null,o);const l=Mr(a,o,n.list),u=sc(e,t,n.list,s,r,i),f=ae(i+c+d);for(const t of n.matched){const n=Wl(t.oldRow,t.newRow);if(0===n.length)continue;const o=l.newIndexes[t.position];for(const i of n)void 0!==o?oc(e,vn(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 sc(e,t,n,o,s,null)}function sc(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!==hl)return i}}const u=!!po&&(po=!1,!0);if(!(l in e)&&null!==t.parentAddress&&!a.elementPaths.has(l)){const f=El(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}Ql(a,l,g,p,n,()=>f[h]);const m=kl(a,t),y=Xt(a,t);null!==xt&&xt({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:g}),Jl(a,l,y,p,g);let w=!1;try{if(void 0===h&&se(Ki(`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!==hl)return i;w=!1}}return Reflect.set(f,h,n)}finally{Zl(t,y,s,r,i,m),w?Us(y):ec(a,l,y,n,m),Xl(a,t.pathInfo,{value:n})}}}let f,h=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=El(e,t,s,r);if(Dl(e,t,s,r)&&Object.is(o,n))return!0;f=o,h=!0}Ql(a,l,h,f,n,()=>El(e,t,s,r));const p=a.elementPaths.has(t.pathInfo.path),g=kl(a,t),m=Xt(a,t);null!==xt&&xt({type:"state:write",absoluteAddress:m,value:n,oldValue:f,hasOldValue:h}),Jl(a,l,m,f,h);try{return p?nc(e,t,m,n,s,r,i,g):tc(e,t,m,n,s,r,i,g)}finally{p||ec(a,l,m,n,g),Xl(a,t.pathInfo,{value:n})}}function rc(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(Hi("$resolve",t,i.wildcardParentPathInfos.length,s.length));const a=vn(i,Ol(e,n,o,i,s));if(0===r.length)return El(e,a,n,o);xl(o),oc(e,a,r[0],n,o)}}function ic(e,t,n,o){const s=rc(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(Hi("$getAll",t,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let e=i.wildcardPaths.length-1;e>=0;e--){const t=Al(o,i.wildcardPaths[e]);if(t){r=sn(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=Ml(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 ac(e,t,n,o){const s=t.pathInfo;switch(t.wildcardType){case"none":return null;case"context":return Al(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=Fs(El(e,vn(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 lc(e,t,n,o){return(t,s,r,i)=>{xl(o);const a=ae(t);Array.isArray(s)||se(Gi(t,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&se(Hi("$setAll",t,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&se(Gi(t,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&se(Gi(t,"requires an array as the value when { spread: true } is set."));const d=Ml(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=Ol(e,n,o,a,d[t]);u.push(vn(a,s))}let f=0;for(let t=0;t<u.length;t++){const s=u[t];let i;if(c){i=r(El(e,s,n,o),...d[t])}else i=l?r[t]:r;void 0!==i&&(oc(e,s,i,n,o),f++)}return f}}function cc(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 dc=/^\$\d+$/,uc=`${Y}${c}`,fc=`${Q}${c}`,hc=new WeakMap;function pc(e,t,n,o){const s=M[t];if(void 0===s&&"string"==typeof t&&36===t.charCodeAt(0)&&dc.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=on(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!==hl)return i}}if("$"===t[0]){switch(t){case"$stateElement":return o.stateElement;case"$getAll":return(t,s)=>ic(e,0,n,o)(t,s);case"$setAll":return(t,s,r,i)=>lc(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=Il(t),i=ac(e,r,n,o),a=vn(r.pathInfo,i),l=Xt(s,a),c=or();c.enqueueAbsoluteAddress(l),Kl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",e=>{const t=Xt(s,e);Us(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)=>rc(e,0,n,o)(t,s,...r);case"$dependOn":case"$trackDependency":return e=>function(e,t,n,o){return e=>{-1!==e.indexOf(J)&&se(`[wcs/recursion-unsupported] ${String(t)}("${e}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&se(`No active state reference to track dependency for path "${e}".`);const n=o.lastAddressStack?.pathInfo??se("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==e&&s.addDynamicDependency(e,n.path)}}(0,t,0,o)(e);case"$eq":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(cc(o.stateElement,e))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&$r(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)&&vr(o.stateElement,e,t,Xt(o.stateElement,s),r),Object.is(r,t)};case"$eqPath":return(e,t)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=cc(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?$r(o.stateElement,e):vr(o.stateElement,e,i,Xt(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=on(s.listIndex,t-1,s.pathInfo.wildcardCount);if(null===r&&se(`$eqIndex("${e}", ${t}): no list index at that level.`),cc(o.stateElement,e))return o.stateElement.getterPaths.has(s.pathInfo.path)&&$r(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?zs(l):null;null!==t?function(e,t,n,o,s){lr=!0,pr(e).lastValue.set(t,s),hr(e,t);let r=cr.get(e);void 0===r&&cr.set(e,r=new Map);let i=r.get(t);void 0===i&&r.set(t,i=new Set);let a,l=dr.get(o);void 0===l?dr.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){lr=!0;const r=pr(e);hr(e,t),br(r,t,s,o,yr(r,t,n.index,o),{stateElement:e,path:t,absAddress:o,levelListIndex:n})}(o.stateElement,e,r,Xt(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untracked":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 fl(o.stateElement)}if(!t.startsWith(uc)&&!t.startsWith(fc))return}const r=Il(t),i=ac(e,r,n,o),a=vn(r.pathInfo,i);return El(e,a,n,o)}if("symbol"==typeof t){const s=function(e){let t=hc.get(e);return void 0===t&&(t=new Map,hc.set(e,t)),t}(o),r=s.get(t);if(void 0!==r)return r;let i;switch(t){case Rt: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 jt:i=t=>El(e,t,n,o);break;case Lt:i=t=>Dl(e,t,n,o);break;case Wt:i=(t,s)=>oc(e,t,s,n,o);break;case Dt:i=()=>async function(e,t,n){const o=Reflect.get(e,O);"function"==typeof o&&await o.call(n)}(e,0,n);break;case Bt:i=()=>function(e,t,n){const o=Reflect.get(e,R);"function"==typeof o&&o.call(n)}(e,0,n);break;case zt: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=sn(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 Ft: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 gc{_stateElement;_addressStack=Array(f).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(e,t){const n=xa(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 pc(e,t,n,this)}set(e,t,n,o){return xl(this),function(e,t,n,o,s){if("string"==typeof t){const r=Il(t),i=ac(e,r,o,s);return oc(e,vn(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 mc=Promise.resolve(),yc=new Map;let wc=[];function bc(e,t){yc.set(e,t),wc=Array.from(yc.values()).sort((e,t)=>e.order-t.order)}function vc(e,t){return se(ga(e,t))}const $c="undefined"==typeof HTMLElement?class{}:HTMLElement;function xc(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 Sc=null;const Pc=new Set(["for","if","elseif","else"]);function Ic(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=Xt(e,t);if(i.has(n))return;i.add(n);const o=mn(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(vn(n,t.listIndex))}};Et();try{if(e.createState("readonly",t=>{for(const o of n){const n=vn(ae(o),null);a(n);try{Kl(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)Pc.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=()=>{ca(o,void 0,{updatedCallback:!1})};if(t())return void s();const i=Js("state",s);void 0!==i&&i.catch(er)}finally{Mt()}}class Ac extends $c{static hasConnectedCallbackPromise=!0;static getBindingsReady(e){return Sa(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 sl}();_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){ll(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<wl.length;o++)wl[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<wl.length;o++)wl[o].validate?.(e,t,n)}(this,e,n),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].preCommit?.(e,t,n)}(this,e,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=e,void 0!==t&&Sc?.reset(this),this._hasUpdatedCallback=j in e,this._hasErrorCallback=L in e,i=this,On.delete(i),function(e,t,n){for(let o=0;o<wl.length;o++)wl[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.`),Rn(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=xc(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<wl.length;o++)wl[o].apply?.(e,t,n)}(this,e,n),this._listKeys=r,this._rebuildPathInfo(),function(e,t,n){for(let o=0;o<wl.length;o++)wl[o].register?.(e,t,n)}(this,e,n),$l(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")?ya('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 nl(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 ol(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&&(Aa(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===xa(this._rootNode)&&(function(e,t){const n=Promise.reject(t);n.catch(()=>{}),ba.set(e,n)}(this._rootNode,e),function(e,t,n){for(let o=0;o<wc.length;o++)wc[o].initializeFailed?.(e,t,n)}(this,this._rootNode,e)),e}async _callStateConnectedCallback(){await this.createStateAsync("writable",async e=>{O in e&&await e[Dt]()})}_callStateDisconnectedCallback(){this.createState("writable",e=>{R in e&&e[Bt]()})}async connectedCallback(){this._rootNode=this.getRootNode();const e=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(e){for(let t=0;t<wc.length;t++)if(!0===wc[t].reconnecting?.(e))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||xa(this._rootNode)===this||Aa(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<wc.length;t++){const n=wc[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{vc("dcc",`a <${o.tagNames.state}> inside a [${Z}] host`)}catch(e){this._failInitializeLoudly(e)}if(this.hasAttribute("mount"))try{vc("scopes",'the "mount" attribute')}catch(e){this._failInitializeLoudly(e,!1)}let n=!1;try{const e=function(e){for(let t=0;t<wc.length;t++){const n=wc[t].preparing?.(e);if(null!=n)return n}return null}(this);null===e&&this.hasAttribute("bind-component")&&vc("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 ya('the "enable-ssr" attribute').emitSnapshot(this)}catch(e){throw this._rejectConnectedCallback?.(e),e}$l(this,e),this._resolveConnectedCallback?.()}disconnectedCallback(){var e;if(!function(e){for(let t=0;t<wc.length;t++)if(!0===wc[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<wc.length;n++)wc[n].initializeFailureCleared?.(e,t)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Aa(this.rootNode,null),e=this,ul.delete(e),function(e){for(let t=0;t<bl.length;t++)bl[t].deactivate?.(e)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(e=>(ll(e),e))}markTreeless(){this._treeless=!0}failInitializeLoudly(e){return this._failInitializeLoudly(e)}get connectGeneration(){return this._connectGeneration}setWatchPaths(e){this._watchPaths=e}setScanPaths(e){this._scanPaths=e}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(e){this._recursionRegistry=e}addGeneratedPath(e){this._generatedPaths.add(e)}setBoundComponent(e,t){this._boundComponent=e,this._boundComponentStateProp=t}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(e){if(0===e.size)return;const t=new Set(this._watchPaths??[]);for(const n of e)t.add(n);this._watchPaths=t,this.attachAddressHooks("watch",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 zi(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=gl.get(e);return void 0===n&&se(ga(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<pl.length;n++){const o=pl[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),Sc?.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 gc(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<wc.length;t++)wc[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(xc(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){Ic(this,e,this._pathRegistrations.keys())}}const Nc=[];function kc(e=customElements){for(let t=0;t<Nc.length;t++)Nc[t](e);e.get(o.tagNames.state)||e.define(o.tagNames.state,Ac)}function _c(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 Tc(e,t){const o=_c(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)),kc(t),function(){const e=globalThis;void 0===e[r]&&(e[r]=Za)}()}function Cc(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 Ec(e,t){for(const n of e)if(Cc(t,n.innerSegments))return n;return null}function Mc(e,t){const n=t.slice(e.innerSegments.length);return 0===n.length?e.outerPathInfo.path:e.outerPathInfo.path+c+n.join(c)}let Oc=0;const Rc=["$watch",H,"$scan","$listKeys",j,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],jc=new Set;function Lc(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 Wc(e,t,n,o,s,r=new Set){0===n.length&&se(`Cannot build a mount record without host bindings for "${t}".`),ll(s);const i=[],a=new Set;let l=null;for(const e of n){const t=e.propSegments.slice(1),n=t.join(c);a.has(n)&&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=++Oc,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 Dc(e){const t=e.indexOf(c);return-1===t?e:e.slice(0,t)}function Bc(e,t){const n=Ec(e.entries,t);return null===n?null:Mc(n,t)}function zc(e,t){return e.markerBasePath+c+t}function Fc(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 qc(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 Vc(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}.${Dc(t)}: path") or declare the key on the component state.`}const Hc=/^\$(\d+)$/;function Uc(e,t){const n=t[0];if("$"===n||"#"===n)return null;if(e.getterKeys.has(t)||e.setterKeys.has(t))return null;const o=Dc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o)||qc(e,o))return null;const s=function(e,t){return Ec(e.entries,t)}(e,t.split(c));return null!==s&&s.readonly?s:null}function Gc(e,t){const n=Uc(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 Kc(e,t)}function Kc(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 Fc(e,e.markerBasePath,t,t),zc(e,t);if(qc(e,n[0]))return Fc(e,e.markerBasePath,t,t),zc(e,t);const s=n.slice(0,o+1),r=n.slice(o+1),i=Bc(e,s);null===i&&se(Vc(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 Fc(e,a,r.join(c),t),a+c+r.join(c)}(e,t);const o=Dc(t);if(e.getterKeys.has(o)||e.setterKeys.has(o))return zc(e,t);if(qc(e,o))return zc(e,t);const s=Bc(e,t.split(c));if(null!==s)return s;se(Vc(e,t))}function Jc(e,t,n){let o;const s=Hc.exec(t.statePathName);if(null!==s){const r=function(e,t){return void 0===t?e.delta:ae(Kc(e,t)).wildcardCount-ae(t).wildcardCount}(e,n);o=0===r?t.statePathName:`$${Number(s[1])+r}`}else if(o=Kc(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!==Uc(e,t.statePathName);return o!==t.statePathName||i?{...t,statePathName:o,statePathInfo:ae(o),...i?{propModifiers:[...r,y]}:{}}:t}function Xc(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 Yc=new WeakMap,Qc=new WeakMap;const Zc=new WeakMap;const ed=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)}),td=new WeakMap;function nd(e){return td.get(e)??null}let od=!1;function sd(){od||(od=!0,bt=e=>Yc.has(e)?e.host:null)}function rd(e){const t=Zc.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 id(e,t){const n=t.lastIndexOf("#");if(-1===n)return null;const o=Zc.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 ad="3.2.0",ld=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function cd(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 dd(e){const t=function(e){const t=sr.get(e);return void 0===t?null:{byPath:t.byPath,lastValue:t.lastValue,tracked:t.tracked,watchers:cr.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 ud="__WCSTACK_DEVTOOLS_HOOK__";function fd(){const e=globalThis,t=e[ud];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[ud]=n,n}const hd=e=>{null!==xt&&xt({type:"state:update-batch",addresses:e})};function pd(e){const t=null!==xt;!function(e){xt=e}(e);const n=null!==e;n&&!t?Zs(hd,0):!n&&t&&function(e){const t=Xs.findIndex(t=>t.listener===e);-1!==t&&Xs.splice(t,1)}(hd)}function gd(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 md(e){return xa(e)??se("devtools: no state tree on this root")}let yd=null;function wd(){if(t())return;if(null!==yd)return;const e={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:ad,getStateElements(){const e=[];for(const t of va)e.push(gd(t));return e},overlays:e=>rd(md(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=>dd(md(e)),keys(e){const t=md(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 md(e).createState("readonly",e=>{o=e.$resolve(t,n??[])}),o},write(e,t,n,o){md(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=_a(e);if(null!==t)for(const e of t.nodeInfos)for(const t of e.parseBindTextResults)r(cd(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=st(t,Re(n));for(const o of e)r(cd(t,o,"attribute",n))}catch{}continue}const t=ld.exec(e.data.trim());if(null===t)continue;const n=t[1]||o.commentTextPrefix,s=t[2],a=_a(s);if(null===a){if(n===o.commentTextPrefix)try{r(cd(e,Be(s),"comment",s))}catch{}}else r(cd(e,a.parseBindTextResult,"comment",s)),i(s)}return t}(e),_setSink:pd};yd=e,fd().register(e)}const bd={name:"devtools",install(){wd()}},vd=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),$d=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});const xd=new WeakMap;const Sd=new WeakMap,Pd=new WeakSet,Id=new WeakMap;function Ad(e,t,n,o){console.warn(`[@wcstack/state] [${qi[n]}] ${Vi[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!==xt&&xt({type:"state:path-unresolved",source:n,path:t,missingSegment:o.missingSegment})}const Nd={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=xd.get(e);return void 0===n&&(n=new Set,xd.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!==zi(e,t))return $d;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!==zi(e,r))return vd;if(Object(s)!==s)return vd;if(i===d){if(!Array.isArray(s)||0===s.length)return vd;s=s[0];continue}const l=zi(s,i);if(void 0===l)return{existence:"missing",missingSegment:i,candidates:Fi(s,a,n)};if("function"==typeof l.get)return t===o.length-1?$d:vd;s=l.value}return $d}(t,n,e.getterPaths);"missing"===i.existence&&(function(e,t){return!0===Id.get(e)?.has(t)}(e,n)||("binding"!==o?Ad(e,n,o,i):function(e,t,n){let o=Sd.get(e);void 0===o&&(o=new Map,Sd.set(e,o));if(o.set(t,n),Pd.has(e))return;Pd.add(e),setTimeout(()=>function(e){Pd.delete(e);const t=Sd.get(e);if(void 0===t)return;Sd.delete(e);for(const[n,o]of t)Ad(e,n,"binding",o)}(e),0)}(e,n,i)))},reset:function(e){xd.delete(e),Sd.delete(e)},markExported:function(e,t){let n=Id.get(e);void 0===n&&(n=new Set,Id.set(e,n)),n.add(t),Sd.get(e)?.delete(t)}};let kd=!1;function _d(){kd||(kd=!0,function(e){Sc=e}(Nd))}const Td={name:"diagnostics",install(){_d()}};function Cd(e){se(`filter ${e} requires at least one option`)}function Ed(e){se(`filter ${e} requires a number as option`)}function Md(e){se(`filter ${e} requires a number value`)}function Od(e){se(`filter ${e} requires a date value`)}const Rd={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function jd(e){return!(!e||isNaN(Number(e)))}const Ld={eq:(e,t)=>{const n=e?.[0]??Cd("eq"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(jd(n)||Ed("eq"),e===Number(n)):"string"==typeof e?e===n:e===o},ne:(e,t)=>{const n=e?.[0]??Cd("ne"),o=void 0!==t&&t.length>0?t[0]:n;return e=>"number"==typeof e?(jd(n)||Ed("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]??Cd("lt");return jd(t)||Ed("lt"),e=>("number"!=typeof e&&Md("lt"),e<Number(t))},le:e=>{const t=e?.[0]??Cd("le");return jd(t)||Ed("le"),e=>("number"!=typeof e&&Md("le"),e<=Number(t))},gt:e=>{const t=e?.[0]??Cd("gt");return jd(t)||Ed("gt"),e=>("number"!=typeof e&&Md("gt"),e>Number(t))},ge:e=>{const t=e?.[0]??Cd("ge");return jd(t)||Ed("ge"),e=>("number"!=typeof e&&Md("ge"),e>=Number(t))},add:e=>{const t=e?.[0]??Cd("add");return jd(t)||Ed("add"),e=>("number"!=typeof e&&Md("add"),e+Number(t))},sub:e=>{const t=e?.[0]??Cd("sub");return jd(t)||Ed("sub"),e=>("number"!=typeof e&&Md("sub"),e-Number(t))},mul:e=>{const t=e?.[0]??Cd("mul");return jd(t)||Ed("mul"),e=>("number"!=typeof e&&Md("mul"),e*Number(t))},div:e=>{const t=e?.[0]??Cd("div");return jd(t)||Ed("div"),e=>("number"!=typeof e&&Md("div"),e/Number(t))},mod:e=>{const t=e?.[0]??Cd("mod");return jd(t)||Ed("mod"),e=>("number"!=typeof e&&Md("mod"),e%Number(t))},abs:e=>e=>("number"!=typeof e&&Md("abs"),Math.abs(e)),clamp:e=>{const t=e?.[0]??Cd("clamp");jd(t)||Ed("clamp");const n=e?.[1]??Cd("clamp");jd(n)||Ed("clamp");const o=Number(t),s=Number(n);return e=>("number"!=typeof e&&Md("clamp"),Math.min(Math.max(e,o),s))},toFixed:e=>{const t=e?.[0]??"0";return jd(t)||Ed("toFixed"),e=>("number"!=typeof e&&Md("toFixed"),e.toFixed(Number(t)))},locale:e=>{const t=e?.[0];return e=>("number"!=typeof e&&Md("locale"),e.toLocaleString(t??o.locale))},upper:e=>e=>String(e).toUpperCase(),lower:e=>e=>String(e).toLowerCase(),capitalize: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]??Cd("slice");jd(n)||Ed("slice"),t.push(Number(n));const o=e?.[1];return void 0!==o&&(jd(o)||Ed("slice"),t.push(Number(o))),e=>String(e).slice(...t)},substr:e=>{const t=e?.[0]??Cd("substr");jd(t)||Ed("substr");const n=e?.[1]??Cd("substr");return jd(n)||Ed("substr"),e=>String(e).substr(Number(t),Number(n))},padStart:e=>{const t=e?.[0]??Cd("padStart");jd(t)||Ed("padStart");const n=e?.[1]??"0";return e=>String(e).padStart(Number(t),n)},padEnd:e=>{const t=e?.[0]??Cd("padEnd");jd(t)||Ed("padEnd");const n=e?.[1]??" ";return e=>String(e).padEnd(Number(t),n)},repeat:e=>{const t=e?.[0]??Cd("repeat");return jd(t)||Ed("repeat"),e=>String(e).repeat(Number(t))},reverse:e=>e=>String(e).split("").reverse().join(""),truncate:e=>{const t=e?.[0]??Cd("truncate");jd(t)||Ed("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 jd(t)||Ed("round"),e=>{"number"!=typeof e&&Md("round");const n=Math.pow(10,Number(t));return Math.round(e*n)/n}},floor:e=>{const t=e?.[0]??"0";return jd(t)||Ed("floor"),e=>{"number"!=typeof e&&Md("floor");const n=Math.pow(10,Number(t));return Math.floor(e*n)/n}},ceil:e=>{const t=e?.[0]??"0";return jd(t)||Ed("ceil"),e=>{"number"!=typeof e&&Md("ceil");const n=Math.pow(10,Number(t));return Math.ceil(e*n)/n}},percent:e=>{const t=e?.[0]??"0";return jd(t)||Ed("percent"),e=>("number"!=typeof e&&Md("percent"),`${(100*e).toFixed(Number(t))}%`)},unit:e=>{const t=e?.[0]??Cd("unit");return e=>null==e?e:String(e)+t},date:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("date"),e.toLocaleDateString(t??o.locale))},time:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("time"),e.toLocaleTimeString(t??o.locale))},datetime:e=>{const t=e?.[0];return e=>(e instanceof Date||Od("datetime"),e.toLocaleString(t??o.locale))},ymd:e=>{const t=e?.[0]??"-";return e=>{e instanceof Date||Od("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||Od("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]??Cd("defaults"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e||o},coalesce:(e,t)=>{const n=e?.[0]??Cd("coalesce"),o=void 0!==t&&t.length>0?t[0]:n;return e=>e??o},boolean:e=>e=>Boolean(e),number:e=>e=>Number(e),string:e=>e=>String(e),nullIfEmpty:e=>e=>""===e?null:e},Wd={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},Dd=Ld,Bd=Ld;let zd=!1;const Fd={name:"formats",install(){zd||(zd=!0,we("input",Bd,Wd,Rd),we("output",Dd,Wd,Rd))}};function qd(e){return-1!==e.indexOf(J)}function Vd(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(qd(o))return null;const s=o.slice(1).split(c);return s[0]===d||s.some(e=>0===e.length)?null:o}function Hd(e){return 0===e.length?e:c+Kd(e.slice(1))}function Ud(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 Gd(e,t,n){for(let o=n.length;o>0;o=n.lastIndexOf(c,o-1))if(Ud(e,t,n.slice(0,o)))return!0;return!1}function Kd(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 Jd(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 Xd(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 Yd(e,t){return Xd(e,"",t)}function Qd(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 Zd(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 eu(e,t,n){const o=e.recursionRegistry,s=Vd(o.spec,n);null===s&&se(Ui(n,o.spec.recursiveAnchor));const r=Zd(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 tu(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(vn(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=vn(o,s),c=Xt(n.stateElement,l),u=El(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=Mr(s,Tt(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(vn(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)Ct(e,t);return i}function nu(e,t,n,o,s,r,i){xl(n);const a=n.stateElement.recursionRegistry,l=Vd(a.spec,o);null===l&&se(Ui(o,a.spec.recursiveAnchor));const c=Hd(l);Array.isArray(s)||se(Gi(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(Gi(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&se(Gi(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){Jd(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=tu(e,t,n,a,l);let f=0;for(let o=0;o<u.length;o++)void 0!==r&&(oc(e,u[o],r,t,n),f++);return f}const ou={write(e,t){if(!0!==e.hasRecursion)return hl;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.`),hl},get(e,t,n,o){if(!0!==e.stateElement.hasRecursion)return hl;if("$getAll"===t)return(t,s)=>{if(qd(t)){if(void 0!==s)return function(e,t,n,o,s){const r=n.stateElement.recursionRegistry,i=Vd(r.spec,o);null===i&&se(Ui(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=tu(e,t,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(El(e,a[o],t,n));return l}(o,n,e,t,s);t=eu(e.stateElement,e,t)}return ic(o,0,n,e)(t,s)};if("$setAll"===t)return(t,s,r,i)=>qd(t)?nu(o,n,e,t,s,r,i):lc(o,0,n,e)(t,s,r,i);if(36!==t.charCodeAt(0)&&qd(t)){const s=Il(eu(e.stateElement,e,t)),r=ac(o,s,n,e);return El(o,vn(s.pathInfo,r),n,e)}return hl}};let su=!1;function ru(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 iu=new WeakSet;function au(e){return"function"==typeof e.get&&iu.has(e.get)}function lu(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&au(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 Hs(Yt(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=zs(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 cu="[wcs/recursion-declaration-invalid]";class du{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=xc(t);for(const[t,o]of Object.entries(n)){if(!qd(t))continue;"function"==typeof o.set&&se(`${cu} 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(`${cu} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Vd(e,t);null===n&&se(Ui(t,e.recursiveAnchor)),0===n.length&&se(`${cu} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${c}total"), not the node.`),Jd(e,Hd(n))&&se(`${cu} "${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(qd(t)||au(n))continue;const e=this._matchExpansion(t);null!==e&&se(`${cu} "${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++)Ud(this.spec,e[t].suffix,e[n].suffix)&&se(`${cu} "${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(Gd(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=Kd(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!==Qd(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=Qd(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||au(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,iu.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(Yd(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 lu(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=Xd(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 uu="recursionSpec",fu="recursionRegistry",hu={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];ru("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}").`),ru("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(uu,o),n.set(fu,null===o?null:new du(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(fu)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",K)},apply(e,t,n){const o=n.get(uu)??null;null!==o&&e.addListPath(o.anchorList)}};let pu=!1;function gu(){pu||(pu=!0,su||(su=!0,ml("recursion",ou)),vl("recursion",hu))}const mu={name:"recursion",install(){gu()}};const yu={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 wu=!1;function bu(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 vu(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 $u(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 xu(e){return e.startsWith("$")}function Su(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)||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 Iu(e){ll(e);const t=Pu(e,D)??[],n=Pu(e,B)??[],o=xc(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,Su(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,Su(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 Au(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=Je(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}=Iu(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=Je(this._shadow);return null!==e&&Xe(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?(wu||(wu=!0,ml("dcc",yu)),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=xc(n);for(const[e,t]of Object.entries(m)){if(xu(e))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof t.value){const o="AsyncFunction"===t.value.constructor?.name;n.value=$u(e,o)}else n.get=bu(e),n.set=vu(e);Object.defineProperty(g.prototype,e,n)}for(const e of u)Object.defineProperty(g.prototype,e,{configurable:!0,enumerable:!0,get:bu(e),set:vu(e)});r.define(s,g)}async function Nu(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 ol(t);se(`DCC: Unsupported src type: ${t}`)}const n=e.querySelector('script[type="module"]');if(n)return await nl(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);Au(t,n,s),e.markTreeless(),e.markInitialized(),e.clearConnectedRootNode(),e.settleInitialization()}catch(t){e.failInitializeLoudly(t)}}const ku={order:10,connecting(e){const t=e.parentNode;return t instanceof ShadowRoot&&t.host.hasAttribute(Z)?Nu(e,t.host,t):null}};let _u=!1;const Tu=new WeakMap;function Cu(e,t,n){let o=Tu.get(e);void 0===o&&(o=new Map,Tu.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 Eu(e,t){if(null===e)return!1;const n=Tu.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 Mu=new WeakMap;const Ou=[];function Ru(e,t,n,o){if(t.length>0){const s=n.split(c),r=Ec(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.`),Mc(r,s)}return e+c+n}function ju(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 Lu(e,t,n=Ou){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](Ru(e,n,s,!1),...r)}return"$setAll"===s?(o,...s)=>t.$setAll(Ru(e,n,o,!0),...s):"$resolve"===s?(o,...s)=>t.$resolve(Ru(e,n,o,s.length>1),...s):t[s]}return t[Ru(e,n,s,!1)]}},set:(o,s,r)=>("string"!=typeof s||(t[Ru(e,n,s,!0)]=r),!0),has:(e,t)=>"string"==typeof t&&"$"!==t[0]&&"#"!==t[0]})}const Wu=new WeakMap,Du=[];const Bu=new WeakMap,zu=new WeakSet;function Fu(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 qu=null;const Vu=new WeakMap,Hu=new Set;function Uu(e,t,n,o){let s=Vu.get(e);if(void 0===s){if(!o)return null;s=new Map,Vu.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 Gu(e,t){if(!e.component.isConnected)return!1;const n=vt(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 Ku(e,t,n,o){const s=Uu(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&&Gu(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?Gu(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 Ju(e){const t=e.parentStateElement,n=vt(e.component);if(!(!1===t.isConnected||e.delta>0&&null===n))for(const o of e.exports.values())t.createState("readonly",e=>{e[Rt](n,()=>{e.$postUpdate(o.exportedPath)})})}const Xu=new WeakMap;class Yu{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 vn(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(Kc(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?Gc(e,t):Kc(e,t),a=Xc(0,t,i,s??[],n);return o.$resolve(i,a,...r)};const s=t;return(t,r,...i)=>{const a="$setAll"===s?Gc(e,t):Kc(e,t),l=Xc(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 Nl(this.handler,this.accessorAddress(t)),e[t];const o=this.record.stateObject[t];if("function"==typeof o)return o.bind(n)}return this.receiver[Kc(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[Gc(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 Kc(this.record,t),!0}catch{return!1}}}function Qu(e,t,n,o){const s=t.pathInfo.path,r=s===e.markerBasePath,i=r?function(e,t){let n=Xu.get(e);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Xu.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 Yu(e,s,t.listIndex,r,n,o))}function Zu(e){const t=e.parentStateElement,n=(t,n)=>{const o=vt(e.component);let s;return t[Rt](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(Kc(e,t))):(n,o,...r)=>{const i="$setAll"===t||"$resolve"===t&&r.length>0,a=i?Gc(e,n):Kc(e,n),l=vt(e.component)?.listIndex.indexes??[],c=Xc(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:Kc(e,s)])}),r},set:(o,s,r)=>("string"!=typeof s||t.createState("writable",t=>{n(t,()=>{t["$"===s[0]?s:Gc(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 Kc(e,n),!0}catch{return!1}}})}function ef(e,t){const n=function(e){return Yc.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&&ps(t).dispose(),function(e,t){sd(),Yc.set(e,t),td.set(t,e);let n=Zc.get(t.parentStateElement);void 0===n&&(n=new Map,Zc.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&&ed.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=wa.get(e);if(void 0!==n){if(n===t)return;se("A state tree is already registered on this root.")}wa.set(e,t)}(t,e.parentStateElement),function(e,t){const n=(t,n)=>Jc(e,t,n);ne(t);const o=vt(e.component);Ua(t instanceof ShadowRoot?t:t.getRootNode(),t,void 0,n),da(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=Kc(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),Uu(e.parentStateElement,a.parentPath,a.lastSegment,!0).holders.add({ref:new WeakRef(e),entry:l}),e.parentStateElement.addDynamicDependency(t,i),Sc?.markExported(e.parentStateElement,i)}e.parentStateElement.markHasMounts?.()}(e),function(e){const t=vt(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(Hu.has(s))continue;const r=ae(o.exportedPath);let i;e.parentStateElement.createState("readonly",e=>{e[Rt](t,()=>{i=e[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Hu.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(),ba.set(o,s),s.then(()=>Ia(o),()=>{})}function tf(e,t){const n=ps(t),o=vt(e.component);n.forEachActiveBindingNode(e=>$t(e,o));ca(n.rebindAddresses()),Ju(e)}function nf(e,t){if(function(e){const t=Zc.get(e);return void 0!==t&&t.size>0}(t))for(const n of rd(t)){if(!of(n.component,e))continue;const t=nd(n);null!==t&&tf(n,t)}}function of(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 sf={read(e,t,n,o){if(!0===e.hasMounts&&35===t.pathInfo.lastSegment.charCodeAt(0)){const s=id(e,t.pathInfo.path);if(null!==s)return Qu(s,t,n,o)}return hl},readMissing(e,t,n,o,s){if(null===n){if(Eu(e.rootNode??null,t.pathInfo.path))return;return hl}if(!0===e.hasMounts){const n=Ku(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s){const r=Qu(e,vn(ae(t.markerTerminalPath),n),o,s);return Reflect.get(r,t.suffix)}(n.record,n.entry,t.listIndex,o,s)}return hl},write(e,t){if(!0===e.hasGraftedVolumes){const n=t.pathInfo.path,o=function(e,t){const n=Mu.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 hl},writeMissing(e,t,n,o,s,r,i){if(!0===e.hasMounts){const n=Ku(e,t.parentAddress.pathInfo.path,t.pathInfo.lastSegment,t.listIndex);if(null!==n)return function(e,t,n,o,s,r){const i=Qu(e,vn(ae(t.markerTerminalPath),n),s,r);return Reflect.set(i,t.suffix,o)}(n.record,n.entry,t.listIndex,s,r,i)}return hl},indexShift(e,t){const n=e.stateElement,o=t.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const e=id(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=Yc.get(n);if(void 0!==e)return e;n=n.parentNode}return Yc.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 Wu.get(e)??Du}(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=ju(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=sn(n.listIndex,a);(r[i]??=[]).push(e)}}if(o.size>0)try{s.callback.call(Lu(s.mountPath,n,s.injections),Array.from(o),r)}catch(e){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,e)}}},suppressPathDiagnostic:(e,t)=>Eu(!1===e.isConnected?null:e.rootNode??null,t),rowReused(e,t){nf(t,e)}};let rf=!1;const af=new WeakMap;function lf(e){let t=af.get(e);return void 0===t&&(t={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},af.set(e,t)),t}function cf(e,t){null!==t.slotRootNode&&(!function(e,t,n){const o=Tu.get(e);o?.get(t)===n&&o.set(t,null)}(t.slotRootNode,t.mountPath,e),t.slotRootNode=null)}function df(e,t,n){if(t.slotRootNode===n)return!0;const s=t.mountPath;try{Cu(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 xa(n)?.markHasVolume?.(),t.slotRootNode=n,!0}async function uf(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 Re(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).`),Cu(s,r,e),xa(s)?.markHasVolume?.(),t.mountPath=r,t.slotRootNode=s}catch(t){throw e.settleInitialization(),t}t.initializing=!0,null===xa(s)&&function(e,t){const n=()=>{if(null!==xa(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&&cf(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&&df(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 yp(t,a);bp(),function(e,t){if(zu.has(e))return void Fu(t);let n=Bu.get(e);void 0===n&&(n=[],Bu.set(e,n)),n.push(t)}(e,a)}(c,xa(c),r,l,a,()=>df(e,t,c),i):a(null)}const ff={order:20,connecting(e){if(!e.hasAttribute("mount"))return null;const t=lf(e);if(t.initializing){const n=e.connectedRootNode;if(null!=n&&t.detachedFrom===n)try{Cu(n,t.mountPath,e),xa(n)?.markHasVolume?.(),t.slotRootNode=n}catch{}return t.detachedFrom=null,mc}return uf(e,t)},reconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=lf(e),n=e.connectedRootNode??null;return null!==t.graftInfo&&null!==n&&xa(n)===t.graftInfo.rootStateElement&&pp(t.graftInfo,"$connectedCallback"),!0},replacingState(e){if(!0!==af.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){zu.add(e);const t=Bu.get(e);if(void 0!==t){Bu.delete(e);for(const e of t)Fu(e)}}(t)},initializeFailureCleared(e,t){!function(e){zu.delete(e)}(t)},disconnecting(e){if(!e.hasAttribute("mount"))return!1;const t=lf(e);return null!==t.graftInfo&&pp(t.graftInfo,"$disconnectedCallback"),!0!==e.initialized&&(t.detachedFrom=t.slotRootNode,cf(e,t)),e.clearConnectedRootNode(),!0}};let hf=!1;const pf=new WeakMap;function gf(e,t){let n=pf.get(e);n||(n=new Set,pf.set(e,n)),n.add(t)}const mf=new WeakMap;const yf=new WeakMap,wf=new WeakMap;const bf=new WeakMap;const vf={isComplete:function(e,t){return!0===pf.get(e)?.has(t)},isDeclared:function(e,t){return!0===mf.get(e)?.has(t)},rememberOverwrittenObject:function(e,t,n){let o=yf.get(e);o||(o=new Map,yf.set(e,o)),o.has(t)||o.set(t,n)},recordInjectedKey:function(e,t,n){let o=wf.get(e);o||(o=new Map,wf.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=bf.get(e);s||(s=new Map,bf.set(e,s));let r=s.get(t);r||(r=new Map,s.set(t,r)),r.has(n)||r.set(n,o)}};function $f(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 xf=new WeakMap;class Sf{_innerStateElement;constructor(e,t){this._innerStateElement=function(e,t){const n=xf.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 Pf=e=>()=>e;function If(e,t,n,o){!function(e,t,n){let o=xf.get(e);o||(o=new Map,xf.set(e,o)),o.set(t,n)}(t,n,e),e.setInitialState($f(o));const s=function(e,t){const n=new Sf(e,t);return new Proxy({},n)}(t,n);Object.defineProperty(t,n,{get:Pf(s),enumerable:!0,configurable:!0}),gf(t,n),Af(t,n)}function Af(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 Nf=new Set;function kf(e,t){Nf.has(e)||(Nf.add(e),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${t} See docs/state-mount-design.md §4-3.`))}function _f(e){const t=e.rootEntry,n=vt(e.component);if(t.outerPathInfo.wildcardCount>0&&null===n)return;let o;return e.parentStateElement.createState("readonly",e=>{e[Rt](n,()=>{o=e[t.outerPathInfo.path]})}),o}const Tf=new WeakMap;function Cf(e,t){e.landInitialization(),se(t)}async function Ef(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?Ge(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)||Cf(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=mf.get(e);n||(n=new Set,mf.set(e,n)),n.add(t)}(a,d);const u=Je(a);null===u&&se(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await Ve(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=yf.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=lt(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||(lt(a)??[]).some(e=>e.propSegments[0]===d)||Cf(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=(lt(a)??[]).filter(e=>e.propSegments[0]===d);if(o.length>0){const c=xa(a.getRootNode())??Cf(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=bf.get(e)?.get(t);if(void 0!==o){for(const[e,t]of o)n[e]=t;bf.get(e).delete(t)}}(a,d,f),u=Wc(a,d,o,c,f,function(e,t){return wf.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=_f(e),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const t=e.rootEntry.outerPathInfo.path;kf(`${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{ef(u,i instanceof ShadowRoot?i:a)}catch(t){throw e.landInitialization(),t}if(!h){const e=Zu(u);Object.defineProperty(a,d,{get:()=>e,enumerable:!0,configurable:!0}),gf(a,d)}return Af(a,d),function(e){const t=Rc.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}`;jc.has(n)||(jc.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 Lc(u,"$connectedCallback")}}If(e,t.boundComponent,t.boundComponentStateProp,f)}var s,r}const Mf={order:30,preparing(e){if(!e.hasAttribute("bind-component"))return null;const t=function(e){let t=Tf.get(e);return void 0===t&&(t={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Tf.set(e,t)),t}(e);return Ef(e,t).then(()=>null!==t.mountRecord&&(e.markInitialized(),e.settleInitialization(),!0))},reconnecting(e){const t=Tf.get(e);if(void 0===t||null===t.mountRecord)return!1;const n=t.mountRecord,o=e.parentNode;return queueMicrotask(()=>{null!=e.connectedRootNode&&tf(n,o)}),Lc(n,"$connectedCallback"),!0},disconnecting(e){const t=Tf.get(e);return void 0!==t&&null!==t.mountRecord&&(Lc(t.mountRecord,"$disconnectedCallback"),Ju(t.mountRecord),e.clearConnectedRootNode(),!0)}};let Of=!1;function Rf(){Of||(Of=!0,bc("bindComponent",Mf),ms=vf)}const jf=new WeakMap,Lf=new Set,Wf=new Set;function Df(e){return e.byFromPath.size>0||e.byResetPath.size>0}function Bf(e,t,n){const o=e.get(t);void 0===o?e.set(t,[n]):o.push(n)}function zf(e){return jf.get(e)}function Ff(e){qf(e),jf.delete(e)}function qf(e){Lf.delete(e),Wf.delete(e)}const Vf=new WeakMap,Hf=new WeakMap,Uf=new Set,Gf=new Map;function Kf(e){return Vf.get(e)??Gf}function Jf(e){Uf.add(e),function(e){const t=jf.get(e);void 0!==t&&(Df(t)&&Lf.add(e),function(e){return e.eventResetByPath.size>0}(t)&&Wf.add(e))}(e)}const Xf=new Map;function Yf(e){return Hf.get(e)??Xf}function Qf(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 Zf(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=Qf(t);o.set(t,{path:t,pathInfo:n,handler:i,order:r++}),s.add(t),e.setPathInfo(t,"prop","watch")}return function(e,t){Vf.set(e,t)}(e,o),s.size>0?s:null}let eh=0,th=0;function nh(e){eh=e+1}function oh(){eh=0}function sh(){eh>th&&(th=eh)}const rh=new WeakMap;function ih(e,t,n){let o=rh.get(e);void 0===o&&(o=new Map,rh.set(e,o)),o.set(t,n)}const ah=new Map;function lh(e,t){ah.has(e)||ah.set(e,t)}function ch(e){return ah.get(e)}const dh={writeObserve(e,t,n,o,s){if(!s)return;const r=e.watchPaths,i=e.scanPaths;!0!==r?.has(t)&&!0!==i?.has(t)||lh(n,o)},swapped(e,t,n){var o;o=n,ah.has(o)&&lh(t,ch(n))}};function uh(e){for(let t=e;null!==t;t=t.parentListIndex)if(Ds(t))return!0;return!1}function fh(e,t,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<t.wildcardCount;i++){const a=e[jt](vn(t.wildcardParentPathInfos[i],r)),l=zs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=on(o,i,t.wildcardCount);if(l!==c&&!js(l,c)){if(Ds(c))return"gone";s="replaced"}r=l}return s}function hh(e,t,n){const o=new Map;for(const s of n){const n=fh(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 ph=new Set;function gh(e){ph.delete(e)}function mh(){return ph}const yh=Symbol("wcs-stream-last-notified-uncertain"),wh=new WeakMap;function bh(e,t){const n=wh.get(e);if(void 0!==n)for(const e of n.keys())t.has(e)||n.delete(e)}function vh(e,t){const n=wh.get(e);if(void 0===n)return;const o=n.get(t);void 0!==o&&n.set(t,{status:"idle"===o.status?o.status:yh,error:Object.is(o.error,null)?null:yh})}const $h=new WeakMap;function xh(e){return $h.get(e)??new Map}function Sh(e){gh(e);const t=$h.get(e);if(void 0!==t)for(const n of t.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,vh(e,n.name)}const Ph=new WeakSet;let Ih=0;function Ah(e){return zf(e.absolutePathInfo.stateElement)?.eventResetByPath.get(e.absolutePathInfo.pathInfo.path)}function Nh(e){if(0===Wf.size)return;if(t=e.absolutePathInfo.stateElement,!Wf.has(t))return;var t;const n=Ah(e);if(void 0!==n)for(const e of n)kh(e)}function kh(e){Ph.has(e)||(Ph.add(e),Ih++)}function _h(e){return!!Ph.delete(e)&&(Ih--,!0)}const Th=/^(?:0|[1-9]\d*)$/;function Ch(e,t){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n.enumerable&&"value"in n}function Eh(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&&Th.test(t)&&Ch(e,t))?"array":null}return(t===Object.prototype||null===t)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&Ch(e,t))?"object":null}function Mh(e,t){const n=Eh(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]=Mh(o[e],t);return r}function Oh(e){return Mh(e,new Map)}function Rh(e,t,n){if(Object.is(e,t))return!0;const o=Eh(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(Eh(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(!Rh(s[t],r[t],n))return!1;return!0}return Object.keys(r).every(e=>Object.prototype.hasOwnProperty.call(s,e)&&Rh(s[e],r[e],n))}function jh(e,t){return Rh(e,t,new Map)}const Lh=new WeakMap;function Wh(e,t){if("function"!=typeof t)return;const n=Lh.get(t);void 0===n?Lh.set(t,new Set([e])):n.add(e)}const Dh={"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}".`},Bh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function zh(e,t,n){null!==xt&&xt({type:"state:watch-error",phase:t,path:`${G}.${e}`,error:n})}function Fh(e,t,n){console.error(`[@wcstack/state] ${Dh[n](e)}`,t),zh(e,Bh[n],t)}function qh(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function Vh(e,t){t.then(void 0,()=>{}),Fh(e,new TypeError(`${G} fold for "${e}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Hh=new WeakSet;const Uh=Object.freeze([]);function Gh(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 Kh(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===zf(e.stateElement)?.entries.has(e.entry)}function Xh(e){const{entry:t,stateElement:n}=e;"event"!==t.source.kind||t.resetOn.some(e=>Yh(n,e))||_h(t)}function Yh(e,t){return or().hasQueuedPath(e,t)}function Qh(e,t){!function(e,t,n){if(0!==Ih)for(const o of e){const e=o.absolutePathInfo.stateElement;if(!0===t?.has(e))continue;const s=Ah(o);if(void 0!==s)for(const t of s)t.resetOn.some(t=>n(e,t))||_h(t)}}(e,t,Yh)}function Zh(e,t,n){return 0===t.pathInfo.wildcardCount?e[t.path]:e.$resolve(t.path,n.indexes)}function ep(e,t,n){if(!Jh(e,n))return Xh(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(Hh.has(e))return;Hh.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}`),zh(t,"fold",new Error(o))}(s,s.name,r.path),null;if(function(e,t,n){const o=xh(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:hh(t,r.pathInfo,e.rows);i.failure="threw";const a=s.fold;let l=n;for(const e of o.sort(Kh)){let n;try{n=Zh(t,r,e)}catch(e){Fh(s.name,e,"read-source");continue}const o=a(l,n,ch(e.absAddress),...e.indexes);if(qh(o))return void Vh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:e,next:l})})}catch(e){Fh(s.name,e,i.failure)}return i.plan}function tp(e,t){const{group:n}=e;if(!Jh(n,t))return void Xh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||_h(s))try{o.createState("writable",t=>{const o=t[s.name];if(n.reset?!jh(o,s.initial):!Object.is(o,e.next)){const o=n.reset?Oh(s.initial):e.next;t[s.name]=o,Wh(s.name,o)}})}catch(e){Fh(s.name,e,"write")}}function np(e,t,n){if(Qh(e,t),0===Lf.size)return Uh;const o=new Map;for(const n of e){const e=n.absolutePathInfo.stateElement;if(!t.has(e))continue;const s=zf(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=sn(n.listIndex,r.wildcardCount)}for(const s of i)Gh(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)Gh(o,e,t).reset=!0}if(0===o.size)return Uh;const s=Array.from(o.values()).sort((e,t)=>e.entry.order-t.entry.order),r=[];nh(n);try{for(const n of s){const o=ep(n,e,t);null!==o&&r.push(o)}}finally{oh()}return r}function op(e){fp(),(0!==Kf(e).size||0!==Yf(e).size||function(e){const t=jf.get(e);return void 0!==t&&Df(t)}(e))&&(Jf(e),function(e){const t=[];for(const n of Kf(e).values())sp(e,n)&&t.push(n);for(const n of Yf(e).values())for(const o of n)sp(e,o)&&t.push(o);if(0===t.length)return;e.createState("readonly",n=>{for(const o of t)try{ih(e,Yt(e,o.pathInfo,null),n[o.path])}catch(t){ip(e,o.path,"prime",t)}})}(e))}function sp(e,t){return 0===t.pathInfo.wildcardCount&&e.getterPaths.has(t.path)}const rp={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function ip(e,t,n,o){console.error(`[@wcstack/state] $watch ${rp[n]} "${t}" threw.`,o),null!==xt&&xt({type:"state:watch-error",phase:n,path:t,error:o})}function ap(e){const t=Uf;try{if(0===t.size)return void Qh(e,t);const n=function(){const e=th;return th=0,e}();if(n>32){Qh(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!==xt&&xt({type:"state:watch-chain-limit",maxDepth:32,paths:t}))}!function(e,t,n){if(0!==e.length){nh(n);try{for(const n of e)tp(n,t)}finally{oh()}}}(np(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=Kf(e).get(s),i=Yf(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=sn(n.listIndex,t.pathInfo.wildcardCount)}o.push({stateElement:e,entry:t,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(cp);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];(uh(o.absAddress.listIndex)||s?.entry===o.entry&&lp(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(hh(e,o.pathInfo,t));for(const e of t)s.has(e)||n.add(e)})}catch(e){ip(0,o.path,"evaluate",e);for(const e of t)n.add(e)}}return e.filter(e=>!n.has(e))}(o);nh(n);try{for(const e of s){if(!t.has(e.stateElement))continue;const n=Kf(e.stateElement).get(e.entry.path)===e.entry,o=!0===Yf(e.stateElement).get(e.entry.path)?.includes(e.entry);(n||o)&&dp(e)}}finally{oh()}}(e,t,n)}finally{ah.clear()}}function lp(e,t){for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function cp(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 dp(e){const{stateElement:t,entry:n,absAddress:o,indexes:s}=e,r=sp(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 ip(0,n.path,"evaluate",e)}const a=r?function(e,t){return rh.get(e)?.get(t)}(t,o):ch(o);r&&ih(t,o,i),null!==xt&&xt({type:"state:watch-fired",path:n.path,stateElement:t}),n.handler.call(e,i,a,...s)})}catch(e){ip(0,n.path,"handler",e)}}let up=!1;function fp(){up||(up=!0,ml("watch",dh),vl("watch",hp),Zs(ap,10),Qs(sh))}const hp={order:10,register(e,t){var n;n=e,Uf.delete(n),qf(n),Vf.delete(n),function(e){rh.delete(e)}(e);const o=Zf(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)&&op(e)},deactivate(e){var t;t=e,Uf.delete(t),qf(t)}};function pp(e,t){const n=e.volumeState[t];"function"==typeof n&&e.rootStateElement.createState("writable",o=>{const s=n.call(Lu(e.mountPath,o,e.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${e.mountPath}" ${t} failed.`,n)})})}function gp(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=Ru(t,o,a,!1),c=function(e,n,...s){l.call(Lu(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=Hf.get(e);void 0===n&&(n=new Map,Hf.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),op(e))}const r=n[X];if(void 0!==r){const n=new Map;for(const[e,s]of Object.entries(r))n.set(Ru(t,o,e,!1),s);e.mergeVolumeListKeys?.(n)}const i=n[j];"function"==typeof i&&(!function(e,t){let n=Wu.get(e);void 0===n&&(n=[],Wu.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 mp(e,t,n,o=[]){ll(n),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.`),Qf(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=Ru(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[H]&&se(`Volume "${t}" declares ${H}, 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(xc(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=Mu.get(e);void 0===n&&(n=new Set,Mu.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(Lu(t,this,o))}),"function"==typeof a&&(l.set=function(e){a.call(Lu(t,this,o),e)}),e.defineTreeAccessor(r,l)}gp(e,t,n,o);const l=n.$connectedCallback;return"function"==typeof l&&e.createState("writable",e=>{let n;try{n=l.call(Lu(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 yp(e,t){if(!t.acquireSlot())return void t.onGrafted(null);let n=null;try{n=mp(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 wp=!1;function bp(){var e;wp||(wp=!0,rf||(rf=!0,ml("scopes",sf)),hf||(hf=!0,bc("scopes",ff)),Rf(),qu=yp,e=vp,$a.includes(e)||$a.push(e))}function vp(e,t){(function(e){const t=Tu.get(e);return void 0!==t&&t.size>0})(e)&&t.markHasVolume?.(),function(e,t){zu.delete(e);const n=Bu.get(e);if(void 0===n||0===n.length||null===qu)return;Bu.delete(e);const o=qu;queueMicrotask(()=>{for(const e of n)o(t,e)})}(e,t)}const $p={name:"scopes",install(){bp(),_u||(_u=!0,bc("dcc",ku))}},xp=/^@@wcs-(?:for|if|elseif|else):[^-]/,Sp=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,Pp=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Ip=/^@@wcs-text-start:(.+)$/;function Ap(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Np extends $c{_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=ad.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=Ap(JSON.stringify(t)),e.appendChild(n);const s=Array.from(Na.keys());for(const t of s){const n=_a(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(_i);if(r.length>0){const t={};for(let e=0;e<r.length;e++){const n=r[e],o=ki(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=Ap(JSON.stringify(t)),e.appendChild(n)}}_i.clear()}static removeBlockBoundaryComments(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),n=[];for(;t.nextNode();){const e=t.currentNode;(Sp.test(e.data)||Pp.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;xp.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=Ip.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;Sp.test(e.data)&&i.push(e)}for(const e of i){const t=Sp.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()}Np.restoreTextBindings(t);const a=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const e=a.currentNode;if(xp.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 kp={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",ad),Np.buildContent(o,Np.extractStateData(e)),e.parentNode?.insertBefore(o,e)}}};const _p=new Set(["for","if","elseif","else"]);function Tp(e){const t=new hs;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]=gt(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 Cp(e,t,n){for(const o of t)"event"===o.bindingType||_p.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in M||ae(o.statePathName).wildcardCount>n||e.push(o)}function Ep(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 Mp(e,t){const n=e;let s=null;for(const[e,r]of t.templates){let t=Re(r.getAttribute(o.bindAttributeName)||"")[0];const i=t.bindingType;"else"===i&&s&&(t={...s,outFilters:[...s.outFilters,Ea()],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;za(a),"string"==typeof l&&Wa(a,l),Ua(n,a,l);ka(e,n,{fragment:a,parseBindTextResult:t,nodeInfos:Ba(a)})}}const Op={hydrate:async function(e){await fa(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="${ad}". Falling back to full render.`),Np.cleanupDom(e),!1}for(const n of t)Mp(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=Sp.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=ii(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=Tp(s.nodes);Wr(t,a);for(const e of i)e.nodeType===Node.ELEMENT_NODE&&e.setAttribute("data-wcs-completed","");xs(t,r),zr(t,i);const l=[];for(const e of r)e.statePathName in M&&l.push(e);if(Is(t,l),"for"===s.type&&null!==s.index){const i=Ep(e,"for",s.uuid);if(i){const e=Es(null,s.index);yi(i,e,t),wi(i,s.nodes[s.nodes.length-1]),Qr(i,t);const l=ae(s.path+"."+d);Fr(t,vn(l,e)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Cp(o,r,l.wildcardCount);let c=n.get(s.uuid);c||(c=[],n.set(s.uuid,c)),c.push(e)}}else{const n=Ep(e,s.type,s.uuid);n&&(Qr(n,t),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Cp(o,r,0))}}for(const[t,o]of n){const n=Ep(e,"for",t);if(!n)continue;const s=n.getRootNode(),r=_a(t);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=xa(s);a&&a.createState("readonly",e=>{const t=e[i];Array.isArray(t)&&qs(t,o)})}return o}(document.body,n);Np.removeBlockBoundaryComments(document.body);const r=[];for(const e of t)e.parentNode&&(r.push({el:e,parent:e.parentNode,next:e.nextSibling}),e.remove());Np.restoreTextBindings(document.body);const[i,a]=gt(document.body);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){const t=e;t.hasAttribute("data-wcs-completed")||($t(e,null),t.setAttribute("data-wcs-completed",""))}else $t(e,null);const l=[],c=[],u=ps(document.body).initialize(a);for(const e of u)if("event"!==e.bindingType)if(_p.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=dn(e),n=xa(e.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[e.statePathName];Array.isArray(o)&&(It(t,o),Ct(t,o))})}ca([...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=Np.find(t);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(e){await Sa(e.rootNode);const t=Np.extractStateData(e),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",ad),Np.buildContent(n,t),e.parentNode?.insertBefore(n,e)}};let Rp=!1;function jp(){var t;Rp||(Rp=!0,ma=Op,t=e=>{e.get(o.tagNames.ssr)||e.define(o.tagNames.ssr,Np)},Nc.includes(t)||Nc.push(t),function(){const t=globalThis;void 0===t[e]&&(t[e]=kp)}())}const Lp={name:"ssr",install(){jp()}},Wp="[wcs/scan-declaration-invalid]",Dp=Object.freeze([]);function Bp(e){return`${G} entry "${e}"`}function zp(e,t){for(const n of e.cumulativePaths)if(t.has(n))return n;return null}function Fp(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 qp(e,t,n){0===n.length&&se(`${Wp} ${e} "${t}" must be a non-empty state path.${ue}`),n.startsWith("$")&&se(`${Wp} ${e} ${t} "${n}" must not start with "$" (reserved namespace).${ue}`),n.includes("@")&&se(`${Wp} ${e} ${t} "${n}" must not contain "@" — there is a single state tree per root.${ue}`),n in Object.prototype&&se(`${Wp} ${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(`${Wp} ${e} ${t} "${n}" has an empty path segment.${ue}`);return o.wildcardCount>u&&se(`${Wp} ${e} ${t} "${n}" exceeds the maximum wildcard depth (128).`),o}function Vp(e,t,n,o){const s=Bp(e);0===e.length&&se(`${Wp} ${G} entry name must be a non-empty string.${ue}`),(e.includes(c)||e.includes(d))&&se(`${Wp} ${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(`${Wp} ${s} must not start with "$" (reserved namespace).${ue}`),e in Object.prototype&&se(`${Wp} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${ue}`),t.has(e)&&se(`${Wp} ${s} conflicts with a getter declared on the state.${ue}`),n.has(e)&&se(`${Wp} ${s} conflicts with a setter declared on the state.${ue}`),o.has(e)&&se(`${Wp} ${s} conflicts with the ${H} entry of the same name — each output has exactly one owner.${ue}`)}function Hp(e,t,n){const o=t.get(e);t.has(e)&&o!==n.initial&&!function(e,t){return"function"==typeof t&&!0===Lh.get(t)?.has(e)}(e,o)&&se(`${Wp} ${Bp(e)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${ue}`)}function Up(e,t,n,o,s,r){const i=Bp(e),a=void 0!==t.from,l=void 0!==t.on;if(a===l&&se(`${Wp} ${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(`${Wp} ${i} "on" must be a non-empty event-token name.${ue}`),n.has(e)||se(`${Wp} ${i} on "${e}" is not declared in ${q}.${de(e,n)}${ue}`),{kind:"event",tokenName:e}}const d=t.from;"string"!=typeof d&&se(`${Wp} ${i} "from" must be a state path string.${ue}`);const u=qp(i,"from",d),f=zp(u,o)??r?.recursiveGetterOwning(d)??null;null!==f&&se(Fp(i,"from",d,f));const h=zp(u,s);return null!==h&&se(function(e,t,n){return`${Wp} ${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(`${Wp} ${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 Gp(e,t,n,o){if(void 0===t)return Dp;const s=Bp(e);Array.isArray(t)||se(`${Wp} ${s} "resetOn" must be an array of state paths.${ue}`);const r=[];for(const e of t){"string"!=typeof e&&se(`${Wp} ${s} "resetOn" must contain only state path strings.${ue}`);const t=qp(s,"resetOn",e);t.wildcardCount>0&&se(`${Wp} ${s} resetOn "${e}" must not contain "${d}" — a reset returns the whole output to "initial".${ue}`);const i=zp(t,o);null!==i&&se(Fp(s,"resetOn",e,i)),"path"===n.kind&&e===n.path&&se(`${Wp} ${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(`${Wp} ${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 Kp(e,t,n=null){const o=e[G];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&se(`${Wp} ${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(xc(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){ll(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)){Vp(e,s,r,l),("object"!=typeof u||null===u||Array.isArray(u))&&se(`${Wp} ${Bp(e)} must be an object ({ from | on, initial, fold, resetOn? }).${ue}`);const o=u;Hp(e,a,o);const f=Up(e,o,t,s,i,n);"initial"in o||se(`${Wp} ${Bp(e)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${ue}`),"function"!=typeof o.fold&&se(`${Wp} ${Bp(e)} fold must be a function.${ue}`);const h=Gp(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(`${Wp} ${Bp(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(`${Wp} ${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 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 Ph.has(e)}(e),l=a&&!jh(n,e.initial)?Oh(e.initial):n,c=t(l,o,...s);if(qh(c))return void Vh(e.name,c);Object.is(c,n)||(i="write",r[e.name]=c,Wh(e.name,c)),a&&_h(e)}catch(t){Fh(e.name,t,i)}}}function Xp(e,t,n){const o=function(e,t){Ff(e);const n=new Map,o=new Map,s=new Map;for(const e of t){"path"===e.source.kind&&Bf(n,e.source.path,e);for(const t of e.resetOn)Bf(o,t,e),"event"===e.source.kind&&Bf(s,t,e)}const r={entries:new Set(t),byFromPath:n,byResetPath:o,eventResetByPath:s};return jf.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)&&or().hasQueuedPath(e,n))&&kh(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 Yp="scanEntries",Qp={order:8,validate(e,t,n){const o=Kp(t,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Yp,o)},applyEarly(e,t,n){const o=n.get(Yp)??null;null!==o&&(function(e,t){for(const n of t)if(!(n.name in e)){const t=Oh(n.initial);e[n.name]=t,Wh(n.name,t)}}(t,o),function(e,t){for(const n of t)"event"===n.source.kind&&Rn(e,n.source.tokenName).subscribe(Jp(n))}(e,o))},register(e,t,n){const o=n.get(Yp)??null,s=function(e){const t=new Map,n=zf(e);if(void 0!==n)for(const e of n.entries)_h(e)&&t.set(e.name,e.resetOn);return Ff(e),t}(e);e.setScanPaths?.(null===o?null:Xp(e,o,s))}};let Zp=!1;const eg=Object.freeze([]),tg=Object.freeze([]);function ng(e,t,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=e.staticDependency.get(n)??eg,i=e.dynamicDependency.get(n)??eg,a=t.byFromPath.get(n)??tg;for(const e of[...r,...i,...a.map(e=>e.name)])o.has(e)||(o.add(e),s.push(e))}return o}const og=(e,t)=>t,sg=new Set;function rg(e,t){ll(t);const n=t[H];if(void 0===n)return void bh(e,sg);"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??og,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){$h.set(e,t)}(e,o),bh(e,new Set(o.keys()))}const ig=new WeakMap,ag=new WeakMap;function lg(e,t,n){return new Proxy(Object.create(null),{get(t,o){if("string"!=typeof o)return;const s=xh(e).get(o);return void 0!==s?n(s):void 0},has:(t,n)=>"string"==typeof n&&xh(e).has(n),ownKeys:()=>Array.from(xh(e).keys()),getOwnPropertyDescriptor(t,o){if("string"!=typeof o)return;const s=xh(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 cg(e){const t=ig.get(e);if(void 0!==t)return t;const n=lg(e,Y,e=>e.status);return ig.set(e,n),n}function dg(e){const t=ag.get(e);if(void 0!==t)return t;const n=lg(e,Q,e=>e.error);return ag.set(e,n),n}function ug(e){ig.delete(e),ag.delete(e)}let fg=null;function hg(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 pg={read(e,t){!function(e,t){null!==fg&&fg.add(Xt(e,t))}(e,t);const n=t.pathInfo.segments[0];return n===Y?hg(cg(e),t.pathInfo.segments):n===Q?hg(dg(e),t.pathInfo.segments):hl},get:(e,t)=>t===Y?cg(e.stateElement):t===Q?dg(e.stateElement):hl};async function gg(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 mg(e){Sg();const t=xh(e);if(0!==t.size){!function(e){ph.add(e)}(e);for(const n of t.values())yg(e,n)}}function yg(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=fg,s=new Set;let r;fg=s;try{e.createState("readonly",e=>{r=n(e)})}finally{fg=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=zf(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=ng(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}),wg(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(){wg(e,t,"done",null)},fail(o){wg(e,t,"error",o),n.abort()}};gg(s.source,o,n.signal,r)}function wg(e,t,n,o){t.status=n,t.error=o;const s=function(e,t){return wh.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=wh.get(e);void 0===s&&(s=new Map,wh.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 bg(e){const t=mh();if(0===t.size)return;const n=[];for(const o of t)for(const t of xh(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)&&xh(e).get(o.name)===o)try{yg(e,o)}catch(n){o.controller?.abort(),t.has(e)&&xh(e).get(o.name)===o&&wg(e,o,"error",n)}}let vg=!1;const $g=new WeakMap,xg={order:20,apply(e,t){var n;ug(e),Sh(n=e),gh(n),$h.delete(n),rg(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 mg(e),void $g.set(e,e.connectGeneration??0)}n===e.connectGeneration&&$g.get(e)!==n&&mg(e)}},deactivate(e){Sh(e),ug(e)}};function Sg(){vg||(vg=!0,ml("streams",pg),vl("streams",xg),Zs(bg,20))}const Pg=[Fd,{name:"temporal",install(){fp(),Zp||(Zp=!0,vl("scan",Qp),Qs(Nh)),Sg()}},mu,$p,Lp,bd,Td];function Ig(e,t){!function(e){for(let t=0;t<e.length;t++)e[t].install()}(Pg),Tc(e,t)}function Ag(e){return e}const Ng={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"]},add:{description:"加算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,maxArgs:1,argTypes:["number"]},sub:{description:"減算",hasArgs:!0,resultType:"number",acceptTypes:["number"],minArgs:1,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"]},toFixed:{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"]},upper:{description:"大文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},lower:{description:"小文字に変換",hasArgs:!1,resultType:"string",acceptTypes:["string"],minArgs:0,maxArgs:0},capitalize:{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"]},padStart:{description:"先頭を埋める (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},padEnd:{description:"末尾を埋める (length[,char])",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:2,argTypes:["number","string"]},repeat:{description:"繰り返し (count)",hasArgs:!0,resultType:"string",acceptTypes:["string"],minArgs:1,maxArgs:1,argTypes:["number"]},reverse:{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"]},coalesce:{description:"null / undefined の場合デフォルト値",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},nullIfEmpty:{description:"空文字列をnullに変換",hasArgs:!1,resultType:"passthrough",acceptTypes:["string"],minArgs:0,maxArgs:0}},kg=1;function _g(){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(Dd),filterMeta:Ng,filterAliases:Rd,reservedLifecycle:[O,R,j,L,W],reservedStateApi:[D,B,z,F,q,V,H,U,G,X,K,Y,Q]}}const Tg=new Set(["wcstack.types","wcstack.async","wcstack.platformCapabilities","wcstack.application"]),Cg=Object.freeze([]);function Eg(e){if(!o.enableContractAnalyzer)return Cg;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))Tg.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?Mg(e,o,s,n):n({type:"contract:drift",reason:"component-not-loaded",tag:e})}}(e,Og,e=>{t.push(e),null!==xt&&xt(e)}),t}function Mg(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 Og(e){const t=Je(),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{Np as Ssr,Ti as TRUSTED_TYPES_POLICY_SLOT,ad as VERSION,kg as WCS_MANIFEST_VERSION,Eg as analyzeContract,Ig as bootstrapState,ha as buildBindings,Ng as builtinFilterMeta,Ag as defineState,Sa as getBindingsReady,s as getConfig,Ci as getTrustedTypesPolicy,_g as getWcsManifest,Ei as setTrustedTypesPolicy};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|