wcstack 2.4.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/package.json +1 -1
package/dist/auto.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n,s=".",r="*",i=128,a=128,l="|",c="prevent",u="stop",d="ro",h="init",f="sync",p="else",m="...",g="on",y="eventToken",b="command",w="class",v="attr",_="style",$={};for(let t=0;t<i;t++)$[`$${t+1}`]=t;const S=Object.freeze($),x="$connectedCallback",N="$disconnectedCallback",P="$updatedCallback",I="$errorCallback",k="$stateReadyCallback",A="$bindables",E="$commands",C="$commandTokens",T="$command",M="$eventTokens",O="$on",L="$streams",R="$watch",j="$scan",D="$recursion",W="**",B="$listKeys",z="$streamStatus",F="$streamError",H="data-wc-definition",U=new WeakMap,q=new WeakSet;let G=0;async function V(t){const e=function(t){let e,n=U.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++G,promise:o,resolve:e},U.set(t,n),q.has(t)&&n.resolve(),n}(t);await e.promise}function K(t){const e=U.get(t);void 0===e?q.add(t):e.resolve()}function J(t){throw new Error(`[@wcstack/state] ${t}`)}const Q=new Map;let X=0;function Y(t){let e=Q.get(t);return void 0!==e||(-1!==t.indexOf(W)&&J(`[wcs/recursion-unsupported] "${t}" uses "${W}", 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.`),e=Object.freeze(new Z(t)),Q.set(t,e)),e}let Z=class{id=++X;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:Y(e),n=t.split("."),o=[],s=[],i=[],a={},l=[],c=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===r&&(i.push(h),a[h]=p,l.push(e(h)),c.push(f),u.push(e(f)),d.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=i.length>0?i[i.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=i,this.wildcardPathSet=new Set(i),this.indexByWildcardPath=a,this.wildcardPathInfos=l,this.wildcardPathInfoSet=new Set(l),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=u,this.wildcardParentPathInfoSet=new Set(u),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}};const tt=new WeakMap;function et(t){const e=tt.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{tt.set(t,n)}}function nt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function ot(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return nt(e);if(void 0!==n)return nt(n)}return nt(globalThis.customElements)}function st(t,e){t.upgrade?.(e)}function rt(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=ct(s.properties,it);if(null===r)return null;const i=void 0===s.inputs?new Map:ct(s.inputs,at);if(null===i)return null;const a=void 0===s.commands?new Map:ct(s.commands,lt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function it(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function at(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function lt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function ct(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function ut(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:Y(n),inFilters:[],outFilters:[],bindingType:"prop"}}function dt(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function ht(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&J("Spread binding requires an element node.");const e=t,o=et(e);null===o&&J(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=ot(e);if(null===a&&J(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||J(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}st(a,e);const l=rt(e);null===l&&J(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=ut(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=ut(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=dt(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=dt(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function ft(t,e){let n=t;if(0===e.length)return n;for(let t=0;t<e.length&&(n=n?.childNodes[e[t]]??null,null!==n);t++);return n}const pt=new WeakMap;function mt(t){return pt.get(t)||null}function gt(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function yt(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=gt(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const bt=" Validate statically: npx @wcstack/lint <file>.",wt=new Set(["if","elseif","else","for"]);function vt(t){J(`filter ${t} requires at least one option`)}function _t(t){J(`filter ${t} requires a number as option`)}function $t(t){J(`filter ${t} requires a number value`)}function St(t){J(`filter ${t} requires a date value`)}function xt(t){return!(!t||isNaN(Number(t)))}const Nt={eq:t=>{const e=t?.[0]??vt("eq");return t=>"number"==typeof t?(xt(e)||_t("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??vt("ne");return t=>"number"==typeof t?(xt(e)||_t("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&J("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??vt("lt");return xt(e)||_t("lt"),t=>("number"!=typeof t&&$t("lt"),t<Number(e))},le:t=>{const e=t?.[0]??vt("le");return xt(e)||_t("le"),t=>("number"!=typeof t&&$t("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??vt("gt");return xt(e)||_t("gt"),t=>("number"!=typeof t&&$t("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??vt("ge");return xt(e)||_t("ge"),t=>("number"!=typeof t&&$t("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??vt("inc");return xt(e)||_t("inc"),t=>("number"!=typeof t&&$t("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??vt("dec");return xt(e)||_t("dec"),t=>("number"!=typeof t&&$t("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??vt("mul");return xt(e)||_t("mul"),t=>("number"!=typeof t&&$t("mul"),t*Number(e))},div:t=>{const e=t?.[0]??vt("div");return xt(e)||_t("div"),t=>("number"!=typeof t&&$t("div"),t/Number(e))},mod:t=>{const e=t?.[0]??vt("mod");return xt(e)||_t("mod"),t=>("number"!=typeof t&&$t("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&$t("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??vt("clamp");xt(e)||_t("clamp");const n=t?.[1]??vt("clamp");xt(n)||_t("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&$t("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return xt(e)||_t("fix"),t=>("number"!=typeof t&&$t("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&$t("locale"),t.toLocaleString(e??o.locale))},uc:t=>t=>String(t).toUpperCase(),lc:t=>t=>String(t).toLowerCase(),cap:t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)},trim:t=>t=>String(t).trim(),slice:t=>{const e=[],n=t?.[0]??vt("slice");xt(n)||_t("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(xt(o)||_t("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??vt("substr");xt(e)||_t("substr");const n=t?.[1]??vt("substr");return xt(n)||_t("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??vt("pad");xt(e)||_t("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??vt("rep");return xt(e)||_t("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??vt("truncate");xt(e)||_t("truncate");const n=Number(e),o=t?.[1]??"…";return t=>{const e=String(t);return e.length<=n?e:e.slice(0,n)+o}},join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||J("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=t?.[0]??"0";return xt(e)||_t("round"),t=>{"number"!=typeof t&&$t("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return xt(e)||_t("floor"),t=>{"number"!=typeof t&&$t("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return xt(e)||_t("ceil"),t=>{"number"!=typeof t&&$t("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return xt(e)||_t("percent"),t=>("number"!=typeof t&&$t("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??vt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||St("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||St("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||St("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||St("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||St("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!1===t||null==t||0===t||""===t||Number.isNaN(t),truthy:t=>t=>!1!==t&&null!=t&&0!==t&&""!==t&&!Number.isNaN(t),defaults:t=>{const e=t?.[0]??vt("defaults");return t=>!1===t||null==t||0===t||""===t||Number.isNaN(t)?e:t},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),null:t=>t=>""===t?null:t},Pt=Nt,It={input:Nt,output:Pt},kt=(t,e)=>n=>{const o=n[t];return o||J(`[wcs/filter-unknown] filter not found: ${t}.${yt(t,Object.keys(n))}${bt}`),o(e)};function At(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const Et=new Map;function Ct(t,e){const n=It[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&J(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&J(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=Et.get(s);return void 0===r&&(r=kt(o,[])(n),Et.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=t.substring(o+1,s),i=t.substring(0,o).trim(),a=function(t){const e=[];let n="",o=null,s=!1,r=-1,i=-1;const a=()=>{e.push(At(n,r,i)),n="",s=!1,r=-1,i=-1};for(let e=0;e<t.length;e++){const l=t[e];o?l===o?o=null:(-1===r&&(r=n.length),n+=l,i=n.length):'"'===l||"'"===l?(o=l,s=!0):","===l?a():n+=l}const l=At(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=Et.get(l);return void 0===c&&(c=kt(i,a)(n),Et.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const Tt=t=>t.trim(),Mt=new Map,Ot=new Map;function Lt(t){const e=t.indexOf(l);let n="",o=[],s="",r=[];return-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Ot.has(s)?r=Ot.get(s):(o=s.split(l).map(Tt),r=Ct(o,"output"),Ot.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&J(`"${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.`),{statePathName:n,statePathInfo:Y(n),outFilters:r}}function Rt(t){const[...e]=t.split(";").map(Tt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&J(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===p){const t=Y("#else");return{propName:p,propSegments:[p],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===m){const e=Lt(o);return e.outFilters.length>0&&J(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&J(`Invalid spread binding "${t}": spread target path is required.`),{propName:m,propSegments:[m],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Lt(o),bindingType:n};{const t=Lt(o),e=function(t){const e=t.indexOf(l);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),Mt.has(r)?i=Mt.get(r):(o=r.split(l).map(Tt),i=Ct(o,"input"),Mt.set(r,i))):n=t.trim();const[a,c]=n.split("#").map(Tt),u=a.split(s).map(Tt);return{propName:a,propSegments:u,propModifiers:c?c.split(",").map(Tt):[],inFilters:i}}(n);return e.propSegments[0]===y||e.propSegments[0].startsWith(g)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>wt.has(t.bindingType))&&J(`[wcs/template-syntax] Invalid bindText: "${t}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${bt}`),n}const jt=new WeakMap,Dt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Wt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Bt(t){const e=jt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Wt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Dt.has(r)?(jt.set(t,s[2]),s[2]):null}function zt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Lt(t),bindingType:"text"}}const Ft=new Map;function Ht(t,e,n){if(null===n)Ft.delete(t);else{Ft.set(t,n);const o=ia(e);null===o&&J("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function Ut(t){return Ft.get(t)||null}function qt(t){if(t.nodeType===Node.ELEMENT_NODE)return Rt(t.getAttribute(o.bindAttributeName)||"");if(t.nodeType===Node.COMMENT_NODE){const e=Bt(t);null===e&&J("Comment node binding text not found.");const n=Ut(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=zt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function Gt(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function Vt(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Gt(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function Kt(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function Jt(t){const e=[],n=Vt(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Bt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&Kt(t,n)||e.push(t)}return e}const Qt=new WeakSet;function Xt(t,e,n,o){const s=ht(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?et(t):null;return null===n&&J("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}Qt.add(t);const r=function(t,e){const n=[];for(const o of e)if("text"!==o.bindingType)n.push({...o,node:t,replaceNode:t});else{const e=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,node:t,replaceNode:e})}return n}(t,function(t,e){return void 0===e?t:t.map(t=>null!=t.uuid?t:e(t))}(s,o));return function(t,e){pt.set(t,e)}(t,r),K(t),{bindings:r,deferred:null}}function Yt(t,e){const n=Jt(t),o=[],s=[];for(const t of n){if(Qt.has(t))continue;const n=Xt(t,qt(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Zt(t){Qt.add(t)}function te(t){const{node:e,parseResults:n,transform:o}=t;return function(t){Qt.delete(t)}(e),Xt(e,n,{allowDeferred:!1},o).bindings}let ee=0;const ne=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion"],oe=new Set;function se(t,e){const n=t.stateObject[e];if("function"==typeof n)try{const o=t.component[t.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function re(t){const e=t.indexOf(s);return-1===e?t:t.slice(0,e)}function ie(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function ae(t,e){for(const n of t.entries)if(ie(e,n.innerSegments)){const t=e.slice(n.innerSegments.length);return 0===t.length?n.outerPathInfo.path:n.outerPathInfo.path+s+t.join(s)}return null}function le(t,e){return t.markerBasePath+s+e}function ce(t,e,n,o){let r=t.accessorBySuffixByMarkerParent.get(e);void 0===r&&(r=new Map,t.accessorBySuffixByMarkerParent.set(e,r));const i=e+s+n;r.set(n,{accessorName:o,indexShift:Y(i).wildcardCount-Y(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(i),t.addedGetterPaths.add(i))}function ue(t,e){return!t.injectedKeys.has(e)&&("function"==typeof t.stateObject[e]&&!t.getterKeys.has(e)||Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function de(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(s)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${re(e)}: path") or declare the key on the component state.`}const he=/^\$(\d+)$/;function fe(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(s);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===r){o=t;break}if(-1===o)return ce(t,t.markerBasePath,e,e),le(t,e);if(ue(t,n[0]))return ce(t,t.markerBasePath,e,e),le(t,e);const i=n.slice(0,o+1),a=n.slice(o+1),l=ae(t,i);null===l&&J(de(t,e)),0===a.length&&J(`Wildcard-terminal accessor "${e}" on mounted <${t.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const c=l+s+t.marker;return ce(t,c,a.join(s),e),c+s+a.join(s)}(t,e);const o=re(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return le(t,e);if(ue(t,o))return le(t,e);const i=ae(t,e.split(s));if(null!==i)return i;J(de(t,e))}function pe(t,e,n,o,s){if(void 0===o)return;const r=Y(n).wildcardCount-Y(e).wildcardCount;return 0===r?o:(s.length<r&&J(`Cannot resolve "${e}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const me=new WeakMap,ge=new WeakMap,ye=new WeakMap,be=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)});function we(t){return me.get(t)??null}function ve(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=ye.get(t);if(void 0===o)return null;const r=e.indexOf(s,n),i=-1===r?e.slice(n):e.slice(n,r),a=o.get(i);if(void 0===a)return null;const l=a.deref();return void 0===l?(o.delete(i),null):l}const _e=new WeakMap;function $e(t){let e=t;for(;e;){const t=_e.get(e);if(t)return t;let n=e.parentNode;null===n&&e instanceof ShadowRoot&&null!==we(e)&&(n=e.host),e=n}return null}function Se(t,e){null!==e?_e.set(t,e):_e.delete(t)}let xe=null;const Ne=new WeakMap;function Pe(t){return Ne.get(t)??[]}function Ie(t,e){Ne.set(t,e)}function ke(t){return Ne.has(t)}const Ae=new WeakMap;let Ee=null,Ce=0;function Te(t){return Ae.get(t)??[]}function Me(t,e){null===Ee?Ae.set(t,e):Ee.set(t,e)}function Oe(t){return(Ee?.has(t)??!1)||Ae.has(t)}const Le=Symbol("$$setLoopContext"),Re=Symbol("$$getByAddress"),je=Symbol("$$hasByAddress"),De=Symbol("$$setByAddress"),We=Symbol("$$connectedCallback"),Be=Symbol("$$disconnectedCallback"),ze=Symbol("$$updatedCallback"),Fe=Symbol("$$errorCallback"),He=new WeakMap;function Ue(t,e){if(He.has(t)){const n=He.get(t);if(n.has(e))return n.get(e)}else He.set(t,new WeakMap);const n=Object.freeze(new qe(t,e));return He.get(t).set(e,n),n}class qe{pathInfo;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Ue(t,e.parentPathInfo)}}const Ge=new WeakMap,Ve=new WeakMap;class Ke{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const t=this.absolutePathInfo.parentAbsolutePathInfo;if(null===t)return null;let e=null;return e=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=Je(t,e)}}function Je(t,e){if(null===e){let e=Ve.get(t);return void 0!==e||(e=new Ke(t,null),Ve.set(t,e)),e}{let n=Ge.get(e);void 0===n&&(n=new WeakMap,Ge.set(e,n));let o=n.get(t);return void 0!==o||(o=new Ke(t,e),n.set(t,o)),o}}const Qe=new WeakMap;function Xe(t,e){null===e?Qe.delete(t):Qe.set(t,e)}function Ye(t){return Qe.get(t)||null}const Ze=new Map;function tn(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=Ze.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Ze.set(s,r)),r}function en(t,e,n){return e<0||e>=n?null:t.at(e-n)}function nn(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const on=new WeakMap;function sn(t){const e=$e(t.node);if(null===e)return null;let n=on.get(e);if(void 0===n)n=new WeakMap,on.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=tn(e.pathInfo,t.statePathInfo);return n>0&&(o=en(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const rn=new WeakMap;function an(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Ye(n);null===e?J(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function ln(t,e){let n=null;if(n=rn.get(t)||null,null!==n)return n;const o=an(t,e),s=sn(t),r=ia(o);return null===r&&J("No state tree found on this root for binding."),n=Je(Ue(r,t.statePathInfo),s),rn.set(t,n),n}function cn(t){rn.delete(t)}const un=new WeakMap;function dn(t,e){const n=un.get(t);void 0===n?un.set(t,e):n instanceof Set?n.add(e):n!==e&&un.set(t,new Set([n,e])),null!==xe&&xe({type:"state:binding-added",absoluteAddress:t,binding:e})}function hn(t,e){const n=un.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&un.delete(t),null!==xe&&xe({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const fn=new WeakMap;function pn(t,e,n){const o=fn.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==xe&&xe({type:"state:binding-removed",absoluteAddress:Je(t,e),binding:n}))}function mn(t){const e=un.get(t);return void 0!==e?e:null!==t.listIndex?fn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const gn=new WeakMap,yn=new WeakMap;class bn{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=wn(t,e)}}function wn(t,e){if(null===e){let e=yn.get(t);return void 0!==e||(e=new bn(t,null),yn.set(t,e)),e}{let n=gn.get(e);void 0===n&&(n=new WeakMap,gn.set(e,n));let o=n.get(t);return void 0!==o||(o=new bn(t,e),n.set(t,o)),o}}const vn=new WeakMap;function _n(t){let e=null;if(e=vn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=sn(t);null===n&&J(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=wn(t.statePathInfo,n)}else e=wn(t.statePathInfo,null);return vn.set(t,e),e}function $n(t){vn.delete(t)}function Sn(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const xn=new Map,Nn=Sn();function Pn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function In(t){let e="input";for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function kn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function An(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)kn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class En{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)e.push(n(...t));return e}}class Cn extends En{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==xe&&xe({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const Tn=new WeakMap;function Mn(t,e){let n=Tn.get(t);void 0===n&&(n=new Map,Tn.set(t,n));let o=n.get(e);return void 0===o&&(o=new Cn(e,t),n.set(e,o)),o}const On=new WeakMap;class Ln extends En{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==xe&&xe({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function Rn(t){return t instanceof Ln}const jn=new Map,Dn=Sn();function Wn(t){const e=t.propModifiers.filter(t=>t===c||t===u).sort().join(",");return`${t.statePathName}::${e}`}function Bn(t){if(!t.propName.startsWith(g))return!1;const e=Wn(t);let n=jn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(c)&&o.preventDefault(),e.includes(u)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ia(r);null===i&&J("No state tree found on this root for event handler.");const a=$e(s),l=t.startsWith(T+".");i.createStateAsync("writable",async e=>{const c=e[Le](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a&&!0===i.hasMounts){const t=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=me.get(n);if(void 0!==t)return t;n=n.parentNode}return me.get(e)??null}(s,r);if(null!==t){const e=t.indexShiftByLoopElementPath.get(a.pathInfo.path);c=void 0!==e?c-e:0}}const u=null!==a?nn(a.listIndex,c):[];if(l){const s=e[Re](wn(n,null));return Rn(s)||J(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...u)}const d=e[t];return"function"!=typeof d&&J(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});An(c,`"${t}"`)})})(t.statePathName,t.propModifiers,t.statePathInfo),jn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Dn.add(e,t),!0}const zn=new Map,Fn=Sn();function Hn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Un(t){let e="input";for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}const qn=new Set(["radio","checkbox"]),Gn=new Set(["value","valueAsNumber","valueAsDate"]);function Vn(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(qn.has(t)&&"checked"===e)return!0;if(Gn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=et(n);if(null!==s){const t=ot(n)?.get(s);void 0===t&&J(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=rt(n);if(o?.knownProperties.has(e))return!0}return!1}let Kn=1,Jn=1,Qn=1;const Xn=new WeakMap;function Yn(t,e,n){let o=Xn.get(t);void 0===o&&(o=new Map,Xn.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=Kn++,o.set(s,r)),r}function Zn(t,e){return"to-element"===e?2*t:2*t+1}const to=new Set;function eo(t){return{transactionId:Jn++,originBindingId:t,visitedEdges:to,hop:0}}function no(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let oo=null;function so(){return oo}function ro(t,e){const n=oo;oo=t;try{return e()}finally{oo=n}}const io=[];let ao=!1;const lo=new Map,co=Sn(),uo=new WeakMap,ho=t=>t.detail,fo=new WeakMap;function po(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function mo(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=et(t.node);if(null!==n){const o=ot(t.node)?.get(n);void 0===o&&J(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=rt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function go(t){if(null!==et(t.node)){const e=rt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??ho}return null}function yo(t){if(null===et(t.node))return!1;const e=rt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const bo=new WeakSet;function wo(t){bo.add(t)}function vo(t){return!!bo.has(t)&&(bo.delete(t),!0)}const _o=new WeakSet;function $o(t){_o.add(t)}function So(t){return!!_o.has(t)&&(_o.delete(t),!0)}let xo=0;function No(){xo--}function Po(){return xo>0}class Io{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const ko=new WeakMap;function Ao(t){let e=ko.get(t);return void 0===e&&(e=new Io(t),ko.set(t,e)),e}function Eo(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==h&&s!==f&&J(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&J(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Co(t){return t.propModifiers.some(t=>t.includes("="))}const To=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Mo=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Oo(t,e){return"state"===t&&"call"===e?To:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Lo(t){if(!o.enableDirectionalInitialSync)return Co(t)&&J("init=/sync= modifiers require enableDirectionalInitialSync."),To;const e=null===(n=Eo(t,h))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:J(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":J(`Invalid sync modifier value "${t}".`)}(Eo(t,f));if("event"===t.bindingType)return null!==e&&"none"!==e&&J("Event bindings only allow init=none."),"call"===s?Mo:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===b)return Oo("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&J(`Binding type "${t.bindingType}" does not support init=${e}.`),Oo(e??"state",s);const r=rt(t.node);if(null===r)return Oo(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||J(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||J(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||J(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let Ro=0,jo=0;const Do=new WeakMap,Wo=new WeakMap,Bo=new WeakMap,zo=new WeakMap;function Fo(t,e){const n=zo.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):zo.set(t,new Set([n,e]))):zo.set(t,e)}function Ho(t){return zo.has(t)}function Uo(t,e){const n=zo.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function qo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))qo(n,e)}function Go(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class Vo{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(const o of t)e.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));const o=[];for(const t of e)vo(t)||qo(t,t=>{Uo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)So(t)&&!Po()||qo(t,t=>{Uo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&hi(o)}}const Ko=new WeakMap;function Jo(t){let e=Ko.get(t);return void 0===e&&(e=new Vo(t),Ko.set(t,e)),e}function Qo(t){const e=t.inFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|"),n=t.outFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function Xo(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class Yo{records=new Set;rowPlan=null;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=Do.get(t);void 0===o||"disposed"===o.phase||"failed"===o.phase?(this.start(t,s,n),r.push(t)):(this.observe(o.anchor),s.registerAddress&&null===o.address&&null===o.patternListIndex&&(o.options.registerAddress=!0,this.registerAddress(o)),"active"===o.phase&&this.settleInitialRecord(o),this.settleConnectedSnapshot(o))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(Go(e)&&Jo(e),null===this.rowPlan)for(const n of t){const t=Do.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return Co(t)&&Lo(t),!0;const e=Do.get(t);return void 0===e||e.session!==this||!e.options.registerAddress||"waiting-definition"===e.phase||"failed"!==e.phase&&("active"===e.phase&&this.settleInitialRecord(e),e.initialApplyDone?"state"===e.resolvedAuthority||!e.outputOnlyMember&&!e.observationPending:(e.initialApplyDone=!0,"state"===e.resolvedAuthority))}getRecord(t){const e=Do.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=Do.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(Xo(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=ot(t);null===s&&J(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Fo(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Ao(s).wait(e,()=>{if(a())try{st(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=Do.get(t);void 0!==e&&e.session===this&&this.disposeRecord(e)}dispose(){for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.records)null!==t.address&&(hn(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];for(const e of this.records){if("active"!==e.phase)continue;const n=e.info;if(null===e.address&&null===e.patternListIndex)continue;const o="for"===n.bindingType?ln(n):null;if(null!==e.address?(hn(e.address,n),e.address=null):(pn(e.patternPathInfo,e.patternListIndex,n),e.patternPathInfo=null,e.patternListIndex=null),$n(n),cn(n),this.registerAddress(e),null!==o){const t=ln(n);t!==o&&ke(o)&&Ie(t,Pe(o)),t!==o&&Oe(o)&&Me(t,Te(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return Go(e)?e:null}(t);null!==e&&Jo(e)}handleMutations(t,e,n){for(const n of e)qo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)qo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&hi(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Do.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=Bo.get(e);void 0===t&&(t=Qo(e),Bo.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Fo(n,this);const o=this.knownMapFor(n);let s=Bo.get(t);void 0===s&&(s=Qo(t),Bo.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n={registerAddress:!1,registerPathInfo:!1,applyOnReconnect:!1},o=t.slots;for(let s=0;s<e.length;s++){const r=e[s],i=o[s],a=r.replaceNode;Fo(a,this),this.addKnownRowBinding(a,r,s),this.optionsByBinding.set(r,n);const l={id:++Ro,info:r,generation:++jo,phase:"active",teardowns:null,session:this,anchor:a,options:n,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:i.policy,resolvedAuthority:i.authority,initialSettled:!0,initialApplyDone:!1,outputOnlyMember:i.policy.outputOnly,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};if(Do.set(r,l),this.records.add(l),i.isEvent){try{Bn(r)}catch(t){throw l.phase="failed",this.runTeardowns(l),this.records.delete(l),t}l.eventAttached=!0}}}activatePlanRows(t,e,n){const o=t.slots;for(let s=0;s<e.length;s++){const r=e[s],i=Do.get(r);if(void 0!==i&&i.session===this){if(i.options.registerAddress=!0,"disposed"===i.phase||"failed"===i.phase){const e=o[s];if(i.generation=++jo,i.phase="active",i.initialPolicy=e.policy,i.resolvedAuthority=e.authority,i.initialSettled=!0,i.initialApplyDone=!1,i.outputOnlyMember=e.policy.outputOnly,this.records.add(i),e.isEvent){try{Bn(r)}catch(t){throw i.phase="failed",this.runTeardowns(i),this.records.delete(i),t}i.eventAttached=!0}this.registerAddress(i,n);continue}null===i.address&&null===i.patternListIndex&&this.registerAddress(i,n)}else this.initialize([r],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++Ro,info:t,generation:++jo,phase:"discovered",teardowns:null,session:this,anchor:t.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Do.set(t,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;Bn(e)?t.eventAttached=!0:e.propSegments[0]!==y?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=Un(t),s=Hn(t,o);let r=zn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const t of n)s=t.filterFn(s);const r=ia(o.getRootNode());null===r&&J("No state tree found on this root for two-way binding.");const i=$e(o);r.createState("writable",t=>{t[Le](i,()=>{t[e]=s})})},zn.set(s,r)),t.node.addEventListener(o,r),Fn.add(s,t),!0}var e,n;return!1}(e)&&Xo(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=Un(t),n=Hn(t,e),o=zn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Fn.countOf(n)&&(Fn.remove(n,t)&&zn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=In(t),s=Pn(t,o);let r=xn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const t of n)r=t.filterFn(r);const i=ia(o.getRootNode());null===i&&J("No state tree found on this root for two-way binding.");const a=$e(o);i.createState("writable",t=>{t[Le](a,()=>{let n=t[e];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(t[e]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(t[e]=n.toSpliced(o,1))}else t[e]=s?[r]:[]})})},xn.set(s,r)),t.node.addEventListener(o,r),Nn.add(s,t),!0}var e,n;return!1}(e)&&Xo(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=In(t),n=Pn(t,e),o=xn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Nn.countOf(n)&&(Nn.remove(n,t)&&xn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Vn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const n=function(t,e,n){let o=uo.get(t);void 0===o&&(o=new Map,uo.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&uo.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});Xo(t,n)}!function(t){const e=et(t.node);if(null!==e){const n=ot(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&J(`CustomElementRegistry is unavailable for <${e}>.`))}if(Vn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=mo(t),n=go(t),s=yo(t),r=po(t,e,null!==n,s);let i=lo.get(r);void 0===i&&(i=((t,e,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==ho||r||function(t,e,n){const o=t[e];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${e} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,e)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${e}" key while element.${e} is ${typeof o}`),null===s)return;let r=fo.get(t);void 0===r&&(r=new Set,fo.set(t,r)),r.has(e)||(r.add(e),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${t.tagName.toLowerCase()}> "${e}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${e}, or (e) => e.target.${e}) on that wcBindable property.`))}(a,t,l);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const t of n)c=t.filterFn(c);const u=uo.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(o.enablePropagationContext){const n=Yn(a,t,e),s=function(t,e){for(let n=io.length-1;n>=0;n--){const o=io[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==xe&&xe({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Zn(n,"to-state"),node:a,member:t}));const r=Zn(n,"to-state"),i=so();if(null!==i&&i.visitedEdges.has(r))return void(null!==xe&&xe({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=no(i??eo(n),r)}const h=ia(a.getRootNode());null===h&&J("No state tree found on this root for two-way binding.");const f=$e(a),p=()=>{r&&(ao=!0);try{h.createState("writable",t=>{t[Le](f,()=>{t[e]=c})})}finally{r&&(ao=!1)}};null!==d?ro(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),lo.set(r,i)),t.node.addEventListener(e,i),co.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==y)return!1;const e=t.node,n=et(e),o=ot(e);if(null!==n&&void 0===o?.get(n))return null===o&&J(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(On.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||J('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===et(t)?null:rt(t)}(e);null===r&&J(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&J(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${yt(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,d=t.propModifiers,h=t=>{d.includes(c)&&t.preventDefault(),d.includes(u)&&t.stopPropagation();const n=ia(e.getRootNode());null===n&&J("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||J(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${yt(l,n.eventTokenNames)}${bt}`);const o=$e(e);n.createStateAsync("writable",async e=>{An(e[Le](o,()=>{const s=null!==o?nn(o.listIndex,o.pathInfo.wildcardCount):[];return Mn(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,h),On.set(t,{eventName:a,handler:h}),!0})(e)&&Xo(t,()=>function(t){if(t.propSegments[0]!==y)return!1;const e=On.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),On.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=et(t.info.node);if(null===n)return void e();const o=ot(t.info.node);if(null===o&&J(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=Ao(o).wait(n,()=>{if(this.isAlive(t,s))try{st(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});Xo(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Lo(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=ia(t.replaceNode.getRootNode());null===e&&J("No state tree found on this root for binding.");const n=_n(t);let o=!1;return e.createState("readonly",t=>{o=t[je](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void xo++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,No()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=ia(t.node.getRootNode());null===o&&J("No state tree found on this root for initial binding sync.");const s=$e(t.node);o.createState("writable",e=>{e[Le](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=sn(n);if(null!==o){const s=ia(an(n,e));null===s&&J("No state tree found on this root for binding.");const r=Ue(s,n.statePathInfo);!function(t,e,n){let o=fn.get(t);void 0===o&&(o=new WeakMap,fn.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==xe&&xe({type:"state:binding-added",absoluteAddress:Je(t,e),binding:n})}(r,o,n),t.patternPathInfo=r,t.patternListIndex=o}else{const o=ln(n,e);dn(o,n),t.address=o}if(!t.options.registerPathInfo)return;const s=ia(n.replaceNode.getRootNode());null===s&&J("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Do.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,No());const e=t.info;if(null!==t.address)try{hn(t.address,e),t.address=null,$n(e),cn(e)}catch{}else if(null!==t.patternListIndex)try{pn(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,$n(e),cn(e)}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=et(t.node);if(null!==e){const n=ot(t.node),o=n?.get(e);if(void 0===o)return}if(Vn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=mo(t),n=po(t,e,null!==go(t),yo(t)),o=lo.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),co.remove(n,t)&&lo.delete(n)}}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{!function(t){if(!t.propName.startsWith(g))return!1;const e=Wn(t),n=jn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==Dn.countOf(e)&&Dn.remove(e,t)&&jn.delete(e)}(e)}catch{}}}}function Zo(t){let e=Wo.get(t);return void 0===e&&(e=new Yo(t),Wo.set(t,e)),e}function ts(t){return Do.get(t)?.session??null}const es=new WeakMap;function ns(t,e){let n=es.get(t);n||(n=new Set,es.set(t,n)),n.add(e)}const os=new WeakMap;function ss(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const rs=Object.freeze([]),is=new WeakMap,as=new WeakMap;function ls(t){return as.get(t)??[]}function cs(t,e){as.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let us=0;function ds(){return`u${(us++).toString(36)}`}let hs=0,fs=0;const ps=Symbol("wcs.listIndex.noValue");class ms{uuid=ds();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=ps,this._index=e,this._version=hs,this._chainGeneration=fs}get index(){return this._index}set index(t){this._index=t,this._version=++hs,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(t){this._value=t}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=hs),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===fs||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=fs),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++hs,fs++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function gs(t,e,n=t){return new ms(t,e,n)}function ys(t,e){t.reparent(e)}function bs(t){return t.homeParentListIndex}function ws(t,e){t.value=e}function vs(t,e){const n=t.value;return n!==ps&&n===e.value}const _s=new WeakMap,$s=new WeakSet;function Ss(t){return $s.has(t)}function xs(t){const e=_s.get(t);return void 0===e?null:e}function Ns(t,e){const n=_s.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o){const t=function(t,e){const n=bs(t),o=t.parentListIndex;return null===n||n===o||$s.has(n)?function(t,e,n){return null!==t&&null!==n&&n!==e&&!!$s.has(t)&&!$s.has(n)&&n.position===t.position&&vs(n,t)}(n,o,e)||function(t,e){return t!==e&&null!==t&&null!==e&&t.position===e.position&&$s.has(t)&&!$s.has(e)}(o,e)?e:null:n}(o,e);if(null!==t)for(const e of n)ys(e,t)}return n}function Ps(t,e){null!==e?_s.set(t,e):_s.delete(t)}const Is=new WeakMap,ks=Object.freeze([]),As=new Set;function Es(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:ks,s=Array.isArray(n)&&n.length>0?n:ks,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:ks,o=Array.isArray(e)&&e.length>0?e:ks;let s=Is.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Ns(o,t)||[],a=i.length>0?bs(i[0]):t;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:As,deleteIndexSet:new Set(i),addIndexSet:As};let e=Ns(s,t);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=gs(t,n,a);e.push(o)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:As,deleteIndexSet:As,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:As,deleteIndexSet:As,addIndexSet:As};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],u=n.get(l),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=gs(t,o,a);e.push(n),c.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:c}}finally{void 0!==l&&(function(t,e,n){let o=Is.get(t);o||(o=new WeakMap,Is.set(t,o)),o.set(e,n)}(o,s,l),Ps(s,l.newIndexes))}}(t,e,n);return function(t,e){for(let n=0;n<t.length;n++)t[n].index!==n&&(t[n].index=n),ws(t[n],e[n])}(o.newIndexes,Array.isArray(n)&&n.length>0?n:ks),function(t){for(const e of t)$s.add(e)}(o.deleteIndexSet),function(t){for(const e of t)$s.delete(e)}(o.newIndexes),o}const Cs=new WeakMap;function Ts(t){return Cs.get(t)??[]}function Ms(t,e){Cs.set(t,e)}const Os=new WeakMap;function Ls(t){return Os.get(t)??null}function Rs(t,e){Os.set(t,e)}const js=new WeakMap;function Ds(t){return js.get(t)??[]}function Ws(t,e){js.set(t,e)}function Bs(t,e){const n=Ds(t);for(const t of n)Se(t,e)}function zs(t,e,n){Bs(t,e);const o=Ts(t),s=Ls(t);null!==s&&s.activate(o,n.rootNode);for(const t of o)null===s&&dn(ln(t),t),(null===s||s.shouldApplyState(t))&&ui(t,n)}function Fs(t){if(!t.mounted)return;const e=Ts(t),n=Ls(t);for(const t of e)null!==n?n.disposeBinding(t):hn(ln(t),t);!function(t){const e=Ds(t);for(const t of e)Se(t,null)}(t)}const Hs=new WeakMap,Us=Object.freeze(new Set);function qs(t,e){const n=Hs.get(t);n?n.add(e):Hs.set(t,new Set([e]))}function Gs(t){const e=Hs.get(t);return void 0!==e?e:Us}function Vs(t,e){const n=Hs.get(t);n&&(n.delete(e),0===n.size&&Hs.delete(t))}const Ks=new Set(["if","elseif","else","for"]);class Js{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e,this._childNodeArray=Array.from(this._content.childNodes),this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(t){for(const e of this._childNodeArray)$o(e),t.appendChild(e);this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){$o(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=Ls(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)wo(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=Ts(this);for(const t of e)if(Ks.has(t.bindingType)){const e=Gs(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){Ls(this)?.dispose();for(const t of this._childNodeArray)wo(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=Ts(this);for(const e of t){if(Ks.has(e.bindingType)){const t=Gs(e.node);for(const e of t)e.unmount()}$n(e),cn(e)}this._mounted=!1}}function Qs(t){const e=document.createDocumentFragment(),n=new Js(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function Xs(t){void 0!==t.uuid&&null!==t.uuid||J("BindingInfo.uuid is null.");const n=Ut(t.uuid);n||J(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=ft(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===b||s===y)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==et(r))return null;if("prop"===o&&Vn(r,t.propName))return null;let i;try{i=Lo({...t,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;n.push({nodeIndex:e,template:t,isEvent:"event"===o,isIndexBinding:t.statePathName in S,policy:i,authority:i.authority})}}return{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=ft(o,s[t].nodePath);null===e&&J(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Zt(e),K(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e){const n=new Yo;return n.initializeRow(t,e),n}(n,a),u=new Js(o);return Rs(u,c),Ms(u,a),cs(u,l),Ws(u,r),qs(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=ft(t,s.nodePath);if(null===e&&J(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Qt.has(e))continue;const r=Xt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new Yo;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new Js(i,s);Rs(l,a.bindingSession),Ms(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in S&&c.push(t);return cs(l,c),Ws(l,a.nodes),qs(t.node,l),l}const Ys=Symbol.for("wcstack.transition-runner");function Zs(t){const e=globalThis[Ys];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}const tr=new WeakSet,er=Symbol.for("wcstack.state.view-transition-naming");function nr(){const t=Zs("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function or(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||tr.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[er]??={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.`)):(tr.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const sr=new WeakMap,rr=new WeakMap,ir=new WeakMap,ar=new WeakMap;function lr(t,e,n){!function(t,e,n){let o=rr.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,rr.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function cr(t,e){sr.set(t,e)}function ur(t,e){let n=ir.get(t.node);void 0===n&&(n=[],ir.set(t.node,n)),n.length<1e3?n.push(e):Vs(t.node,e)}function dr(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}function hr(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function fr(t,n,s){const r=Boolean(s);let i;const a=Gs(t.node);i=0===a.size?Xs(t):a.values().next().value;const l=e(),c=t.uuid??"",u=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${hr(t)}`),Fs(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${hr(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);zs(i,$e(t.node),n);const e=nr();null!==e&&or(i,"branch",e)}}const pr=new WeakMap,mr=new WeakMap,gr=new WeakMap,yr=new WeakMap;function br(t){return yr.get(t)??[]}const wr=new Set,vr=Symbol.for("wcstack.trustedTypes.policy");function _r(){const t=globalThis[vr];return null===t||"object"!=typeof t?null:t}let $r,Sr=!1;const xr={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}};function Nr(t,n,s){if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0],u=r[c];if(u!==s){null!==u&&"object"==typeof u&&null!==s&&"object"==typeof s&&null!==et(r)&&function(t,e,n){let o=pr.get(t);o||(o=new Map,pr.set(t,o)),o.has(e)||o.set(e,n)}(r,c,u);const e="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let t=!1;try{r[c]=e?function(t){if("string"!=typeof t)return t;const e=_r(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(Sr)return;if(!function(){if(void 0!==$r)return $r;if(!("trustedTypes"in globalThis))return $r=!1,$r;try{document.createElement("div").innerHTML="<i></i>",$r=!1}catch{$r=!0}return $r}())return;Sr=!0;const n="function"==typeof _r()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${e}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:t,property:e})}(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=et(t);if(null===n)return null;const o=ot(t)?.get(n);if(void 0===o)return null;const s=rt(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&Vn(r,c)){const e=Yn(r,c,t.statePathName),o=Zn(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??so()??eo(e);if(a.visitedEdges.has(o))null!==xe&&xe({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=no(a,o);ro(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Qn++,writtenValue:n};io.push({receipt:i,node:t});try{return r()}finally{io.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=xr[c];t?t(r,s):(function(t,e,n){let o=yr.get(t);o||(o=[],yr.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,s),a=r,wr.add(a))}return}var a,l;const c=i[0];let u=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==u)return;u=u[e]}const d=i[i.length-1],h=u[d];if(h!==s){if(Object.isFrozen(u))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:s}));2===i.length&&"object"==typeof u&&null!==u&&null!==et(r)&&(d in u?function(t,e,n,o){let s=gr.get(t);s||(s=new Map,gr.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}(r,c,d,u[d]):function(t,e,n){let o=mr.get(t);o||(o=new Map,mr.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)}(r,c,d));try{u[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:s,error:t})}}}const Pr=new WeakSet;function Ir(t,e,n){}const kr=new WeakMap;function Ar(t,e){if(null===t)return!1;const n=kr.get(t);if(void 0===n||0===n.size)return!1;for(const t of n)if(e===t||e.startsWith(t+s)||t.startsWith(e+s))return!0;return!1}const Er=new WeakMap;function Cr(t,e){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{e.$postUpdate(t+s+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...r)=>e[n](t+s+o,...r)}return e[o]}return e[t+s+o]}},set:(n,o,r)=>("string"!=typeof o||(e[t+s+o]=r),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Tr=new WeakMap,Mr=[],Or=new WeakMap,Lr=new WeakSet;function Rr(t){console.error(`[@wcstack/state] volume "${t.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),t.onGrafted(null)}let jr=null;const Dr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Wr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function Br(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function zr(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),r=e.length>0?e+s:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(s)&&o.push(e)}return o}const Fr={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Hr={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function Ur(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${bt}`}function qr(t,e){return`[wcs/recursion-anchor] "${t}" does not match the declared recursion anchor "${e}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function Gr(t,e){return`$setAll("${t}") ${e}`}function Vr(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${bt}`}const Kr=new WeakMap;const Jr=new WeakMap,Qr=new WeakSet,Xr=new WeakMap;function Yr(t,e){let n=Xr.get(t);void 0===n&&(n=new Set,Xr.set(t,n)),n.add(e),Jr.get(t)?.delete(e)}function Zr(t,e,n,o){console.warn(`[@wcstack/state] [${Fr[n]}] ${Hr[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${yt(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${bt}`),null!==xe&&xe({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const ti=new WeakSet;function ei(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const ni=Object.freeze({[w]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&J("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[v]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[_]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[b]:function(t,e,n){Rn(n)||J("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=is.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||J('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=et(t);if(null===e)return null;const n=ot(t)?.get(e);return void 0===n&&J(`Custom element <${e}> is not defined for command binding.`),rt(t)}(r);null===a&&J(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||J(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${yt(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),is.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void is.delete(t);const o=n[i];return"function"!=typeof o&&J(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),is.set(t,{token:o,unsubscribe:c,elementRef:l})}}),oi={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Pr.has(t.replaceNode)){Pr.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,i=sn(t),a=ln(t),l=Pe(a),c=l.length>0&&!rr.has(t.node)?[]:l,u=Es(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);const d=Array.isArray(c)&&c.length===u.deleteIndexSet.size&&u.deleteIndexSet.size>0;if(d&&null!==t.node.parentNode){let e=ar.get(t.node);if(void 0===e){const n=sr.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(n.nodeType===Node.ELEMENT_NODE||n.nodeType===Node.TEXT_NODE&&""!==(n.textContent?.trim()??"")){s=!1;break}n=n.previousSibling}for(;null!==o;){if(o.nodeType===Node.ELEMENT_NODE||o.nodeType===Node.TEXT_NODE&&""!==(o.textContent?.trim()??"")){s=!1;break}o=o.nextSibling}return s}(t.node,n),ar.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let h=rr.get(t.node),f=d?1e3-function(t){return ir.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==h){for(const e of u.deleteIndexSet){const n=h.get(e);void 0!==n&&(f<=0&&n.tryDestroy()?Vs(t.node,n):(Fs(n),n.unmount(),ur(t,n),f-=1),d||h.delete(e))}d&&(rr.delete(t.node),h=void 0)}let p=t.node;const m=Y(s.path+"."+r),g=n.stateElement.loopContextStack,y=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const t of i)a.add(n[t]);return a}(u);let b=null;u.newIndexes.length==u.addIndexSet.size&&u.newIndexes.length>0&&p.isConnected&&(b=document.createDocumentFragment(),Xe(b,n.rootNode));const w=e(),v=nr(),_=t.uuid??"",$=ir.get(t.node);for(const e of u.newIndexes){let o;if(u.addIndexSet.has(e)){const r=wn(m,e);g.createLoopContext(r,r=>{if(o=void 0!==$?$.pop():void 0,void 0===o&&(o=Xs(t)),null!==b)w&&b.appendChild(document.createComment(`@@wcs-for-start:${_}:${s.path}:${e.index}`)),o.appendTo(b),w&&b.appendChild(document.createComment(`@@wcs-for-end:${_}:${s.path}:${e.index}`));else{if(p.nextSibling!==o.firstNode){if(w){const t=document.createComment(`@@wcs-for-start:${_}:${s.path}:${e.index}`);p.parentNode.insertBefore(t,p.nextSibling),p=t}o.mountAfter(p)}if(w){const t=document.createComment(`@@wcs-for-end:${_}:${s.path}:${e.index}`),n=o.lastNode??p;n.parentNode.insertBefore(t,n.nextSibling)}}zs(o,r,n),null!==v&&or(o,"row",v)}),void 0===o&&J(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=void 0!==h?h.get(e)??null:null,u.changeIndexSet.has(e)){const t=ls(o);for(const e of t)ui(e,n)}null===o&&J(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==y&&y.has(e)&&dr(p,o.firstNode)||p.nextSibling===o.firstNode||o.mountAfter(p),t){const t=o,s=wn(m,e);g.createLoopContext(s,e=>{zs(t,e,n)})}}p=o.lastNode||p,void 0===h&&(h=new WeakMap,rr.set(t.node,h)),h.set(e,o)}sr.set(t.node,p),null!==b&&(t.node.parentNode.insertBefore(b,t.node.nextSibling),Xe(b,null))},if:fr,else:fr,elseif:fr,radio:function(t,e,n){const o=t.node,s=ss(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=ss(o.value,t.inFilters),r=Array.isArray(n)?n:rs;o.checked=r.includes(s)}},si=new WeakMap,ri=new WeakMap,ii=new WeakMap;function ai(){}function li(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===es.get(t)?.has(e)}(e,n)?Ir:function(t,e){return!0===os.get(t)?.has(e)}(e,n)?ai:Nr}function ci(t,e){const n=ss(function(t,e){const n=_n(e);if(n.pathInfo.path in S){const t=$e(e.node);return null===t&&J(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&J("ListIndex not found for loopContext:");const n=S[e];void 0===n&&J(`Invalid index name: ${e}`);const o=en(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&J(Vr(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Re](n)}(e.state,t),t.outFilters);if(!0===ri.get(t))return void e.deferredSelectBindings.push({binding:t,value:n,stateElement:e.stateElement});let o=si.get(t);if(void 0===o){if(si.has(t))return o=li(t),o===Ir&&si.set(t,o),void o(t,e,n);if(o=oi[t.bindingType],void 0===o){const e=t.propSegments[0];o=ni[e],si.set(t,o),void 0===o&&(et(t.replaceNode)?(o=li(t),o===Ir&&si.set(t,o)):(o=Nr,si.set(t,o)))}if(o===Nr&&"SELECT"===t.node.tagName){const o=t.propSegments[0];if("value"===o||"selectedIndex"===o)return e.deferredSelectBindings.push({binding:t,value:n,stateElement:e.stateElement}),void ri.set(t,!0)}o(t,e,n)}else o(t,e,n)}function ui(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=ln(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=ts(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==ii.get(t)){const e=et(t.replaceNode);if(e&&void 0===ot(t.replaceNode)?.get(e))return void function(t,e){if(ti.has(t))return;ti.add(t);const n=()=>{ti.delete(t);const e=ts(t);(null===e||e.shouldApplyState(t))&&hi([t])},o=n=>{ti.delete(t),ei(e,n)},s=ts(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{ti.delete(t),r()})||(ti.delete(t),r()))}const r=ot(t.replaceNode);if(null===r)return ti.delete(t),void ei(e,new Error("CustomElementRegistry is unavailable."));Ao(r).wait(e,()=>{t.replaceNode.isConnected?n():ti.delete(t)},o)}(t,e);ii.set(t,!0)}if(!0===e.sameRootVerified)return void ci(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Ye(o),null===o&&J("Root node for fragment not found for binding.")),o!==e.rootNode){const n=ia(o);null===n&&J("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};ci(t,r)})}else ci(t,e)}function di(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==xe&&xe({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function hi(t,e){let n=0;const s=new Set,r=new Map,i=new Map,a=[],l=new Map;for(;n<t.length;){let c=t[n];if(!1===c.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${c.bindingType} ${c.statePathName} on ${c.node.nodeName}`,c),n++;continue}let u=c.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=Ye(u),null===u&&J("Root node for fragment not found for binding."));const d=ia(u);null===d&&J("No state tree found on this root for binding."),d.createState("readonly",o=>{const h={rootNode:u,stateElement:d,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{ui(c,h)}catch(t){di(c,t,d,l)}n++;const e=t[n];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;c=e}})}for(const{binding:t,value:n,stateElement:o}of a)try{Nr(t,{propagationContextByBinding:e},n)}catch(e){di(t,e,o??null,l)}for(const[t,e]of r.entries())Ie(t,e),Me(t,e);for(const[t,e]of i.entries())t.createState("writable",t=>{t[ze](Array.from(e))});for(const[t,e]of l.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[Fe](n,o)}catch(t){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:t,original:n,node:o.node})}})}function fi(t,e,n){const[o,s,r]=Yt(t,n),i=Zo(t);for(const t of o)Se(t,e);hi(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=te(o);0!==t.length&&(Se(o.node,e),hi(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const pi=/\{\{\s*(.+?)\s*\}\}/g,mi=new Set(["SCRIPT","STYLE"]);function gi(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&mi.has(t.parentElement.tagName)||yi(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),gi(e.content)}else gi(t.content)}function yi(t){const e=t.data;if(pi.lastIndex=0,!pi.test(e))return;pi.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=pi.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}let bi;function wi(){if(bi)return bi;const t=[],e=kt("not",t)(Pt);return bi={filterName:"not",args:t,filterFn:e},bi}const vi=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function _i(t,e){const n=e+s+r,o=t.indexOf("|");let i,a;if(-1!==o?(i=t.slice(0,o).trim(),a=t.slice(o)):(i=t.trim(),a=""),"."===i)i=n;else{if(!i.startsWith("."))return t;i=n+s+i.slice(1)}return a.length>0?i+a:i}function $i(t,e){const n=vi.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+_i(s,e)+r}function Si(t,e){const n=t.split(";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=n.indexOf(":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=_i(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function xi(t,e){return Si(t,e)}function Ni(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=$i(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=Si(r,e);t!==r&&o.setAttribute(n,t)}}}function Pi(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}function Ii(t){const e=[],n=Jt(t);for(const t of n){const n=qt(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:Pi(o),parseBindTextResults:n})}return e}function ki(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const Ai=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),Ei=wi();function Ci(t,e){const n=e.outFilters;return{...e,outFilters:[...n,Ei],bindingType:t}}function Ti(t,e,n,o,s,r=!0){ki(e),"string"==typeof o&&Ni(e,o),Mi(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:Ii(e)};return void 0!==s&&function(t,e,n){for(const o of t)for(let t=0;t<o.parseBindTextResults.length;t++){const s=o.parseBindTextResults[t];null==s.uuid&&(o.parseBindTextResults[t]=e(s,n))}}(i.nodeInfos,s,o),i}function Mi(t,e,n,s){const r=o.commentElsePrefix,i=Vt(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],u=[];for(;a.nextNode();){const t=a.currentNode;u.push(t)}for(const e of u){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=xi(i,n));let a=Rt(i)[0];const u=Ai.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=ds();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&J("'else' binding found without preceding 'if' or 'elseif' binding."),a=Ci("else",l.parseBindTextResult),p=Ti(t,h,a,m,s,!1),Ht(f,t,p);const n=c.at(-1),o=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:Pi(o),parseBindTextResults:qt(o)})):e.replaceWith(o)}else if("elseif"===d){null===l&&J("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Ti(t,h,a,m,s),Ht(f,t,p);const n=document.createComment(`@@${u}:${f}`),o=ds(),i={fragment:document.createDocumentFragment(),parseBindTextResult:Ci("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:Pi(n),parseBindTextResults:qt(n)}),Ht(o,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:Pi(g),parseBindTextResults:qt(g)})):e.replaceWith(g)}else{p=Ti(t,h,a,m,s),Ht(f,t,p);const n=document.createComment(`@@${u}:${f}`);e.replaceWith(n)}"if"===d?(c.length=0,l=p):"elseif"===d?l=p:"else"===d&&(l=null,c.length=0)}}async function Oi(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=ot(t);null===s&&J(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(Gt(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function Li(t){if(t===document)await Oi(document),gi(document),Mi(document,document),fi(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await V(e.host),await Oi(e),gi(e),Mi(e,e),fi(e,null)}}const Ri="2.4.0",ji="undefined"==typeof HTMLElement?class{}:HTMLElement,Di=/^@@wcs-(?:for|if|elseif|else):[^-]/,Wi=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,Bi=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,zi=/^@@wcs-text-start:(.+)$/;function Fi(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Hi extends ji{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=Ri.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=o.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(e,t);if(void 0!==o&&"function"==typeof o.get)continue;const s=e[t];"function"!=typeof s&&(n[t]=s)}return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=Fi(JSON.stringify(e)),t.appendChild(n);const s=Array.from(Ft.keys());for(const e of s){const n=Ut(e);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",e);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),t.appendChild(s)}const r=Array.from(wr);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=br(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const t of o)i[t.propName]=t.value;e[s]=i}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=Fi(JSON.stringify(e)),t.appendChild(n)}}wr.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(Wi.test(t.data)||Bi.test(t.data))&&n.push(t)}for(const t of n)t.remove()}static removeStructuralComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;Di.test(t.data)&&n.push(t)}for(const t of n)t.remove()}static restoreTextBindings(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode,o=zi.exec(t.data);o&&n.push({comment:t,path:o[1]})}for(const{comment:t,path:e}of n){const n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}const r=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const t=r.currentNode;Wi.test(t.data)&&i.push(t)}for(const t of i){const e=Wi.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}Hi.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(Di.test(t.data)){const e=t.data.split(":")[1];l.push({comment:t,uuid:e})}}for(const{comment:t,uuid:e}of l){const n=s.get(e);if(n){const e=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&e.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)e.content.appendChild(r);else for(const t of Array.from(n.childNodes))e.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(e,t)}}const c=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of c)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const Ui=new Set(["for","if","elseif","else"]);function qi(t){const e=new Yo;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i]=Yt(s),a=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:e}}function Gi(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const t=i.currentNode;if(t.data===r)return t}return null}function Vi(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Rt(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,wi()],bindingType:"else"}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;ki(a),"string"==typeof l&&Ni(a,l),Mi(n,a,l),Ht(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:Ii(a)})}}const Ki=Symbol.for("wcstack.binder"),Ji=Symbol.for("wcstack.binder.pending"),Qi=Symbol.for("wcstack.binder.taken");function Xi(t){if(Ho(t))return!0;if(!Yi(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Ho(e)}function Yi(t){return 1===t.nodeType}function Zi(t){if(Xi(t))return;gi(t),Mi(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);fi(e&&s?n:t,null)}const ta=[];function ea(){const t=ta.splice(0,ta.length);for(const e of t)Zi(e);!function(){const t=function(){const t=globalThis[Ki];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[Ji];return void 0===e&&(e=[],t[Ji]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[Qi];return void 0===e&&(e=new WeakSet,t[Qi]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const na={protocol:"wcs-binder",version:1,bind:function(t){var e;Yi(t)&&!Xi(t)&&(e=t.getRootNode(),la.has(e)?Zi(t):ta.push(t))}},oa=new WeakMap,sa=new WeakMap,ra=new Set;function ia(t){return oa.get(t)??null}function aa(t){return sa.get(t)??Promise.resolve()}const la=new WeakSet;function ca(t){la.add(t)}function ua(t,n){const s=oa.get(t);if(null===n){if(void 0===s)return;oa.delete(t),ra.delete(s),null!==xe&&xe({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const s=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{s&&await async function(t){await Oi(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${Ri}". Falling back to full render.`),Hi.cleanupDom(t),!1}for(const n of e)Vi(t,n);const n=function(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const t of o){const n=Wi.exec(t.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 u=t.nextSibling;const d=`@@wcs-${o}-end:${s}`;for(;u&&(u.nodeType!==Node.COMMENT_NODE||u.data!==d);)c.push(u),u=u.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body);!function(t,e){const n=new Map;for(const o of e){if(0===o.nodes.length)continue;const e=Qs(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=qi(o.nodes);Rs(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");Ms(e,s),Ws(e,i);const l=[];for(const t of s)t.statePathName in S&&l.push(t);if(cs(e,l),"for"===o.type&&null!==o.index){const i=Gi(t,"for",o.uuid);if(i){const t=gs(null,o.index);lr(i,t,e),cr(i,o.nodes[o.nodes.length-1]),qs(i,e),Bs(e,wn(Y(o.path+"."+r),t)),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});let l=n.get(o.uuid);l||(l=[],n.set(o.uuid,l)),l.push(t)}}else{const n=Gi(t,o.type,o.uuid);n&&(qs(n,e),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=Gi(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Ut(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ia(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&Ps(e,o)})}}(document.body,n),Hi.removeBlockBoundaryComments(document.body);const s=[];for(const t of e)t.parentNode&&(s.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());Hi.restoreTextBindings(document.body);const[i,a]=Yt(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(Se(t,null),e.setAttribute("data-wcs-completed",""))}else Se(t,null);const l=[],c=[],u=Zo(document.body).initialize(a);for(const t of u)if("event"!==t.bindingType)if(Ui.has(t.bindingType))c.push(t);else{if(t.statePathName.includes(r))continue;l.push(t)}for(const t of c)if("for"===t.bindingType){const e=ln(t),n=ia(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&(Ie(e,o),Me(e,o))})}hi(l);for(const{el:t,parent:e,next:n}of s)e.insertBefore(t,n);const d=t.querySelectorAll(o.tagNames.ssr);for(const e of d){const n=e.hydrateProps;for(const[e,o]of Object.entries(n)){const n=t.querySelector(`[data-wcs-ssr-id="${e}"]`);if(n)for(const[t,e]of Object.entries(o))n[t]=e}}const h=t.querySelectorAll("[data-wcs-completed]");for(const t of h)t.removeAttribute("data-wcs-completed");return!0}(t)||await Li(t),ca(t),ea(),e()}catch(t){n(t)}})});sa.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await Li(t),ca(t),ea(),e()}catch(t){n(t)}})});sa.set(t,e)}}void 0!==s&&J('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="...">.'),oa.set(t,n),ra.add(n),function(t,e){Lr.delete(t);const n=Or.get(t);if(void 0===n||0===n.length||null===jr)return;Or.delete(t);const o=jr;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,n),null!==xe&&xe({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}let da=0,ha=0;function fa(t){da=t+1}function pa(){da=0}const ma=new WeakMap,ga=new Set,ya=new Set;function ba(t){return t.byFromPath.size>0||t.byResetPath.size>0}function wa(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function va(t){return ma.get(t)}function _a(t){$a(t),ma.delete(t)}function $a(t){ga.delete(t),ya.delete(t)}const Sa=new WeakSet;let xa=0;function Na(t){return va(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function Pa(t){Sa.has(t)||(Sa.add(t),xa++)}function Ia(t){return!!Sa.delete(t)&&(xa--,!0)}const ka=[];function Aa(t,e=0){const n=ka.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?ka.push(o):ka.splice(n,0,o)}function Ea(t){queueMicrotask(()=>{throw t})}const Ca=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){da>ha&&(ha=da),function(t){if(0===ya.size)return;if(e=t.absolutePathInfo.stateElement,!ya.has(e))return;var e;const n=Na(t);if(void 0!==n)for(const t of n)Pa(t)}(t);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&(Ce++,null===Ee&&(Ee=new Map),queueMicrotask(()=>{const t=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(t)}))}hasQueuedPath(t,e){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===t&&n.absoluteAddress.absolutePathInfo.pathInfo.path===e)}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t){const n=new Map;for(const e of t){const t=n.get(e.absoluteAddress);null!==xe&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&xe({type:"propagation:coalesced",absoluteAddress:e.absoluteAddress,droppedTransactionId:t.transactionId,winnerTransactionId:e.context.transactionId}),n.set(e.absoluteAddress,e.context)}const o=[],s=new Map;for(const[t,e]of n){if(null!==e&&e.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),null!==xe&&xe({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=mn(t);if(void 0!==n)if(n instanceof Set)for(const t of n)!1!==t.replaceNode.isConnected&&(o.push(t),null!==e&&s.set(t,e));else!1!==n.replaceNode.isConnected&&(o.push(n),null!==e&&s.set(n,e))}try{const t=()=>{s.size>0?hi(o,s):hi(o)};if(e()||0===o.length)t();else{const e=function(t,e){const n=Zs(t);if(null!==n)return n.run(e,{source:t,types:void 0});e()}("state",t);void 0!==e&&e.catch(Ea)}}finally{!function(){if(0!==Ce&&(Ce--,!(Ce>0||null===Ee))){for(const[t,e]of Ee)Ae.set(t,e);Ee=null}}(),function(t){for(const e of ka.slice())e.listener(t)}(new Set(n.keys()))}}};function Ta(){return Ca}const Ma=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Oa(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const La="__WCSTACK_DEVTOOLS_HOOK__";const Ra=t=>{null!==xe&&xe({type:"state:update-batch",addresses:t})};function ja(t){const e=null!==xe;!function(t){xe=t}(t);const n=null!==t;n&&!e?Aa(Ra,0):!n&&e&&function(t){const e=ka.findIndex(e=>e.listener===t);-1!==e&&ka.splice(e,1)}(Ra)}function Da(t){return{rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function Wa(t){return ia(t)??J("devtools: no state tree on this root")}let Ba=null;function za(){if(e())return;if(null!==Ba)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Ri,getStateElements(){const t=[];for(const e of ra)t.push(Da(e));return t},overlays:t=>function(t){const e=ye.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}(Wa(t)).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join("."),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]})),keys(t){const e=Wa(t),n=[];return e.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}n.push(e)}}),n},read(t,e,n){let o;return Wa(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){Wa(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=[...t.inFilters,...t.outFilters].map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=Ut(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Oa(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=ht(e,Rt(n));for(const o of t)r(Oa(e,o,"attribute",n))}catch{}continue}const e=Ma.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=Ut(s);if(null===a){if(n===o.commentTextPrefix)try{r(Oa(t,zt(s),"comment",s))}catch{}}else r(Oa(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:ja};Ba=t,function(){const t=globalThis,e=t[La];if(void 0!==e)return 2!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 2. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:2,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[La]=n,n}().register(t)}const Fa={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of s){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Ri),Hi.buildContent(o,Hi.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}},Ha="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ua=0;async function qa(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++Ua}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${Ha}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${Ha}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Ga(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){J(`Failed to load script file: ${t}`)}}class Va{_loopContextStack=Array(a).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&J("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=a&&J("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&&J("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&J("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&&J(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const Ka=new WeakMap;function Ja(t,e){let n=Ka.get(t);void 0===n&&(n=new Map,Ka.set(t,n));let o=n.get(e);return void 0===o&&(o=new Ln(e,t),n.set(e,o)),o}const Qa=new WeakMap;function Xa(t){const e=Qa.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return Ja(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Ja(t,n)}},set(){J("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){J("$command namespace is read-only; deleting from it is not allowed.")}});return Qa.set(t,n),n}const Ya=Symbol("wcs-stream-last-notified-uncertain"),Za=new WeakMap;function tl(t,e){const n=Za.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function el(t,e){const n=Za.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:Ya,error:Object.is(o.error,null)?null:Ya})}const nl=new Set;function ol(t){nl.delete(t)}const sl=new WeakMap;function rl(t){return sl.get(t)??new Map}function il(t){ol(t);const e=sl.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,el(t,n.name)}const al=(t,e)=>e,ll=new Set;function cl(t,e){"string"==typeof e&&0!==e.length||J(`[wcs/recursion-declaration-invalid] ${D} ${t} must be a non-empty string.`);const n=e.split(s);n.some(t=>0===t.length)&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not contain empty path segments.`),n.length<2&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must name a list element: a property path ending with "${s}${r}" (for example "nodes${s}${r}").`),n[n.length-1]!==r&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must end with "${s}${r}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===r&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must have exactly one "${r}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===W&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not contain "${W}" — the declaration is what gives "${W}" its meaning.`),isNaN(Number(n[o]))||J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}function ul(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}function dl(t){return-1!==t.indexOf(W)}function hl(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+s;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(dl(o))return null;const i=o.slice(1).split(s);return i[0]===r||i.some(t=>0===t.length)?null:o}function fl(t){return 0===t.length?t:s+gl(t.slice(1))}function pl(t,e,n){const o=s+t.repeat,r=e.length<=n.length?e:n,i=e.length<=n.length?n:e;if(!i.endsWith(r))return!1;const a=i.slice(0,i.length-r.length);if(0===a.length)return!0;if(a.length%o.length!==0)return!1;for(let t=0;t<a.length;t+=o.length)if(!a.startsWith(o,t))return!1;return!0}function ml(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(s,o-1))if(pl(t,e,n.slice(0,o)))return!0;return!1}function gl(t){const e=t.split(s);for(let t=0;t<e.length;t++)e[t]===r||Number.isNaN(Number(e[t]))||(e[t]=r);return e.join(s)}function yl(t,e){const n=t.repeat.split(s),o=s+t.repeat;let r=e;for(;r.startsWith(o);)r=r.slice(o.length);if(0===r.length||r===s+t.repeatList+s+"length")return!0;for(let t=1;t<n.length;t++)if(r===s+n.slice(0,t).join(s))return!0;return!1}function bl(t,e,n){n<0&&J(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=s+t.repeat;const a=o+e;let l=0;for(const t of a.split(s))t===r&&l++;return l>i&&J(`[wcs/recursion-depth-exceeded] Recursion on "${t.anchor}" reached depth ${n} ("${a}"), which needs ${l} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),a}function wl(t,e){return bl(t,"",e)}function vl(t,e,n){if(!n.startsWith(t.anchor))return null;if(e.length>0&&!n.endsWith(e))return null;if(n.length<t.anchor.length+e.length)return null;const o=n.slice(t.anchor.length,n.length-e.length);if(0===o.length)return 0;const r=s+t.repeat;let i=0,a=0;for(;a<o.length;){if(!o.startsWith(r,a))return null;a+=r.length,i++}return i}const _l=new WeakMap;function $l(t,e){null===e?_l.delete(t):_l.set(t,e)}function Sl(t){const e=_l.get(t);e&&(e.dirty=!0)}const xl=new WeakSet;function Nl(t){return"function"==typeof t.get&&xl.has(t.get)}const Pl="[wcs/recursion-declaration-invalid]";class Il{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(t,e){this.spec=t;const n=ul(e);for(const[e,o]of Object.entries(n)){if(!dl(e))continue;"function"==typeof o.set&&J(`${Pl} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&J(`${Pl} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=hl(t,e);null===n&&J(qr(e,t.recursiveAnchor)),0===n.length&&J(`${Pl} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${s}total"), not the node.`),yl(t,fl(n))&&J(`${Pl} "${e}" names the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${t.recursiveAnchor}${s}total").`),this._definitions.set(e,{recursivePath:e,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(t){for(const[e,n]of Object.entries(t)){if(dl(e)||Nl(n))continue;const t=this._matchExpansion(e);null!==t&&J(`${Pl} "${e}" is already defined on the state, so the recursive getter "${t}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const t=Array.from(this._definitions.values());for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)pl(this.spec,t[e].suffix,t[n].suffix)&&J(`${Pl} "${t[e].recursivePath}" and "${t[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(t){for(const e of this._definitions.values())if(ml(this.spec,e.suffix,t))return e.recursivePath;return null}recursiveGetterOwningPath(t){const e=this._ownerByPathInfo.get(t);if(void 0!==e)return e;const n=this.recursiveGetterOwning(t.path);return this._ownerByPathInfo.set(t,n),n}recursiveGetterOwning(t){const e=this._accessors.get(t);if(void 0!==e)return e.recursivePath;const n=gl(t),o=this._ownerByPath.get(n);if(void 0!==o)return o;let r=null;if(n.startsWith(this.spec.anchor)){r=this._matchExpansion(n);for(let t=n.lastIndexOf(s);null===r&&t>this.spec.anchor.length;t=n.lastIndexOf(s,t-1))r=this._matchExpansion(n.slice(0,t))}return this._ownerByPath.set(n,r),r}_matchExpansion(t){for(const e of this._definitions.values())if(null!==vl(this.spec,e.suffix,t))return e.recursivePath;return null}materializeForPathInfo(t,e){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(e);if(void 0!==n)return n;const o=this.materializeFor(t,e.path);return this._accessorByPathInfo.set(e,o),o}materializeFor(t,e){const n=this._accessors.get(e);if(void 0!==n)return n;if(!e.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const t of this._definitions.values()){const n=vl(this.spec,t.suffix,e);null!==n&&(null!==o&&J(`"${e}" matches both "${o.recursivePath}" and "${t.recursivePath}".`),o=t,s=n)}return null===o?null:this._define(t,o,s,e)}_define(t,e,n,o){const s=t.findStateDescriptor(o);void 0===s||Nl(s)||J(`"${o}" is already defined on the state, so the recursive getter "${e.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:e.recursivePath,depth:n}),i=e.get,a=function(){return i.call(this)};var l;return l=a,xl.add(l),t.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(t,n),this._accessors.set(o,r),r}_registerListPaths(t,e){for(const n of function(t,e){const n=[];n.push(t.anchorList);for(let o=0;o<e;o++)n.push(wl(t,o)+s+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){const n=new Set(this._accessors.keys());return function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&Nl(n)&&delete e[t]}for(const e of[t.staticDependency,t.dynamicDependency]){for(const t of n)e.delete(t);for(const[t,o]of e){let s=null;for(let t=0;t<o.length;t++)n.has(o[t])?s??=o.slice(0,t):s?.push(o[t]);null!==s&&(0===s.length?e.delete(t):e.set(t,s))}}!function(t,e,n){for(const o of n){const n=Y(o),s=Ue(t,n),r=n.wildcardParentPathInfos,i=(t,e,n)=>{if(n===r.length)return void $l(Je(s,e),null);const o=0===n?0:r[n-1].segments.length+1;let a=t;for(const t of r[n].segments.slice(o))a=a?.[t];if(!Array.isArray(a))return;const l=xs(a);if(null===l)return;const c=Math.min(l.length,a.length);for(let t=0;t<c;t++)i(a[t],l[t],n+1)};i(e,null,0)}}(t,e,n)}}(t,e,n),n}concretePathAt(t,e){let n=this._concreteBySuffix.get(t);void 0===n&&(n=[],this._concreteBySuffix.set(t,n));let o=n[e];return void 0===o&&(o=bl(this.spec,t,e),n[e]=o),o}accessorFor(t){return this._accessors.get(t)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const kl=new WeakMap,Al=new WeakMap;function El(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=rl(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&rl(t).has(n),ownKeys:()=>Array.from(rl(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=rl(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){J(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){J(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Cl(t){const e=kl.get(t);if(void 0!==e)return e;const n=El(t,z,t=>t.status);return kl.set(t,n),n}function Tl(t){const e=Al.get(t);if(void 0!==e)return e;const n=El(t,F,t=>t.error);return Al.set(t,n),n}function Ml(t){kl.delete(t),Al.delete(t)}const Ol=Object.freeze([]),Ll=Object.freeze([]);function Rl(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Ol,i=t.dynamicDependency.get(n)??Ol,a=e.byFromPath.get(n)??Ll;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}let jl=null;function Dl(t){const e=rl(t);if(0!==e.size){!function(t){nl.add(t)}(t);for(const n of e.values())Wl(t,n)}}function Wl(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=jl,r=new Set;let i;jl=r;try{t.createState("readonly",t=>{i=n(t)})}finally{jl=o}i instanceof Promise&&J(`${L} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${z}${s}${e.name}`,l=`${F}${s}${e.name}`;for(const n of r){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==a&&o.path!==l||J(`${L} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&J(`${L} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=r,i}(t,e);!function(t,e){const n=va(t);if(void 0!==n&&0!==e.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==e.name)continue;const s=Rl(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&J(`[wcs/scan-feedback-loop] ${L} entry "${e.name}" args read "${n}", which is derived from the ${j} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,e),t.createState("writable",t=>{t[e.name]=e.definition.initial}),Bl(t,e,"active",null);const r=e.definition,i={fold(n){t.createState("writable",t=>{t[e.name]=r.fold(t[e.name],n)})},done(){Bl(t,e,"done",null)},fail(o){Bl(t,e,"error",o),n.abort()}};!async function(t,e,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 t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",i)}}(r.source,o,n.signal,i)}function Bl(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return Za.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),i=r.status!==n,a=!Object.is(r.error,o);(i||a)&&(function(t,e,n,o){let s=Za.get(t);void 0===s&&(s=new Map,Za.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${z}${s}${e.name}`),a&&t.$postUpdate(`${F}${s}${e.name}`)}))}Aa(function(t){const e=nl;if(0===e.size)return;const n=[];for(const o of e)for(const e of rl(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&rl(t).get(o.name)===o)try{Wl(t,o)}catch(n){o.controller?.abort(),e.has(t)&&rl(t).get(o.name)===o&&Bl(t,o,"error",n)}},20);const zl=new WeakMap,Fl=new WeakMap,Hl=new Set,Ul=new Map;function ql(t){return zl.get(t)??Ul}const Gl=new Map;function Vl(t){return Fl.get(t)??Gl}function Kl(t){0===t.length&&J(`[wcs/watch-declaration-invalid] ${R} entry name must be a non-empty state path.`),t.startsWith("$")&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" must not start with "$" (reserved namespace).${bt}`),t.includes("@")&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${bt}`),t in Object.prototype&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=Y(t);for(const n of e.segments)0===n.length&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" has an empty path segment.${bt}`);return e.wildcardCount>i&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const Jl=new WeakMap;function Ql(t,e,n){let o=Jl.get(t);void 0===o&&(o=new Map,Jl.set(t,o)),o.set(e,n)}const Xl=new Map;function Yl(t){return Xl.get(t)}function Zl(t){for(let e=t;null!==e;e=e.parentListIndex)if(Ss(e))return!0;return!1}function tc(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[Re](wn(e.wildcardParentPathInfos[i],r)),l=xs(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=en(o,i,e.wildcardCount);if(l!==c&&!vs(l,c)){if(Ss(c))return"gone";s="replaced"}r=l}return s}function ec(t,e,n){const o=new Map;for(const s of n){const n=tc(t,e,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),t=>t.row)}const nc=/^(?:0|[1-9]\d*)$/;function oc(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function sc(t){if("object"!=typeof t||null===t||Object.isFrozen(t))return null;const e=Object.getPrototypeOf(t);return Array.isArray(t)?e===Array.prototype&&Reflect.ownKeys(t).every(e=>"length"===e||"string"==typeof e&&nc.test(e)&&oc(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&oc(t,e))?null:"object"}function rc(t,e){const n=sc(t);if(null===n)return t;const o=t,s=e.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(t.length):null===Object.getPrototypeOf(t)?Object.create(null):{},e.set(o,r);for(const t of Object.keys(o))r[t]=rc(o[t],e);return r}function ic(t){return rc(t,new Map)}function ac(t,e,n){if(Object.is(t,e))return!0;const o=sc(e);if(null===o||"object"!=typeof t||null===t)return!1;const s=t,r=e;if("array"===o){if(!Array.isArray(t)||t.length!==e.length)return!1}else if(Array.isArray(t)||Object.keys(s).length!==Object.keys(r).length)return!1;if(sc(t)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let e=0;e<t.length;e++)if(!ac(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&ac(s[t],r[t],n))}function lc(t,e){return ac(t,e,new Map)}const cc=new WeakMap;function uc(t,e){if("function"!=typeof e)return;const n=cc.get(e);void 0===n?cc.set(e,new Set([t])):n.add(t)}const dc={"read-source":t=>`${j} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-output":t=>`${j} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${j} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${j} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${j} could not write the output "${t}".`},hc={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function fc(t,e,n){null!==xe&&xe({type:"state:watch-error",phase:e,path:`${j}.${t}`,error:n})}function pc(t,e,n){console.error(`[@wcstack/state] ${dc[n](t)}`,e),fc(t,hc[n],e)}function mc(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function gc(t,e){e.then(void 0,()=>{}),pc(t,new TypeError(`${j} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const yc=new WeakSet,bc=Object.freeze([]);function wc(t,e,n){let o=t.get(n);return void 0===o&&(o={stateElement:e,entry:n,rows:[],reset:!1},t.set(n,o)),o}function vc(t,e){let n=0;for(;n<t.indexes.length-1&&t.indexes[n]===e.indexes[n];)n++;return t.indexes[n]-e.indexes[n]}function _c(t,e){return e.has(t.stateElement)&&!0===va(t.stateElement)?.entries.has(t.entry)}function $c(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Sc(n,t))||Ia(e)}function Sc(t,e){return Ta().hasQueuedPath(t,e)}function xc(t,e){!function(t,e,n){if(0!==xa)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=Na(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||Ia(e)}}(t,e,Sc)}function Nc(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function Pc(t,e,n){if(!_c(t,n))return $c(t),null;const{stateElement:o,entry:s}=t;if(t.reset)return{group:t,next:s.initial};const r=s.source;if(function(t,e){for(const n of e.pathInfo.cumulativePaths)if(t.getterPaths.has(n))return!0;return!1}(o,r))return function(t,e,n){if(yc.has(t))return;yc.add(t);const o=`[wcs/scan-source-computed] ${j} entry "${e}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),fc(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=rl(t).get(e);if(void 0===o)return!1;for(const t of o.depAddresses)if(n.has(t))return!0;return!1}(o,r.pathInfo.segments[0],e))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",e=>{const n=e[s.name],o=0===r.pathInfo.wildcardCount?t.rows:ec(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(vc)){let n;try{n=Nc(e,r,t)}catch(t){pc(s.name,t,"read-source");continue}const o=a(l,n,Yl(t.absAddress),...t.indexes);if(mc(o))return void gc(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){pc(s.name,t,i.failure)}return i.plan}function Ic(t,e){const{group:n}=t;if(!_c(n,e))return void $c(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Ia(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!lc(o,s.initial):!Object.is(o,t.next)){const o=n.reset?ic(s.initial):t.next;e[s.name]=o,uc(s.name,o)}})}catch(t){pc(s.name,t,"write")}}function kc(t){(0!==ql(t).size||0!==Vl(t).size||function(t){const e=ma.get(t);return void 0!==e&&ba(e)}(t))&&(function(t){Hl.add(t),function(t){const e=ma.get(t);void 0!==e&&(ba(e)&&ga.add(t),function(t){return t.eventResetByPath.size>0}(e)&&ya.add(t))}(t)}(t),function(t){const e=[];for(const n of ql(t).values())Ec(t,n)&&e.push(n);for(const n of Vl(t).values())for(const o of n)Ec(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{Ql(t,Ac(t,o),n[o.path])}catch(e){Tc(t,o.path,"prime",e)}})}(t))}function Ac(t,e){return Je(Ue(t,e.pathInfo),null)}function Ec(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Cc={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Tc(t,e,n,o){console.error(`[@wcstack/state] $watch ${Cc[n]} "${e}" threw.`,o),null!==xe&&xe({type:"state:watch-error",phase:n,path:e,error:o})}function Mc(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Oc(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function Lc(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Ec(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void Tc(0,n.path,"evaluate",t)}const a=r?function(t,e){return Jl.get(t)?.get(e)}(e,o):Yl(o);r&&Ql(e,o,i),null!==xe&&xe({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){Tc(0,n.path,"handler",t)}}Aa(function(t){const e=Hl;try{if(0===e.size)return void xc(t,e);const n=function(){const t=ha;return ha=0,t}();if(n>32){xc(t,null);const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==xe&&xe({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}!function(t,e,n){if(0!==t.length){fa(n);try{for(const n of t)Ic(n,e)}finally{pa()}}}(function(t,e,n){if(xc(t,e),0===ga.size)return bc;const o=new Map;for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=va(t);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let e=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;e=nn(n.listIndex,r.wildcardCount)}for(const s of i)wc(o,t,s).rows.push({absAddress:n,indexes:e})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const e of a)wc(o,t,e).reset=!0}if(0===o.size)return bc;const s=Array.from(o.values()).sort((t,e)=>t.entry.order-e.entry.order),r=[];fa(n);try{for(const n of s){const o=Pc(n,t,e);null!==o&&r.push(o)}}finally{pa()}return r}(t,e,n),e,n),function(t,e,n){const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=ql(t).get(s),i=Vl(t).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const e of a){let s=[];if(e.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=nn(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Oc);const s=function(t){let e=null;for(let n=0;n<t.length;n++){const o=t[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=t[n-1];(Zl(o.absAddress.listIndex)||s?.entry===o.entry&&Mc(s.indexes,o.indexes))&&(e??=new Set).add(o.entry)}if(null===e)return t;const n=new Set;for(const o of e){const e=t.filter(t=>t.entry===o),s=e[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(ec(t,o.pathInfo,e));for(const t of e)s.has(t)||n.add(t)})}catch(t){Tc(0,o.path,"evaluate",t);for(const t of e)n.add(t)}}return t.filter(t=>!n.has(t))}(o);fa(n);try{for(const t of s){if(!e.has(t.stateElement))continue;const n=ql(t.stateElement).get(t.entry.path)===t.entry,o=!0===Vl(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&Lc(t)}}finally{pa()}}(t,e,n)}finally{Xl.clear()}},10);const Rc="[wcs/scan-declaration-invalid]",jc=Object.freeze([]);function Dc(t){return`${j} entry "${t}"`}function Wc(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function Bc(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${r}${r}`)?`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.${bt}`}function zc(t,e,n){0===n.length&&J(`${Rc} ${t} "${e}" must be a non-empty state path.${bt}`),n.startsWith("$")&&J(`${Rc} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${bt}`),n.includes("@")&&J(`${Rc} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${bt}`),n in Object.prototype&&J(`${Rc} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${bt}`);const o=Y(n);for(const s of o.segments)0===s.length&&J(`${Rc} ${t} ${e} "${n}" has an empty path segment.${bt}`);return o.wildcardCount>i&&J(`${Rc} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function Fc(t,e,n,o){const i=Dc(t);0===t.length&&J(`${Rc} ${j} entry name must be a non-empty string.${bt}`),(t.includes(s)||t.includes(r))&&J(`${Rc} ${i} must be a flat property name ("${s}" and "${r}" are not allowed). The output is a property the runtime owns.${bt}`),t.startsWith("$")&&J(`${Rc} ${i} must not start with "$" (reserved namespace).${bt}`),t in Object.prototype&&J(`${Rc} ${i} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${bt}`),e.has(t)&&J(`${Rc} ${i} conflicts with a getter declared on the state.${bt}`),n.has(t)&&J(`${Rc} ${i} conflicts with a setter declared on the state.${bt}`),o.has(t)&&J(`${Rc} ${i} conflicts with the ${L} entry of the same name — each output has exactly one owner.${bt}`)}function Hc(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!function(t,e){return"function"==typeof e&&!0===cc.get(e)?.has(t)}(t,o)&&J(`${Rc} ${Dc(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${bt}`)}function Uc(t,e,n,o,r,i){const a=Dc(t),l=void 0!==e.from,c=void 0!==e.on;if(l===c&&J(`${Rc} ${a} must declare exactly one of "from" (a state path) or "on" (an event-token name).${bt}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||J(`${Rc} ${a} "on" must be a non-empty event-token name.${bt}`),n.has(t)||J(`${Rc} ${a} on "${t}" is not declared in ${M}.${yt(t,n)}${bt}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&J(`${Rc} ${a} "from" must be a state path string.${bt}`);const d=zc(a,"from",u),h=Wc(d,o)??i?.recursiveGetterOwning(u)??null;null!==h&&J(Bc(a,"from",u,h));const f=Wc(d,r);return null!==f&&J(function(t,e,n){return`${Rc} ${t} from "${e}" ${n===e?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${bt}`}(a,u,f)),(u===t||u.startsWith(t+s))&&J(`${Rc} ${a} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${bt}`),{kind:"path",path:u,pathInfo:d}}function qc(t,e,n,o){if(void 0===e)return jc;const i=Dc(t);Array.isArray(e)||J(`${Rc} ${i} "resetOn" must be an array of state paths.${bt}`);const a=[];for(const t of e){"string"!=typeof t&&J(`${Rc} ${i} "resetOn" must contain only state path strings.${bt}`);const e=zc(i,"resetOn",t);e.wildcardCount>0&&J(`${Rc} ${i} resetOn "${t}" must not contain "${r}" — a reset returns the whole output to "initial".${bt}`);const l=Wc(e,o);null!==l&&J(Bc(i,"resetOn",t,l)),"path"===n.kind&&t===n.path&&J(`${Rc} ${i} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${bt}`),"path"===n.kind&&t.startsWith(n.path+s)&&J(`${Rc} ${i} resetOn "${t}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${bt}`),a.push(t)}return a}function Gc(t){const e=t.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[t.name];i="threw";const a=function(t){return Sa.has(t)}(t),l=a&&!lc(n,t.initial)?ic(t.initial):n,c=e(l,o,...s);if(mc(c))return void gc(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,uc(t.name,c)),a&&Ia(t)}catch(e){pc(t.name,e,i)}}}function Vc(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function Kc(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function Jc(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function Qc(t){return t.startsWith("$")}function Xc(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function Yc(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||J(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||J(`${e} entries must be non-empty strings.`),t.startsWith("$")&&J(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&J(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}const Zc=new Map;class tu{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=Y(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function eu(t){let e;return Zc.get(t)??(Zc.set(t,e=new tu(t)),e)}function nu(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:en(n.listIndex,o,n.pathInfo.wildcardCount)}function ou(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=tn(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?en(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?en(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}const su=new WeakMap;class ru{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,s,r){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return wn(Y(this.markerParentPath+s+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(fe(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,s,...r)=>{const i=fe(t,e),a=pe(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a=fe(t,e),l=pe(0,e,a,r,n);return o[s](a,l,...i)}}return this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return ou(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[fe(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||J(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(t,e)?(t[e]=n,!0):(this.receiver[fe(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return fe(this.record,e),!0}catch{return!1}}}function iu(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=su.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},su.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(i,new ru(t,s,e.listIndex,r,n,o))}const au=new WeakMap,lu=new Set;function cu(t,e,n,o){let s=au.get(t);if(void 0===s){if(!o)return null;s=new Map,au.set(t,s)}let r=s.get(e);if(void 0===r){if(!o)return null;r=new Map,s.set(e,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function uu(t,e){if(!t.component.isConnected)return!1;const n=$e(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function du(t,e,n,o){const r=cu(t,e,n,!1);if(null===r)return null;const i=null===o?r.noIndex:r.byListIndex.get(o)??null;if(null!==i){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&uu(n,e)?n:null}(i,o);if(null!==t)return{record:t,entry:i.entry}}let a=null,l=null;for(const t of r.holders){const i=t.ref.deref();void 0!==i?uu(i,o)&&(null!==l&&J(`[wcs/mount-export-ambiguous] "${e}${s}${n}" is exported by two mounted components on the same instance: <${l.component.tagName.toLowerCase()}> and <${i.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),a=t,l=i):r.holders.delete(t)}return null===a||null===l?null:(null===o?r.noIndex=a:r.byListIndex.set(o,a),{record:l,entry:a.entry})}function hu(t){const e=t.parentStateElement,n=$e(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[Le](n,()=>{t.$postUpdate(o.exportedPath)})})}function fu(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function pu(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}function mu(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===T)return pu(Xa(s),e.pathInfo.segments);if(i===z)return pu(Cl(s),e.pathInfo.segments);if(i===F)return pu(Tl(s),e.pathInfo.segments);if(!0===s.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const t=ve(s,e.pathInfo.path);if(null!==t)return iu(t,e,n,o)}if(!(e.pathInfo.path in t)){if(null===e.parentAddress&&Ar(function(t){return t.rootNode??null}(s),e.pathInfo.path))return;const i=e.parentAddress??J(function(t,e,n){return`[${Fr.binding}] Path "${t}" does not exist on the state tree.${yt(t,zr(e,"",n))}${bt}`}(e.pathInfo.path,t,s.getterPaths)),a=gu(t,i,n,o);if(null==a)return;const l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(!0===s.hasMounts&&l!==r&&!(l in Object(a))){const t=du(s,i.pathInfo.path,l,e.listIndex);if(null!==t)return function(t,e,n,o,s){const r=iu(t,wn(Y(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(t.record,t.entry,e.listIndex,n,o)}if(l===r){const t=e.listIndex?.index??J(Vr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(a,t)}return Reflect.get(a,l)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}function gu(t,e,n,o){ou(o,e),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,e.pathInfo),function(t,e){if(null===jl)return;const n=Ue(t,e.pathInfo);jl.add(Je(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return fu(s,e)?function(t,e,n,o,s){const r=Je(Ue(s,e.pathInfo),e.listIndex),i=function(t){return _l.get(t)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=mu(t,e,n,o,s);return $l(r,{value:l,dirty:!1,generation:a}),l}(t,e,n,o,s):mu(t,e,n,o,s)}function yu(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,u,d)=>{const h=o[s]??null;if(null===h)return void d.push(u);const f=wn(h,r),p=Je(Ue(n.stateElement,h),r),m=Te(p),g=gu(t,f,e,n),y=Es(r,m,g).newIndexes,b=l[c]??null;if(i.set(p,g),null===b)for(let t=0;t<y.length;t++){const e=y[t];a(o,s+1,e,l,c+1,u.concat(e.index),d)}else{const t=y[b]??J(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,u.concat(t.index),d):d.push(u.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Me(t,Array.isArray(e)?e:[]);return l}function bu(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Ns(gu(t,wn(a,r),e,n),r);null==l&&J(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??J(`ListIndex not found at index ${c} of ${a.path}`)}return r}function wu(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}function vu(t,e,n,o){"object"==typeof t&&null!==t||J(`${B} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&J(`${B} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function _u(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&J(`${B} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function $u(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];vu(a,n,o,i);const l=_u(a,e,n,o,i);r.has(l)&&J(`${B} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Su(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function xu(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=gu(t,s,n,o);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=e.pathInfo.lastSegment;if(a===r){const t=e.listIndex?.index;return"number"==typeof t&&t in i}return a in i}const Nu=new WeakMap;function Pu(t,e){null===e?Nu.delete(t):Nu.set(t,e)}function Iu(t,e,n){const s=Y(t.wildcardParentPaths[e]),r=Ue(t.stateElement,s),i=wn(s,n),a=Je(r,n),l=Te(a),c=t.stateProxy[Re](i),u=Es(i.listIndex,l,c);t.observedListValueByAbsAddress.set(a,Array.isArray(c)?c:[]);const d=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(u,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...d);else for(const n of d)Iu(t,e+1,n)}const ku=[];function Au(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:ku,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:ku,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Eu=[];function Cu(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Eu;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=Y(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??Eu}function Tu(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=Y(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[Re](e),a=Je(Ue(t.stateElement,e.pathInfo),e.listIndex),l=Te(a),c=Es(e.listIndex,l,r);t.observedListValueByAbsAddress.set(a,Array.isArray(r)?r:[]);const u=Au(t,o,0,0,c);for(const e of u.fullRows){const o=wn(s,e);t.result.add(o),n.push(o)}if(null!==u.movedRows){const e=Cu(t,i,s);if(null===e)for(const e of u.movedRows){const o=wn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of u.movedRows)for(const s of e){const e=wn(s,o);t.result.add(e),n.push(e)}}}else{const o=wn(s,e.listIndex);t.result.add(o),n.push(o)}}const i=t.dynamicMap.get(o);if(i)for(const o of i){const s=Y(o),r=[];if(s.wildcardCount>0){const n=tn(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&J(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=en(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Iu(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&J(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=en(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=wn(s,e);t.result.add(o),n.push(o)}}}function Mu(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&J(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),d={ranks:u,stateElement:t,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,Tu(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(d,e,a);for(const[t,e]of d.observedListValueByAbsAddress)Me(t,e);return Array.from(d.result)}function Ou(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||function(t,e){Xl.has(t)||Xl.set(t,e)}(n,o)}function Lu(t,e,n,s,r,i){const a=o.enablePropagationContext?so()??eo(-1):null,l=Ta();l.enqueueAbsoluteAddress(e,a),i&&Sl(e),Mu(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=Je(Ue(s.stateElement,e.pathInfo),e.listIndex);Sl(n),l.enqueueAbsoluteAddress(n,a)},{listExpansion:"diff",keyedMergePath:r})}function Ru(t,e,n,o,s){s&&(t.getterPaths.has(e)?Sl(n):$l(n,{value:o,dirty:!1,generation:t.stateGeneration}))}function ju(t,e,n,o,s,i,a,l){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const a=gu(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??J(Vr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(a,t,o)}return Reflect.set(a,l,o)}if(!i.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);i.pushAddress(e),i.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}finally{Lu(e,n,s,i,a,l)}}function Du(t,e,n,o,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(n)){const l=a.get(e.pathInfo.path);if(void 0!==l){const a=gu(t,e,o,i),c=function(t,e,n,o){const s=$u(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=$u(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,l,a,n);if(null!==c)return function(t,e,n,o,i,a){const l=e.pathInfo.path,c=e.listIndex;null===xs(o)&&Es(c,null,o);const u=Es(c,o,n.list),d=Wu(t,e,n.list,i,a,l),h=Y(l+s+r);for(const e of n.matched){const n=Su(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const r of n)void 0!==o?Du(t,wn(Y(h.path+s+r.field),o),r.value,i,a):e.oldRow[r.field]=r.value}return d}(t,e,c,a,o,i)}}return Wu(t,e,n,o,i,null)}function Wu(t,e,n,i,a,l){const c=a.stateElement,u=e.pathInfo.path;if(!0===c.hasGraftedVolumes){const t=function(t,e){const n=Er.get(t);if(void 0===n||0===n.size)return null;const o=e+s;for(const t of n)if(t.startsWith(o))return t;return null}(c,u);null!==t&&J(`Cannot replace "${u}" wholesale: a volume is mounted at "${t}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${t}" itself, or individual fields inside "${u}", instead.`)}if(!0===c.hasRecursion){const t=c.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);null!==t&&J(`[wcs/recursion-readonly] "${u}" writes into the recursive getter "${t}" (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.`)}const d=!!ao&&(ao=!1,!0);if(!(u in t)&&null!==e.parentAddress&&!c.elementPaths.has(u)){const s=gu(t,e.parentAddress,i,a);if("object"==typeof s&&null!==s){const t=e.pathInfo.lastSegment,h=t===r?e.listIndex?.index:t;let f,p=!1;if(!d&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==h&&h in s,e=void 0!==h?s[h]:void 0;if(t&&Object.is(e,n))return!0;f=e,p=!0}const m=fu(c,e),g=Je(Ue(c,e.pathInfo),e.listIndex);null!==xe&&xe({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:p}),Ou(c,u,g,f,p);let y=!1;try{if(void 0===h&&J(Vr(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),!0===c.hasMounts&&t!==r&&!(h in s)){const o=du(c,e.parentAddress.pathInfo.path,t,e.listIndex);if(null!==o)return y=!0,function(t,e,n,o,s,r){const i=iu(t,wn(Y(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(o.record,o.entry,e.listIndex,n,i,a)}return Reflect.set(s,h,n)}finally{Lu(e,g,i,a,l,m),y?Sl(g):Ru(c,u,g,n,m),wu(c,e.pathInfo,{value:n})}}}let h,f=!1;if(!d&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=gu(t,e,i,a);if(xu(t,e,i,a)&&Object.is(o,n))return!0;h=o,f=!0}const p=c.elementPaths.has(e.pathInfo.path),m=fu(c,e),g=Je(Ue(c,e.pathInfo),e.listIndex);null!==xe&&xe({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:f}),Ou(c,u,g,h,f);try{return p?function(t,e,n,o,s,r,i,a){let l=e.parentAddress??J(`address.parentAddress is undefined path: ${e.pathInfo.path}`),c=function(t){return Nu.get(t)??null}(l);if(null===c){const e=gu(t,l,s,r)??[],n=xs(e)??[];c={value:[...e],listIndexes:[...n]},Pu(l,c)}try{return ju(t,e,n,o,s,r,i,a)}finally{const n=c.value.indexOf(o),i=gu(t,l,s,r)??[],a=Array.isArray(i)?xs(i)??[]:[],u=e.listIndex.index,d=-1!==n?c.listIndexes[n]:gs(l.listIndex,-1);if(a[u]=d,new Set(i).size===c.value.length){for(let t=0;t<a.length;t++)a[t].index=t;Pu(l,null)}}}(t,e,g,n,i,a,l,m):ju(t,e,g,n,i,a,l,m)}finally{Ru(c,u,g,n,m),wu(c,e.pathInfo,{value:n})}}function Bu(t,e,n,o){return(e,s,r)=>{const i=Y(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&J(Ur("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=wn(i,bu(t,n,o,i,s));if(void 0===r)return gu(t,a,n,o);Du(t,a,r,n,o)}}function zu(t,e,n){const o=t.recursionRegistry,r=hl(o.spec,n);null===r&&J(qr(n,o.spec.recursiveAnchor));const i=function(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=e.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(t,e){const n=t.spec;if(!e.startsWith(n.anchor))return null;const o=s+n.repeat;let r=0,i=n.anchor.length;for(;e.startsWith(o,i);)i+=o.length,r++;return i!==e.length&&46!==e.charCodeAt(i)?null:r}(e,n.pathInfo.path)}(e,o);return null===i&&J(`[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(r,i)}function Fu(t,e,n,o,r){const i=o.spec,a=[],l=new Map,c=[],u=i.repeatList,d=i.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void a.push(wn(t,n));const s=m(o[e],n,null).rows;for(let n=0;n<s.length;n++)p(t,e+1,s[n])};function m(o,s,r){const a=wn(o,s),c=Je(Ue(n.stateElement,o),s),d=gu(t,a,e,n),f=null===r?null:((t,e,n)=>{if(!Array.isArray(e)||0===e.length)return null;const o=e;return h.has(o)&&J(`[wcs/recursion-cycle] "${t}" is reachable from itself: the recursion on "${i.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)&&J(`[wcs/recursion-shared-list] "${t}" is the same array instance as a list reached from another node. The recursion on "${i.anchor}" needs a tree: give each node its own "${u}" array.`),o})(o.path,d,r),p=Es(s,Te(c),d);return l.set(c,Array.isArray(d)?d:[]),null!==f&&null!==r&&r.add(f),{rows:p.newIndexes,tracked:f}}const g=(t,e,n)=>{const{rows:i,tracked:l}=m(e,n,f);if(0===i.length)return;const d=(t=>{const e=c[t];if(void 0!==e)return e;const n=o.concretePathAt(r,t),i=0===r.length?n:o.concretePathAt("",t),a={nodePath:i,concretePathInfo:Y(n),childListPathInfo:Y(i+s+u)};return c[t]=a,a})(t),y=l;h.add(y);const b=d.concretePathInfo.wildcardCount===t+1;for(let e=0;e<i.length;e++){const n=i[e];b?a.push(wn(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,Y(d),null);for(const[t,e]of l)Me(t,e);return a}function Hu(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return nu(o,s.wildcardPaths.at(-1)??J(`lastWildcardPath is null: ${e.pathInfo.path}`))??J(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??J(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=Ns(gu(t,wn(i,s),n,o),s)??J(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??J(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??J(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":J(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}const Uu=/^\$\d+$/,qu=`${z}${s}`,Gu=`${F}${s}`,Vu=new WeakMap;function Ku(t,e,n,o){const r=S[e];if(void 0===r&&"string"==typeof e&&36===e.charCodeAt(0)&&Uu.test(e)&&J(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==r){0===o.addressStackLength&&J(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const i=t?.listIndex;null==i&&J(`ListIndex not found: ${e.toString()}`);let a=r;const l=t.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const t=ve(o.stateElement,l.path);null!==t&&(a=r+function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(s,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const r=-1===o?e:e.slice(0,o),i=-1===o?"":e.slice(o+1),a=t.accessorBySuffixByMarkerParent.get(r)?.get(i);return void 0!==a?a.indexShift:t.delta}(t,l.path))}const c=en(i,a,l.wildcardCount);return c?.index??J(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>function(t,e,n,o){const s=Bu(t,0,n,o);return(e,r)=>{if(!0===o.stateElement.hasRecursion&&dl(e)){if(void 0!==r)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=hl(r.spec,o);null===i&&J(qr(o,r.spec.recursiveAnchor)),Array.isArray(s)||J(`[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&&J(`[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=Fu(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(gu(t,a[o],e,n));return l}(t,n,o,e,r);e=zu(o.stateElement,o,e)}const i=Y(e);if(void 0===r||Array.isArray(r)||J(`$getAll("${e}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&J(Ur("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=nu(o,i.wildcardPaths[t]);if(e){r=nn(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&J(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(e,t.pathInfo.path)),r=[]}}const a=yu(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>function(t,e,n,o){return(e,s,r,i)=>{if(!0===o.stateElement.hasRecursion&&dl(e))return function(t,e,n,o,s,r,i){const a=n.stateElement.recursionRegistry,l=hl(a.spec,o);null===l&&J(qr(o,a.spec.recursiveAnchor));const c=fl(l);Array.isArray(s)||J(Gr(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&J(`[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&&J(Gr(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&J(Gr(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(t,e,n){yl(t,n)&&J(`[wcs/recursion-structural-write] "${e}" writes the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const u=a.conflictingRecursiveGetter(c);null!==u&&J(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${u}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const d=Fu(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(Du(t,d[o],r,e,n),h++);return h}(t,n,o,e,s,r,i);const a=Y(e);Array.isArray(s)||J(Gr(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&J(Ur("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&J(Gr(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&J(Gr(e,"requires an array as the value when { spread: true } is set."));const u=yu(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&J(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,u.length,r.length));const d=[];for(let e=0;e<u.length;e++){const s=bu(t,n,o,a,u[e]);d.push(wn(a,s))}let h=0;for(let e=0;e<d.length;e++){const s=d[e];let i;i=c?r(gu(t,s,n,o),...u[e]):l?r[e]:r,void 0!==i&&(Du(t,s,i,n,o),h++)}return h}}(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=eu(e),i=Hu(t,r,n,o),a=wn(r.pathInfo,i),l=Je(Ue(s,a.pathInfo),a.listIndex),c=Ta();c.enqueueAbsoluteAddress(l),Mu(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Je(Ue(s,t.pathInfo),t.listIndex);Sl(e),c.enqueueAbsoluteAddress(e)}),wu(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>Bu(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{dl(t)&&J(`[wcs/recursion-unsupported] $trackDependency("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&J(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??J("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(e.path)&&e.path!==t&&n.addDynamicDependency(t,e.path)}}(0,0,0,o)(t);case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case T:return Xa(o.stateElement);case z:return Cl(o.stateElement);case F:return Tl(o.stateElement)}if(!e.startsWith(qu)&&!e.startsWith(Gu))return}const s=eu(!0===o.stateElement?.hasRecursion&&dl(e)?zu(o.stateElement,o,e):e),r=Hu(t,s,n,o),i=wn(s.pathInfo,r);return gu(t,i,n,o)}if("symbol"==typeof e){const r=function(t){let e=Vu.get(t);return void 0===e&&(e=new Map,Vu.set(t,e)),e}(o),i=r.get(e);if(void 0!==i)return i;let a;switch(e){case Le:a=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&J("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case Re:a=e=>gu(t,e,n,o);break;case je:a=e=>xu(t,e,n,o);break;case De:a=(e,s)=>Du(t,e,s,n,o);break;case We:a=()=>async function(t,e,n){const o=Reflect.get(t,x);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Be:a=()=>function(t,e,n){const o=Reflect.get(t,N);"function"==typeof o&&o.call(n)}(t,0,n);break;case ze:a=e=>function(t,e,n,o){const r=Reflect.get(t,P);let i;if("function"==typeof r){const t=new Set,s={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,r=e.path;if(-1===r.indexOf("#")&&(t.add(r),e.wildcardCount>0)){const t=nn(n.listIndex,e.wildcardCount),o=s[r];void 0===o?s[r]=[t]:o.push(t)}}i=r.call(n,Array.from(t),s)}const a=o.stateElement?(l=o.stateElement,Tr.get(l)??Mr):[];var l;if(a.length>0)for(const t of a){const r=t.mountPath+s,i=new Set,a={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo.path;if(e!==t.mountPath&&!e.startsWith(r))continue;if(-1!==e.indexOf("#"))continue;const s=e===t.mountPath?"":e.slice(r.length);if(""===s)continue;i.add(s);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const t=nn(n.listIndex,l);(a[s]??=[]).push(t)}}if(i.size>0)try{t.callback.call(Cr(t.mountPath,n),Array.from(i),a)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" $updatedCallback threw.`,e)}}return i}(t,e,n,o);break;case Fe:a=(e,o)=>function(t,e,n,o){const s=Reflect.get(t,I);"function"==typeof s&&s.call(o,e,n)}(t,e,o,n);break;default:return Reflect.get(t,e,n)}return r.set(e,a),a}}class Ju{_stateElement;_addressStack=Array(a).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=ia(t);null===n&&J("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&J("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=a&&(this._hasRepeatedAddress()&&J(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),J(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const n=this._addressStack[e];if(n){if(t.has(n))return!0;t.add(n)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&J(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return Ku(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&J("This state is readonly."),function(t,e,n,o,s){if("string"==typeof e){const r=eu(e),i=Hu(t,r,o,s);return Du(t,wn(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}}const Qu=new WeakMap;class Xu{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=Qu.get(t);return n?n.get(e)??null:null}(t,e)??J("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const Yu=t=>()=>t;function Zu(t,e,n,o){!function(t,e,n){let o=Qu.get(t);o||(o=new Map,Qu.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(function(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}(o));const s=function(t,e){const n=new Xu(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:Yu(s),enumerable:!0,configurable:!0}),ns(e,n),td(e,n)}function td(t,e){if(k in t){const n=t[k];"function"==typeof n?n.call(t,e).catch(t=>{J(`Error in ${k}: ${t instanceof Error?t.message:String(t)}`)}):J(`${k} is not a function.`)}}function ed(t,e){const n=we(e);var o,i;null!==n&&n.stateProp!==t.stateProp&&J(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&Zo(e).dispose(),function(t,e){me.set(t,e);let n=ye.get(e.parentStateElement);void 0===n&&(n=new Map,ye.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=ge.get(e.component);void 0===o&&(o=new Map,ge.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&be.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}(e,t),e instanceof ShadowRoot&&function(t,e){const n=oa.get(t);if(void 0!==n){if(n===e)return;J("A state tree is already registered on this root.")}oa.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const i=he.exec(e.statePathName);if(null!==i){const s=function(t,e){return void 0===e?t.delta:Y(fe(t,e)).wildcardCount-Y(e).wildcardCount}(t,n);o=0===s?e.statePathName:`$${Number(i[1])+s}`}else if(o=fe(t,e.statePathName),"for"===e.bindingType){const n=Y(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+s+r,n)}return o===e.statePathName?e:{...e,statePathName:o,statePathInfo:Y(o)}}(t,e,n);gi(e);const o=$e(t.component);Mi(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),fi(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=fe(t,n)}catch{continue}const o=e.indexOf(s+t.marker);if(-1===o)continue;const r=e.slice(0,o+1+t.marker.length),i=e.slice(r.length+1),a=e.slice(0,o)+s+i,l=Y(a);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:r,suffix:i,markerPath:e,exportedPath:a};t.exports.set(a,c),cu(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,a),Yr(t.parentStateElement,a)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=$e(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const s=`${n}|${o.exportedPath}`;if(lu.has(s))continue;const r=Y(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[Le](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(lu.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(t),hu(t),o=e,i=Promise.resolve(),sa.set(o,i),i.then(()=>ca(o),()=>{})}const nd=new Set;function od(t,e){nd.has(t)||(nd.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function sd(t){const e=t.rootEntry,n=$e(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Le](n,()=>{o=t[e.outerPathInfo.path]})}),o}function rd(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(Cr(t.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function id(t,e,n){!function(t,e,n){const o=n[R];if(void 0!==o){"object"==typeof o&&null!==o||J(`${R} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&J(`${R} entry "${t}" must be a function.`),Kl(t)}const r=n[B];if(void 0!==r){"object"==typeof r&&null!==r||J(`${B} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(r))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&J(`${B} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+s+n)&&J(`${B} entry "${e+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&J(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&J(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[D]&&J(`Volume "${e}" declares ${D}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys(ul(n)))-1!==t.indexOf(W)&&J(`Volume "${e}" declares "${t}", which uses "${W}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n);const{data:o,accessors:r}=function(t){const e={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(t)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(e[o]=s.value):n.set(o,s));return{data:e,accessors:n}}(n),i=Y(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;J(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],r=""===n?o in t:void 0!==t[n+s+o];n=""===n?o:n+s+o,r||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(a)return;J(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=o}),function(t,e){let n=Er.get(t);void 0===n&&(n=new Set,Er.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,o]of r){const r=e+s+n,i=o.get,a=o.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(Cr(e,this))}),"function"==typeof a&&(l.set=function(t){a.call(Cr(e,this),t)}),t.defineTreeAccessor(r,l)}!function(t,e,n){const o=n[R];if(void 0!==o){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(o)){const o=e+s+a,c=function(t,n,...o){l.call(Cr(e,this),t,n,...o)};n.push({path:o,pathInfo:Y(o),handler:c,order:1e6+i++}),r.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(function(t,e){let n=Fl.get(t);void 0===n&&(n=new Map,Fl.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}(t,n),t.addVolumeWatchPaths?.(r),kc(t))}const r=n[B];if(void 0!==r){const n=new Map;for(const[t,o]of Object.entries(r))n.set(e+s+t,o);t.mergeVolumeListKeys?.(n)}const i=n[P];"function"==typeof i&&(function(t,e){let n=Tr.get(t);void 0===n&&(n=[],Tr.set(t,n)),n.push(e)}(t,{mountPath:e,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}(t,e,n);const l=n.$connectedCallback;return"function"==typeof l&&t.createState("writable",t=>{const n=l.call(Cr(e,t));n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function ad(t,e){let n=null;try{n=id(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}jr=ad;class ld extends ji{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return aa(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Va}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_volumeGraftInfo=null;_volumeInitializing=!1;_mountRecord=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_dcc=!1;_connectGeneration=0;_streamsStartedGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&J(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){const n=this.__state,o=function(t){const e=t[D];if(void 0===e)return null;"object"==typeof e&&null!==e||J(`[wcs/recursion-declaration-invalid] ${D} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(e);0===n.length&&J(`[wcs/recursion-declaration-invalid] ${D} must declare exactly one anchor; it is empty.`),n.length>1&&J(`[wcs/recursion-declaration-invalid] ${D} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,i]=n[0];cl("anchor",o),"string"!=typeof i&&J(`[wcs/recursion-declaration-invalid] ${D} entry "${o}" must map to the repeating sub-path as a string (for example "children${s}${r}").`),cl("repeating sub-path",i);const a=o.slice(0,o.lastIndexOf(s)),l=i.slice(0,i.lastIndexOf(s)),c=a+s+W;return Object.freeze({anchor:o,repeat:i,recursiveAnchor:c,anchorList:a,repeatList:l})}(t),i=null===o?null:new Il(o,t),a=function(t){const e=new Set,n=t[C];if(void 0===n)return e;Array.isArray(n)||J(`${C} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||J(`${C} entries must be non-empty strings.`),t===T&&J(`${C} entry "${t}" conflicts with the reserved namespace name "${T}".`),e.has(t)&&J(`${C} entry "${t}" is duplicated.`),e.add(t);return e}(t),l=function(t){const e=new Set,n=t[M];if(void 0===n)return e;Array.isArray(n)||J(`${M} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||J(`${M} entries must be non-empty strings.`),e.has(t)&&J(`${M} entry "${t}" is duplicated.`),e.add(t);return e}(t),c=function(t){const e=t[B];if(void 0===e)return null;"object"==typeof e&&null!==e||J(`${B} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&J(`${B} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&J(`${B} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&J(`${B} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),-1!==t.indexOf(W)&&J(`[wcs/recursion-unsupported] ${B} entry "${t}" uses "${W}", which ${B} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${s}${r}${s}children").`),"function"!=typeof o?("string"!=typeof o&&J(`${B} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&J(`${B} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&J(`${B} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&J(`${B} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t),u=function(t,e,n=null){const o=t[j];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&J(`${Rc} ${j} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${bt}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(ul(t)))"function"==typeof n.get?s.add(e):"function"==typeof n.set&&i.add(e),"function"==typeof n.set&&r.add(e),"function"==typeof n.value&&a.set(e,n.value);const l=function(t){const e=t[L];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];let u=0;for(const[t,d]of Object.entries(o)){Fc(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&J(`${Rc} ${Dc(t)} must be an object ({ from | on, initial, fold, resetOn? }).${bt}`);const o=d;Hc(t,a,o);const h=Uc(t,o,e,s,i,n);"initial"in o||J(`${Rc} ${Dc(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${bt}`),"function"!=typeof o.fold&&J(`${Rc} ${Dc(t)} fold must be a function.${bt}`);const f=qc(t,o.resetOn,h,s);c.push({name:t,source:h,fold:o.fold,initial:o.initial,resetOn:f,order:u++})}return function(t){const e=new Set(t.map(t=>t.name)),n=new Map;for(const o of t){for(const t of o.resetOn){const n=Y(t).segments[0];e.has(n)&&J(`${Rc} ${Dc(o.name)} resetOn "${t}" reads the ${j} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${bt}`)}if("path"===o.source.kind){const t=o.source.pathInfo.segments[0];e.has(t)&&n.set(o.name,t)}}for(const t of n.keys()){const o=[t];let s=n.get(t);for(;void 0!==s&&o.length<=e.size;)s===t&&J(`${Rc} ${j} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${bt}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}(t,l,i);if(null!==this._recursionRegistry)for(const t of this._recursionRegistry.forgetGenerated(this,n))this._generatedPaths.add(t);this._recursionRegistry=i,this._commandTokenNames=a,this._eventTokenNames=l,this._stateGeneration++,this.__state=t,this._hasUpdatedCallback=P in t,this._hasErrorCallback=I in t,Tn.delete(this),null!==u&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=ic(n.initial);t[n.name]=e,uc(n.name,e)}}(t,u),function(t,e){for(const n of e)"event"===n.source.kind&&Mn(t,n.source.tokenName).subscribe(Gc(n))}(this,u)),function(t,e,n){const o=e[O];if(void 0!==o){"object"==typeof o&&null!==o||J(`${O} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||J(`${O} entry "${e}" is not declared in $eventTokens.${yt(e,n)}`),"function"!=typeof s&&J(`${O} entry "${e}" must be a function.`),Mn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const d=function(t){const e=new Set,n=new Set,o=ul(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of d.getterPaths)this._getterPaths.add(t);for(const t of d.setterPaths)this._setterPaths.add(t);Ml(this),function(t){il(t),ol(t),sl.delete(t)}(this),function(t,e){const n=e[L];if(void 0===n)return void tl(t,ll);"object"==typeof n&&null!==n||J(`${L} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[i,a]of Object.entries(n)){0===i.length&&J(`${L} entry name must be a non-empty string.`),i.includes(s)&&J(`${L} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&J(`${L} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&J(`${L} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&J(`${L} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&J(`${L} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&J(`${L} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||J(`${L} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&J(`${L} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&J(`${L} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&J(`${L} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&J(`${L} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??al,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};i in e||(e[i]=c.definition.initial),o.set(i,c)}!function(t,e){sl.set(t,e)}(t,o),tl(t,new Set(o.keys()))}(this,t),this._listKeys=c,null!==o&&this._listPaths.add(o.anchorList),this._rebuildPathInfo();const h=function(t){const e=new Map,n=va(t);if(void 0!==n)for(const t of n.entries)Ia(t)&&e.set(t.name,t.resetOn);return _a(t),e}(this);this._scanPaths=null===u?null:function(t,e,n){const o=function(t,e){_a(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&wa(n,t.source.path,t);for(const e of t.resetOn)wa(o,e,t),"event"===t.source.kind&&wa(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return ma.set(t,r),r}(t,e);for(const o of e){const e=n.get(o.name);"event"===o.source.kind&&void 0!==e&&o.resetOn.some(n=>e.includes(n)&&Ta().hasQueuedPath(t,n))&&Pa(o)}const s=new Set;for(const e of o.byFromPath.keys())s.add(e),t.setPathInfo(e,"prop","scan");for(const e of o.byResetPath.keys())t.setPathInfo(e,"prop","scan");return s.size>0?s:null}(this,u,h),function(t){Hl.delete(t),$a(t),zl.delete(t)}(this),function(t){Jl.delete(t)}(this),this._watchPaths=function(t,e){const n=e[R];if(void 0===n)return null;"object"==typeof n&&null!==n||J(`[wcs/watch-declaration-invalid] ${R} must be an object mapping state paths to handler functions.${bt}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&J(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must be a function.${bt}`);const n=Kl(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){zl.set(t,e)}(t,o),s.size>0?s:null}(this,t),this._initialized&&null!==this._rootNode&&!e()&&(kc(this),Dl(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}attributeChangedCallback(t,e,n){this._initialized&&e!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===e?"absent":`"${e}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const t=this.parentNode;if(!t)return null;const e=Hi.find(t);if(!e)return null;const n=e.stateData;return Object.keys(n).length>0?n:null}async _loadStateFromSource(){try{if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){J("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await qa(t,o.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||J(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await Ga(t);J(`Unsupported src file type: ${t}`)}}catch(t){J(`Failed to initialize state: ${t}`)}}async _initializeVolume(){const t=this._rootNode,e=this.getAttribute("mount");try{!function(t){0===t.length&&J('"mount" requires a non-empty tree path.');const e=Y(t);for(const n of e.segments)0===n.length&&J(`"mount" path "${t}" has an empty segment.`),n===r&&J(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&J(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(e),this.hasAttribute("bind-component")&&J('"mount" cannot be combined with "bind-component".'),this.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),function(t,e){let n=kr.get(t);void 0===n&&(n=new Set,kr.set(t,n)),n.has(e)&&J(`Volume slot "${e}" is already mounted on this tree.`),n.add(e)}(t,e)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}this._volumeInitializing=!0,null===ia(t)&&function(t,e){const n=()=>{if(null!==ia(t))return;const n=t.querySelectorAll(o.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=t.ownerDocument??t;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(t,e);const n=t=>{this._volumeGraftInfo=t,this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()};let s;try{s=await this._loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${e}" failed to load.`,t),void n(null)}null!==this._rootNode?function(t,e,n,o,s){null===e?function(t,e){if(Lr.has(t))return void Rr(e);let n=Or.get(t);void 0===n&&(n=[],Or.set(t,n)),n.push(e)}(t,{mountPath:n,volumeState:o,onGrafted:s}):ad(e,{mountPath:n,volumeState:o,onGrafted:s})}(t,ia(t),e,s,n):n(null)}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}return await this._loadingPromise,null!==this._rootNode&&(ua(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),J(t)}_failInitializeLoudly(t){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),null!==this._rootNode&&null===ia(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),sa.set(t,n)}(this._rootNode,t),function(t){Lr.add(t);const e=Or.get(t);if(void 0!==e){Or.delete(t);for(const t of e)Rr(t)}}(this._rootNode)),t}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const i=this.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?et(a):null;null!==a&&null!==l||J(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${this.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(t=>this.hasAttribute(t));null!==this.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&J(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const u=this.getAttribute("bind-component");!function(t,e){let n=os.get(t);n||(n=new Set,os.set(t,n)),n.add(e)}(a,u);const d=ot(a);null===d&&J(`CustomElementRegistry is unavailable for <${l}>.`),await d.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await V(a),u in a||J(`Component does not have property "${u}" for state binding.`);let h=a[u];"object"==typeof h&&null!==h||J(`Component property "${u}" is not an object for state binding.`);const f=function(t,e){const n=pr.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,u);if(void 0!==f&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=mt(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,u)&&(a[u]=f,h=f),this._boundComponent=a,this._boundComponentStateProp=u,i instanceof ShadowRoot||(mt(a)??[]).some(t=>t.propSegments[0]===u)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${u}: path").`),a.hasAttribute(o.bindAttributeName)){const o=(mt(a)??[]).filter(t=>t.propSegments[0]===u);if(o.length>0){const c=ia(a.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${l}>.`);let d=(n=a,r=u,ge.get(n)?.get(r)??null);const f=null!==d;if(null===d&&(function(t,e,n){const o=gr.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;gr.get(t).delete(e)}}(a,u,h),d=function(t,e,n,o,r,i=new Set){0===n.length&&J(`Cannot build a mount record without host bindings for "${e}".`);const a=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(s);l.has(n)&&J("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo};a.push(o),0===e.length&&(c=o)}a.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++ee,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(r),p={};for(const t of Object.keys(r))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof r[t]&&(i.has(t)||(p[t]=r[t]));return{id:u,marker:d,component:t,stateProp:e,parentStateElement:o,entries:a,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?d:c.outerPathInfo.path+s+d,stateObject:r,getterKeys:h,setterKeys:f,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(a,u,o,c,h,(t=a,e=u,mr.get(t)?.get(e))),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp,s=new Map;for(const e of t.entries)1===e.innerSegments.length&&s.set(e.innerSegments[0],e.outerPathInfo.path);let r,i=!1;for(const a of e){const e=s.get(a);if(void 0!==e){od(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted entry "${o}.${a}: ${e}" (the host value no longer reaches it). Remove the default to read the tree, or rename it to keep it private.`);continue}if(null===t.rootEntry)continue;if(i||(r=sd(t),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=t.rootEntry.outerPathInfo.path;od(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted tree key "${l}.${a}" (${o}: ${l}). Remove the default to read the tree, or rename it to keep it private.`)}}(d)),this._mountRecord=d,this.parentNode!==i)return;try{ed(d,i instanceof ShadowRoot?i:a)}catch(t){throw this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}if(!f){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=$e(t.component);let s;return e[Le](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(t,e,n){const o=t.parentStateElement,s=(t,e)=>{let s;return o.createState(t,t=>{s=n(t,()=>e(t))}),s};return"$postUpdate"===e?e=>s("readonly",n=>n.$postUpdate(fe(t,e))):(n,o,...r)=>{const i=fe(t,n),a=$e(t.component)?.listIndex.indexes??[],l=pe(0,n,i,"$resolve"===e?o??[]:o,a),c="$setAll"===e||"$resolve"===e&&r.length>0?"writable":"readonly";return s(c,t=>t[e](i,l,...r))}}(t,s,n);let r;return e.createState("readonly",e=>{r=n(e,()=>e["$"===s[0]?s:fe(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:fe(t,s)]=r})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return fe(t,n),!0}catch{return!1}}})}(d);Object.defineProperty(a,u,{get:()=>t,enumerable:!0,configurable:!0}),ns(a,u)}return td(a,u),function(t){const e=ne.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(W)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;oe.has(n)||(oe.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(d),void se(d,"$connectedCallback")}}Zu(this,this._boundComponent,this._boundComponentStateProp,h)}var t,e,n,r}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{x in t&&await t[We]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await Ga(t):J(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await qa(e,t.tagName.toLowerCase()):J(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){J(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||J(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=ot(t);null!==r&&"function"==typeof r.define||J(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&J(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const t of Array.from(e.childNodes))i.content.appendChild(a.importNode(t,!0));const l=e.mode,{bindables:c,commands:u,streamBackedBindables:d}=function(t){const e=Yc(t,A)??[],n=Yc(t,E)??[],o=ul(t),s=function(t){const e=t[L];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}J(`${A} entry "${t}" is not declared on the state.${yt(t,Xc(o,"value"))}`)}"function"==typeof e.value&&J(`${A} entry "${t}" is a method. Declare it in ${E} instead.`)}for(const t of n){const e=o[t];void 0===e&&J(`${E} entry "${t}" is not declared on the state.${yt(t,Xc(o,"method"))}`),"function"!=typeof e.value&&J(`${E} entry "${t}" is not a method. Declare it in ${A} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||u.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(H))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=ot(this._shadow);return null!==t&&st(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(m.bindableEventMap).length>0){const e=t.querySelector(p);e?e.setBindableEventMap(m.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${A} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=ul(n);for(const[t,e]of Object.entries(g)){if(Qc(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=Jc(t,o)}else n.get=Vc(t),n.set=Kc(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:Vc(t),set:Kc(t)});r.define(s,m)}(t,e,n),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",t=>{N in t&&t[Be]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&ia(this._rootNode)===this._volumeGraftInfo.rootStateElement&&rd(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const t=this._mountRecord,e=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&function(t,e){const n=Zo(e),o=$e(t.component);n.forEachActiveBindingNode(t=>Se(t,o)),hi(n.rebindAddresses()),hu(t)}(t,e)}),se(t,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||ia(this._rootNode)===this||ua(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=this.parentNode;if(e instanceof ShadowRoot&&e.host.hasAttribute(H)){try{this.hasAttribute("bind-component")&&J(`"bind-component" cannot be used inside a [${H}] host. DCC state comes from the template, not from a component property.`),await this._initializeDCC(e.host,e)}catch(t){this._failInitializeLoudly(t)}return}if(this.hasAttribute("mount")){if(this._volumeInitializing)return;return void await this._initializeVolume()}try{await this._initializeBindWebComponent()}catch(t){this._failInitializeLoudly(t)}if(null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();let n=!1;try{n=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!n)return;this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||t!==this._connectGeneration||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await aa(this.rootNode);const t=Hi.extractStateData(this),e=document.createElement(o.tagNames.ssr);e.setAttribute("version",Ri),Hi.buildContent(e,t),this.parentNode?.insertBefore(e,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||kc(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||Dl(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&rd(this._volumeGraftInfo,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._mountRecord)return se(this._mountRecord,"$disconnectedCallback"),hu(this._mountRecord),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&(t=this._rootNode,Lr.delete(t)),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{ua(this.rootNode,null),Qa.delete(this),il(this),Ml(this),function(t){Hl.delete(t),$a(t)}(this),this._rootNode=null}}var t}get initialized(){return this._initialized}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&J(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return Br(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&J("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0}get hasGraftedVolumes(){return this._hasGraftedVolumes}markHasGraftedVolumes(){this._hasGraftedVolumes=!0}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(t);void 0!==o&&"for"===o.bindingType||this._pathRegistrations.set(t,{bindingType:e,source:n})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+r)),!this._pathSet.has(t)){const e=Y(t);if(this._pathSet.add(t),function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(Ar(t.rootNode??null,n))return;const i=Y(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=Kr.get(t);return void 0===n&&(n=new Set,Kr.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const a=function(t,e,n){if(void 0!==Br(t,e))return Wr;const o=Y(e).segments;let i=t,a="";for(let e=0;e<o.length;e++){const l=o[e],c=a;if(a=0===e?l:a+s+l,e>0&&e<o.length-1&&void 0!==Br(t,a))return Dr;if(Object(i)!==i)return Dr;if(l===r){if(!Array.isArray(i)||0===i.length)return Dr;i=i[0];continue}const u=Br(i,l);if(void 0===u)return{existence:"missing",missingSegment:l,candidates:zr(i,c,n)};if("function"==typeof u.get)return e===o.length-1?Wr:Dr;i=u.value}return Wr}(e,n,t.getterPaths);"missing"===a.existence&&(function(t,e){return!0===Xr.get(t)?.has(e)}(t,n)||("binding"!==o?Zr(0,n,o,a):function(t,e,n){let o=Jr.get(t);void 0===o&&(o=new Map,Jr.set(t,o)),o.set(e,n),Qr.has(t)||(Qr.add(t),setTimeout(()=>function(t){Qr.delete(t);const e=Jr.get(t);if(void 0!==e){Jr.delete(t);for(const[t,n]of e)Zr(0,t,"binding",n)}}(t),0))}(t,n,a)))}(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=Y(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))this._generatedPaths.has(t)||this.setPathInfo(t,e.bindingType,e.source)}_createState(t,e,n){try{const o=function(t,e,n){const o=new Ju(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&J(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);(this._hasGraftedVolumes||this._hasMounts)&&J("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."),this._state=t}}await function(){const e=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(void 0);var s;e&&((s=e).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)),function(t=customElements){t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,Hi),t.get(o.tagNames.state)||t.define(o.tagNames.state,ld)}(void 0),function(){const t=globalThis;void 0===t[Ki]&&(t[Ki]=na)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=Fa)}(),za()}();const cd={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},ud=!1,dd=[".html"];function hd(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function fd(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let pd=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const md={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function gd(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function yd(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}const bd={static:2,param:1,"catch-all":0};let wd=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&fd(`${cd.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&fd(`${cd.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=bd[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(md).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||fd(`${cd.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath,o=await this._guardHandler(e,n,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:gd(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new pd("Navigation cancelled by guard.",o);if(!o)throw new pd("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new pd("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},vd=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=hd();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new wd(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||fd(`${cd.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):fd(`${cd.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&fd(`${cd.route} with fallback attribute must be a direct child of ${cd.router}.`),t.fallbackRoute&&fd(`${cd.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const _d=Symbol.for("wcstack.trustedTypes.policy"),$d=Symbol.for("wcstack.trustedTypes.internal"),Sd="wcstack";function xd(){const t=globalThis[_d];return null===t||"object"!=typeof t?null:t}let Nd=!1;function Pd(t){const e=function(){const t=globalThis,e=t[$d];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Sd,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof xd()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Sd}". Allow it in the CSP (\`trusted-types ${Sd};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[$d]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=xd(),s=o?.createHTML;return"function"==typeof s?(Nd||(Nd=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Sd}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Sd};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Id=new Map;let kd=class extends HTMLElement{_uuid=hd();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||fd(`${cd.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Id.set(t,n),n}catch(e){fd(`${cd.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${cd.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Id.has(t)?n.innerHTML=Pd(Id.get(t)||""):n.innerHTML=Pd(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Pd(t):console.warn(`${cd.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&ud}get name(){return this.getAttribute("name")||""}},Ad=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||fd(`${cd.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&ud}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Ed=new Set(["props","states","attr",""]);function Cd(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function Td(t,e){t.hasAttribute("data-bind")||fd(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Ed.has(n)||fd(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&Cd(t,e,o)}).catch(()=>{fd(`Failed to define custom element: ${s}`)}):Cd(t,e,o)}let Md=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||fd(`${cd.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${cd.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{Td(e,t)}),e.hasAttribute("data-bind")&&Td(e,t))}};function Od(){return document.createElement(cd.layoutOutlet)}const Ld="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Rd(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){fd(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${Ld}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${Ld}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function jd(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function Dd(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===cd.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),jd(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===cd.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Rd(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===cd.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=Od();o.layout=n,i=o,a=e}}const c=await Dd(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function Wd(t){const e=new Map;return await Dd(t,t.template.content,[],e)}function Bd(t){return!1!==t.checkVisibility?.()}function zd(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",n=md[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)zd(s,e,n,o)}function Fd(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)zd(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let Hd=null,Ud=null;function qd(){const t=dd;return 0===t.length?null:(Hd===t&&Ud||(Hd=t,Ud=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Ud)}function Gd(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=qd();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Vd(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function Kd(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=qd();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function Jd(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function Qd(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{Td(e,t.typedParams)}),n.hasAttribute("data-bind")&&Td(n,t.typedParams),n.querySelectorAll(cd.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===cd.layoutOutlet&&n.assignParams(t.typedParams)}}function Xd(t,e){Qd(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const Yd=Symbol.for("wcstack.transition-runner");const Zd=Symbol.for("wcstack.binder");function th(){const t=globalThis[Zd];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const eh=Symbol.for("wcstack.binder.pending"),nh=Symbol.for("wcstack.binder.taken");function oh(){const t=globalThis;let e=t[nh];return void 0===e&&(e=new WeakSet,t[nh]=e),e}function sh(t){const e=th();return null===e?(function(){const t=globalThis;let e=t[eh];return void 0===e&&(e=[],t[eh]=e),e}().push(t),!1):(oh().add(t),e.bind(t),!0)}const rh=new WeakSet,ih="data-wcs";function ah(t,e,n){!rh.has(t)&&function(t){return t.hasAttribute(ih)||null!==t.querySelector(`[${ih}]`)}(t)&&(rh.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==th()||(o=t,oh().has(o))||console.warn(`[@wcstack/router] ${e} contains ${ih} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function lh(t){for(const e of t.childNodeArray)1===e.nodeType&&(sh(e)||ah(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.'))}async function ch(t,e){try{let t=null;for(const n of e.routes){const o=await n.guardCheck(e);o&&(t=null===t?o:Object.assign({},t,o))}e.data=t}catch(e){if(e instanceof pd)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function uh(t,e,n,o,s=""){const r=Vd(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:s,path:r}),!0;let i=Fd(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:fd(`${cd.router} No route matched for path: ${r}`)),i.lastPath=o,i.search=s;const a=e.lastRoutes,l=await async function(t,e,n){if(!await ch(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||Jd(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=Xd(o,e),n.length>0&&!s.has(o)&&lh(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[Yd];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",data:i.data??null,search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(Bd(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(Bd(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(t,i),!0)}function dh(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function hh(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function fh(t){return"?"===t?"":t}function ph(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function mh(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const gh="data-wcs-ssr",yh="data-wcs-ssr-link",bh="@@wcs-route-ph:",wh="@@wcs-route-start:",vh="@@wcs-route-end:",_h=Object.freeze({});class $h extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=_h;_typedParams=_h;_searchParams=_h;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return Gd(t)}_normalizeBasename(t){return Kd(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(cd.outlet))return t;const e=document.createElement(cd.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||fd(`${cd.router} has no outlet.`),this._outlet}get template(){return this._template||fd(`${cd.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=gd(t.search),s=t.data??null,r=this._data!==s,i=!yd(this._params,e),a=this._routeName!==t.routeName,l=!yd(this._searchParams,o),c=this._path!==t.path;r&&(this._data=s),i&&(this._params=e,this._typedParams=n),a&&(this._routeName=t.routeName),l&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,r&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${cd.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${cd.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=hh(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+fh(n.search)+n.hash,r=dh();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(Vd(t,this._basename));await uh(this,this.outlet,t,this._path,fh(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(Vd(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await uh(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${cd.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await uh(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=mh();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||fd(`${cd.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||fd(`${cd.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await Wd(this),r=!t&&this._outlet.hasAttribute(gh);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&fd(`${cd.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(gh);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await uh(this,this.outlet,i,this._path,window.location.search||""),(r||null!==th())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(cd.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(bh)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(wh)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith(vh)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=Vd(t,this._basename);let d=Fd(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of d.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(wh)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===cd.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(gh);for(const t of d.routes)Qd(t,d);return this.outlet.lastRoutes=d.routes,!await ch(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(t){const e=Vd(t,this._basename),n=Fd(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&fd(`${cd.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await uh(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${bh}${t.absolutePath}`}),this.outlet.setAttribute(gh,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${wh}${t.absolutePath}`),s=document.createComment(`${vh}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&sh(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!ph(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),mh()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=dh();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(dh()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Sh=["title","rel","target","download","hreflang","lang","dir"];class xh extends HTMLElement{static get observedAttributes(){return["to",...Sh]}_childNodeArray=[];_uuid=hd();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(cd.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(cd.router);if(n)return this._router=n;fd(`${cd.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return Gd(t)}_joinInternalPath(t,e){const n=Kd(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=hh(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+fh(o)+s}else try{t.href=new URL(e).toString()}catch{fd(`[${cd.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){mh()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(yh)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(yh),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||Sh.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,mh())return this._updateActiveState(),void n.setAttribute(yh,"");dh()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!dh()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){dh()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Sh.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=hh(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Nh=[],Ph=new Map;let Ih=!1;const kh=new WeakMap;class Ah extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Ih||(this._captureInitialHead(),Ih=!0),Nh.push(this),this._reapplyHead()}disconnectedCallback(){const t=Nh.indexOf(this);-1!==t&&Nh.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||fd("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=kh.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return kh.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Ph.has(t)||Ph.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Nh)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Ph.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=Nh.length-1;e>=0;e--){const o=Nh[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Ph.has(n)&&(t=Ph.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),sh(t)||ah(t,`<${t.tagName.toLowerCase()}> inside <${cd.head}>`,`<${cd.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(cd.layout)||t.define(cd.layout,kd),t.get(cd.layoutOutlet)||t.define(cd.layoutOutlet,Md),t.get(cd.outlet)||t.define(cd.outlet,Ad),t.get(cd.route)||t.define(cd.route,vd),t.get(cd.router)||t.define(cd.router,$h),t.get(cd.link)||t.define(cd.link,xh),t.get(cd.head)||t.define(cd.head,Ah)}(void 0);const Eh="data-fetchtarget",Ch={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Th=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function Mh(t,e){return e.every(e=>"available"===t.availability.get(e))}const Oh=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Lh=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new Th("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return Mh(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),u=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",d=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:u,userActivation:d},epoch:e.epoch??0,lastError:e.lastError}}(Oh,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!Mh(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:u="auto",timeout:d=0}=e;let h=null;d>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},d));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===u)s=await n.blob();else if("arrayBuffer"===u)s=await n.arrayBuffer();else if("text"===u)s=await n.text();else if("json"===u)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,d)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},Rh=!1;function jh(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Eh}]`);if(!n)return;const o=n.getAttribute(Eh);if(!o)return;const s=customElements.get(Ch.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function Dh(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}const Wh=Symbol.for("wcstack.trustedTypes.policy");function Bh(){const t=globalThis[Wh];return null===t||"object"!=typeof t?null:t}let zh,Fh=!1;let Hh=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Lh.wcBindable,properties:[...Lh.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new Lh(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(Ch.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(Ch.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&function(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=Bh(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==zh)return zh;if(!("trustedTypes"in globalThis))return zh=!1,zh;try{document.createElement("div").innerHTML="<i></i>",zh=!1}catch{zh=!0}return zh}())return void function(){if(Fh)return;Fh=!0;const t="function"==typeof Bh()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}(t,s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Dh(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Rh||(Rh=!0,document.addEventListener("click",jh)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Uh extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class qh extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Gh=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof Hh&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(Ch.fetch)||t.define(Ch.fetch,Hh),t.get(Ch.fetchHeader)||t.define(Ch.fetchHeader,Uh),t.get(Ch.fetchBody)||t.define(Ch.fetchBody,qh),t.get(Ch.infiniteScroll)||t.define(Ch.infiniteScroll,Gh)}(void 0);const Vh="data-storagetarget",Kh={storage:"wcs-storage"},Jh="wcs-storage:value-changed",Qh="wcs-storage:loading-changed",Xh="wcs-storage:error",Yh="wcs-storage:error-info-changed",Zh="wcs-storage:trigger-changed";let tf=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Jh,semantics:"state",getter:t=>t.detail},{name:"loading",event:Qh,semantics:"state"},{name:"error",event:Xh,semantics:"state"},{name:"errorInfo",event:Yh,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(Qh,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(Xh,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(Yh,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(Jh,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},ef=!1;function nf(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Vh}]`);if(!n)return;const o=n.getAttribute(Vh);if(!o)return;const s=customElements.get(Kh.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function of(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let sf=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...tf.wcBindable,properties:[...tf.wcBindable.properties,{name:"trigger",event:Zh,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new tf(this),this._internals=this._initInternals(),this._wireStates({[Qh]:t=>({loading:!0===t}),[Xh]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(Zh,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!of(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",ef||(ef=!0,document.addEventListener("click",nf)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(Kh.storage)||t.define(Kh.storage,sf)}(void 0);const rf="*",af="vanilla",lf={scanImportmap:!0,loaders:{[af]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[rf]:af},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function cf(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function uf(t,e,n){let o;if(null===e||e===rf||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===rf)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[rf],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const df=new Set,hf=new Map;let ff=new WeakMap;function pf(t){if(t===globalThis.customElements)return hf;let e=ff.get(t);return void 0===e&&(e=new Map,ff.set(t,e)),e}const mf=new Map;async function gf(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of mf)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){df.has(e)||(console.error(`Failed to eager load component '${e}':`,t),df.add(e))}}function yf(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function bf(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&mf.set(t,e)});const wf=new WeakSet,vf=new WeakSet;async function _f(t,e,n){t.shadowRoot&&(wf.has(t)||await async function(t,e,n){wf.add(t),await Nf(t.shadowRoot,e,n)}(t,e,n))}async function $f(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=pf(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=uf("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),df.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Sf(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=bf(t);void 0===o.get(s.name)?(vf.has(t)||(vf.add(t),o.whenDefined(s.name).then(async()=>{await _f(t,e,n)})),a.has(s.name)||df.has(s.name)||(a.add(s.name),i.push(s))):await _f(t,e,n)}let l=0;for(const t of i)await $f(t,e,n,o),l++;return l}async function xf(t,e,n,o){for(;await Sf(t,e,n,o)>0;);}async function Nf(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return yf(e)}return yf(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await xf(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await xf(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Pf extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Pf._instance)throw new Error(`${lf.tagNames.autoloader} can only be instantiated once.`);Pf._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=cf(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=uf(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(gf(s,o,r))}await Promise.all(n)}(n,lf.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await Nf(document,lf,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Pf._instance===this&&(Pf._instance=null)}}!function(t=customElements){t.get(lf.tagNames.autoloader)||t.define(lf.tagNames.autoloader,Pf)}(void 0);
|
|
1
|
+
const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n,s=".",r="*",i=128,a=128,l="|",c="prevent",u="stop",d="ro",h="init",f="sync",p="else",m="...",g="on",y="eventToken",b="command",w="class",v="attr",_="style",$={};for(let t=0;t<i;t++)$[`$${t+1}`]=t;const S=Object.freeze($),N="$connectedCallback",x="$disconnectedCallback",P="$updatedCallback",I="$errorCallback",k="$stateReadyCallback",A="$bindables",E="$commands",C="$commandTokens",T="$command",M="$eventTokens",O="$on",L="$streams",R="$watch",j="$scan",D="$recursion",W="**",B="$listKeys",z="$streamStatus",F="$streamError",H="data-wc-definition",q=new WeakMap,U=new WeakSet;let G=0;async function V(t){const e=function(t){let e,n=q.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++G,promise:o,resolve:e},q.set(t,n),U.has(t)&&n.resolve(),n}(t);await e.promise}function K(t){const e=q.get(t);void 0===e?U.add(t):e.resolve()}function J(t){throw new Error(`[@wcstack/state] ${t}`)}const Q=new Map;let X=0;function Y(t){let e=Q.get(t);return void 0!==e||(-1!==t.indexOf(W)&&J(`[wcs/recursion-unsupported] "${t}" uses "${W}", 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.`),e=Object.freeze(new Z(t)),Q.set(t,e)),e}let Z=class{id=++X;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:Y(e),n=t.split("."),o=[],s=[],i=[],a={},l=[],c=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===r&&(i.push(h),a[h]=p,l.push(e(h)),c.push(f),u.push(e(f)),d.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=i.length>0?i[i.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=i,this.wildcardPathSet=new Set(i),this.indexByWildcardPath=a,this.wildcardPathInfos=l,this.wildcardPathInfoSet=new Set(l),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=u,this.wildcardParentPathInfoSet=new Set(u),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}};const tt=new WeakMap;function et(t){const e=tt.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{tt.set(t,n)}}function nt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function ot(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return nt(e);if(void 0!==n)return nt(n)}return nt(globalThis.customElements)}function st(t,e){t.upgrade?.(e)}function rt(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=ct(s.properties,it);if(null===r)return null;const i=void 0===s.inputs?new Map:ct(s.inputs,at);if(null===i)return null;const a=void 0===s.commands?new Map:ct(s.commands,lt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function it(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function at(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function lt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function ct(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function ut(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:Y(n),inFilters:[],outFilters:[],bindingType:"prop"}}function dt(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function ht(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&J("Spread binding requires an element node.");const e=t,o=et(e);null===o&&J(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=ot(e);if(null===a&&J(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||J(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}st(a,e);const l=rt(e);null===l&&J(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=ut(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=ut(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=dt(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=dt(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function ft(t,e){let n=t;if(0===e.length)return n;for(let t=0;t<e.length&&(n=n?.childNodes[e[t]]??null,null!==n);t++);return n}const pt=new WeakMap;function mt(t){return pt.get(t)||null}function gt(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function yt(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=gt(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const bt=" Validate statically: npx @wcstack/lint <file>.",wt=new Set(["if","elseif","else","for"]);function vt(t){J(`filter ${t} requires at least one option`)}function _t(t){J(`filter ${t} requires a number as option`)}function $t(t){J(`filter ${t} requires a number value`)}function St(t){J(`filter ${t} requires a date value`)}function Nt(t){return!(!t||isNaN(Number(t)))}const xt={eq:t=>{const e=t?.[0]??vt("eq");return t=>"number"==typeof t?(Nt(e)||_t("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??vt("ne");return t=>"number"==typeof t?(Nt(e)||_t("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&J("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??vt("lt");return Nt(e)||_t("lt"),t=>("number"!=typeof t&&$t("lt"),t<Number(e))},le:t=>{const e=t?.[0]??vt("le");return Nt(e)||_t("le"),t=>("number"!=typeof t&&$t("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??vt("gt");return Nt(e)||_t("gt"),t=>("number"!=typeof t&&$t("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??vt("ge");return Nt(e)||_t("ge"),t=>("number"!=typeof t&&$t("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??vt("inc");return Nt(e)||_t("inc"),t=>("number"!=typeof t&&$t("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??vt("dec");return Nt(e)||_t("dec"),t=>("number"!=typeof t&&$t("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??vt("mul");return Nt(e)||_t("mul"),t=>("number"!=typeof t&&$t("mul"),t*Number(e))},div:t=>{const e=t?.[0]??vt("div");return Nt(e)||_t("div"),t=>("number"!=typeof t&&$t("div"),t/Number(e))},mod:t=>{const e=t?.[0]??vt("mod");return Nt(e)||_t("mod"),t=>("number"!=typeof t&&$t("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&$t("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??vt("clamp");Nt(e)||_t("clamp");const n=t?.[1]??vt("clamp");Nt(n)||_t("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&$t("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return Nt(e)||_t("fix"),t=>("number"!=typeof t&&$t("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&$t("locale"),t.toLocaleString(e??o.locale))},uc:t=>t=>String(t).toUpperCase(),lc:t=>t=>String(t).toLowerCase(),cap:t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)},trim:t=>t=>String(t).trim(),slice:t=>{const e=[],n=t?.[0]??vt("slice");Nt(n)||_t("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(Nt(o)||_t("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??vt("substr");Nt(e)||_t("substr");const n=t?.[1]??vt("substr");return Nt(n)||_t("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??vt("pad");Nt(e)||_t("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??vt("rep");return Nt(e)||_t("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??vt("truncate");Nt(e)||_t("truncate");const n=Number(e),o=t?.[1]??"…";return t=>{const e=String(t);return e.length<=n?e:e.slice(0,n)+o}},join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||J("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=t?.[0]??"0";return Nt(e)||_t("round"),t=>{"number"!=typeof t&&$t("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return Nt(e)||_t("floor"),t=>{"number"!=typeof t&&$t("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return Nt(e)||_t("ceil"),t=>{"number"!=typeof t&&$t("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return Nt(e)||_t("percent"),t=>("number"!=typeof t&&$t("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??vt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||St("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||St("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||St("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||St("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||St("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!1===t||null==t||0===t||""===t||Number.isNaN(t),truthy:t=>t=>!1!==t&&null!=t&&0!==t&&""!==t&&!Number.isNaN(t),defaults:t=>{const e=t?.[0]??vt("defaults");return t=>!1===t||null==t||0===t||""===t||Number.isNaN(t)?e:t},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),null:t=>t=>""===t?null:t},Pt=xt,It={input:xt,output:Pt},kt=(t,e)=>n=>{const o=n[t];return o||J(`[wcs/filter-unknown] filter not found: ${t}.${yt(t,Object.keys(n))}${bt}`),o(e)};function At(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const Et=new Map;function Ct(t,e){const n=It[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&J(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&J(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=Et.get(s);return void 0===r&&(r=kt(o,[])(n),Et.set(s,r)),{filterName:o,args:[],filterFn:r}}{const r=t.substring(o+1,s),i=t.substring(0,o).trim(),a=function(t){const e=[];let n="",o=null,s=!1,r=-1,i=-1;const a=()=>{e.push(At(n,r,i)),n="",s=!1,r=-1,i=-1};for(let e=0;e<t.length;e++){const l=t[e];o?l===o?o=null:(-1===r&&(r=n.length),n+=l,i=n.length):'"'===l||"'"===l?(o=l,s=!0):","===l?a():n+=l}const l=At(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=Et.get(l);return void 0===c&&(c=kt(i,a)(n),Et.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const Tt=t=>t.trim(),Mt=new Map,Ot=new Map;function Lt(t){const e=t.indexOf(l);let n="",o=[],s="",r=[];return-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Ot.has(s)?r=Ot.get(s):(o=s.split(l).map(Tt),r=Ct(o,"output"),Ot.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&J(`"${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.`),{statePathName:n,statePathInfo:Y(n),outFilters:r}}function Rt(t){const[...e]=t.split(";").map(Tt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&J(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===p){const t=Y("#else");return{propName:p,propSegments:[p],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===m){const e=Lt(o);return e.outFilters.length>0&&J(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&J(`Invalid spread binding "${t}": spread target path is required.`),{propName:m,propSegments:[m],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Lt(o),bindingType:n};{const t=Lt(o),e=function(t){const e=t.indexOf(l);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),Mt.has(r)?i=Mt.get(r):(o=r.split(l).map(Tt),i=Ct(o,"input"),Mt.set(r,i))):n=t.trim();const[a,c]=n.split("#").map(Tt),u=a.split(s).map(Tt);return{propName:a,propSegments:u,propModifiers:c?c.split(",").map(Tt):[],inFilters:i}}(n);return e.propSegments[0]===y||e.propSegments[0].startsWith(g)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>wt.has(t.bindingType))&&J(`[wcs/template-syntax] Invalid bindText: "${t}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${bt}`),n}const jt=new WeakMap,Dt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Wt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Bt(t){const e=jt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Wt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Dt.has(r)?(jt.set(t,s[2]),s[2]):null}function zt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Lt(t),bindingType:"text"}}const Ft=new Map;function Ht(t,e,n){if(null===n)Ft.delete(t);else{Ft.set(t,n);const o=Aa(e);null===o&&J("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function qt(t){return Ft.get(t)||null}function Ut(t){if(t.nodeType===Node.ELEMENT_NODE)return Rt(t.getAttribute(o.bindAttributeName)||"");if(t.nodeType===Node.COMMENT_NODE){const e=Bt(t);null===e&&J("Comment node binding text not found.");const n=qt(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=zt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function Gt(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function Vt(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Gt(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function Kt(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function Jt(t){const e=[],n=Vt(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Bt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&Kt(t,n)||e.push(t)}return e}const Qt=new WeakSet;function Xt(t,e,n,o){const s=ht(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?et(t):null;return null===n&&J("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}Qt.add(t);const r=function(t,e){const n=[];for(const o of e)if("text"!==o.bindingType)n.push({...o,node:t,replaceNode:t});else{const e=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,node:t,replaceNode:e})}return n}(t,function(t,e){return void 0===e?t:t.map(t=>null!=t.uuid?t:e(t))}(s,o));return function(t,e){pt.set(t,e)}(t,r),K(t),{bindings:r,deferred:null}}function Yt(t,e){const n=Jt(t),o=[],s=[];for(const t of n){if(Qt.has(t))continue;const n=Xt(t,Ut(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Zt(t){Qt.add(t)}function te(t){const{node:e,parseResults:n,transform:o}=t;return function(t){Qt.delete(t)}(e),Xt(e,n,{allowDeferred:!1},o).bindings}let ee=0;const ne=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion"],oe=new Set;function se(t,e){const n=t.stateObject[e];if("function"==typeof n)try{const o=t.component[t.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function re(t){const e=t.indexOf(s);return-1===e?t:t.slice(0,e)}function ie(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function ae(t,e){for(const n of t.entries)if(ie(e,n.innerSegments)){const t=e.slice(n.innerSegments.length);return 0===t.length?n.outerPathInfo.path:n.outerPathInfo.path+s+t.join(s)}return null}function le(t,e){return t.markerBasePath+s+e}function ce(t,e,n,o){let r=t.accessorBySuffixByMarkerParent.get(e);void 0===r&&(r=new Map,t.accessorBySuffixByMarkerParent.set(e,r));const i=e+s+n;r.set(n,{accessorName:o,indexShift:Y(i).wildcardCount-Y(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(i),t.addedGetterPaths.add(i))}function ue(t,e){return!t.injectedKeys.has(e)&&("function"==typeof t.stateObject[e]&&!t.getterKeys.has(e)||Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function de(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(s)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${re(e)}: path") or declare the key on the component state.`}const he=/^\$(\d+)$/;function fe(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(s);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===r){o=t;break}if(-1===o)return ce(t,t.markerBasePath,e,e),le(t,e);if(ue(t,n[0]))return ce(t,t.markerBasePath,e,e),le(t,e);const i=n.slice(0,o+1),a=n.slice(o+1),l=ae(t,i);null===l&&J(de(t,e)),0===a.length&&J(`Wildcard-terminal accessor "${e}" on mounted <${t.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const c=l+s+t.marker;return ce(t,c,a.join(s),e),c+s+a.join(s)}(t,e);const o=re(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return le(t,e);if(ue(t,o))return le(t,e);const i=ae(t,e.split(s));if(null!==i)return i;J(de(t,e))}function pe(t,e,n,o,s){if(void 0===o)return;const r=Y(n).wildcardCount-Y(e).wildcardCount;return 0===r?o:(s.length<r&&J(`Cannot resolve "${e}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const me=new WeakMap,ge=new WeakMap,ye=new WeakMap,be=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)}),we=new WeakMap;function ve(t){return we.get(t)??null}function _e(t){return me.get(t)??null}function $e(t){const e=ye.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}function Se(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=ye.get(t);if(void 0===o)return null;const r=e.indexOf(s,n),i=-1===r?e.slice(n):e.slice(n,r),a=o.get(i);if(void 0===a)return null;const l=a.deref();return void 0===l?(o.delete(i),null):l}const Ne=new WeakMap;function xe(t){let e=t;for(;e;){const t=Ne.get(e);if(t)return t;let n=e.parentNode;null===n&&e instanceof ShadowRoot&&null!==_e(e)&&(n=e.host),e=n}return null}function Pe(t,e){null!==e?Ne.set(t,e):Ne.delete(t)}let Ie=null;const ke=new WeakMap;function Ae(t){return ke.get(t)??[]}function Ee(t,e){ke.set(t,e)}function Ce(t){return ke.has(t)}const Te=new WeakMap;let Me=null,Oe=0;function Le(t){return Te.get(t)??[]}function Re(t,e){null===Me?Te.set(t,e):Me.set(t,e)}function je(){Oe++,null===Me&&(Me=new Map)}function De(){if(0!==Oe&&(Oe--,!(Oe>0||null===Me))){for(const[t,e]of Me)Te.set(t,e);Me=null}}function We(t){return(Me?.has(t)??!1)||Te.has(t)}const Be=Symbol("$$setLoopContext"),ze=Symbol("$$getByAddress"),Fe=Symbol("$$hasByAddress"),He=Symbol("$$setByAddress"),qe=Symbol("$$connectedCallback"),Ue=Symbol("$$disconnectedCallback"),Ge=Symbol("$$updatedCallback"),Ve=Symbol("$$errorCallback"),Ke=new WeakMap;function Je(t,e){if(Ke.has(t)){const n=Ke.get(t);if(n.has(e))return n.get(e)}else Ke.set(t,new WeakMap);const n=Object.freeze(new Qe(t,e));return Ke.get(t).set(e,n),n}class Qe{pathInfo;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Je(t,e.parentPathInfo)}}const Xe=new WeakMap,Ye=new WeakMap;class Ze{absolutePathInfo;listIndex;_parentAbsoluteAddress;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}get parentAbsoluteAddress(){if(void 0!==this._parentAbsoluteAddress)return this._parentAbsoluteAddress;const t=this.absolutePathInfo.parentAbsolutePathInfo;if(null===t)return null;let e=null;return e=this.absolutePathInfo.pathInfo.segments[this.absolutePathInfo.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAbsoluteAddress=tn(t,e)}}function tn(t,e){if(null===e){let e=Ye.get(t);return void 0!==e||(e=new Ze(t,null),Ye.set(t,e)),e}{let n=Xe.get(e);void 0===n&&(n=new WeakMap,Xe.set(e,n));let o=n.get(t);return void 0!==o||(o=new Ze(t,e),n.set(t,o)),o}}const en=new WeakMap;function nn(t,e){null===e?en.delete(t):en.set(t,e)}function on(t){return en.get(t)||null}const sn=new Map;function rn(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=sn.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,sn.set(s,r)),r}function an(t,e,n){return e<0||e>=n?null:t.at(e-n)}function ln(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const cn=new WeakMap;function un(t){const e=xe(t.node);if(null===e)return null;let n=cn.get(e);if(void 0===n)n=new WeakMap,cn.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=rn(e.pathInfo,t.statePathInfo);return n>0&&(o=an(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const dn=new WeakMap;function hn(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=on(n);null===e?J(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function fn(t,e){let n=null;if(n=dn.get(t)||null,null!==n)return n;const o=hn(t,e),s=un(t),r=Aa(o);return null===r&&J("No state tree found on this root for binding."),n=tn(Je(r,t.statePathInfo),s),dn.set(t,n),n}function pn(t){dn.delete(t)}const mn=new WeakMap;function gn(t,e){const n=mn.get(t);void 0===n?mn.set(t,e):n instanceof Set?n.add(e):n!==e&&mn.set(t,new Set([n,e])),null!==Ie&&Ie({type:"state:binding-added",absoluteAddress:t,binding:e})}function yn(t,e){const n=mn.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&mn.delete(t),null!==Ie&&Ie({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const bn=new WeakMap;function wn(t,e,n){const o=bn.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==Ie&&Ie({type:"state:binding-removed",absoluteAddress:tn(t,e),binding:n}))}function vn(t){const e=mn.get(t);return void 0!==e?e:null!==t.listIndex?bn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const _n=new WeakMap,$n=new WeakMap;class Sn{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===r?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=Nn(t,e)}}function Nn(t,e){if(null===e){let e=$n.get(t);return void 0!==e||(e=new Sn(t,null),$n.set(t,e)),e}{let n=_n.get(e);void 0===n&&(n=new WeakMap,_n.set(e,n));let o=n.get(t);return void 0!==o||(o=new Sn(t,e),n.set(t,o)),o}}const xn=new WeakMap;function Pn(t){let e=null;if(e=xn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=un(t);null===n&&J(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=Nn(t.statePathInfo,n)}else e=Nn(t.statePathInfo,null);return xn.set(t,e),e}function In(t){xn.delete(t)}function kn(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const An=new Map,En=kn();function Cn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Tn(t){let e="input";for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function Mn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function On(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Mn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class Ln{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)e.push(n(...t));return e}}class Rn extends Ln{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==Ie&&Ie({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const jn=new WeakMap;function Dn(t,e){let n=jn.get(t);void 0===n&&(n=new Map,jn.set(t,n));let o=n.get(e);return void 0===o&&(o=new Rn(e,t),n.set(e,o)),o}const Wn=new WeakMap;class Bn extends Ln{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==Ie&&Ie({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function zn(t){return t instanceof Bn}const Fn=new Map,Hn=kn();function qn(t){const e=t.propModifiers.filter(t=>t===c||t===u).sort().join(",");return`${t.statePathName}::${e}`}function Un(t){if(!t.propName.startsWith(g))return!1;const e=qn(t);let n=Fn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(c)&&o.preventDefault(),e.includes(u)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Aa(r);null===i&&J("No state tree found on this root for event handler.");const a=xe(s),l=t.startsWith(T+".");i.createStateAsync("writable",async e=>{const c=e[Be](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a&&!0===i.hasMounts){const t=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=me.get(n);if(void 0!==t)return t;n=n.parentNode}return me.get(e)??null}(s,r);if(null!==t){const e=t.indexShiftByLoopElementPath.get(a.pathInfo.path);c=void 0!==e?c-e:0}}const u=null!==a?ln(a.listIndex,c):[];if(l){const s=e[ze](Nn(n,null));return zn(s)||J(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...u)}const d=e[t];return"function"!=typeof d&&J(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});On(c,`"${t}"`)})})(t.statePathName,t.propModifiers,t.statePathInfo),Fn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Hn.add(e,t),!0}const Gn=new Map,Vn=kn();function Kn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Jn(t){let e="input";for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}const Qn=new Set(["radio","checkbox"]),Xn=new Set(["value","valueAsNumber","valueAsDate"]);function Yn(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(Qn.has(t)&&"checked"===e)return!0;if(Xn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=et(n);if(null!==s){const t=ot(n)?.get(s);void 0===t&&J(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=rt(n);if(o?.knownProperties.has(e))return!0}return!1}let Zn=1,to=1,eo=1;const no=new WeakMap;function oo(t,e,n){let o=no.get(t);void 0===o&&(o=new Map,no.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=Zn++,o.set(s,r)),r}function so(t,e){return"to-element"===e?2*t:2*t+1}const ro=new Set;function io(t){return{transactionId:to++,originBindingId:t,visitedEdges:ro,hop:0}}function ao(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let lo=null;function co(){return lo}function uo(t,e){const n=lo;lo=t;try{return e()}finally{lo=n}}const ho=[];let fo=!1;const po=new Map,mo=kn(),go=new WeakMap,yo=t=>t.detail,bo=new WeakMap;function wo(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function vo(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=et(t.node);if(null!==n){const o=ot(t.node)?.get(n);void 0===o&&J(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=rt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(g)&&(e=n.slice(2));return e}function _o(t){if(null!==et(t.node)){const e=rt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??yo}return null}function $o(t){if(null===et(t.node))return!1;const e=rt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const So=new WeakSet;function No(t){So.add(t)}function xo(t){return!!So.has(t)&&(So.delete(t),!0)}const Po=new WeakSet;function Io(t){Po.add(t)}function ko(t){return!!Po.has(t)&&(Po.delete(t),!0)}let Ao=0;function Eo(){Ao--}function Co(){return Ao>0}class To{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const Mo=new WeakMap;function Oo(t){let e=Mo.get(t);return void 0===e&&(e=new To(t),Mo.set(t,e)),e}function Lo(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==h&&s!==f&&J(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&J(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Ro(t){return t.propModifiers.some(t=>t.includes("="))}const jo=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Do=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Wo(t,e){return"state"===t&&"call"===e?jo:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Bo(t){if(!o.enableDirectionalInitialSync)return Ro(t)&&J("init=/sync= modifiers require enableDirectionalInitialSync."),jo;const e=null===(n=Lo(t,h))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:J(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":J(`Invalid sync modifier value "${t}".`)}(Lo(t,f));if("event"===t.bindingType)return null!==e&&"none"!==e&&J("Event bindings only allow init=none."),"call"===s?Do:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===b)return Wo("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&J(`Binding type "${t.bindingType}" does not support init=${e}.`),Wo(e??"state",s);const r=rt(t.node);if(null===r)return Wo(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||J(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||J(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||J(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let zo=0,Fo=0;const Ho=new WeakMap,qo=new WeakMap,Uo=new WeakMap,Go=new WeakMap;function Vo(t,e){const n=Go.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Go.set(t,new Set([n,e]))):Go.set(t,e)}function Ko(t){return Go.has(t)}function Jo(t,e){const n=Go.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Qo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Qo(n,e)}function Xo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class Yo{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(const o of t)e.push(...Array.from(o.removedNodes)),n.push(...Array.from(o.addedNodes));const o=[];for(const t of e)xo(t)||Qo(t,t=>{Jo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)ko(t)&&!Co()||Qo(t,t=>{Jo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&ta(o)}}const Zo=new WeakMap;function ts(t){let e=Zo.get(t);return void 0===e&&(e=new Yo(t),Zo.set(t,e)),e}function es(t){const e=t.inFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|"),n=t.outFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function ns(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class os{records=new Set;rowPlan=null;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=Ho.get(t);void 0===o||"disposed"===o.phase||"failed"===o.phase?(this.start(t,s,n),r.push(t)):(this.observe(o.anchor),s.registerAddress&&null===o.address&&null===o.patternListIndex&&(o.options.registerAddress=!0,this.registerAddress(o)),"active"===o.phase&&this.settleInitialRecord(o),this.settleConnectedSnapshot(o))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(Xo(e)&&ts(e),null===this.rowPlan)for(const n of t){const t=Ho.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return Ro(t)&&Bo(t),!0;const e=Ho.get(t);return void 0===e||e.session!==this||!e.options.registerAddress||"waiting-definition"===e.phase||"failed"!==e.phase&&("active"===e.phase&&this.settleInitialRecord(e),e.initialApplyDone?"state"===e.resolvedAuthority||!e.outputOnlyMember&&!e.observationPending:(e.initialApplyDone=!0,"state"===e.resolvedAuthority))}getRecord(t){const e=Ho.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=Ho.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(ns(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=ot(t);null===s&&J(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Vo(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Oo(s).wait(e,()=>{if(a())try{st(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=Ho.get(t);void 0!==e&&e.session===this&&this.disposeRecord(e)}dispose(){for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.records)null!==t.address&&(yn(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];for(const e of this.records){if("active"!==e.phase)continue;const n=e.info;if(null===e.address&&null===e.patternListIndex)continue;const o="for"===n.bindingType?fn(n):null;if(null!==e.address?(yn(e.address,n),e.address=null):(wn(e.patternPathInfo,e.patternListIndex,n),e.patternPathInfo=null,e.patternListIndex=null),In(n),pn(n),this.registerAddress(e),null!==o){const t=fn(n);t!==o&&Ce(o)&&Ee(t,Ae(o)),t!==o&&We(o)&&Re(t,Le(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return Xo(e)?e:null}(t);null!==e&&ts(e)}handleMutations(t,e,n){for(const n of e)Qo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Qo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&ta(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Ho.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=Uo.get(e);void 0===t&&(t=es(e),Uo.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Vo(n,this);const o=this.knownMapFor(n);let s=Uo.get(t);void 0===s&&(s=es(t),Uo.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n={registerAddress:!1,registerPathInfo:!1,applyOnReconnect:!1},o=t.slots;for(let s=0;s<e.length;s++){const r=e[s],i=o[s],a=r.replaceNode;Vo(a,this),this.addKnownRowBinding(a,r,s),this.optionsByBinding.set(r,n);const l={id:++zo,info:r,generation:++Fo,phase:"active",teardowns:null,session:this,anchor:a,options:n,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:i.policy,resolvedAuthority:i.authority,initialSettled:!0,initialApplyDone:!1,outputOnlyMember:i.policy.outputOnly,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};if(Ho.set(r,l),this.records.add(l),i.isEvent){try{Un(r)}catch(t){throw l.phase="failed",this.runTeardowns(l),this.records.delete(l),t}l.eventAttached=!0}}}activatePlanRows(t,e,n){const o=t.slots;for(let s=0;s<e.length;s++){const r=e[s],i=Ho.get(r);if(void 0!==i&&i.session===this){if(i.options.registerAddress=!0,"disposed"===i.phase||"failed"===i.phase){const e=o[s];if(i.generation=++Fo,i.phase="active",i.initialPolicy=e.policy,i.resolvedAuthority=e.authority,i.initialSettled=!0,i.initialApplyDone=!1,i.outputOnlyMember=e.policy.outputOnly,this.records.add(i),e.isEvent){try{Un(r)}catch(t){throw i.phase="failed",this.runTeardowns(i),this.records.delete(i),t}i.eventAttached=!0}this.registerAddress(i,n);continue}null===i.address&&null===i.patternListIndex&&this.registerAddress(i,n)}else this.initialize([r],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++zo,info:t,generation:++Fo,phase:"discovered",teardowns:null,session:this,anchor:t.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Ho.set(t,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;Un(e)?t.eventAttached=!0:e.propSegments[0]!==y?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=Jn(t),s=Kn(t,o);let r=Gn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const t of n)s=t.filterFn(s);const r=Aa(o.getRootNode());null===r&&J("No state tree found on this root for two-way binding.");const i=xe(o);r.createState("writable",t=>{t[Be](i,()=>{t[e]=s})})},Gn.set(s,r)),t.node.addEventListener(o,r),Vn.add(s,t),!0}var e,n;return!1}(e)&&ns(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=Jn(t),n=Kn(t,e),o=Gn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Vn.countOf(n)&&(Vn.remove(n,t)&&Gn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=Tn(t),s=Cn(t,o);let r=An.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const t of n)r=t.filterFn(r);const i=Aa(o.getRootNode());null===i&&J("No state tree found on this root for two-way binding.");const a=xe(o);i.createState("writable",t=>{t[Be](a,()=>{let n=t[e];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(t[e]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(t[e]=n.toSpliced(o,1))}else t[e]=s?[r]:[]})})},An.set(s,r)),t.node.addEventListener(o,r),En.add(s,t),!0}var e,n;return!1}(e)&&ns(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=Tn(t),n=Cn(t,e),o=An.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==En.countOf(n)&&(En.remove(n,t)&&An.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Yn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const n=function(t,e,n){let o=go.get(t);void 0===o&&(o=new Map,go.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&go.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});ns(t,n)}!function(t){const e=et(t.node);if(null!==e){const n=ot(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&J(`CustomElementRegistry is unavailable for <${e}>.`))}if(Yn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=vo(t),n=_o(t),s=$o(t),r=wo(t,e,null!==n,s);let i=po.get(r);void 0===i&&(i=((t,e,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==yo||r||function(t,e,n){const o=t[e];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${e} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,e)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${e}" key while element.${e} is ${typeof o}`),null===s)return;let r=bo.get(t);void 0===r&&(r=new Set,bo.set(t,r)),r.has(e)||(r.add(e),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${t.tagName.toLowerCase()}> "${e}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${e}, or (e) => e.target.${e}) on that wcBindable property.`))}(a,t,l);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const t of n)c=t.filterFn(c);const u=go.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(o.enablePropagationContext){const n=oo(a,t,e),s=function(t,e){for(let n=ho.length-1;n>=0;n--){const o=ho[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==Ie&&Ie({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:so(n,"to-state"),node:a,member:t}));const r=so(n,"to-state"),i=co();if(null!==i&&i.visitedEdges.has(r))return void(null!==Ie&&Ie({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=ao(i??io(n),r)}const h=Aa(a.getRootNode());null===h&&J("No state tree found on this root for two-way binding.");const f=xe(a),p=()=>{r&&(fo=!0);try{h.createState("writable",t=>{t[Be](f,()=>{t[e]=c})})}finally{r&&(fo=!1)}};null!==d?uo(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),po.set(r,i)),t.node.addEventListener(e,i),mo.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==y)return!1;const e=t.node,n=et(e),o=ot(e);if(null!==n&&void 0===o?.get(n))return null===o&&J(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Wn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||J('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===et(t)?null:rt(t)}(e);null===r&&J(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&J(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${yt(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,d=t.propModifiers,h=t=>{d.includes(c)&&t.preventDefault(),d.includes(u)&&t.stopPropagation();const n=Aa(e.getRootNode());null===n&&J("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||J(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${yt(l,n.eventTokenNames)}${bt}`);const o=xe(e);n.createStateAsync("writable",async e=>{On(e[Be](o,()=>{const s=null!==o?ln(o.listIndex,o.pathInfo.wildcardCount):[];return Dn(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,h),Wn.set(t,{eventName:a,handler:h}),!0})(e)&&ns(t,()=>function(t){if(t.propSegments[0]!==y)return!1;const e=Wn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),Wn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=et(t.info.node);if(null===n)return void e();const o=ot(t.info.node);if(null===o&&J(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=Oo(o).wait(n,()=>{if(this.isAlive(t,s))try{st(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});ns(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Bo(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=Aa(t.replaceNode.getRootNode());null===e&&J("No state tree found on this root for binding.");const n=Pn(t);let o=!1;return e.createState("readonly",t=>{o=t[Fe](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void Ao++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,Eo()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=Aa(t.node.getRootNode());null===o&&J("No state tree found on this root for initial binding sync.");const s=xe(t.node);o.createState("writable",e=>{e[Be](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=un(n);if(null!==o){const s=Aa(hn(n,e));null===s&&J("No state tree found on this root for binding.");const r=Je(s,n.statePathInfo);!function(t,e,n){let o=bn.get(t);void 0===o&&(o=new WeakMap,bn.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==Ie&&Ie({type:"state:binding-added",absoluteAddress:tn(t,e),binding:n})}(r,o,n),t.patternPathInfo=r,t.patternListIndex=o}else{const o=fn(n,e);gn(o,n),t.address=o}if(!t.options.registerPathInfo)return;const s=Aa(n.replaceNode.getRootNode());null===s&&J("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Ho.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,Eo());const e=t.info;if(null!==t.address)try{yn(t.address,e),t.address=null,In(e),pn(e)}catch{}else if(null!==t.patternListIndex)try{wn(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,In(e),pn(e)}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=et(t.node);if(null!==e){const n=ot(t.node),o=n?.get(e);if(void 0===o)return}if(Yn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=vo(t),n=wo(t,e,null!==_o(t),$o(t)),o=po.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),mo.remove(n,t)&&po.delete(n)}}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{!function(t){if(!t.propName.startsWith(g))return!1;const e=qn(t),n=Fn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==Hn.countOf(e)&&Hn.remove(e,t)&&Fn.delete(e)}(e)}catch{}}}}function ss(t){let e=qo.get(t);return void 0===e&&(e=new os(t),qo.set(t,e)),e}function rs(t){return Ho.get(t)?.session??null}const is=new WeakMap;function as(t,e){let n=is.get(t);n||(n=new Set,is.set(t,n)),n.add(e)}const ls=new WeakMap;function cs(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const us=Object.freeze([]),ds=new WeakMap,hs=new WeakMap;function fs(t){return hs.get(t)??[]}function ps(t,e){hs.set(t,e)}const ms=new WeakMap;function gs(t){return ms.get(t)??[]}function ys(t,e){ms.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let bs=0;function ws(){return`u${(bs++).toString(36)}`}let vs=0,_s=0;const $s=Symbol("wcs.listIndex.noValue");class Ss{uuid=ws();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=$s,this._index=e,this._version=vs,this._chainGeneration=_s}get index(){return this._index}set index(t){this._index=t,this._version=++vs,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(t){this._value=t}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=vs),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(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++vs,_s++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function Ns(t,e,n=t){return new Ss(t,e,n)}function xs(t,e){t.reparent(e)}function Ps(t){return t.homeParentListIndex}function Is(t,e){t.value=e}function ks(t,e){const n=t.value;return n!==$s&&n===e.value}const As=new WeakMap,Es=new WeakSet;function Cs(t){return Es.has(t)}function Ts(t){const e=As.get(t);return void 0===e?null:e}function Ms(t,e){const n=As.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o){const t=function(t,e){const n=Ps(t),o=t.parentListIndex;return null===n||n===o||Es.has(n)?function(t,e,n){return null!==t&&null!==n&&n!==e&&!!Es.has(t)&&!Es.has(n)&&n.position===t.position&&ks(n,t)}(n,o,e)||function(t,e){return t!==e&&null!==t&&null!==e&&t.position===e.position&&Es.has(t)&&!Es.has(e)}(o,e)?e:null:n}(o,e);if(null!==t)for(const e of n)xs(e,t)}return n}function Os(t,e){null!==e?As.set(t,e):As.delete(t)}const Ls=new WeakMap,Rs=Object.freeze([]),js=new Set;function Ds(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:Rs,s=Array.isArray(n)&&n.length>0?n:Rs,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:Rs,o=Array.isArray(e)&&e.length>0?e:Rs;let s=Ls.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Ms(o,t)||[],a=i.length>0?Ps(i[0]):t;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:js,deleteIndexSet:new Set(i),addIndexSet:js};let e=Ms(s,t);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=Ns(t,n,a);e.push(o)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:js,deleteIndexSet:js,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:js,deleteIndexSet:js,addIndexSet:js};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],u=n.get(l),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=Ns(t,o,a);e.push(n),c.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:c}}finally{void 0!==l&&(function(t,e,n){let o=Ls.get(t);o||(o=new WeakMap,Ls.set(t,o)),o.set(e,n)}(o,s,l),Os(s,l.newIndexes))}}(t,e,n);return function(t,e){for(let n=0;n<t.length;n++)t[n].index!==n&&(t[n].index=n),Is(t[n],e[n])}(o.newIndexes,Array.isArray(n)&&n.length>0?n:Rs),function(t){for(const e of t)Es.add(e)}(o.deleteIndexSet),function(t){for(const e of t)Es.delete(e)}(o.newIndexes),o}const Ws=new WeakSet,Bs=new WeakMap;function zs(t){return Bs.get(t)??null}function Fs(t,e){Bs.set(t,e)}const Hs=new WeakMap;function qs(t){return Hs.get(t)??[]}function Us(t,e){Hs.set(t,e)}function Gs(t,e){const n=qs(t);for(const t of n)Pe(t,e)}function Vs(t,e,n){Gs(t,e);const o=fs(t),s=zs(t);null!==s&&s.activate(o,n.rootNode);for(const t of o)null===s&&gn(fn(t),t),(null===s||s.shouldApplyState(t))&&Yi(t,n)}function Ks(t){if(!t.mounted)return;const e=fs(t),n=zs(t);for(const t of e)null!==n?n.disposeBinding(t):yn(fn(t),t);!function(t){const e=qs(t);for(const t of e)Pe(t,null)}(t)}const Js=new WeakMap,Qs=Object.freeze(new Set);function Xs(t,e){const n=Js.get(t);n?n.add(e):Js.set(t,new Set([e]))}function Ys(t){const e=Js.get(t);return void 0!==e?e:Qs}function Zs(t,e){const n=Js.get(t);n&&(n.delete(e),0===n.size&&Js.delete(t))}const tr=new Set(["if","elseif","else","for"]);class er{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e,this._childNodeArray=Array.from(this._content.childNodes),this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(t){for(const e of this._childNodeArray)Io(e),t.appendChild(e);this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){Io(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=zs(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)No(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=fs(this);for(const t of e)if(tr.has(t.bindingType)){const e=Ys(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmountInPlace(){zs(this)?.dispose(),this._teardownBindings()}_teardownBindings(){const t=fs(this);for(const e of t){if(tr.has(e.bindingType)){const t=Ys(e.node);for(const e of t)e.unmount()}In(e),pn(e)}}unmount(){zs(this)?.dispose();for(const t of this._childNodeArray)No(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=fs(this);for(const e of t){if(tr.has(e.bindingType)){const t=Ys(e.node);for(const e of t)e.unmount()}In(e),pn(e)}this._mounted=!1}}function nr(t){const e=document.createDocumentFragment(),n=new er(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function or(t){void 0!==t.uuid&&null!==t.uuid||J("BindingInfo.uuid is null.");const n=qt(t.uuid);n||J(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=ft(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===b||s===y)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==et(r))return null;if("prop"===o&&Yn(r,t.propName))return null;let i;try{i=Bo({...t,node:r,replaceNode:r})}catch{return null}if(i.observable||"auto"===i.authority)return null;n.push({nodeIndex:e,template:t,isEvent:"event"===o,isIndexBinding:t.statePathName in S,policy:i,authority:i.authority})}}return{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=ft(o,s[t].nodePath);null===e&&J(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Zt(e),K(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e){const n=new os;return n.initializeRow(t,e),n}(n,a),u=new er(o);return Fs(u,c),ps(u,a),ys(u,l),Us(u,r),Xs(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=ft(t,s.nodePath);if(null===e&&J(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Qt.has(e))continue;const r=Xt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new os;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new er(i,s);Fs(l,a.bindingSession),ps(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in S&&c.push(t);return ys(l,c),Us(l,a.nodes),Xs(t.node,l),l}const sr=/\{\{\s*(.+?)\s*\}\}/g,rr=new Set(["SCRIPT","STYLE"]);function ir(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&rr.has(t.parentElement.tagName)||ar(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),ir(e.content)}else ir(t.content)}function ar(t){const e=t.data;if(sr.lastIndex=0,!sr.test(e))return;sr.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=sr.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}let lr;function cr(){if(lr)return lr;const t=[],e=kt("not",t)(Pt);return lr={filterName:"not",args:t,filterFn:e},lr}const ur=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function dr(t,e){const n=e+s+r,o=t.indexOf("|");let i,a;if(-1!==o?(i=t.slice(0,o).trim(),a=t.slice(o)):(i=t.trim(),a=""),"."===i)i=n;else{if(!i.startsWith("."))return t;i=n+s+i.slice(1)}return a.length>0?i+a:i}function hr(t,e){const n=ur.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+dr(s,e)+r}function fr(t,e){const n=t.split(";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=n.indexOf(":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=dr(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function pr(t,e){return fr(t,e)}function mr(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=hr(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=fr(r,e);t!==r&&o.setAttribute(n,t)}}}function gr(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}function yr(t){const e=[],n=Jt(t);for(const t of n){const n=Ut(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:gr(o),parseBindTextResults:n})}return e}function br(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const wr=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),vr=cr();function _r(t,e){const n=e.outFilters;return{...e,outFilters:[...n,vr],bindingType:t}}function $r(t,e,n,o,s,r=!0){br(e),"string"==typeof o&&mr(e,o),Sr(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:yr(e)};return void 0!==s&&function(t,e,n){for(const o of t)for(let t=0;t<o.parseBindTextResults.length;t++){const s=o.parseBindTextResults[t];null==s.uuid&&(o.parseBindTextResults[t]=e(s,n))}}(i.nodeInfos,s,o),i}function Sr(t,e,n,s){const r=o.commentElsePrefix,i=Vt(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],u=[];for(;a.nextNode();){const t=a.currentNode;u.push(t)}for(const e of u){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=pr(i,n));let a=Rt(i)[0];const u=wr.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=ws();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&J("'else' binding found without preceding 'if' or 'elseif' binding."),a=_r("else",l.parseBindTextResult),p=$r(t,h,a,m,s,!1),Ht(f,t,p);const n=c.at(-1),o=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:gr(o),parseBindTextResults:Ut(o)})):e.replaceWith(o)}else if("elseif"===d){null===l&&J("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=$r(t,h,a,m,s),Ht(f,t,p);const n=document.createComment(`@@${u}:${f}`),o=ws(),i={fragment:document.createDocumentFragment(),parseBindTextResult:_r("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:gr(n),parseBindTextResults:Ut(n)}),Ht(o,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:gr(g),parseBindTextResults:Ut(g)})):e.replaceWith(g)}else{p=$r(t,h,a,m,s),Ht(f,t,p);const n=document.createComment(`@@${u}:${f}`);e.replaceWith(n)}"if"===d?(c.length=0,l=p):"elseif"===d?l=p:"else"===d&&(l=null,c.length=0)}}const Nr=new WeakMap;function xr(t,e,n){let o=Nr.get(t);void 0===o&&(o=new Map,Nr.set(t,o));null!=o.get(e)&&J(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function Pr(t,e){if(null===t)return!1;const n=Nr.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+s)||t.startsWith(e+s))return!0;return!1}const Ir=new WeakMap;function kr(t,e){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{e.$postUpdate(t+s+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...r)=>e[n](t+s+o,...r)}return e[o]}return e[t+s+o]}},set:(n,o,r)=>("string"!=typeof o||(e[t+s+o]=r),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Ar=new WeakMap,Er=[],Cr=new WeakMap,Tr=new WeakSet;function Mr(t){console.error(`[@wcstack/state] volume "${t.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),t.onGrafted(null)}let Or=null;const Lr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Rr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function jr(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function Dr(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),r=e.length>0?e+s:"";for(const t of n){if(r.length>0&&!t.startsWith(r))continue;const e=t.slice(r.length);e.length>0&&-1===e.indexOf(s)&&o.push(e)}return o}const Wr={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Br={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function zr(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${bt}`}function Fr(t,e){return`[wcs/recursion-anchor] "${t}" does not match the declared recursion anchor "${e}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function Hr(t,e){return`$setAll("${t}") ${e}`}function qr(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${bt}`}const Ur=new WeakMap;const Gr=new WeakMap,Vr=new WeakSet,Kr=new WeakMap;function Jr(t,e){let n=Kr.get(t);void 0===n&&(n=new Set,Kr.set(t,n)),n.add(e),Gr.get(t)?.delete(e)}function Qr(t,e,n,o){console.warn(`[@wcstack/state] [${Wr[n]}] ${Br[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${yt(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${bt}`),null!==Ie&&Ie({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const Xr=new WeakMap,Yr=new Set;function Zr(t,e,n,o){let s=Xr.get(t);if(void 0===s){if(!o)return null;s=new Map,Xr.set(t,s)}let r=s.get(e);if(void 0===r){if(!o)return null;r=new Map,s.set(e,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function ti(t,e){if(!t.component.isConnected)return!1;const n=xe(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function ei(t,e,n,o){const r=Zr(t,e,n,!1);if(null===r)return null;const i=null===o?r.noIndex:r.byListIndex.get(o)??null;if(null!==i){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&ti(n,e)?n:null}(i,o);if(null!==t)return{record:t,entry:i.entry}}let a=null,l=null;for(const t of r.holders){const i=t.ref.deref();void 0!==i?ti(i,o)&&(null!==l&&J(`[wcs/mount-export-ambiguous] "${e}${s}${n}" is exported by two mounted components on the same instance: <${l.component.tagName.toLowerCase()}> and <${i.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),a=t,l=i):r.holders.delete(t)}return null===a||null===l?null:(null===o?r.noIndex=a:r.byListIndex.set(o,a),{record:l,entry:a.entry})}function ni(t){const e=t.parentStateElement,n=xe(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[Be](n,()=>{t.$postUpdate(o.exportedPath)})})}function oi(t,e){const n=_e(e);var o,i;null!==n&&n.stateProp!==t.stateProp&&J(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&ss(e).dispose(),function(t,e){me.set(t,e),we.set(e,t);let n=ye.get(e.parentStateElement);void 0===n&&(n=new Map,ye.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=ge.get(e.component);void 0===o&&(o=new Map,ge.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&be.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}(e,t),e instanceof ShadowRoot&&function(t,e){const n=Pa.get(t);if(void 0!==n){if(n===e)return;J("A state tree is already registered on this root.")}Pa.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const i=he.exec(e.statePathName);if(null!==i){const s=function(t,e){return void 0===e?t.delta:Y(fe(t,e)).wildcardCount-Y(e).wildcardCount}(t,n);o=0===s?e.statePathName:`$${Number(i[1])+s}`}else if(o=fe(t,e.statePathName),"for"===e.bindingType){const n=Y(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+s+r,n)}return o===e.statePathName?e:{...e,statePathName:o,statePathInfo:Y(o)}}(t,e,n);ir(e);const o=xe(t.component);Sr(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),ea(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=fe(t,n)}catch{continue}const o=e.indexOf(s+t.marker);if(-1===o)continue;const r=e.slice(0,o+1+t.marker.length),i=e.slice(r.length+1),a=e.slice(0,o)+s+i,l=Y(a);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:r,suffix:i,markerPath:e,exportedPath:a};t.exports.set(a,c),Zr(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,a),Jr(t.parentStateElement,a)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=xe(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const s=`${n}|${o.exportedPath}`;if(Yr.has(s))continue;const r=Y(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[Be](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Yr.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(t),ni(t),o=e,i=Promise.resolve(),Ia.set(o,i),i.then(()=>Ta(o),()=>{})}function si(t,e){const n=ss(e),o=xe(t.component);n.forEachActiveBindingNode(t=>Pe(t,o)),ta(n.rebindAddresses()),ni(t)}function ri(t,e){if(function(t){const e=ye.get(t);return void 0!==e&&e.size>0}(e))for(const n of $e(e)){if(!ii(n.component,t))continue;const e=ve(n);null!==e&&si(n,e)}}function ii(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const ai=Symbol.for("wcstack.transition-runner");function li(t){const e=globalThis[ai];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}function ci(t,e,n){const o=li(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const ui=new WeakSet,di=Symbol.for("wcstack.state.view-transition-naming");function hi(){const t=li("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function fi(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||ui.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[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.`)):(ui.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const pi=new WeakMap,mi=new WeakMap,gi=new WeakMap,yi=new WeakMap;function bi(t,e,n){!function(t,e,n){let o=mi.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,mi.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function wi(t,e){pi.set(t,e)}function vi(t,e){let n=gi.get(t.node);void 0===n&&(n=[],gi.set(t.node,n)),n.length<1e3?n.push(e):Zs(t.node,e)}function _i(t){return t.nodeType===Node.ELEMENT_NODE||(t.nodeType===Node.TEXT_NODE?""!==(t.textContent?.trim()??""):t.nodeType===Node.COMMENT_NODE&&t.data.startsWith("@@wcs-"))}function $i(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const Si=new Set(["if","elseif","else","for"]);function Ni(t,e){for(const n of fs(t))if(e.appliedBindingSet.delete(n),Si.has(n.bindingType))for(const t of Ys(n.node))Ni(t,e)}function xi(t){for(const e of fs(t)){if(!Si.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of Ys(e.node))xi(n),t&&n.mounted&&(Ks(n),n.unmount(),Zs(e.node,n))}}function Pi(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function Ii(t,n,s){const r=Boolean(s);let i;const a=Ys(t.node);i=0===a.size?or(t):a.values().next().value;const l=e(),c=t.uuid??"",u=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Pi(t)}`),Ks(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Pi(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);Vs(i,xe(t.node),n);const e=hi();null!==e&&fi(i,"branch",e)}}const ki=new WeakMap,Ai=new WeakMap,Ei=new WeakMap,Ci=new WeakMap;function Ti(t){return Ci.get(t)??[]}const Mi=new Set,Oi=Symbol.for("wcstack.trustedTypes.policy");function Li(){const t=globalThis[Oi];return null===t||"object"!=typeof t?null:t}let Ri,ji=!1;const Di={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}};function Wi(t,n,s){if(void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0],u=r[c];if(u!==s){null!==u&&"object"==typeof u&&null!==s&&"object"==typeof s&&null!==et(r)&&function(t,e,n){let o=ki.get(t);o||(o=new Map,ki.set(t,o)),o.has(e)||o.set(e,n)}(r,c,u);const e="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let t=!1;try{r[c]=e?function(t){if("string"!=typeof t)return t;const e=Li(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(ji)return;if(!function(){if(void 0!==Ri)return Ri;if(!("trustedTypes"in globalThis))return Ri=!1,Ri;try{document.createElement("div").innerHTML="<i></i>",Ri=!1}catch{Ri=!0}return Ri}())return;ji=!0;const n="function"==typeof Li()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${e}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:t,property:e})}(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=et(t);if(null===n)return null;const o=ot(t)?.get(n);if(void 0===o)return null;const s=rt(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&Yn(r,c)){const e=oo(r,c,t.statePathName),o=so(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??co()??io(e);if(a.visitedEdges.has(o))null!==Ie&&Ie({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=ao(a,o);uo(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:eo++,writtenValue:n};ho.push({receipt:i,node:t});try{return r()}finally{ho.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=Di[c];t?t(r,s):(function(t,e,n){let o=Ci.get(t);o||(o=[],Ci.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,s),a=r,Mi.add(a))}return}var a,l;const c=i[0];let u=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==u)return;u=u[e]}const d=i[i.length-1],h=u[d];if(h!==s){if(Object.isFrozen(u))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:s}));2===i.length&&"object"==typeof u&&null!==u&&null!==et(r)&&(d in u?function(t,e,n,o){let s=Ei.get(t);s||(s=new Map,Ei.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}(r,c,d,u[d]):function(t,e,n){let o=Ai.get(t);o||(o=new Map,Ai.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)}(r,c,d));try{u[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:s,error:t})}}}const Bi=new WeakSet;function zi(t,e,n){}const Fi=new WeakSet;function Hi(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const qi=Object.freeze({[w]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&J("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[v]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[_]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[b]:function(t,e,n){zn(n)||J("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ds.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||J('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=et(t);if(null===e)return null;const n=ot(t)?.get(e);return void 0===n&&J(`Custom element <${e}> is not defined for command binding.`),rt(t)}(r);null===a&&J(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||J(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${yt(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ds.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void ds.delete(t);const o=n[i];return"function"!=typeof o&&J(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),ds.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Ui={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!Bi.has(t.replaceNode)){Bi.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,i=un(t),a=fn(t),l=Ae(a),c=l.length>0&&!mi.has(t.node)?[]:l,u=Ds(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);let d=mi.get(t.node);const h=void 0!==d?function(t,e,n){if(o=e,!Ws.has(o))return null;var o;let s=null;for(let e=0;e<n.newIndexes.length;e++){const o=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?t.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}(d,c,u):null,f=Array.isArray(c)&&c.length===u.deleteIndexSet.size&&u.deleteIndexSet.size>0;if(f&&null===h&&null!==t.node.parentNode){let e=yi.get(t.node);if(void 0===e){const n=pi.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(_i(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(_i(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n),yi.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let p=f?1e3-function(t){return gi.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==d){for(const e of u.deleteIndexSet){const n=d.get(e);void 0!==n&&(null!==h&&h.reused.has(n)?(Ks(n),xi(n),n.unmountInPlace()):p<=0&&n.tryDestroy()?Zs(t.node,n):(Ks(n),n.unmount(),vi(t,n),p-=1),f||d.delete(e))}f&&(mi.delete(t.node),d=void 0)}let m=t.node;const g=Y(s.path+"."+r),y=n.stateElement.loopContextStack,b=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const t of i)a.add(n[t]);return a}(u);let w=null;u.newIndexes.length==u.addIndexSet.size&&u.newIndexes.length>0&&m.isConnected&&null===h&&(w=document.createDocumentFragment(),nn(w,n.rootNode));const v=e(),_=hi(),$=t.uuid??"",S=gi.get(t.node);for(const e of u.newIndexes){let o;if(u.addIndexSet.has(e)){const r=Nn(g,e);y.createLoopContext(r,r=>{if(o=h?.byAddedIndex.get(e)??(void 0!==S?S.pop():void 0),void 0===o?o=or(t):Ni(o,n),null!==w)v&&w.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`)),o.appendTo(w),v&&w.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const t=document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`);m.parentNode.insertBefore(t,m.nextSibling),m=t}o.mountAfter(m)}if(v){const t=document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`),n=o.lastNode??m;n.parentNode.insertBefore(t,n.nextSibling)}}Vs(o,r,n),null!==_&&fi(o,"row",_)}),void 0===o&&J(`Content not found for ListIndex: ${e.index} at path "${s.path}"`),null!==h&&h.reused.has(o)&&ri(o,n.stateElement)}else{if(o=void 0!==d?d.get(e)??null:null,u.changeIndexSet.has(e)){const t=gs(o);for(const e of t)Yi(e,n)}null===o&&J(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==b&&b.has(e)&&$i(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),t){const t=o,s=Nn(g,e);y.createLoopContext(s,e=>{Vs(t,e,n)})}}m=o.lastNode||m,void 0===d&&(d=new WeakMap,mi.set(t.node,d)),d.set(e,o)}pi.set(t.node,m),null!==w&&(t.node.parentNode.insertBefore(w,t.node.nextSibling),nn(w,null))},if:Ii,else:Ii,elseif:Ii,radio:function(t,e,n){const o=t.node,s=cs(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=cs(o.value,t.inFilters),r=Array.isArray(n)?n:us;o.checked=r.includes(s)}},Gi=new WeakMap,Vi=new WeakMap,Ki=new WeakMap;function Ji(){}function Qi(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===is.get(t)?.has(e)}(e,n)?zi:function(t,e){return!0===ls.get(t)?.has(e)}(e,n)?Ji:Wi}function Xi(t,e){const n=cs(function(t,e){const n=Pn(e);if(n.pathInfo.path in S){const t=xe(e.node);return null===t&&J(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&J("ListIndex not found for loopContext:");const n=S[e];void 0===n&&J(`Invalid index name: ${e}`);const o=an(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&J(qr(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[ze](n)}(e.state,t),t.outFilters);if(!0===Vi.get(t))return void e.deferredSelectBindings.push({binding:t,value:n,stateElement:e.stateElement});let o=Gi.get(t);if(void 0===o){if(Gi.has(t))return o=Qi(t),o===zi&&Gi.set(t,o),void o(t,e,n);if(o=Ui[t.bindingType],void 0===o){const e=t.propSegments[0];o=qi[e],Gi.set(t,o),void 0===o&&(et(t.replaceNode)?(o=Qi(t),o===zi&&Gi.set(t,o)):(o=Wi,Gi.set(t,o)))}if(o===Wi&&"SELECT"===t.node.tagName){const o=t.propSegments[0];if("value"===o||"selectedIndex"===o)return e.deferredSelectBindings.push({binding:t,value:n,stateElement:e.stateElement}),void Vi.set(t,!0)}o(t,e,n)}else o(t,e,n)}function Yi(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=fn(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=rs(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Ki.get(t)){const e=et(t.replaceNode);if(e&&void 0===ot(t.replaceNode)?.get(e))return void function(t,e){if(Fi.has(t))return;Fi.add(t);const n=()=>{Fi.delete(t);const e=rs(t);(null===e||e.shouldApplyState(t))&&ta([t])},o=n=>{Fi.delete(t),Hi(e,n)},s=rs(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Fi.delete(t),r()})||(Fi.delete(t),r()))}const r=ot(t.replaceNode);if(null===r)return Fi.delete(t),void Hi(e,new Error("CustomElementRegistry is unavailable."));Oo(r).wait(e,()=>{t.replaceNode.isConnected?n():Fi.delete(t)},o)}(t,e);Ki.set(t,!0)}if(!0===e.sameRootVerified)return void Xi(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=on(o),null===o&&J("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Aa(o);null===n&&J("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};Xi(t,r)})}else Xi(t,e)}function Zi(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==Ie&&Ie({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function ta(t,e,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<t.length;){let n=t[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=on(u),null===u&&J("Root node for fragment not found for binding."));const d=Aa(u);null===d&&J("No state tree found on this root for binding."),d.createState("readonly",o=>{const h={rootNode:u,stateElement:d,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Yi(n,h)}catch(t){Zi(n,t,d,c)}s++;const e=t[s];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{Wi(t,{propagationContextByBinding:e},n)}catch(e){Zi(t,e,o??null,c)}for(const[t,e]of i.entries())Ee(t,e),Re(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[Ge](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[Ve](n,o)}catch(t){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:t,original:n,node:o.node})}})}function ea(t,e,n){const[o,s,r]=Yt(t,n),i=ss(t);for(const t of o)Pe(t,e);ta(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=te(o);0!==t.length&&(Pe(o.node,e),ta(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}async function na(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=ot(t);null===s&&J(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(Gt(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function oa(t){if(t===document)await na(document),ir(document),Sr(document,document),ea(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await V(e.host),await na(e),ir(e),Sr(e,e),ea(e,null)}}const sa="2.5.0",ra="undefined"==typeof HTMLElement?class{}:HTMLElement,ia=/^@@wcs-(?:for|if|elseif|else):[^-]/,aa=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,la=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,ca=/^@@wcs-text-start:(.+)$/;function ua(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class da extends ra{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=sa.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=o.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(e,t);if(void 0!==o&&"function"==typeof o.get)continue;const s=e[t];"function"!=typeof s&&(n[t]=s)}return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=ua(JSON.stringify(e)),t.appendChild(n);const s=Array.from(Ft.keys());for(const e of s){const n=qt(e);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",e);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),t.appendChild(s)}const r=Array.from(Mi);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=Ti(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const t of o)i[t.propName]=t.value;e[s]=i}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=ua(JSON.stringify(e)),t.appendChild(n)}}Mi.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(aa.test(t.data)||la.test(t.data))&&n.push(t)}for(const t of n)t.remove()}static removeStructuralComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;ia.test(t.data)&&n.push(t)}for(const t of n)t.remove()}static restoreTextBindings(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode,o=ca.exec(t.data);o&&n.push({comment:t,path:o[1]})}for(const{comment:t,path:e}of n){const n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}const r=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const t=r.currentNode;aa.test(t.data)&&i.push(t)}for(const t of i){const e=aa.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}da.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(ia.test(t.data)){const e=t.data.split(":")[1];l.push({comment:t,uuid:e})}}for(const{comment:t,uuid:e}of l){const n=s.get(e);if(n){const e=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&e.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)e.content.appendChild(r);else for(const t of Array.from(n.childNodes))e.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(e,t)}}const c=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of c)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const ha=new Set(["for","if","elseif","else"]);function fa(t){const e=new os;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i]=Yt(s),a=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:e}}function pa(t,e,n){for(const o of e)"event"===o.bindingType||ha.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in S||Y(o.statePathName).wildcardCount>n||t.push(o)}function ma(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const t=i.currentNode;if(t.data===r)return t}return null}function ga(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Rt(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,cr()],bindingType:"else"}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;br(a),"string"==typeof l&&mr(a,l),Sr(n,a,l),Ht(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:yr(a)})}}const ya=Symbol.for("wcstack.binder"),ba=Symbol.for("wcstack.binder.pending"),wa=Symbol.for("wcstack.binder.taken");function va(t){if(Ko(t))return!0;if(!_a(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Ko(e)}function _a(t){return 1===t.nodeType}function $a(t){if(va(t))return;ir(t),Sr(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);ea(e&&s?n:t,null)}const Sa=[];function Na(){const t=Sa.splice(0,Sa.length);for(const e of t)$a(e);!function(){const t=function(){const t=globalThis[ya];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[ba];return void 0===e&&(e=[],t[ba]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[wa];return void 0===e&&(e=new WeakSet,t[wa]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const xa={protocol:"wcs-binder",version:1,bind:function(t){var e;_a(t)&&!va(t)&&(e=t.getRootNode(),Ca.has(e)?$a(t):Sa.push(t))}},Pa=new WeakMap,Ia=new WeakMap,ka=new Set;function Aa(t){return Pa.get(t)??null}function Ea(t){return Ia.get(t)??Promise.resolve()}const Ca=new WeakSet;function Ta(t){Ca.add(t)}function Ma(t,n){const s=Pa.get(t);if(null===n){if(void 0===s)return;Pa.delete(t),ka.delete(s),null!==Ie&&Ie({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const s=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{s&&await async function(t){await na(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${sa}". Falling back to full render.`),da.cleanupDom(t),!1}for(const n of e)ga(t,n);const n=function(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const t of o){const n=aa.exec(t.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 u=t.nextSibling;const d=`@@wcs-${o}-end:${s}`;for(;u&&(u.nodeType!==Node.COMMENT_NODE||u.data!==d);)c.push(u),u=u.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body),s=function(t,e){const n=new Map,o=[];for(const s of e){if(0===s.nodes.length)continue;const e=nr(s.nodes),{bindingInfos:i,subscriberNodes:a,bindingSession:l}=fa(s.nodes);Fs(e,l);for(const t of a)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");ps(e,i),Us(e,a);const c=[];for(const t of i)t.statePathName in S&&c.push(t);if(ys(e,c),"for"===s.type&&null!==s.index){const a=ma(t,"for",s.uuid);if(a){const t=Ns(null,s.index);bi(a,t,e),wi(a,s.nodes[s.nodes.length-1]),Xs(a,e);const c=Y(s.path+"."+r);Gs(e,Nn(c,t)),l.initialize(i,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),pa(o,i,c.wildcardCount);let u=n.get(s.uuid);u||(u=[],n.set(s.uuid,u)),u.push(t)}}else{const n=ma(t,s.type,s.uuid);n&&(Xs(n,e),l.initialize(i,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),pa(o,i,0))}}for(const[e,o]of n){const n=ma(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=qt(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Aa(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&Os(e,o)})}return o}(document.body,n);da.removeBlockBoundaryComments(document.body);const i=[];for(const t of e)t.parentNode&&(i.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());da.restoreTextBindings(document.body);const[a,l]=Yt(document.body);for(const t of a)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(Pe(t,null),e.setAttribute("data-wcs-completed",""))}else Pe(t,null);const c=[],u=[],d=ss(document.body).initialize(l);for(const t of d)if("event"!==t.bindingType)if(ha.has(t.bindingType))u.push(t);else{if(t.statePathName.includes(r))continue;c.push(t)}for(const t of u)if("for"===t.bindingType){const e=fn(t),n=Aa(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&(Ee(e,o),Re(e,o))})}ta([...c,...s]);for(const{el:t,parent:e,next:n}of i)e.insertBefore(t,n);const h=t.querySelectorAll(o.tagNames.ssr);for(const e of h){const n=e.hydrateProps;for(const[e,o]of Object.entries(n)){const n=t.querySelector(`[data-wcs-ssr-id="${e}"]`);if(n)for(const[t,e]of Object.entries(o))n[t]=e}}const f=t.querySelectorAll("[data-wcs-completed]");for(const t of f)t.removeAttribute("data-wcs-completed");return!0}(t)||await oa(t),Ta(t),Na(),e()}catch(t){n(t)}})});Ia.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await oa(t),Ta(t),Na(),e()}catch(t){n(t)}})});Ia.set(t,e)}}void 0!==s&&J('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="...">.'),Pa.set(t,n),ka.add(n),function(t,e){Tr.delete(t);const n=Cr.get(t);if(void 0===n||0===n.length||null===Or)return;Cr.delete(t);const o=Or;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,n),null!==Ie&&Ie({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}let Oa=0,La=0;function Ra(t){Oa=t+1}function ja(){Oa=0}const Da=new WeakMap,Wa=new Set,Ba=new Set;function za(t){return t.byFromPath.size>0||t.byResetPath.size>0}function Fa(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function Ha(t){return Da.get(t)}function qa(t){Ua(t),Da.delete(t)}function Ua(t){Wa.delete(t),Ba.delete(t)}const Ga=new WeakSet;let Va=0;function Ka(t){return Ha(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function Ja(t){Ga.has(t)||(Ga.add(t),Va++)}function Qa(t){return!!Ga.delete(t)&&(Va--,!0)}const Xa=[];function Ya(t,e=0){const n=Xa.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Xa.push(o):Xa.splice(n,0,o)}function Za(t){queueMicrotask(()=>{throw t})}const tl=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){Oa>La&&(La=Oa),function(t){if(0===Ba.size)return;if(e=t.absolutePathInfo.stateElement,!Ba.has(e))return;var e;const n=Ka(t);if(void 0!==n)for(const t of n)Ja(t)}(t);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(t){const e=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(t),e&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){je(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(t,e)})}hasQueuedPath(t,e){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===t&&n.absoluteAddress.absolutePathInfo.pathInfo.path===e)}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t,n=[]){const o=new Map;for(const e of t){const t=o.get(e.absoluteAddress);null!==Ie&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&Ie({type:"propagation:coalesced",absoluteAddress:e.absoluteAddress,droppedTransactionId:t.transactionId,winnerTransactionId:e.context.transactionId}),o.set(e.absoluteAddress,e.context)}const s=new Set(o.keys());for(const t of n)o.has(t)||o.set(t,null);const r=[],i=new Map;for(const[t,e]of o){if(null!==e&&e.hop>=32){console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:t.absolutePathInfo.pathInfo.path,transactionId:e.transactionId,hop:e.hop,maxHops:32}),null!==Ie&&Ie({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=vn(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 t=()=>{i.size>0?ta(r,i):ta(r)};if(e()||0===r.length)t();else{const e=ci("state",t);void 0!==e&&e.catch(Za)}}finally{De(),function(t){for(const e of Xa.slice())e.listener(t)}(s)}}};function el(){return tl}const nl=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function ol(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const sl="__WCSTACK_DEVTOOLS_HOOK__";const rl=t=>{null!==Ie&&Ie({type:"state:update-batch",addresses:t})};function il(t){const e=null!==Ie;!function(t){Ie=t}(t);const n=null!==t;n&&!e?Ya(rl,0):!n&&e&&function(t){const e=Xa.findIndex(e=>e.listener===t);-1!==e&&Xa.splice(e,1)}(rl)}function al(t){return{rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function ll(t){return Aa(t)??J("devtools: no state tree on this root")}let cl=null;function ul(){if(e())return;if(null!==cl)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:sa,getStateElements(){const t=[];for(const e of ka)t.push(al(e));return t},overlays:t=>$e(ll(t)).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join("."),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]})),keys(t){const e=ll(t),n=[];return e.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}n.push(e)}}),n},read(t,e,n){let o;return ll(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){ll(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=[...t.inFilters,...t.outFilters].map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=qt(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(ol(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=ht(e,Rt(n));for(const o of t)r(ol(e,o,"attribute",n))}catch{}continue}const e=nl.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=qt(s);if(null===a){if(n===o.commentTextPrefix)try{r(ol(t,zt(s),"comment",s))}catch{}}else r(ol(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:il};cl=t,function(){const t=globalThis,e=t[sl];if(void 0!==e)return 2!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 2. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:2,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[sl]=n,n}().register(t)}const dl={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of s){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",sa),da.buildContent(o,da.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}},hl="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let fl=0;async function pl(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++fl}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${hl}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${hl}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function ml(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){J(`Failed to load script file: ${t}`)}}class gl{_loopContextStack=Array(a).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&J("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=a&&J("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&&J("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&J("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&&J(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const yl=new WeakMap;function bl(t,e){let n=yl.get(t);void 0===n&&(n=new Map,yl.set(t,n));let o=n.get(e);return void 0===o&&(o=new Bn(e,t),n.set(e,o)),o}const wl=new WeakMap;function vl(t){const e=wl.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return bl(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:bl(t,n)}},set(){J("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){J("$command namespace is read-only; deleting from it is not allowed.")}});return wl.set(t,n),n}const _l=Symbol("wcs-stream-last-notified-uncertain"),$l=new WeakMap;function Sl(t,e){const n=$l.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Nl(t,e){const n=$l.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:_l,error:Object.is(o.error,null)?null:_l})}const xl=new Set;function Pl(t){xl.delete(t)}const Il=new WeakMap;function kl(t){return Il.get(t)??new Map}function Al(t){Pl(t);const e=Il.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Nl(t,n.name)}const El=(t,e)=>e,Cl=new Set;function Tl(t,e){"string"==typeof e&&0!==e.length||J(`[wcs/recursion-declaration-invalid] ${D} ${t} must be a non-empty string.`);const n=e.split(s);n.some(t=>0===t.length)&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not contain empty path segments.`),n.length<2&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must name a list element: a property path ending with "${s}${r}" (for example "nodes${s}${r}").`),n[n.length-1]!==r&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must end with "${s}${r}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===r&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must have exactly one "${r}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===W&&J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not contain "${W}" — the declaration is what gives "${W}" its meaning.`),isNaN(Number(n[o]))||J(`[wcs/recursion-declaration-invalid] ${D} ${t} "${e}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}function Ml(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}function Ol(t){return-1!==t.indexOf(W)}function Ll(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+s;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(Ol(o))return null;const i=o.slice(1).split(s);return i[0]===r||i.some(t=>0===t.length)?null:o}function Rl(t){return 0===t.length?t:s+Wl(t.slice(1))}function jl(t,e,n){const o=s+t.repeat,r=e.length<=n.length?e:n,i=e.length<=n.length?n:e;if(!i.endsWith(r))return!1;const a=i.slice(0,i.length-r.length);if(0===a.length)return!0;if(a.length%o.length!==0)return!1;for(let t=0;t<a.length;t+=o.length)if(!a.startsWith(o,t))return!1;return!0}function Dl(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(s,o-1))if(jl(t,e,n.slice(0,o)))return!0;return!1}function Wl(t){const e=t.split(s);for(let t=0;t<e.length;t++)e[t]===r||Number.isNaN(Number(e[t]))||(e[t]=r);return e.join(s)}function Bl(t,e){const n=t.repeat.split(s),o=s+t.repeat;let r=e;for(;r.startsWith(o);)r=r.slice(o.length);if(0===r.length||r===s+t.repeatList+s+"length")return!0;for(let t=1;t<n.length;t++)if(r===s+n.slice(0,t).join(s))return!0;return!1}function zl(t,e,n){n<0&&J(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=s+t.repeat;const a=o+e;let l=0;for(const t of a.split(s))t===r&&l++;return l>i&&J(`[wcs/recursion-depth-exceeded] Recursion on "${t.anchor}" reached depth ${n} ("${a}"), which needs ${l} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),a}function Fl(t,e){return zl(t,"",e)}function Hl(t,e,n){if(!n.startsWith(t.anchor))return null;if(e.length>0&&!n.endsWith(e))return null;if(n.length<t.anchor.length+e.length)return null;const o=n.slice(t.anchor.length,n.length-e.length);if(0===o.length)return 0;const r=s+t.repeat;let i=0,a=0;for(;a<o.length;){if(!o.startsWith(r,a))return null;a+=r.length,i++}return i}const ql=new WeakMap;function Ul(t,e){null===e?ql.delete(t):ql.set(t,e)}function Gl(t){const e=ql.get(t);e&&(e.dirty=!0)}const Vl=new WeakSet;function Kl(t){return"function"==typeof t.get&&Vl.has(t.get)}const Jl="[wcs/recursion-declaration-invalid]";class Ql{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(t,e){this.spec=t;const n=Ml(e);for(const[e,o]of Object.entries(n)){if(!Ol(e))continue;"function"==typeof o.set&&J(`${Jl} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&J(`${Jl} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Ll(t,e);null===n&&J(Fr(e,t.recursiveAnchor)),0===n.length&&J(`${Jl} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${s}total"), not the node.`),Bl(t,Rl(n))&&J(`${Jl} "${e}" names the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${t.recursiveAnchor}${s}total").`),this._definitions.set(e,{recursivePath:e,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(t){for(const[e,n]of Object.entries(t)){if(Ol(e)||Kl(n))continue;const t=this._matchExpansion(e);null!==t&&J(`${Jl} "${e}" is already defined on the state, so the recursive getter "${t}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const t=Array.from(this._definitions.values());for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)jl(this.spec,t[e].suffix,t[n].suffix)&&J(`${Jl} "${t[e].recursivePath}" and "${t[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(t){for(const e of this._definitions.values())if(Dl(this.spec,e.suffix,t))return e.recursivePath;return null}recursiveGetterOwningPath(t){const e=this._ownerByPathInfo.get(t);if(void 0!==e)return e;const n=this.recursiveGetterOwning(t.path);return this._ownerByPathInfo.set(t,n),n}recursiveGetterOwning(t){const e=this._accessors.get(t);if(void 0!==e)return e.recursivePath;const n=Wl(t),o=this._ownerByPath.get(n);if(void 0!==o)return o;let r=null;if(n.startsWith(this.spec.anchor)){r=this._matchExpansion(n);for(let t=n.lastIndexOf(s);null===r&&t>this.spec.anchor.length;t=n.lastIndexOf(s,t-1))r=this._matchExpansion(n.slice(0,t))}return this._ownerByPath.set(n,r),r}_matchExpansion(t){for(const e of this._definitions.values())if(null!==Hl(this.spec,e.suffix,t))return e.recursivePath;return null}materializeForPathInfo(t,e){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(e);if(void 0!==n)return n;const o=this.materializeFor(t,e.path);return this._accessorByPathInfo.set(e,o),o}materializeFor(t,e){const n=this._accessors.get(e);if(void 0!==n)return n;if(!e.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const t of this._definitions.values()){const n=Hl(this.spec,t.suffix,e);null!==n&&(null!==o&&J(`"${e}" matches both "${o.recursivePath}" and "${t.recursivePath}".`),o=t,s=n)}return null===o?null:this._define(t,o,s,e)}_define(t,e,n,o){const s=t.findStateDescriptor(o);void 0===s||Kl(s)||J(`"${o}" is already defined on the state, so the recursive getter "${e.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:e.recursivePath,depth:n}),i=e.get,a=function(){return i.call(this)};var l;return l=a,Vl.add(l),t.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(t,n),this._accessors.set(o,r),r}_registerListPaths(t,e){for(const n of function(t,e){const n=[];n.push(t.anchorList);for(let o=0;o<e;o++)n.push(Fl(t,o)+s+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){const n=new Set(this._accessors.keys());return function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&Kl(n)&&delete e[t]}for(const e of[t.staticDependency,t.dynamicDependency]){for(const t of n)e.delete(t);for(const[t,o]of e){let s=null;for(let t=0;t<o.length;t++)n.has(o[t])?s??=o.slice(0,t):s?.push(o[t]);null!==s&&(0===s.length?e.delete(t):e.set(t,s))}}!function(t,e,n){for(const o of n){const n=Y(o),s=Je(t,n),r=n.wildcardParentPathInfos,i=(t,e,n)=>{if(n===r.length)return void Ul(tn(s,e),null);const o=0===n?0:r[n-1].segments.length+1;let a=t;for(const t of r[n].segments.slice(o))a=a?.[t];if(!Array.isArray(a))return;const l=Ts(a);if(null===l)return;const c=Math.min(l.length,a.length);for(let t=0;t<c;t++)i(a[t],l[t],n+1)};i(e,null,0)}}(t,e,n)}}(t,e,n),n}concretePathAt(t,e){let n=this._concreteBySuffix.get(t);void 0===n&&(n=[],this._concreteBySuffix.set(t,n));let o=n[e];return void 0===o&&(o=zl(this.spec,t,e),n[e]=o),o}accessorFor(t){return this._accessors.get(t)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const Xl=new WeakMap,Yl=new WeakMap;function Zl(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=kl(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&kl(t).has(n),ownKeys:()=>Array.from(kl(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=kl(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){J(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){J(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function tc(t){const e=Xl.get(t);if(void 0!==e)return e;const n=Zl(t,z,t=>t.status);return Xl.set(t,n),n}function ec(t){const e=Yl.get(t);if(void 0!==e)return e;const n=Zl(t,F,t=>t.error);return Yl.set(t,n),n}function nc(t){Xl.delete(t),Yl.delete(t)}const oc=Object.freeze([]),sc=Object.freeze([]);function rc(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??oc,i=t.dynamicDependency.get(n)??oc,a=e.byFromPath.get(n)??sc;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}let ic=null;function ac(t){const e=kl(t);if(0!==e.size){!function(t){xl.add(t)}(t);for(const n of e.values())lc(t,n)}}function lc(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=ic,r=new Set;let i;ic=r;try{t.createState("readonly",t=>{i=n(t)})}finally{ic=o}i instanceof Promise&&J(`${L} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${z}${s}${e.name}`,l=`${F}${s}${e.name}`;for(const n of r){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==a&&o.path!==l||J(`${L} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&J(`${L} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=r,i}(t,e);!function(t,e){const n=Ha(t);if(void 0!==n&&0!==e.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==e.name)continue;const s=rc(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&J(`[wcs/scan-feedback-loop] ${L} entry "${e.name}" args read "${n}", which is derived from the ${j} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,e),t.createState("writable",t=>{t[e.name]=e.definition.initial}),cc(t,e,"active",null);const r=e.definition,i={fold(n){t.createState("writable",t=>{t[e.name]=r.fold(t[e.name],n)})},done(){cc(t,e,"done",null)},fail(o){cc(t,e,"error",o),n.abort()}};!async function(t,e,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 t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",i)}}(r.source,o,n.signal,i)}function cc(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return $l.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),i=r.status!==n,a=!Object.is(r.error,o);(i||a)&&(function(t,e,n,o){let s=$l.get(t);void 0===s&&(s=new Map,$l.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${z}${s}${e.name}`),a&&t.$postUpdate(`${F}${s}${e.name}`)}))}Ya(function(t){const e=xl;if(0===e.size)return;const n=[];for(const o of e)for(const e of kl(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&kl(t).get(o.name)===o)try{lc(t,o)}catch(n){o.controller?.abort(),e.has(t)&&kl(t).get(o.name)===o&&cc(t,o,"error",n)}},20);const uc=new WeakMap,dc=new WeakMap,hc=new Set,fc=new Map;function pc(t){return uc.get(t)??fc}const mc=new Map;function gc(t){return dc.get(t)??mc}function yc(t){0===t.length&&J(`[wcs/watch-declaration-invalid] ${R} entry name must be a non-empty state path.`),t.startsWith("$")&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" must not start with "$" (reserved namespace).${bt}`),t.includes("@")&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${bt}`),t in Object.prototype&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=Y(t);for(const n of e.segments)0===n.length&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" has an empty path segment.${bt}`);return e.wildcardCount>i&&J(`[wcs/watch-declaration-invalid] ${R} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const bc=new WeakMap;function wc(t,e,n){let o=bc.get(t);void 0===o&&(o=new Map,bc.set(t,o)),o.set(e,n)}const vc=new Map;function _c(t,e){vc.has(t)||vc.set(t,e)}function $c(t){return vc.get(t)}function Sc(t){return vc.has(t)}function Nc(t){for(let e=t;null!==e;e=e.parentListIndex)if(Cs(e))return!0;return!1}function xc(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[ze](Nn(e.wildcardParentPathInfos[i],r)),l=Ts(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=an(o,i,e.wildcardCount);if(l!==c&&!ks(l,c)){if(Cs(c))return"gone";s="replaced"}r=l}return s}function Pc(t,e,n){const o=new Map;for(const s of n){const n=xc(t,e,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),t=>t.row)}const Ic=/^(?:0|[1-9]\d*)$/;function kc(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function Ac(t){if("object"!=typeof t||null===t||Object.isFrozen(t))return null;const e=Object.getPrototypeOf(t);return Array.isArray(t)?e===Array.prototype&&Reflect.ownKeys(t).every(e=>"length"===e||"string"==typeof e&&Ic.test(e)&&kc(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&kc(t,e))?null:"object"}function Ec(t,e){const n=Ac(t);if(null===n)return t;const o=t,s=e.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(t.length):null===Object.getPrototypeOf(t)?Object.create(null):{},e.set(o,r);for(const t of Object.keys(o))r[t]=Ec(o[t],e);return r}function Cc(t){return Ec(t,new Map)}function Tc(t,e,n){if(Object.is(t,e))return!0;const o=Ac(e);if(null===o||"object"!=typeof t||null===t)return!1;const s=t,r=e;if("array"===o){if(!Array.isArray(t)||t.length!==e.length)return!1}else if(Array.isArray(t)||Object.keys(s).length!==Object.keys(r).length)return!1;if(Ac(t)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let e=0;e<t.length;e++)if(!Tc(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&Tc(s[t],r[t],n))}function Mc(t,e){return Tc(t,e,new Map)}const Oc=new WeakMap;function Lc(t,e){if("function"!=typeof e)return;const n=Oc.get(e);void 0===n?Oc.set(e,new Set([t])):n.add(t)}const Rc={"read-source":t=>`${j} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-output":t=>`${j} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${j} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${j} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${j} could not write the output "${t}".`},jc={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Dc(t,e,n){null!==Ie&&Ie({type:"state:watch-error",phase:e,path:`${j}.${t}`,error:n})}function Wc(t,e,n){console.error(`[@wcstack/state] ${Rc[n](t)}`,e),Dc(t,jc[n],e)}function Bc(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function zc(t,e){e.then(void 0,()=>{}),Wc(t,new TypeError(`${j} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Fc=new WeakSet,Hc=Object.freeze([]);function qc(t,e,n){let o=t.get(n);return void 0===o&&(o={stateElement:e,entry:n,rows:[],reset:!1},t.set(n,o)),o}function Uc(t,e){let n=0;for(;n<t.indexes.length-1&&t.indexes[n]===e.indexes[n];)n++;return t.indexes[n]-e.indexes[n]}function Gc(t,e){return e.has(t.stateElement)&&!0===Ha(t.stateElement)?.entries.has(t.entry)}function Vc(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Kc(n,t))||Qa(e)}function Kc(t,e){return el().hasQueuedPath(t,e)}function Jc(t,e){!function(t,e,n){if(0!==Va)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=Ka(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||Qa(e)}}(t,e,Kc)}function Qc(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function Xc(t,e,n){if(!Gc(t,n))return Vc(t),null;const{stateElement:o,entry:s}=t;if(t.reset)return{group:t,next:s.initial};const r=s.source;if(function(t,e){for(const n of e.pathInfo.cumulativePaths)if(t.getterPaths.has(n))return!0;return!1}(o,r))return function(t,e,n){if(Fc.has(t))return;Fc.add(t);const o=`[wcs/scan-source-computed] ${j} entry "${e}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),Dc(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=kl(t).get(e);if(void 0===o)return!1;for(const t of o.depAddresses)if(n.has(t))return!0;return!1}(o,r.pathInfo.segments[0],e))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",e=>{const n=e[s.name],o=0===r.pathInfo.wildcardCount?t.rows:Pc(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(Uc)){let n;try{n=Qc(e,r,t)}catch(t){Wc(s.name,t,"read-source");continue}const o=a(l,n,$c(t.absAddress),...t.indexes);if(Bc(o))return void zc(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){Wc(s.name,t,i.failure)}return i.plan}function Yc(t,e){const{group:n}=t;if(!Gc(n,e))return void Vc(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Qa(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!Mc(o,s.initial):!Object.is(o,t.next)){const o=n.reset?Cc(s.initial):t.next;e[s.name]=o,Lc(s.name,o)}})}catch(t){Wc(s.name,t,"write")}}function Zc(t){(0!==pc(t).size||0!==gc(t).size||function(t){const e=Da.get(t);return void 0!==e&&za(e)}(t))&&(function(t){hc.add(t),function(t){const e=Da.get(t);void 0!==e&&(za(e)&&Wa.add(t),function(t){return t.eventResetByPath.size>0}(e)&&Ba.add(t))}(t)}(t),function(t){const e=[];for(const n of pc(t).values())eu(t,n)&&e.push(n);for(const n of gc(t).values())for(const o of n)eu(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{wc(t,tu(t,o),n[o.path])}catch(e){ou(t,o.path,"prime",e)}})}(t))}function tu(t,e){return tn(Je(t,e.pathInfo),null)}function eu(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const nu={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function ou(t,e,n,o){console.error(`[@wcstack/state] $watch ${nu[n]} "${e}" threw.`,o),null!==Ie&&Ie({type:"state:watch-error",phase:n,path:e,error:o})}function su(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function ru(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function iu(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=eu(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void ou(0,n.path,"evaluate",t)}const a=r?function(t,e){return bc.get(t)?.get(e)}(e,o):$c(o);r&&wc(e,o,i),null!==Ie&&Ie({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){ou(0,n.path,"handler",t)}}Ya(function(t){const e=hc;try{if(0===e.size)return void Jc(t,e);const n=function(){const t=La;return La=0,t}();if(n>32){Jc(t,null);const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==Ie&&Ie({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}!function(t,e,n){if(0!==t.length){Ra(n);try{for(const n of t)Yc(n,e)}finally{ja()}}}(function(t,e,n){if(Jc(t,e),0===Wa.size)return Hc;const o=new Map;for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=Ha(t);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let e=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;e=ln(n.listIndex,r.wildcardCount)}for(const s of i)qc(o,t,s).rows.push({absAddress:n,indexes:e})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const e of a)qc(o,t,e).reset=!0}if(0===o.size)return Hc;const s=Array.from(o.values()).sort((t,e)=>t.entry.order-e.entry.order),r=[];Ra(n);try{for(const n of s){const o=Xc(n,t,e);null!==o&&r.push(o)}}finally{ja()}return r}(t,e,n),e,n),function(t,e,n){const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=pc(t).get(s),i=gc(t).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const e of a){let s=[];if(e.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=ln(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(ru);const s=function(t){let e=null;for(let n=0;n<t.length;n++){const o=t[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=t[n-1];(Nc(o.absAddress.listIndex)||s?.entry===o.entry&&su(s.indexes,o.indexes))&&(e??=new Set).add(o.entry)}if(null===e)return t;const n=new Set;for(const o of e){const e=t.filter(t=>t.entry===o),s=e[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(Pc(t,o.pathInfo,e));for(const t of e)s.has(t)||n.add(t)})}catch(t){ou(0,o.path,"evaluate",t);for(const t of e)n.add(t)}}return t.filter(t=>!n.has(t))}(o);Ra(n);try{for(const t of s){if(!e.has(t.stateElement))continue;const n=pc(t.stateElement).get(t.entry.path)===t.entry,o=!0===gc(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&iu(t)}}finally{ja()}}(t,e,n)}finally{vc.clear()}},10);const au="[wcs/scan-declaration-invalid]",lu=Object.freeze([]);function cu(t){return`${j} entry "${t}"`}function uu(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function du(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${r}${r}`)?`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.${bt}`}function hu(t,e,n){0===n.length&&J(`${au} ${t} "${e}" must be a non-empty state path.${bt}`),n.startsWith("$")&&J(`${au} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${bt}`),n.includes("@")&&J(`${au} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${bt}`),n in Object.prototype&&J(`${au} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${bt}`);const o=Y(n);for(const s of o.segments)0===s.length&&J(`${au} ${t} ${e} "${n}" has an empty path segment.${bt}`);return o.wildcardCount>i&&J(`${au} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function fu(t,e,n,o){const i=cu(t);0===t.length&&J(`${au} ${j} entry name must be a non-empty string.${bt}`),(t.includes(s)||t.includes(r))&&J(`${au} ${i} must be a flat property name ("${s}" and "${r}" are not allowed). The output is a property the runtime owns.${bt}`),t.startsWith("$")&&J(`${au} ${i} must not start with "$" (reserved namespace).${bt}`),t in Object.prototype&&J(`${au} ${i} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${bt}`),e.has(t)&&J(`${au} ${i} conflicts with a getter declared on the state.${bt}`),n.has(t)&&J(`${au} ${i} conflicts with a setter declared on the state.${bt}`),o.has(t)&&J(`${au} ${i} conflicts with the ${L} entry of the same name — each output has exactly one owner.${bt}`)}function pu(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!function(t,e){return"function"==typeof e&&!0===Oc.get(e)?.has(t)}(t,o)&&J(`${au} ${cu(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${bt}`)}function mu(t,e,n,o,r,i){const a=cu(t),l=void 0!==e.from,c=void 0!==e.on;if(l===c&&J(`${au} ${a} must declare exactly one of "from" (a state path) or "on" (an event-token name).${bt}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||J(`${au} ${a} "on" must be a non-empty event-token name.${bt}`),n.has(t)||J(`${au} ${a} on "${t}" is not declared in ${M}.${yt(t,n)}${bt}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&J(`${au} ${a} "from" must be a state path string.${bt}`);const d=hu(a,"from",u),h=uu(d,o)??i?.recursiveGetterOwning(u)??null;null!==h&&J(du(a,"from",u,h));const f=uu(d,r);return null!==f&&J(function(t,e,n){return`${au} ${t} from "${e}" ${n===e?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${bt}`}(a,u,f)),(u===t||u.startsWith(t+s))&&J(`${au} ${a} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${bt}`),{kind:"path",path:u,pathInfo:d}}function gu(t,e,n,o){if(void 0===e)return lu;const i=cu(t);Array.isArray(e)||J(`${au} ${i} "resetOn" must be an array of state paths.${bt}`);const a=[];for(const t of e){"string"!=typeof t&&J(`${au} ${i} "resetOn" must contain only state path strings.${bt}`);const e=hu(i,"resetOn",t);e.wildcardCount>0&&J(`${au} ${i} resetOn "${t}" must not contain "${r}" — a reset returns the whole output to "initial".${bt}`);const l=uu(e,o);null!==l&&J(du(i,"resetOn",t,l)),"path"===n.kind&&t===n.path&&J(`${au} ${i} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${bt}`),"path"===n.kind&&t.startsWith(n.path+s)&&J(`${au} ${i} resetOn "${t}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${bt}`),a.push(t)}return a}function yu(t){const e=t.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[t.name];i="threw";const a=function(t){return Ga.has(t)}(t),l=a&&!Mc(n,t.initial)?Cc(t.initial):n,c=e(l,o,...s);if(Bc(c))return void zc(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,Lc(t.name,c)),a&&Qa(t)}catch(e){Wc(t.name,e,i)}}}function bu(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function wu(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function vu(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function _u(t){return t.startsWith("$")}function $u(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function Su(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||J(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||J(`${e} entries must be non-empty strings.`),t.startsWith("$")&&J(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&J(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}const Nu=new Map;class xu{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=Y(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Pu(t){let e;return Nu.get(t)??(Nu.set(t,e=new xu(t)),e)}function Iu(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:an(n.listIndex,o,n.pathInfo.wildcardCount)}function ku(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=rn(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?an(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?an(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}const Au=new WeakMap;class Eu{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,s,r){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return Nn(Y(this.markerParentPath+s+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(fe(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,s,...r)=>{const i=fe(t,e),a=pe(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a=fe(t,e),l=pe(0,e,a,r,n);return o[s](a,l,...i)}}return this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return ku(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[fe(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||J(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(t,e)?(t[e]=n,!0):(this.receiver[fe(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return fe(this.record,e),!0}catch{return!1}}}function Cu(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=Au.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Au.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(i,new Eu(t,s,e.listIndex,r,n,o))}function Tu(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Mu(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}function Ou(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===T)return Mu(vl(s),e.pathInfo.segments);if(i===z)return Mu(tc(s),e.pathInfo.segments);if(i===F)return Mu(ec(s),e.pathInfo.segments);if(!0===s.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const t=Se(s,e.pathInfo.path);if(null!==t)return Cu(t,e,n,o)}if(!(e.pathInfo.path in t)){if(null===e.parentAddress&&Pr(function(t){return t.rootNode??null}(s),e.pathInfo.path))return;const i=e.parentAddress??J(function(t,e,n){return`[${Wr.binding}] Path "${t}" does not exist on the state tree.${yt(t,Dr(e,"",n))}${bt}`}(e.pathInfo.path,t,s.getterPaths)),a=Lu(t,i,n,o);if(null==a)return;const l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(!0===s.hasMounts&&l!==r&&!(l in Object(a))){const t=ei(s,i.pathInfo.path,l,e.listIndex);if(null!==t)return function(t,e,n,o,s){const r=Cu(t,Nn(Y(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(t.record,t.entry,e.listIndex,n,o)}if(l===r){const t=e.listIndex?.index??J(qr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(a,t)}return Reflect.get(a,l)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}function Lu(t,e,n,o){ku(o,e),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,e.pathInfo),function(t,e){if(null===ic)return;const n=Je(t,e.pathInfo);ic.add(tn(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return Tu(s,e)?function(t,e,n,o,s){const r=tn(Je(s,e.pathInfo),e.listIndex),i=function(t){return ql.get(t)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=Ou(t,e,n,o,s);return Ul(r,{value:l,dirty:!1,generation:a}),l}(t,e,n,o,s):Ou(t,e,n,o,s)}function Ru(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,u,d)=>{const h=o[s]??null;if(null===h)return void d.push(u);const f=Nn(h,r),p=tn(Je(n.stateElement,h),r),m=Le(p),g=Lu(t,f,e,n),y=Ds(r,m,g).newIndexes,b=l[c]??null;if(i.set(p,g),null===b)for(let t=0;t<y.length;t++){const e=y[t];a(o,s+1,e,l,c+1,u.concat(e.index),d)}else{const t=y[b]??J(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,u.concat(t.index),d):d.push(u.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Re(t,Array.isArray(e)?e:[]);return l}function ju(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Ms(Lu(t,Nn(a,r),e,n),r);null==l&&J(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??J(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Du(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}function Wu(t,e,n,o){"object"==typeof t&&null!==t||J(`${B} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&J(`${B} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Bu(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&J(`${B} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function zu(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];Wu(a,n,o,i);const l=Bu(a,e,n,o,i);r.has(l)&&J(`${B} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Fu(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function Hu(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=Lu(t,s,n,o);if(null===i||"object"!=typeof i&&"function"!=typeof i)return!1;const a=e.pathInfo.lastSegment;if(a===r){const t=e.listIndex?.index;return"number"==typeof t&&t in i}return a in i}const qu=new WeakMap;function Uu(t,e){null===e?qu.delete(t):qu.set(t,e)}function Gu(t,e,n){const s=Y(t.wildcardParentPaths[e]),r=Je(t.stateElement,s),i=Nn(s,n),a=tn(r,n),l=Le(a),c=t.stateProxy[ze](i),u=Ds(i.listIndex,l,c);t.observedListValueByAbsAddress.set(a,Array.isArray(c)?c:[]);const d=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(u,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...d);else for(const n of d)Gu(t,e+1,n)}const Vu=[];function Ku(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:Vu,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:Vu,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Ju=[];function Qu(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Ju;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=Y(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??Ju}function Xu(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=Y(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[ze](e),a=tn(Je(t.stateElement,e.pathInfo),e.listIndex),l=Le(a),c=Ds(e.listIndex,l,r);t.observedListValueByAbsAddress.set(a,Array.isArray(r)?r:[]);const u=Ku(t,o,0,0,c);for(const e of u.fullRows){const o=Nn(s,e);t.result.add(o),n.push(o)}if(null!==u.movedRows){const e=Qu(t,i,s);if(null===e)for(const e of u.movedRows){const o=Nn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of u.movedRows)for(const s of e){const e=Nn(s,o);t.result.add(e),n.push(e)}}}else{const o=Nn(s,e.listIndex);t.result.add(o),n.push(o)}}const i=t.dynamicMap.get(o);if(i)for(const o of i){const s=Y(o),r=[];if(s.wildcardCount>0){const n=rn(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&J(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=an(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Gu(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&J(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=an(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=Nn(s,e);t.result.add(o),n.push(o)}}}function Yu(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&J(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),d={ranks:u,stateElement:t,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,Xu(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(d,e,a);for(const[t,e]of d.observedListValueByAbsAddress)Re(t,e);return Array.from(d.result)}function Zu(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||_c(n,o)}function td(t,e,n,s,r,i,a="diff"){const l=o.enablePropagationContext?co()??io(-1):null,c=el();c.enqueueAbsoluteAddress(e,l),i&&Gl(e),Yu(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=tn(Je(s.stateElement,e.pathInfo),e.listIndex);Gl(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function ed(t,e,n,o,s){s&&(t.getterPaths.has(e)?Gl(n):Ul(n,{value:o,dirty:!1,generation:t.stateGeneration}))}function nd(t,e,n,o,s,i,a,l){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const a=Lu(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??J(qr(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(a,t,o)}return Reflect.set(a,l,o)}if(!i.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);i.pushAddress(e),i.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{i.endUntrack(),i.popAddress()}}finally{td(e,n,s,i,a,l)}}function od(t,e,n,o,i){const a=i.stateElement.listKeys;if(null!=a&&Array.isArray(n)){const l=a.get(e.pathInfo.path);if(void 0!==l){const a=Lu(t,e,o,i),c=function(t,e,n,o){const s=zu(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=zu(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,l,a,n);if(null!==c)return function(t,e,n,o,i,a){const l=e.pathInfo.path,c=e.listIndex;null===Ts(o)&&Ds(c,null,o);const u=Ds(c,o,n.list),d=sd(t,e,n.list,i,a,l),h=Y(l+s+r);for(const e of n.matched){const n=Fu(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const r of n)void 0!==o?od(t,Nn(Y(h.path+s+r.field),o),r.value,i,a):e.oldRow[r.field]=r.value}return d}(t,e,c,a,o,i)}}return sd(t,e,n,o,i,null)}function sd(t,e,n,i,a,l){const c=a.stateElement,u=e.pathInfo.path;if(!0===c.hasGraftedVolumes){const t=function(t,e){const n=Ir.get(t);if(void 0===n||0===n.size)return null;const o=e+s;for(const t of n)if(t.startsWith(o))return t;return null}(c,u);null!==t&&J(`Cannot replace "${u}" wholesale: a volume is mounted at "${t}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${t}" itself, or individual fields inside "${u}", instead.`)}if(!0===c.hasRecursion){const t=c.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);null!==t&&J(`[wcs/recursion-readonly] "${u}" writes into the recursive getter "${t}" (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.`)}const d=!!fo&&(fo=!1,!0);if(!(u in t)&&null!==e.parentAddress&&!c.elementPaths.has(u)){const s=Lu(t,e.parentAddress,i,a);if("object"==typeof s&&null!==s){const t=e.pathInfo.lastSegment,h=t===r?e.listIndex?.index:t;let f,p=!1;if(!d&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==h&&h in s,e=void 0!==h?s[h]:void 0;if(t&&Object.is(e,n))return!0;f=e,p=!0}const m=Tu(c,e),g=tn(Je(c,e.pathInfo),e.listIndex);null!==Ie&&Ie({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:p}),Zu(c,u,g,f,p);let y=!1;try{if(void 0===h&&J(qr(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),!0===c.hasMounts&&t!==r&&!(h in s)){const o=ei(c,e.parentAddress.pathInfo.path,t,e.listIndex);if(null!==o)return y=!0,function(t,e,n,o,s,r){const i=Cu(t,Nn(Y(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(o.record,o.entry,e.listIndex,n,i,a)}return Reflect.set(s,h,n)}finally{td(e,g,i,a,l,m),y?Gl(g):ed(c,u,g,n,m),Du(c,e.pathInfo,{value:n})}}}let h,f=!1;if(!d&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Lu(t,e,i,a);if(Hu(t,e,i,a)&&Object.is(o,n))return!0;h=o,f=!0}const p=c.elementPaths.has(e.pathInfo.path),m=Tu(c,e),g=tn(Je(c,e.pathInfo),e.listIndex);null!==Ie&&Ie({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:f}),Zu(c,u,g,h,f);try{return p?function(t,e,n,o,i,a,l,c){const u=e.parentAddress??J(`address.parentAddress is undefined path: ${e.pathInfo.path}`),d=Lu(t,u,i,a)??[];let h=(f=d,qu.get(f)??null);var f;if(null===h){const t=Ts(d)??[];h={value:[...d],listIndexes:[...t]},Uu(d,h)}try{return nd(t,e,n,o,i,a,l,c)}finally{const n=h.value.indexOf(o),l=Lu(t,u,i,a)??[],c=Array.isArray(l)?Ts(l)??[]:[],f=e.listIndex.index,p=-1!==n?h.listIndexes[n]:Ns(u.listIndex,-1);if(c[f]=p,new Set(l).size===h.value.length){for(let t=0;t<c.length;t++)c[t].index=t;Uu(d,null),function(t,e,n,o,i,a){const l=a.stateElement,c=el(),u=tn(Je(l,t.pathInfo),t.listIndex);Ae(u)===n&&(Os(e.value,e.listIndexes),Ee(u,e.value),function(t){Ws.add(t)}(e.value)),c.enqueueRenderOnlyAddress(u);const d=new Map;e.listIndexes.forEach((t,e)=>d.set(t,e));const h=Y(t.pathInfo.path+s+r),f=Je(l,h);for(let t=0;t<o.length;t++){const n=o[t],s=d.get(n);if(s===t)continue;const r=Nn(h,n),u=tn(f,n);if(void 0===s){const n=tn(f,e.listIndexes[t]??null);Sc(n)&&_c(u,$c(n)),td(r,u,i,a,null,Tu(l,r),"full");continue}Yu(l,r,l.staticDependency,l.dynamicDependency,l.listPaths,i,"new",t=>{const e=tn(Je(l,t.pathInfo),t.listIndex);Gl(e),c.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}}(u,h,l,c,i,a)}}}(t,e,g,n,i,a,l,m):nd(t,e,g,n,i,a,l,m)}finally{p||ed(c,u,g,n,m),Du(c,e.pathInfo,{value:n})}}function rd(t,e,n,o){return(e,s,r)=>{const i=Y(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&J(zr("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=Nn(i,ju(t,n,o,i,s));if(void 0===r)return Lu(t,a,n,o);od(t,a,r,n,o)}}function id(t,e,n){const o=t.recursionRegistry,r=Ll(o.spec,n);null===r&&J(Fr(n,o.spec.recursiveAnchor));const i=function(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=e.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(t,e){const n=t.spec;if(!e.startsWith(n.anchor))return null;const o=s+n.repeat;let r=0,i=n.anchor.length;for(;e.startsWith(o,i);)i+=o.length,r++;return i!==e.length&&46!==e.charCodeAt(i)?null:r}(e,n.pathInfo.path)}(e,o);return null===i&&J(`[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(r,i)}function ad(t,e,n,o,r){const i=o.spec,a=[],l=new Map,c=[],u=i.repeatList,d=i.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void a.push(Nn(t,n));const s=m(o[e],n,null).rows;for(let n=0;n<s.length;n++)p(t,e+1,s[n])};function m(o,s,r){const a=Nn(o,s),c=tn(Je(n.stateElement,o),s),d=Lu(t,a,e,n),f=null===r?null:((t,e,n)=>{if(!Array.isArray(e)||0===e.length)return null;const o=e;return h.has(o)&&J(`[wcs/recursion-cycle] "${t}" is reachable from itself: the recursion on "${i.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)&&J(`[wcs/recursion-shared-list] "${t}" is the same array instance as a list reached from another node. The recursion on "${i.anchor}" needs a tree: give each node its own "${u}" array.`),o})(o.path,d,r),p=Ds(s,Le(c),d);return l.set(c,Array.isArray(d)?d:[]),null!==f&&null!==r&&r.add(f),{rows:p.newIndexes,tracked:f}}const g=(t,e,n)=>{const{rows:i,tracked:l}=m(e,n,f);if(0===i.length)return;const d=(t=>{const e=c[t];if(void 0!==e)return e;const n=o.concretePathAt(r,t),i=0===r.length?n:o.concretePathAt("",t),a={nodePath:i,concretePathInfo:Y(n),childListPathInfo:Y(i+s+u)};return c[t]=a,a})(t),y=l;h.add(y);const b=d.concretePathInfo.wildcardCount===t+1;for(let e=0;e<i.length;e++){const n=i[e];b?a.push(Nn(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,Y(d),null);for(const[t,e]of l)Re(t,e);return a}function ld(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Iu(o,s.wildcardPaths.at(-1)??J(`lastWildcardPath is null: ${e.pathInfo.path}`))??J(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??J(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=Ms(Lu(t,Nn(i,s),n,o),s)??J(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??J(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??J(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":J(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}const cd=/^\$\d+$/,ud=`${z}${s}`,dd=`${F}${s}`,hd=new WeakMap;function fd(t,e,n,o){const r=S[e];if(void 0===r&&"string"==typeof e&&36===e.charCodeAt(0)&&cd.test(e)&&J(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==r){0===o.addressStackLength&&J(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const i=t?.listIndex;null==i&&J(`ListIndex not found: ${e.toString()}`);let a=r;const l=t.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const t=Se(o.stateElement,l.path);null!==t&&(a=r+function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(s,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const r=-1===o?e:e.slice(0,o),i=-1===o?"":e.slice(o+1),a=t.accessorBySuffixByMarkerParent.get(r)?.get(i);return void 0!==a?a.indexShift:t.delta}(t,l.path))}const c=an(i,a,l.wildcardCount);return c?.index??J(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>function(t,e,n,o){const s=rd(t,0,n,o);return(e,r)=>{if(!0===o.stateElement.hasRecursion&&Ol(e)){if(void 0!==r)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=Ll(r.spec,o);null===i&&J(Fr(o,r.spec.recursiveAnchor)),Array.isArray(s)||J(`[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&&J(`[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=ad(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Lu(t,a[o],e,n));return l}(t,n,o,e,r);e=id(o.stateElement,o,e)}const i=Y(e);if(void 0===r||Array.isArray(r)||J(`$getAll("${e}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&J(zr("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Iu(o,i.wildcardPaths[t]);if(e){r=ln(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&J(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(e,t.pathInfo.path)),r=[]}}const a=Ru(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>function(t,e,n,o){return(e,s,r,i)=>{if(!0===o.stateElement.hasRecursion&&Ol(e))return function(t,e,n,o,s,r,i){const a=n.stateElement.recursionRegistry,l=Ll(a.spec,o);null===l&&J(Fr(o,a.spec.recursiveAnchor));const c=Rl(l);Array.isArray(s)||J(Hr(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&J(`[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&&J(Hr(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&J(Hr(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(t,e,n){Bl(t,n)&&J(`[wcs/recursion-structural-write] "${e}" writes the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const u=a.conflictingRecursiveGetter(c);null!==u&&J(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${u}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const d=ad(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(od(t,d[o],r,e,n),h++);return h}(t,n,o,e,s,r,i);const a=Y(e);Array.isArray(s)||J(Hr(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&J(zr("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&J(Hr(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&J(Hr(e,"requires an array as the value when { spread: true } is set."));const u=Ru(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&J(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,u.length,r.length));const d=[];for(let e=0;e<u.length;e++){const s=ju(t,n,o,a,u[e]);d.push(Nn(a,s))}let h=0;for(let e=0;e<d.length;e++){const s=d[e];let i;i=c?r(Lu(t,s,n,o),...u[e]):l?r[e]:r,void 0!==i&&(od(t,s,i,n,o),h++)}return h}}(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=Pu(e),i=ld(t,r,n,o),a=Nn(r.pathInfo,i),l=tn(Je(s,a.pathInfo),a.listIndex),c=el();c.enqueueAbsoluteAddress(l),Yu(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=tn(Je(s,t.pathInfo),t.listIndex);Gl(e),c.enqueueAbsoluteAddress(e)}),Du(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>rd(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{Ol(t)&&J(`[wcs/recursion-unsupported] $trackDependency("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&J(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??J("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(e.path)&&e.path!==t&&n.addDynamicDependency(t,e.path)}}(0,0,0,o)(t);case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case T:return vl(o.stateElement);case z:return tc(o.stateElement);case F:return ec(o.stateElement)}if(!e.startsWith(ud)&&!e.startsWith(dd))return}const s=Pu(!0===o.stateElement?.hasRecursion&&Ol(e)?id(o.stateElement,o,e):e),r=ld(t,s,n,o),i=Nn(s.pathInfo,r);return Lu(t,i,n,o)}if("symbol"==typeof e){const r=function(t){let e=hd.get(t);return void 0===e&&(e=new Map,hd.set(t,e)),e}(o),i=r.get(e);if(void 0!==i)return i;let a;switch(e){case Be:a=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&J("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case ze:a=e=>Lu(t,e,n,o);break;case Fe:a=e=>Hu(t,e,n,o);break;case He:a=(e,s)=>od(t,e,s,n,o);break;case qe:a=()=>async function(t,e,n){const o=Reflect.get(t,N);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Ue:a=()=>function(t,e,n){const o=Reflect.get(t,x);"function"==typeof o&&o.call(n)}(t,0,n);break;case Ge:a=e=>function(t,e,n,o){const r=Reflect.get(t,P);let i;if("function"==typeof r){const t=new Set,s={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,r=e.path;if(-1===r.indexOf("#")&&(t.add(r),e.wildcardCount>0)){const t=ln(n.listIndex,e.wildcardCount),o=s[r];void 0===o?s[r]=[t]:o.push(t)}}i=r.call(n,Array.from(t),s)}const a=o.stateElement?(l=o.stateElement,Ar.get(l)??Er):[];var l;if(a.length>0)for(const t of a){const r=t.mountPath+s,i=new Set,a={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo.path;if(e!==t.mountPath&&!e.startsWith(r))continue;if(-1!==e.indexOf("#"))continue;const s=e===t.mountPath?"":e.slice(r.length);if(""===s)continue;i.add(s);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const t=ln(n.listIndex,l);(a[s]??=[]).push(t)}}if(i.size>0)try{t.callback.call(kr(t.mountPath,n),Array.from(i),a)}catch(e){console.error(`[@wcstack/state] volume "${t.mountPath}" $updatedCallback threw.`,e)}}return i}(t,e,n,o);break;case Ve:a=(e,o)=>function(t,e,n,o){const s=Reflect.get(t,I);"function"==typeof s&&s.call(o,e,n)}(t,e,o,n);break;default:return Reflect.get(t,e,n)}return r.set(e,a),a}}class pd{_stateElement;_addressStack=Array(a).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Aa(t);null===n&&J("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&J("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=a&&(this._hasRepeatedAddress()&&J(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),J(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const n=this._addressStack[e];if(n){if(t.has(n))return!0;t.add(n)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&J(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return fd(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&J("This state is readonly."),function(t,e,n,o,s){if("string"==typeof e){const r=Pu(e),i=ld(t,r,o,s);return od(t,Nn(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}}const md=new WeakMap;class gd{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=md.get(t);return n?n.get(e)??null:null}(t,e)??J("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const yd=t=>()=>t;function bd(t,e,n,o){!function(t,e,n){let o=md.get(t);o||(o=new Map,md.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(function(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}(o));const s=function(t,e){const n=new gd(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:yd(s),enumerable:!0,configurable:!0}),as(e,n),wd(e,n)}function wd(t,e){if(k in t){const n=t[k];"function"==typeof n?n.call(t,e).catch(t=>{J(`Error in ${k}: ${t instanceof Error?t.message:String(t)}`)}):J(`${k} is not a function.`)}}const vd=new Set;function _d(t,e){vd.has(t)||(vd.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function $d(t){const e=t.rootEntry,n=xe(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Be](n,()=>{o=t[e.outerPathInfo.path]})}),o}function Sd(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(kr(t.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function Nd(t,e,n){!function(t,e,n){const o=n[R];if(void 0!==o){"object"==typeof o&&null!==o||J(`${R} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&J(`${R} entry "${t}" must be a function.`),yc(t)}const r=n[B];if(void 0!==r){"object"==typeof r&&null!==r||J(`${B} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(r))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&J(`${B} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+s+n)&&J(`${B} entry "${e+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&J(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&J(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[D]&&J(`Volume "${e}" declares ${D}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys(Ml(n)))-1!==t.indexOf(W)&&J(`Volume "${e}" declares "${t}", which uses "${W}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n);const{data:o,accessors:r}=function(t){const e={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(t)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(e[o]=s.value):n.set(o,s));return{data:e,accessors:n}}(n),i=Y(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;J(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],r=""===n?o in t:void 0!==t[n+s+o];n=""===n?o:n+s+o,r||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(a)return;J(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=o}),function(t,e){let n=Ir.get(t);void 0===n&&(n=new Set,Ir.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,o]of r){const r=e+s+n,i=o.get,a=o.set,l={enumerable:!1,configurable:!0};"function"==typeof i&&(l.get=function(){return i.call(kr(e,this))}),"function"==typeof a&&(l.set=function(t){a.call(kr(e,this),t)}),t.defineTreeAccessor(r,l)}!function(t,e,n){const o=n[R];if(void 0!==o){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(o)){const o=e+s+a,c=function(t,n,...o){l.call(kr(e,this),t,n,...o)};n.push({path:o,pathInfo:Y(o),handler:c,order:1e6+i++}),r.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(function(t,e){let n=dc.get(t);void 0===n&&(n=new Map,dc.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}(t,n),t.addVolumeWatchPaths?.(r),Zc(t))}const r=n[B];if(void 0!==r){const n=new Map;for(const[t,o]of Object.entries(r))n.set(e+s+t,o);t.mergeVolumeListKeys?.(n)}const i=n[P];"function"==typeof i&&(function(t,e){let n=Ar.get(t);void 0===n&&(n=[],Ar.set(t,n)),n.push(e)}(t,{mountPath:e,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}(t,e,n);const l=n.$connectedCallback;return"function"==typeof l&&t.createState("writable",t=>{let n;try{n=l.call(kr(e,t))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function xd(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=Nd(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}Or=xd;const Pd=new Set(["for","if","elseif","else"]);class Id extends ra{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return Ea(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new gl}();_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;_volumeGraftInfo=null;_volumeInitializing=!1;_volumeMountPath=null;_volumeSlotRootNode=null;_volumeDetachedFrom=null;_mountRecord=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_dcc=!1;_connectGeneration=0;_streamsStartedGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&J(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){const n=this.__state,o=function(t){const e=t[D];if(void 0===e)return null;"object"==typeof e&&null!==e||J(`[wcs/recursion-declaration-invalid] ${D} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(e);0===n.length&&J(`[wcs/recursion-declaration-invalid] ${D} must declare exactly one anchor; it is empty.`),n.length>1&&J(`[wcs/recursion-declaration-invalid] ${D} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,i]=n[0];Tl("anchor",o),"string"!=typeof i&&J(`[wcs/recursion-declaration-invalid] ${D} entry "${o}" must map to the repeating sub-path as a string (for example "children${s}${r}").`),Tl("repeating sub-path",i);const a=o.slice(0,o.lastIndexOf(s)),l=i.slice(0,i.lastIndexOf(s)),c=a+s+W;return Object.freeze({anchor:o,repeat:i,recursiveAnchor:c,anchorList:a,repeatList:l})}(t),i=null===o?null:new Ql(o,t),a=function(t){const e=new Set,n=t[C];if(void 0===n)return e;Array.isArray(n)||J(`${C} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||J(`${C} entries must be non-empty strings.`),t===T&&J(`${C} entry "${t}" conflicts with the reserved namespace name "${T}".`),e.has(t)&&J(`${C} entry "${t}" is duplicated.`),e.add(t);return e}(t),l=function(t){const e=new Set,n=t[M];if(void 0===n)return e;Array.isArray(n)||J(`${M} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||J(`${M} entries must be non-empty strings.`),e.has(t)&&J(`${M} entry "${t}" is duplicated.`),e.add(t);return e}(t),c=function(t){const e=t[B];if(void 0===e)return null;"object"==typeof e&&null!==e||J(`${B} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&J(`${B} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&J(`${B} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&J(`${B} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),-1!==t.indexOf(W)&&J(`[wcs/recursion-unsupported] ${B} entry "${t}" uses "${W}", which ${B} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${s}${r}${s}children").`),"function"!=typeof o?("string"!=typeof o&&J(`${B} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&J(`${B} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&J(`${B} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&J(`${B} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t),u=function(t,e,n=null){const o=t[j];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&J(`${au} ${j} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${bt}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(Ml(t)))"function"==typeof n.get?s.add(e):"function"==typeof n.set&&i.add(e),"function"==typeof n.set&&r.add(e),"function"==typeof n.value&&a.set(e,n.value);const l=function(t){const e=t[L];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];let u=0;for(const[t,d]of Object.entries(o)){fu(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&J(`${au} ${cu(t)} must be an object ({ from | on, initial, fold, resetOn? }).${bt}`);const o=d;pu(t,a,o);const h=mu(t,o,e,s,i,n);"initial"in o||J(`${au} ${cu(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${bt}`),"function"!=typeof o.fold&&J(`${au} ${cu(t)} fold must be a function.${bt}`);const f=gu(t,o.resetOn,h,s);c.push({name:t,source:h,fold:o.fold,initial:o.initial,resetOn:f,order:u++})}return function(t){const e=new Set(t.map(t=>t.name)),n=new Map;for(const o of t){for(const t of o.resetOn){const n=Y(t).segments[0];e.has(n)&&J(`${au} ${cu(o.name)} resetOn "${t}" reads the ${j} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${bt}`)}if("path"===o.source.kind){const t=o.source.pathInfo.segments[0];e.has(t)&&n.set(o.name,t)}}for(const t of n.keys()){const o=[t];let s=n.get(t);for(;void 0!==s&&o.length<=e.size;)s===t&&J(`${au} ${j} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${bt}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}(t,l,i);if(null!==this._recursionRegistry)for(const t of this._recursionRegistry.forgetGenerated(this,n))this._generatedPaths.add(t);this._recursionRegistry=i,this._commandTokenNames=a,this._eventTokenNames=l,this._stateGeneration++,this.__state=t,void 0!==n&&(Ur.delete(this),Gr.delete(this)),this._hasUpdatedCallback=P in t,this._hasErrorCallback=I in t,function(t){jn.delete(t)}(this),null!==u&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=Cc(n.initial);t[n.name]=e,Lc(n.name,e)}}(t,u),function(t,e){for(const n of e)"event"===n.source.kind&&Dn(t,n.source.tokenName).subscribe(yu(n))}(this,u)),function(t,e,n){const o=e[O];if(void 0!==o){"object"==typeof o&&null!==o||J(`${O} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||J(`${O} entry "${e}" is not declared in $eventTokens.${yt(e,n)}`),"function"!=typeof s&&J(`${O} entry "${e}" must be a function.`),Dn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const d=function(t){const e=new Set,n=new Set,o=Ml(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of d.getterPaths)this._getterPaths.add(t);for(const t of d.setterPaths)this._setterPaths.add(t);nc(this),function(t){Al(t),Pl(t),Il.delete(t)}(this),function(t,e){const n=e[L];if(void 0===n)return void Sl(t,Cl);"object"==typeof n&&null!==n||J(`${L} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[i,a]of Object.entries(n)){0===i.length&&J(`${L} entry name must be a non-empty string.`),i.includes(s)&&J(`${L} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&J(`${L} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&J(`${L} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&J(`${L} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&J(`${L} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&J(`${L} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||J(`${L} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&J(`${L} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&J(`${L} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&J(`${L} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&J(`${L} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??El,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};i in e||(e[i]=c.definition.initial),o.set(i,c)}!function(t,e){Il.set(t,e)}(t,o),Sl(t,new Set(o.keys()))}(this,t),this._listKeys=c,null!==o&&this._listPaths.add(o.anchorList),this._rebuildPathInfo();const h=function(t){const e=new Map,n=Ha(t);if(void 0!==n)for(const t of n.entries)Qa(t)&&e.set(t.name,t.resetOn);return qa(t),e}(this);this._scanPaths=null===u?null:function(t,e,n){const o=function(t,e){qa(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&Fa(n,t.source.path,t);for(const e of t.resetOn)Fa(o,e,t),"event"===t.source.kind&&Fa(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return Da.set(t,r),r}(t,e);for(const o of e){const e=n.get(o.name);"event"===o.source.kind&&void 0!==e&&o.resetOn.some(n=>e.includes(n)&&el().hasQueuedPath(t,n))&&Ja(o)}const s=new Set;for(const e of o.byFromPath.keys())s.add(e),t.setPathInfo(e,"prop","scan");for(const e of o.byResetPath.keys())t.setPathInfo(e,"prop","scan");return s.size>0?s:null}(this,u,h),function(t){hc.delete(t),Ua(t),uc.delete(t)}(this),function(t){bc.delete(t)}(this),this._watchPaths=function(t,e){const n=e[R];if(void 0===n)return null;"object"==typeof n&&null!==n||J(`[wcs/watch-declaration-invalid] ${R} must be an object mapping state paths to handler functions.${bt}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&J(`[wcs/watch-declaration-invalid] ${R} entry "${e}" must be a function.${bt}`);const n=yc(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){uc.set(t,e)}(t,o),s.size>0?s:null}(this,t),this._initialized&&null!==this._rootNode&&!e()&&(Zc(this),ac(this),this._streamsStartedGeneration=this._connectGeneration),this._resolveLoading?.()}attributeChangedCallback(t,e,n){this._initialized&&e!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===e?"absent":`"${e}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){if(!this.hasAttribute("enable-ssr"))return null;const t=this.parentNode;if(!t)return null;const e=da.find(t);if(!e)return null;const n=e.stateData;return Object.keys(n).length>0?n:null}async _loadStateFromSource(){try{if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){J("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await pl(t,o.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||J(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await ml(t);J(`Unsupported src file type: ${t}`)}}catch(t){J(`Failed to initialize state: ${t}`)}}async _initializeVolume(){const t=this._rootNode,e=this.getAttribute("mount");try{!function(t){0===t.length&&J('"mount" requires a non-empty tree path.');const e=Y(t);for(const n of e.segments)0===n.length&&J(`"mount" path "${t}" has an empty segment.`),n===r&&J(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&J(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(e),this.hasAttribute("bind-component")&&J('"mount" cannot be combined with "bind-component".'),this.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),xr(t,e,this),this._volumeMountPath=e,this._volumeSlotRootNode=t}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}this._volumeInitializing=!0,null===Aa(t)&&function(t,e){const n=()=>{if(null!==Aa(t))return;const n=t.querySelectorAll(o.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=t.ownerDocument??t;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(t,e);const n=t=>{this._volumeGraftInfo=t,this._initialized=!0,null===t&&this._releaseVolumeSlot(),this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()};let s;try{s=await this._loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${e}" failed to load.`,t),void n(null)}if(null===this._rootNode)return void n(null);const i=this._rootNode;this._acquireVolumeSlot(i)?function(t,e,n,o,s,r){const i={mountPath:n,volumeState:o,onGrafted:s,acquireSlot:r};null===e?function(t,e){if(Tr.has(t))return void Mr(e);let n=Cr.get(t);void 0===n&&(n=[],Cr.set(t,n)),n.push(e)}(t,i):xd(e,i)}(i,Aa(i),e,s,n,()=>this._acquireVolumeSlot(i)):n(null)}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}return await this._loadingPromise,null!==this._rootNode&&(Ma(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),J(t)}_failInitializeLoudly(t){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),null!==this._rootNode&&null===Aa(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),Ia.set(t,n)}(this._rootNode,t),function(t){Tr.add(t);const e=Cr.get(t);if(void 0!==e){Cr.delete(t);for(const t of e)Mr(t)}}(this._rootNode)),t}async _initializeBindWebComponent(){if(this.hasAttribute("bind-component")){const i=this.parentNode,a=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,l=a?et(a):null;null!==a&&null!==l||J(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||a.hasAttribute(o.bindAttributeName)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${this.getAttribute("bind-component")}: path").`);const c=["state","src","json"].filter(t=>this.hasAttribute(t));null!==this.querySelector('script[type="module"]')&&c.push('<script type="module">'),c.length>0&&J(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const u=this.getAttribute("bind-component");!function(t,e){let n=ls.get(t);n||(n=new Set,ls.set(t,n)),n.add(e)}(a,u);const d=ot(a);null===d&&J(`CustomElementRegistry is unavailable for <${l}>.`),await d.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await V(a),u in a||J(`Component does not have property "${u}" for state binding.`);let h=a[u];"object"==typeof h&&null!==h||J(`Component property "${u}" is not an object for state binding.`);const f=function(t,e){const n=ki.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,u);if(void 0!==f&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=mt(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,u)&&(a[u]=f,h=f),this._boundComponent=a,this._boundComponentStateProp=u,i instanceof ShadowRoot||(mt(a)??[]).some(t=>t.propSegments[0]===u)||this._failInitialization(`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${l}>, or mount it from the host (data-wcs="${u}: path").`),a.hasAttribute(o.bindAttributeName)){const o=(mt(a)??[]).filter(t=>t.propSegments[0]===u);if(o.length>0){const c=Aa(a.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${l}>.`);let d=(n=a,r=u,ge.get(n)?.get(r)??null);const f=null!==d;if(null===d&&(function(t,e,n){const o=Ei.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;Ei.get(t).delete(e)}}(a,u,h),d=function(t,e,n,o,r,i=new Set){0===n.length&&J(`Cannot build a mount record without host bindings for "${e}".`);const a=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(s);l.has(n)&&J("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo};a.push(o),0===e.length&&(c=o)}a.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++ee,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(r),p={};for(const t of Object.keys(r))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof r[t]&&(i.has(t)||(p[t]=r[t]));return{id:u,marker:d,component:t,stateProp:e,parentStateElement:o,entries:a,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?d:c.outerPathInfo.path+s+d,stateObject:r,getterKeys:h,setterKeys:f,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(a,u,o,c,h,(t=a,e=u,Ai.get(t)?.get(e))),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp,s=new Map;for(const e of t.entries)1===e.innerSegments.length&&s.set(e.innerSegments[0],e.outerPathInfo.path);let r,i=!1;for(const a of e){const e=s.get(a);if(void 0!==e){_d(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted entry "${o}.${a}: ${e}" (the host value no longer reaches it). Remove the default to read the tree, or rename it to keep it private.`);continue}if(null===t.rootEntry)continue;if(i||(r=$d(t),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=t.rootEntry.outerPathInfo.path;_d(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted tree key "${l}.${a}" (${o}: ${l}). Remove the default to read the tree, or rename it to keep it private.`)}}(d)),this._mountRecord=d,this.parentNode!==i)return;try{oi(d,i instanceof ShadowRoot?i:a)}catch(t){throw this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}if(!f){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=xe(t.component);let s;return e[Be](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(t,e,n){const o=t.parentStateElement,s=(t,e)=>{let s;return o.createState(t,t=>{s=n(t,()=>e(t))}),s};return"$postUpdate"===e?e=>s("readonly",n=>n.$postUpdate(fe(t,e))):(n,o,...r)=>{const i=fe(t,n),a=xe(t.component)?.listIndex.indexes??[],l=pe(0,n,i,"$resolve"===e?o??[]:o,a),c="$setAll"===e||"$resolve"===e&&r.length>0?"writable":"readonly";return s(c,t=>t[e](i,l,...r))}}(t,s,n);let r;return e.createState("readonly",e=>{r=n(e,()=>e["$"===s[0]?s:fe(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:fe(t,s)]=r})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return fe(t,n),!0}catch{return!1}}})}(d);Object.defineProperty(a,u,{get:()=>t,enumerable:!0,configurable:!0}),as(a,u)}return wd(a,u),function(t){const e=ne.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(W)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;oe.has(n)||(oe.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(d),void se(d,"$connectedCallback")}}bd(this,this._boundComponent,this._boundComponentStateProp,h)}var t,e,n,r}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{N in t&&await t[qe]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await ml(t):J(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await pl(e,t.tagName.toLowerCase()):J(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){J(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||J(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=ot(t);null!==r&&"function"==typeof r.define||J(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&J(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const t of Array.from(e.childNodes))i.content.appendChild(a.importNode(t,!0));const l=e.mode,{bindables:c,commands:u,streamBackedBindables:d}=function(t){const e=Su(t,A)??[],n=Su(t,E)??[],o=Ml(t),s=function(t){const e=t[L];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}J(`${A} entry "${t}" is not declared on the state.${yt(t,$u(o,"value"))}`)}"function"==typeof e.value&&J(`${A} entry "${t}" is a method. Declare it in ${E} instead.`)}for(const t of n){const e=o[t];void 0===e&&J(`${E} entry "${t}" is not declared on the state.${yt(t,$u(o,"method"))}`),"function"!=typeof e.value&&J(`${E} entry "${t}" is not a method. Declare it in ${A} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||u.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(H))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=ot(this._shadow);return null!==t&&st(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(m.bindableEventMap).length>0){const e=t.querySelector(p);e?e.setBindableEventMap(m.bindableEventMap):console.warn(`[@wcstack/state] DCC: "${s}" declares ${A} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=Ml(n);for(const[t,e]of Object.entries(g)){if(_u(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=vu(t,o)}else n.get=bu(t),n.set=wu(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:bu(t),set:wu(t)});r.define(s,m)}(t,e,n),this._dcc=!0,this._initialized=!0,this._rootNode=null,this._resolveInitialize?.(),this._resolveConnectedCallback?.()}_callStateDisconnectedCallback(){this.createState("writable",t=>{x in t&&t[Ue]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Aa(this._rootNode)===this._volumeGraftInfo.rootStateElement&&Sd(this._volumeGraftInfo,"$connectedCallback"),void this._resolveConnectedCallback?.();if(null!==this._mountRecord){const t=this._mountRecord,e=this.parentNode;return queueMicrotask(()=>{null!==this._rootNode&&si(t,e)}),se(t,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||Aa(this._rootNode)===this||Ma(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=this.parentNode;if(e instanceof ShadowRoot&&e.host.hasAttribute(H)){try{this.hasAttribute("bind-component")&&J(`"bind-component" cannot be used inside a [${H}] host. DCC state comes from the template, not from a component property.`),await this._initializeDCC(e.host,e)}catch(t){this._failInitializeLoudly(t)}return}if(this.hasAttribute("mount")){if(this._volumeInitializing){if(this._volumeDetachedFrom===this._rootNode)try{xr(this._rootNode,this._volumeMountPath,this),this._volumeSlotRootNode=this._rootNode}catch{}return void(this._volumeDetachedFrom=null)}return void await this._initializeVolume()}try{await this._initializeBindWebComponent()}catch(t){this._failInitializeLoudly(t)}if(null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();let n=!1;try{n=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!n)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!e()||t!==this._connectGeneration||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await Ea(this.rootNode);const t=da.extractStateData(this),e=document.createElement(o.tagNames.ssr);e.setAttribute("version",sa),da.buildContent(e,t),this.parentNode?.insertBefore(e,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||Zc(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||ac(this),this._resolveConnectedCallback?.()}_releaseVolumeSlot(){null!==this._volumeSlotRootNode&&(function(t,e,n){const o=Nr.get(t);o?.get(e)===n&&o.set(e,null)}(this._volumeSlotRootNode,this._volumeMountPath,this),this._volumeSlotRootNode=null)}_acquireVolumeSlot(t){if(this._volumeSlotRootNode===t)return!0;const e=this._volumeMountPath;try{xr(t,e,this)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> will not graft: another volume already holds the "${e}" slot on this root. Keep one volume per mount path.`),!1}return this._volumeSlotRootNode=t,!0}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Sd(this._volumeGraftInfo,"$disconnectedCallback"),this._initialized||(this._volumeDetachedFrom=this._volumeSlotRootNode,this._releaseVolumeSlot()),void(this._rootNode=null);if(null!==this._mountRecord)return se(this._mountRecord,"$disconnectedCallback"),ni(this._mountRecord),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&(t=this._rootNode,Tr.delete(t)),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Ma(this.rootNode,null),wl.delete(this),Al(this),nc(this),function(t){hc.delete(t),Ua(t)}(this),this._rootNode=null}}var t}get initialized(){return this._initialized}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&J(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return jr(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&J("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0}get hasGraftedVolumes(){return this._hasGraftedVolumes}markHasGraftedVolumes(){this._hasGraftedVolumes=!0}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(t);void 0===o?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:o.bound||"binding"===n})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+r)),!this._pathSet.has(t)){const e=Y(t);if(this._pathSet.add(t),function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;if(Pr(!1===t.isConnected?null:t.rootNode??null,n))return;const i=Y(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=Ur.get(t);return void 0===n&&(n=new Set,Ur.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const a=function(t,e,n){if(void 0!==jr(t,e))return Rr;const o=Y(e).segments;let i=t,a="";for(let e=0;e<o.length;e++){const l=o[e],c=a;if(a=0===e?l:a+s+l,e>0&&e<o.length-1&&void 0!==jr(t,a))return Lr;if(Object(i)!==i)return Lr;if(l===r){if(!Array.isArray(i)||0===i.length)return Lr;i=i[0];continue}const u=jr(i,l);if(void 0===u)return{existence:"missing",missingSegment:l,candidates:Dr(i,c,n)};if("function"==typeof u.get)return e===o.length-1?Rr:Lr;i=u.value}return Rr}(e,n,t.getterPaths);"missing"===a.existence&&(function(t,e){return!0===Kr.get(t)?.has(e)}(t,n)||("binding"!==o?Qr(0,n,o,a):function(t,e,n){let o=Gr.get(t);void 0===o&&(o=new Map,Gr.set(t,o)),o.set(e,n),Vr.has(t)||(Vr.add(t),setTimeout(()=>function(t){Vr.delete(t);const e=Gr.get(t);if(void 0!==e){Gr.delete(t);for(const[t,n]of e)Qr(0,t,"binding",n)}}(t),0))}(t,n,a)))}(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=Y(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,n){try{const o=function(t,e,n){const o=new pd(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&J(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);this._volumeInitializing&&J(`Cannot replace the state of <${o.tagNames.state} mount="${this.getAttribute("mount")}"> 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 "${this.getAttribute("mount")}" on the root state instead.`),(this._hasGraftedVolumes||this._hasMounts)&&J("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const e=this.__state;this._state=t;const n=function(t){const e=new Set;for(const n of t)if(void 0!==n)for(const[t,o]of Object.entries(Ml(n)))t.startsWith("$")||t.includes(r)||"function"==typeof o.value||e.add(t);return e}([e,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){!function(t,n,o){const s=new Map;for(const t of o){const e=Y(t);if(null===e.lastWildcardPath)continue;const n=s.get(e.lastWildcardPath);void 0===n?s.set(e.lastWildcardPath,[e]):n.push(e)}const r=[],i=new Set,a=e=>{const n=tn(Je(t,e.pathInfo),e.listIndex);if(i.has(n))return;i.add(n);const o=vn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==e.listIndex){const t=s.get(e.pathInfo.path);if(void 0!==t)for(const n of t)a(Nn(n,e.listIndex))}};je();try{if(t.createState("readonly",e=>{for(const o of n){const n=Nn(Y(o),null);a(n);try{Yu(t,n,t.staticDependency,t.dynamicDependency,t.listPaths,e,"new",a)}catch{}}}),0===r.length)return;const o=function(t){const e=[],n=[];for(const o of t)Pd.has(o.bindingType)?e.push(o):n.push(o);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(n)}(r),s=()=>{ta(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=ci("state",s);void 0!==i&&i.catch(Za)}finally{De()}}(this,t,this._pathRegistrations.keys())}}await function(){const e=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(void 0);var s;e&&((s=e).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)),function(t=customElements){t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,da),t.get(o.tagNames.state)||t.define(o.tagNames.state,Id)}(void 0),function(){const t=globalThis;void 0===t[ya]&&(t[ya]=xa)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=dl)}(),ul()}();const kd={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},Ad=!1,Ed=[".html"];function Cd(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function Td(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let Md=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const Od={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function Ld(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function Rd(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}const jd={static:2,param:1,"catch-all":0};let Dd=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&Td(`${kd.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&Td(`${kd.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=jd[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(Od).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||Td(`${kd.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath,o=await this._guardHandler(e,n,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:Ld(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new Md("Navigation cancelled by guard.",o);if(!o)throw new Md("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new Md("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},Wd=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=Cd();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new Dd(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||Td(`${kd.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):Td(`${kd.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&Td(`${kd.route} with fallback attribute must be a direct child of ${kd.router}.`),t.fallbackRoute&&Td(`${kd.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const Bd=Symbol.for("wcstack.trustedTypes.policy"),zd=Symbol.for("wcstack.trustedTypes.internal"),Fd="wcstack";function Hd(){const t=globalThis[Bd];return null===t||"object"!=typeof t?null:t}let qd=!1;function Ud(t){const e=function(){const t=globalThis,e=t[zd];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Fd,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof Hd()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Fd}". Allow it in the CSP (\`trusted-types ${Fd};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[zd]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Hd(),s=o?.createHTML;return"function"==typeof s?(qd||(qd=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Fd}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Fd};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Gd=new Map;let Vd=class extends HTMLElement{_uuid=Cd();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||Td(`${kd.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Gd.set(t,n),n}catch(e){Td(`${kd.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${kd.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Gd.has(t)?n.innerHTML=Ud(Gd.get(t)||""):n.innerHTML=Ud(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Ud(t):console.warn(`${kd.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Ad}get name(){return this.getAttribute("name")||""}},Kd=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||Td(`${kd.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Ad}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Jd=new Set(["props","states","attr",""]);function Qd(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function Xd(t,e){t.hasAttribute("data-bind")||Td(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Jd.has(n)||Td(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&Qd(t,e,o)}).catch(()=>{Td(`Failed to define custom element: ${s}`)}):Qd(t,e,o)}let Yd=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||Td(`${kd.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${kd.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{Xd(e,t)}),e.hasAttribute("data-bind")&&Xd(e,t))}};function Zd(){return document.createElement(kd.layoutOutlet)}const th="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function eh(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){Td(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${th}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${th}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function nh(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function oh(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===kd.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),nh(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===kd.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&eh(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===kd.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=Zd();o.layout=n,i=o,a=e}}const c=await oh(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function sh(t){const e=new Map;return await oh(t,t.template.content,[],e)}function rh(t){return!1!==t.checkVisibility?.()}function ih(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",n=Od[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)ih(s,e,n,o)}function ah(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)ih(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let lh=null,ch=null;function uh(){const t=Ed;return 0===t.length?null:(lh===t&&ch||(lh=t,ch=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),ch)}function dh(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=uh();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function hh(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function fh(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=uh();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function ph(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function mh(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{Xd(e,t.typedParams)}),n.hasAttribute("data-bind")&&Xd(n,t.typedParams),n.querySelectorAll(kd.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===kd.layoutOutlet&&n.assignParams(t.typedParams)}}function gh(t,e){mh(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const yh=Symbol.for("wcstack.transition-runner");const bh=Symbol.for("wcstack.binder");function wh(){const t=globalThis[bh];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const vh=Symbol.for("wcstack.binder.pending"),_h=Symbol.for("wcstack.binder.taken");function $h(){const t=globalThis;let e=t[_h];return void 0===e&&(e=new WeakSet,t[_h]=e),e}function Sh(t){const e=wh();return null===e?(function(){const t=globalThis;let e=t[vh];return void 0===e&&(e=[],t[vh]=e),e}().push(t),!1):($h().add(t),e.bind(t),!0)}const Nh=new WeakSet,xh="data-wcs";function Ph(t,e,n){!Nh.has(t)&&function(t){return t.hasAttribute(xh)||null!==t.querySelector(`[${xh}]`)}(t)&&(Nh.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==wh()||(o=t,$h().has(o))||console.warn(`[@wcstack/router] ${e} contains ${xh} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function Ih(t){for(const e of t.childNodeArray)1===e.nodeType&&(Sh(e)||Ph(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.'))}async function kh(t,e){try{let t=null;for(const n of e.routes){const o=await n.guardCheck(e);o&&(t=null===t?o:Object.assign({},t,o))}e.data=t}catch(e){if(e instanceof Md)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function Ah(t,e,n,o,s=""){const r=hh(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:s,path:r}),!0;let i=ah(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:Td(`${kd.router} No route matched for path: ${r}`)),i.lastPath=o,i.search=s;const a=e.lastRoutes,l=await async function(t,e,n){if(!await kh(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||ph(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=gh(o,e),n.length>0&&!s.has(o)&&Ih(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[yh];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",data:i.data??null,search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(rh(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(rh(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(t,i),!0)}function Eh(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Ch(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function Th(t){return"?"===t?"":t}function Mh(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function Oh(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Lh="data-wcs-ssr",Rh="data-wcs-ssr-link",jh="@@wcs-route-ph:",Dh="@@wcs-route-start:",Wh="@@wcs-route-end:",Bh=Object.freeze({});class zh extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Bh;_typedParams=Bh;_searchParams=Bh;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return dh(t)}_normalizeBasename(t){return fh(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(kd.outlet))return t;const e=document.createElement(kd.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||Td(`${kd.router} has no outlet.`),this._outlet}get template(){return this._template||Td(`${kd.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=Ld(t.search),s=t.data??null,r=this._data!==s,i=!Rd(this._params,e),a=this._routeName!==t.routeName,l=!Rd(this._searchParams,o),c=this._path!==t.path;r&&(this._data=s),i&&(this._params=e,this._typedParams=n),a&&(this._routeName=t.routeName),l&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,r&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${kd.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${kd.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=Ch(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Th(n.search)+n.hash,r=Eh();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(hh(t,this._basename));await Ah(this,this.outlet,t,this._path,Th(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(hh(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await Ah(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${kd.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await Ah(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=Oh();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||Td(`${kd.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||Td(`${kd.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await sh(this),r=!t&&this._outlet.hasAttribute(Lh);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&Td(`${kd.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(Lh);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await Ah(this,this.outlet,i,this._path,window.location.search||""),(r||null!==wh())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(kd.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(jh)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Dh)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith(Wh)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=hh(t,this._basename);let d=ah(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of d.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(Dh)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===kd.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(Lh);for(const t of d.routes)mh(t,d);return this.outlet.lastRoutes=d.routes,!await kh(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(t){const e=hh(t,this._basename),n=ah(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&Td(`${kd.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await Ah(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${jh}${t.absolutePath}`}),this.outlet.setAttribute(Lh,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${Dh}${t.absolutePath}`),s=document.createComment(`${Wh}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&Sh(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Mh(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),Oh()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Eh();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Eh()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Fh=["title","rel","target","download","hreflang","lang","dir"];class Hh extends HTMLElement{static get observedAttributes(){return["to",...Fh]}_childNodeArray=[];_uuid=Cd();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(kd.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(kd.router);if(n)return this._router=n;Td(`${kd.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return dh(t)}_joinInternalPath(t,e){const n=fh(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=Ch(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+Th(o)+s}else try{t.href=new URL(e).toString()}catch{Td(`[${kd.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){Oh()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Rh)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(Rh),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||Fh.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,Oh())return this._updateActiveState(),void n.setAttribute(Rh,"");Eh()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Eh()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Eh()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Fh.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=Ch(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const qh=[],Uh=new Map;let Gh=!1;const Vh=new WeakMap;class Kh extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Gh||(this._captureInitialHead(),Gh=!0),qh.push(this),this._reapplyHead()}disconnectedCallback(){const t=qh.indexOf(this);-1!==t&&qh.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||Td("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Vh.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Vh.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Uh.has(t)||Uh.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of qh)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Uh.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=qh.length-1;e>=0;e--){const o=qh[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Uh.has(n)&&(t=Uh.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),Sh(t)||Ph(t,`<${t.tagName.toLowerCase()}> inside <${kd.head}>`,`<${kd.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(kd.layout)||t.define(kd.layout,Vd),t.get(kd.layoutOutlet)||t.define(kd.layoutOutlet,Yd),t.get(kd.outlet)||t.define(kd.outlet,Kd),t.get(kd.route)||t.define(kd.route,Wd),t.get(kd.router)||t.define(kd.router,zh),t.get(kd.link)||t.define(kd.link,Hh),t.get(kd.head)||t.define(kd.head,Kh)}(void 0);const Jh="data-fetchtarget",Qh={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Xh=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function Yh(t,e){return e.every(e=>"available"===t.availability.get(e))}const Zh=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let tf=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new Xh("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return Yh(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),u=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",d=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:u,userActivation:d},epoch:e.epoch??0,lastError:e.lastError}}(Zh,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!Yh(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:u="auto",timeout:d=0}=e;let h=null;d>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},d));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===u)s=await n.blob();else if("arrayBuffer"===u)s=await n.arrayBuffer();else if("text"===u)s=await n.text();else if("json"===u)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,d)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},ef=!1;function nf(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Jh}]`);if(!n)return;const o=n.getAttribute(Jh);if(!o)return;const s=customElements.get(Qh.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function of(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}const sf=Symbol.for("wcstack.trustedTypes.policy");function rf(){const t=globalThis[sf];return null===t||"object"!=typeof t?null:t}let af,lf=!1;let cf=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...tf.wcBindable,properties:[...tf.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new tf(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(Qh.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(Qh.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&function(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=rf(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==af)return af;if(!("trustedTypes"in globalThis))return af=!1,af;try{document.createElement("div").innerHTML="<i></i>",af=!1}catch{af=!0}return af}())return void function(){if(lf)return;lf=!0;const t="function"==typeof rf()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}(t,s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!of(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",ef||(ef=!0,document.addEventListener("click",nf)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class uf extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class df extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let hf=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof cf&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(Qh.fetch)||t.define(Qh.fetch,cf),t.get(Qh.fetchHeader)||t.define(Qh.fetchHeader,uf),t.get(Qh.fetchBody)||t.define(Qh.fetchBody,df),t.get(Qh.infiniteScroll)||t.define(Qh.infiniteScroll,hf)}(void 0);const ff="data-storagetarget",pf={storage:"wcs-storage"},mf="wcs-storage:value-changed",gf="wcs-storage:loading-changed",yf="wcs-storage:error",bf="wcs-storage:error-info-changed",wf="wcs-storage:trigger-changed";let vf=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:mf,semantics:"state",getter:t=>t.detail},{name:"loading",event:gf,semantics:"state"},{name:"error",event:yf,semantics:"state"},{name:"errorInfo",event:bf,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(gf,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(yf,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(bf,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(mf,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},_f=!1;function $f(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${ff}]`);if(!n)return;const o=n.getAttribute(ff);if(!o)return;const s=customElements.get(pf.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function Sf(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let Nf=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...vf.wcBindable,properties:[...vf.wcBindable.properties,{name:"trigger",event:wf,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new vf(this),this._internals=this._initInternals(),this._wireStates({[gf]:t=>({loading:!0===t}),[yf]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(wf,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Sf(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",_f||(_f=!0,document.addEventListener("click",$f)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(pf.storage)||t.define(pf.storage,Nf)}(void 0);const xf="*",Pf="vanilla",If={scanImportmap:!0,loaders:{[Pf]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[xf]:Pf},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function kf(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function Af(t,e,n){let o;if(null===e||e===xf||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===xf)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[xf],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const Ef=new Set,Cf=new Map;let Tf=new WeakMap;function Mf(t){if(t===globalThis.customElements)return Cf;let e=Tf.get(t);return void 0===e&&(e=new Map,Tf.set(t,e)),e}const Of=new Map;async function Lf(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of Of)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){Ef.has(e)||(console.error(`Failed to eager load component '${e}':`,t),Ef.add(e))}}function Rf(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function jf(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&Of.set(t,e)});const Df=new WeakSet,Wf=new WeakSet;async function Bf(t,e,n){t.shadowRoot&&(Df.has(t)||await async function(t,e,n){Df.add(t),await qf(t.shadowRoot,e,n)}(t,e,n))}async function zf(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=Mf(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=Af("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),Ef.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Ff(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=jf(t);void 0===o.get(s.name)?(Wf.has(t)||(Wf.add(t),o.whenDefined(s.name).then(async()=>{await Bf(t,e,n)})),a.has(s.name)||Ef.has(s.name)||(a.add(s.name),i.push(s))):await Bf(t,e,n)}let l=0;for(const t of i)await zf(t,e,n,o),l++;return l}async function Hf(t,e,n,o){for(;await Ff(t,e,n,o)>0;);}async function qf(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return Rf(e)}return Rf(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Hf(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await Hf(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Uf extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Uf._instance)throw new Error(`${If.tagNames.autoloader} can only be instantiated once.`);Uf._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=kf(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=Af(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(Lf(s,o,r))}await Promise.all(n)}(n,If.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await qf(document,If,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Uf._instance===this&&(Uf._instance=null)}}!function(t=customElements){t.get(If.tagNames.autoloader)||t.define(If.tagNames.autoloader,Uf)}(void 0);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|