wcstack 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto.min.js +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="|",l="prevent",c="stop",d="ro",u="init",h="sync",f="else",p="...",m="on",g="eventToken",y="command",b="class",w="attr",_="style",v={};for(let t=0;t<128;t++)v[`$${t+1}`]=t;const N=Object.freeze(v),S="$connectedCallback",$="$disconnectedCallback",x="$updatedCallback",I="$errorCallback",P="$stateReadyCallback",k="$bindables",E="$commands",C="$commandTokens",A="$command",T="$eventTokens",M="$on",L="$streams",O="$watch",R="$listKeys",j="$streamStatus",D="$streamError",B="data-wc-definition",W=new WeakMap,z=new WeakSet;let F=0;async function H(t){const e=function(t){let e,n=W.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++F,promise:o,resolve:e},W.set(t,n),z.has(t)&&n.resolve(),n}(t);await e.promise}function U(t){const e=W.get(t);void 0===e?z.add(t):e.resolve()}const q=new Map;let G=0;function K(t){let e=q.get(t);return void 0!==e||(e=Object.freeze(new V(t)),q.set(t,e)),e}let V=class{id=++G;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:K(e),n=t.split("."),o=[],s=[],i=[],a={},l=[],c=[],d=[],u=[];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),d.push(e(f)),u.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=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}};const J=new WeakMap;function X(t){const e=J.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{J.set(t,n)}}function Q(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Y(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Q(e);if(void 0!==n)return Q(n)}return Q(globalThis.customElements)}function Z(t,e){t.upgrade?.(e)}function tt(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=st(s.properties,et);if(null===r)return null;const i=void 0===s.inputs?new Map:st(s.inputs,nt);if(null===i)return null;const a=void 0===s.commands?new Map:st(s.commands,ot);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function et(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 nt(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 ot(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 st(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 rt(t){throw new Error(`[@wcstack/state] ${t}`)}function it(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:K(n),inFilters:[],outFilters:[],bindingType:"prop"}}function at(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function lt(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&&rt("Spread binding requires an element node.");const e=t,o=X(e);null===o&&rt(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Y(e);if(null===a&&rt(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||rt(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Z(a,e);const l=tt(e);null===l&&rt(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const t of l.knownProperties.keys()){if(d.has(t))continue;d.add(t);const e=it(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(d.has(t))continue;d.add(t);const e=it(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=at(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=at(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 ct(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 dt=new WeakMap;function ut(t){return dt.get(t)||null}function ht(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 ft(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=ht(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const pt=" Validate statically: npx @wcstack/lint <file>.",mt=new Set(["if","elseif","else","for"]);function gt(t){rt(`filter ${t} requires at least one option`)}function yt(t){rt(`filter ${t} requires a number as option`)}function bt(t){rt(`filter ${t} requires a number value`)}function wt(t){rt(`filter ${t} requires a date value`)}function _t(t){return!(!t||isNaN(Number(t)))}const vt={eq:t=>{const e=t?.[0]??gt("eq");return t=>"number"==typeof t?(_t(e)||yt("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??gt("ne");return t=>"number"==typeof t?(_t(e)||yt("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&rt("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??gt("lt");return _t(e)||yt("lt"),t=>("number"!=typeof t&&bt("lt"),t<Number(e))},le:t=>{const e=t?.[0]??gt("le");return _t(e)||yt("le"),t=>("number"!=typeof t&&bt("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??gt("gt");return _t(e)||yt("gt"),t=>("number"!=typeof t&&bt("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??gt("ge");return _t(e)||yt("ge"),t=>("number"!=typeof t&&bt("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??gt("inc");return _t(e)||yt("inc"),t=>("number"!=typeof t&&bt("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??gt("dec");return _t(e)||yt("dec"),t=>("number"!=typeof t&&bt("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??gt("mul");return _t(e)||yt("mul"),t=>("number"!=typeof t&&bt("mul"),t*Number(e))},div:t=>{const e=t?.[0]??gt("div");return _t(e)||yt("div"),t=>("number"!=typeof t&&bt("div"),t/Number(e))},mod:t=>{const e=t?.[0]??gt("mod");return _t(e)||yt("mod"),t=>("number"!=typeof t&&bt("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&bt("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??gt("clamp");_t(e)||yt("clamp");const n=t?.[1]??gt("clamp");_t(n)||yt("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&bt("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return _t(e)||yt("fix"),t=>("number"!=typeof t&&bt("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&bt("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]??gt("slice");_t(n)||yt("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(_t(o)||yt("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??gt("substr");_t(e)||yt("substr");const n=t?.[1]??gt("substr");return _t(n)||yt("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??gt("pad");_t(e)||yt("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??gt("rep");return _t(e)||yt("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??gt("truncate");_t(e)||yt("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)||rt("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 _t(e)||yt("round"),t=>{"number"!=typeof t&&bt("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return _t(e)||yt("floor"),t=>{"number"!=typeof t&&bt("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return _t(e)||yt("ceil"),t=>{"number"!=typeof t&&bt("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return _t(e)||yt("percent"),t=>("number"!=typeof t&&bt("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??gt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||wt("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||wt("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||wt("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||wt("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||wt("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]??gt("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},Nt=vt,St={input:vt,output:Nt},$t=(t,e)=>n=>{const o=n[t];return o||rt(`[wcs/filter-unknown] filter not found: ${t}.${ft(t,Object.keys(n))}${pt}`),o(e)};function xt(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 It=new Map;function Pt(t,e){const n=St[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&rt(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&rt(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=It.get(s);return void 0===r&&(r=$t(o,[])(n),It.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(xt(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=xt(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=It.get(l);return void 0===c&&(c=$t(i,a)(n),It.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const kt=t=>t.trim(),Et=new Map,Ct=new Map;function At(t){const e=t.indexOf(a);let n="",o=[],s="",r=[];return-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Ct.has(s)?r=Ct.get(s):(o=s.split(a).map(kt),r=Pt(o,"output"),Ct.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&rt(`"${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:K(n),outFilters:r}}function Tt(t){const[...e]=t.split(";").map(kt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&rt(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===f){const t=K("#else");return{propName:f,propSegments:[f],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===p){const e=At(o);return e.outFilters.length>0&&rt(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&rt(`Invalid spread binding "${t}": spread target path is required.`),{propName:p,propSegments:[p],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...At(o),bindingType:n};{const t=At(o),e=function(t){const e=t.indexOf(a);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),Et.has(r)?i=Et.get(r):(o=r.split(a).map(kt),i=Pt(o,"input"),Et.set(r,i))):n=t.trim();const[l,c]=n.split("#").map(kt),d=l.split(s).map(kt);return{propName:l,propSegments:d,propModifiers:c?c.split(",").map(kt):[],inFilters:i}}(n);return e.propSegments[0]===g||e.propSegments[0].startsWith(m)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>mt.has(t.bindingType))&&rt(`[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">).${pt}`),n}const Mt=new WeakMap,Lt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Ot=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Rt(t){const e=Mt.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Ot.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Lt.has(r)?(Mt.set(t,s[2]),s[2]):null}function jt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...At(t),bindingType:"text"}}const Dt=new Map;function Bt(t,e,n){if(null===n)Dt.delete(t);else{Dt.set(t,n);const o=Bi(e);null===o&&rt("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 Wt(t){return Dt.get(t)||null}function zt(t){if(t.nodeType===Node.ELEMENT_NODE)return Tt(t.getAttribute(o.bindAttributeName)||"");if(t.nodeType===Node.COMMENT_NODE){const e=Rt(t);null===e&&rt("Comment node binding text not found.");const n=Wt(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=jt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function Ft(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function Ht(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Ft(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function Ut(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 qt(t){const e=[],n=Ht(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!==Rt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&Ut(t,n)||e.push(t)}return e}const Gt=new WeakSet;function Kt(t,e,n,o){const s=lt(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?X(t):null;return null===n&&rt("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}Gt.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){dt.set(t,e)}(t,r),U(t),{bindings:r,deferred:null}}function Vt(t,e){const n=qt(t),o=[],s=[];for(const t of n){if(Gt.has(t))continue;const n=Kt(t,zt(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Jt(t){Gt.add(t)}function Xt(t){const{node:e,parseResults:n,transform:o}=t;return function(t){Gt.delete(t)}(e),Kt(e,n,{allowDeferred:!1},o).bindings}let Qt=0;const Yt=["$watch","$streams","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on"],Zt=new Set;function te(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 ee(t){const e=t.indexOf(s);return-1===e?t:t.slice(0,e)}function ne(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 oe(t,e){for(const n of t.entries)if(ne(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 se(t,e){return t.markerBasePath+s+e}function re(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:K(i).wildcardCount-K(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(i),t.addedGetterPaths.add(i))}function ie(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 ae(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}.${ee(e)}: path") or declare the key on the component state.`}const le=/^\$(\d+)$/;function ce(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 re(t,t.markerBasePath,e,e),se(t,e);if(ie(t,n[0]))return re(t,t.markerBasePath,e,e),se(t,e);const i=n.slice(0,o+1),a=n.slice(o+1),l=oe(t,i);null===l&&rt(ae(t,e)),0===a.length&&rt(`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 re(t,c,a.join(s),e),c+s+a.join(s)}(t,e);const o=ee(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return se(t,e);if(ie(t,o))return se(t,e);const i=oe(t,e.split(s));if(null!==i)return i;rt(ae(t,e))}function de(t,e,n,o,s){if(void 0===o)return;const r=K(n).wildcardCount-K(e).wildcardCount;return 0===r?o:(s.length<r&&rt(`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 ue=new WeakMap,he=new WeakMap,fe=new WeakMap,pe=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 me(t){return ue.get(t)??null}function ge(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=fe.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 ye=new WeakMap;function be(t){let e=t;for(;e;){const t=ye.get(e);if(t)return t;let n=e.parentNode;null===n&&e instanceof ShadowRoot&&null!==me(e)&&(n=e.host),e=n}return null}function we(t,e){null!==e?ye.set(t,e):ye.delete(t)}let _e=null;const ve=new WeakMap;function Ne(t){return ve.get(t)??[]}function Se(t,e){ve.set(t,e)}function $e(t){return ve.has(t)}const xe=Symbol("$$setLoopContext"),Ie=Symbol("$$getByAddress"),Pe=Symbol("$$hasByAddress"),ke=Symbol("$$setByAddress"),Ee=Symbol("$$connectedCallback"),Ce=Symbol("$$disconnectedCallback"),Ae=Symbol("$$updatedCallback"),Te=Symbol("$$errorCallback"),Me=new WeakMap;function Le(t,e){if(Me.has(t)){const n=Me.get(t);if(n.has(e))return n.get(e)}else Me.set(t,new WeakMap);const n=Object.freeze(new Oe(t,e));return Me.get(t).set(e,n),n}class Oe{pathInfo;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Le(t,e.parentPathInfo)}}const Re=new WeakMap,je=new WeakMap;class De{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=Be(t,e)}}function Be(t,e){if(null===e){let e=je.get(t);return void 0!==e||(e=new De(t,null),je.set(t,e)),e}{let n=Re.get(e);void 0===n&&(n=new WeakMap,Re.set(e,n));let o=n.get(t);return void 0!==o||(o=new De(t,e),n.set(t,o)),o}}const We=new WeakMap;function ze(t,e){null===e?We.delete(t):We.set(t,e)}function Fe(t){return We.get(t)||null}const He=new Map;function Ue(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=He.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,He.set(s,r)),r}function qe(t,e,n){return e<0||e>=n?null:t.at(e-n)}function Ge(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const Ke=new WeakMap;function Ve(t){const e=be(t.node);if(null===e)return null;let n=Ke.get(e);if(void 0===n)n=new WeakMap,Ke.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Ue(e.pathInfo,t.statePathInfo);return n>0&&(o=qe(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const Je=new WeakMap;function Xe(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Fe(n);null===e?rt(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function Qe(t,e){let n=null;if(n=Je.get(t)||null,null!==n)return n;const o=Xe(t,e),s=Ve(t),r=Bi(o);return null===r&&rt("No state tree found on this root for binding."),n=Be(Le(r,t.statePathInfo),s),Je.set(t,n),n}function Ye(t){Je.delete(t)}const Ze=new WeakMap;function tn(t,e){const n=Ze.get(t);void 0===n?Ze.set(t,e):n instanceof Set?n.add(e):n!==e&&Ze.set(t,new Set([n,e])),null!==_e&&_e({type:"state:binding-added",absoluteAddress:t,binding:e})}function en(t,e){const n=Ze.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&Ze.delete(t),null!==_e&&_e({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const nn=new WeakMap;function on(t,e,n){const o=nn.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==_e&&_e({type:"state:binding-removed",absoluteAddress:Be(t,e),binding:n}))}function sn(t){const e=Ze.get(t);return void 0!==e?e:null!==t.listIndex?nn.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const rn=new WeakMap,an=new WeakMap;class ln{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=cn(t,e)}}function cn(t,e){if(null===e){let e=an.get(t);return void 0!==e||(e=new ln(t,null),an.set(t,e)),e}{let n=rn.get(e);void 0===n&&(n=new WeakMap,rn.set(e,n));let o=n.get(t);return void 0!==o||(o=new ln(t,e),n.set(t,o)),o}}const dn=new WeakMap;function un(t){let e=null;if(e=dn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=Ve(t);null===n&&rt(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=cn(t.statePathInfo,n)}else e=cn(t.statePathInfo,null);return dn.set(t,e),e}function hn(t){dn.delete(t)}function fn(){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 pn=new Map,mn=fn();function gn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function yn(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function bn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function wn(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)bn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class _n{_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 vn extends _n{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==_e&&_e({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const Nn=new WeakMap;function Sn(t,e){let n=Nn.get(t);void 0===n&&(n=new Map,Nn.set(t,n));let o=n.get(e);return void 0===o&&(o=new vn(e,t),n.set(e,o)),o}function $n(t){Nn.delete(t)}const xn=new WeakMap;class In extends _n{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==_e&&_e({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function Pn(t){return t instanceof In}const kn=new Map,En=fn();function Cn(t){const e=t.propModifiers.filter(t=>t===l||t===c).sort().join(",");return`${t.statePathName}::${e}`}function An(t){if(!t.propName.startsWith(m))return!1;const e=Cn(t);let n=kn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(l)&&o.preventDefault(),e.includes(c)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Bi(r);null===i&&rt("No state tree found on this root for event handler.");const a=be(s),d=t.startsWith(A+".");i.createStateAsync("writable",async e=>{const l=e[xe](a,()=>{let l=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=ue.get(n);if(void 0!==t)return t;n=n.parentNode}return ue.get(e)??null}(s,r);if(null!==t){const e=t.indexShiftByLoopElementPath.get(a.pathInfo.path);l=void 0!==e?l-e:0}}const c=null!==a?Ge(a.listIndex,l):[];if(d){const s=e[Ie](cn(n,null));return Pn(s)||rt(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...c)}const u=e[t];return"function"!=typeof u&&rt(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(u,e,[o,...c])});wn(l,`"${t}"`)})})(t.statePathName,t.propModifiers,t.statePathInfo),kn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),En.add(e,t),!0}const Tn=new Map,Mn=fn();function Ln(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function On(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}const Rn=new Set(["radio","checkbox"]),jn=new Set(["value","valueAsNumber","valueAsDate"]);function Dn(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(Rn.has(t)&&"checked"===e)return!0;if(jn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=X(n);if(null!==s){const t=Y(n)?.get(s);void 0===t&&rt(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=tt(n);if(o?.knownProperties.has(e))return!0}return!1}let Bn=1,Wn=1,zn=1;const Fn=new WeakMap;function Hn(t,e,n){let o=Fn.get(t);void 0===o&&(o=new Map,Fn.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=Bn++,o.set(s,r)),r}function Un(t,e){return"to-element"===e?2*t:2*t+1}const qn=new Set;function Gn(t){return{transactionId:Wn++,originBindingId:t,visitedEdges:qn,hop:0}}function Kn(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 Vn=null;function Jn(){return Vn}function Xn(t,e){const n=Vn;Vn=t;try{return e()}finally{Vn=n}}const Qn=[];let Yn=!1;const Zn=new Map,to=fn(),eo=new WeakMap,no=t=>t.detail,oo=new WeakMap;function so(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 ro(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=X(t.node);if(null!==n){const o=Y(t.node)?.get(n);void 0===o&&rt(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=tt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function io(t){if(null!==X(t.node)){const e=tt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??no}return null}function ao(t){if(null===X(t.node))return!1;const e=tt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const lo=new WeakSet;function co(t){lo.add(t)}function uo(t){return!!lo.has(t)&&(lo.delete(t),!0)}const ho=new WeakSet;function fo(t){ho.add(t)}function po(t){return!!ho.has(t)&&(ho.delete(t),!0)}let mo=0;function go(){mo--}function yo(){return mo>0}class bo{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 wo=new WeakMap;function _o(t){let e=wo.get(t);return void 0===e&&(e=new bo(t),wo.set(t,e)),e}function vo(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!==u&&s!==h&&rt(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&rt(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function No(t){return t.propModifiers.some(t=>t.includes("="))}const So=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),$o=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function xo(t,e){return"state"===t&&"call"===e?So:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Io(t){if(!o.enableDirectionalInitialSync)return No(t)&&rt("init=/sync= modifiers require enableDirectionalInitialSync."),So;const e=null===(n=vo(t,u))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:rt(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":rt(`Invalid sync modifier value "${t}".`)}(vo(t,h));if("event"===t.bindingType)return null!==e&&"none"!==e&&rt("Event bindings only allow init=none."),"call"===s?$o:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===y)return xo("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&rt(`Binding type "${t.bindingType}" does not support init=${e}.`),xo(e??"state",s);const r=tt(t.node);if(null===r)return xo(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||rt(`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)||rt(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||rt(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let Po=0,ko=0;const Eo=new WeakMap,Co=new WeakMap,Ao=new WeakMap,To=new WeakMap;function Mo(t,e){const n=To.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):To.set(t,new Set([n,e]))):To.set(t,e)}function Lo(t){return To.has(t)}function Oo(t,e){const n=To.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Ro(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Ro(n,e)}function jo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class Do{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)uo(t)||Ro(t,t=>{Oo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)po(t)&&!yo()||Ro(t,t=>{Oo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&qr(o)}}const Bo=new WeakMap;function Wo(t){let e=Bo.get(t);return void 0===e&&(e=new Do(t),Bo.set(t,e)),e}function zo(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 Fo(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class Ho{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=Eo.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(jo(e)&&Wo(e),null===this.rowPlan)for(const n of t){const t=Eo.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 No(t)&&Io(t),!0;const e=Eo.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=Eo.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=Eo.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(Fo(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=Y(t);null===s&&rt(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Mo(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=_o(s).wait(e,()=>{if(a())try{Z(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=Eo.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&&(en(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?Qe(n):null;if(null!==e.address?(en(e.address,n),e.address=null):(on(e.patternPathInfo,e.patternListIndex,n),e.patternPathInfo=null,e.patternListIndex=null),hn(n),Ye(n),this.registerAddress(e),null!==o){const t=Qe(n);t!==o&&$e(o)&&Se(t,Ne(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return jo(e)?e:null}(t);null!==e&&Wo(e)}handleMutations(t,e,n){for(const n of e)Ro(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Ro(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&qr(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=Eo.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=Ao.get(e);void 0===t&&(t=zo(e),Ao.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Mo(n,this);const o=this.knownMapFor(n);let s=Ao.get(t);void 0===s&&(s=zo(t),Ao.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;Mo(a,this),this.addKnownRowBinding(a,r,s),this.optionsByBinding.set(r,n);const l={id:++Po,info:r,generation:++ko,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(Eo.set(r,l),this.records.add(l),i.isEvent){try{An(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=Eo.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=++ko,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{An(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:++Po,info:t,generation:++ko,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};Eo.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;An(e)?t.eventAttached=!0:e.propSegments[0]!==g?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=On(t),s=Ln(t,o);let r=Tn.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=Bi(o.getRootNode());null===r&&rt("No state tree found on this root for two-way binding.");const i=be(o);r.createState("writable",t=>{t[xe](i,()=>{t[e]=s})})},Tn.set(s,r)),t.node.addEventListener(o,r),Mn.add(s,t),!0}var e,n;return!1}(e)&&Fo(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=On(t),n=Ln(t,e),o=Tn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Mn.countOf(n)&&(Mn.remove(n,t)&&Tn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=yn(t),s=gn(t,o);let r=pn.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=Bi(o.getRootNode());null===i&&rt("No state tree found on this root for two-way binding.");const a=be(o);i.createState("writable",t=>{t[xe](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]:[]})})},pn.set(s,r)),t.node.addEventListener(o,r),mn.add(s,t),!0}var e,n;return!1}(e)&&Fo(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const e=yn(t),n=gn(t,e),o=pn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==mn.countOf(n)&&(mn.remove(n,t)&&pn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Dn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const n=function(t,e,n){let o=eo.get(t);void 0===o&&(o=new Map,eo.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&&eo.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});Fo(t,n)}!function(t){const e=X(t.node);if(null!==e){const n=Y(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&rt(`CustomElementRegistry is unavailable for <${e}>.`))}if(Dn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=ro(t),n=io(t),s=ao(t),r=so(t,e,null!==n,s);let i=Zn.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!==no||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=oo.get(t);void 0===r&&(r=new Set,oo.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 d=eo.get(a)?.get(t);if(void 0!==d)for(const t of d)t(c);let u=null;if(o.enablePropagationContext){const n=Hn(a,t,e),s=function(t,e){for(let n=Qn.length-1;n>=0;n--){const o=Qn[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==_e&&_e({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Un(n,"to-state"),node:a,member:t}));const r=Un(n,"to-state"),i=Jn();if(null!==i&&i.visitedEdges.has(r))return void(null!==_e&&_e({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));u=Kn(i??Gn(n),r)}const h=Bi(a.getRootNode());null===h&&rt("No state tree found on this root for two-way binding.");const f=be(a),p=()=>{r&&(Yn=!0);try{h.createState("writable",t=>{t[xe](f,()=>{t[e]=c})})}finally{r&&(Yn=!1)}};null!==u?Xn(u,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),Zn.set(r,i)),t.node.addEventListener(e,i),to.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==g)return!1;const e=t.node,n=X(e),o=Y(e);if(null!==n&&void 0===o?.get(n))return null===o&&rt(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(xn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||rt('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===X(t)?null:tt(t)}(e);null===r&&rt(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&rt(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${ft(s,r.knownProperties.keys())}`);const a=i.event,d=t.statePathName,u=t.propModifiers,h=t=>{u.includes(l)&&t.preventDefault(),u.includes(c)&&t.stopPropagation();const n=Bi(e.getRootNode());null===n&&rt("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(d)||rt(`[wcs/token-undeclared] eventToken "${d}" is not declared in $eventTokens.${ft(d,n.eventTokenNames)}${pt}`);const o=be(e);n.createStateAsync("writable",async e=>{wn(e[xe](o,()=>{const s=null!==o?Ge(o.listIndex,o.pathInfo.wildcardCount):[];return Sn(n,d).emit(e,t,...s)}),`$on."${d}"`)})};return e.addEventListener(a,h),xn.set(t,{eventName:a,handler:h}),!0})(e)&&Fo(t,()=>function(t){if(t.propSegments[0]!==g)return!1;const e=xn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),xn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=X(t.info.node);if(null===n)return void e();const o=Y(t.info.node);if(null===o&&rt(`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=_o(o).wait(n,()=>{if(this.isAlive(t,s))try{Z(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))});Fo(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Io(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=Bi(t.replaceNode.getRootNode());null===e&&rt("No state tree found on this root for binding.");const n=un(t);let o=!1;return e.createState("readonly",t=>{o=t[Pe](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 mo++;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,go()),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=Bi(t.node.getRootNode());null===o&&rt("No state tree found on this root for initial binding sync.");const s=be(t.node);o.createState("writable",e=>{e[xe](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=Ve(n);if(null!==o){const s=Bi(Xe(n,e));null===s&&rt("No state tree found on this root for binding.");const r=Le(s,n.statePathInfo);!function(t,e,n){let o=nn.get(t);void 0===o&&(o=new WeakMap,nn.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==_e&&_e({type:"state:binding-added",absoluteAddress:Be(t,e),binding:n})}(r,o,n),t.patternPathInfo=r,t.patternListIndex=o}else{const o=Qe(n,e);tn(o,n),t.address=o}if(!t.options.registerPathInfo)return;const s=Bi(n.replaceNode.getRootNode());null===s&&rt("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&&Eo.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,go());const e=t.info;if(null!==t.address)try{en(t.address,e),t.address=null,hn(e),Ye(e)}catch{}else if(null!==t.patternListIndex)try{on(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,hn(e),Ye(e)}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=X(t.node);if(null!==e){const n=Y(t.node),o=n?.get(e);if(void 0===o)return}if(Dn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=ro(t),n=so(t,e,null!==io(t),ao(t)),o=Zn.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),to.remove(n,t)&&Zn.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(m))return!1;const e=Cn(t),n=kn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==En.countOf(e)&&En.remove(e,t)&&kn.delete(e)}(e)}catch{}}}}function Uo(t){let e=Co.get(t);return void 0===e&&(e=new Ho(t),Co.set(t,e)),e}function qo(t){return Eo.get(t)?.session??null}const Go=new WeakMap;function Ko(t,e){let n=Go.get(t);n||(n=new Set,Go.set(t,n)),n.add(e)}const Vo=new WeakMap;function Jo(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const Xo=Object.freeze([]),Qo=new WeakMap,Yo=new WeakMap;function Zo(t){return Yo.get(t)??[]}function ts(t,e){Yo.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 es=0;function ns(){return`u${(es++).toString(36)}`}let os=0;class ss{uuid=ns();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(t,e){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._index=e,this._version=os}get index(){return this._index}set index(t){this._index=t,this._version=++os,this.indexes[this.position]=t}get version(){return this._version}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=os),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0===this._listIndexes&&(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)]),this._listIndexes}get varName(){return`$${this.position+1}`}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function rs(t,e){return new ss(t,e)}const is=new WeakMap;function as(t){return is.get(t)||null}function ls(t,e){null!==e?is.set(t,e):is.delete(t)}const cs=new WeakMap,ds=Object.freeze([]),us=new Set;function hs(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:ds,s=Array.isArray(n)&&n.length>0?n:ds,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:ds,o=Array.isArray(e)&&e.length>0?e:ds;let s=cs.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=as(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:us,deleteIndexSet:new Set(i),addIndexSet:us};let e=as(s);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=rs(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:us,deleteIndexSet:us,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 a={oldIndexes:i,newIndexes:i,changeIndexSet:us,deleteIndexSet:us,addIndexSet:us};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,l=new Set;for(let o=0;o<s.length;o++){const a=s[o],c=n.get(a),d=c&&c.length>0?c.shift():void 0;if(void 0===d){const n=rs(t,o);e.push(n),l.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(function(t,e,n){let o=cs.get(t);o||(o=new WeakMap,cs.set(t,o)),o.set(e,n)}(o,s,a),ls(s,a.newIndexes))}}(t,e,n);return function(t){for(let e=0;e<t.length;e++)t[e].index!==e&&(t[e].index=e)}(o.newIndexes),o}const fs=new WeakMap;function ps(t){return fs.get(t)??[]}function ms(t,e){fs.set(t,e)}const gs=new WeakMap;function ys(t){return gs.get(t)??null}function bs(t,e){gs.set(t,e)}const ws=new WeakMap;function _s(t){return ws.get(t)??[]}function vs(t,e){ws.set(t,e)}function Ns(t,e){const n=_s(t);for(const t of n)we(t,e)}function Ss(t,e,n){Ns(t,e);const o=ps(t),s=ys(t);null!==s&&s.activate(o,n.rootNode);for(const t of o)null===s&&tn(Qe(t),t),(null===s||s.shouldApplyState(t))&&Hr(t,n)}function $s(t){if(!t.mounted)return;const e=ps(t),n=ys(t);for(const t of e)null!==n?n.disposeBinding(t):en(Qe(t),t);!function(t){const e=_s(t);for(const t of e)we(t,null)}(t)}const xs=new WeakMap,Is=Object.freeze(new Set);function Ps(t,e){const n=xs.get(t);n?n.add(e):xs.set(t,new Set([e]))}function ks(t){const e=xs.get(t);return void 0!==e?e:Is}function Es(t,e){const n=xs.get(t);n&&(n.delete(e),0===n.size&&xs.delete(t))}const Cs=new Set(["if","elseif","else","for"]);class As{_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)fo(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){fo(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=ys(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)co(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=ps(this);for(const t of e)if(Cs.has(t.bindingType)){const e=ks(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){ys(this)?.dispose();for(const t of this._childNodeArray)co(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=ps(this);for(const e of t){if(Cs.has(e.bindingType)){const t=ks(e.node);for(const e of t)e.unmount()}hn(e),Ye(e)}this._mounted=!1}}function Ts(t){const e=document.createDocumentFragment(),n=new As(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 Ms(t){void 0!==t.uuid&&null!==t.uuid||rt("BindingInfo.uuid is null.");const n=Wt(t.uuid);n||rt(`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=ct(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===y||s===g)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==X(r))return null;if("prop"===o&&Dn(r,t.propName))return null;let i;try{i=Io({...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 N,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=ct(o,s[t].nodePath);null===e&&rt(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Jt(e),U(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 Ho;return n.initializeRow(t,e),n}(n,a),d=new As(o);return bs(d,c),ms(d,a),ts(d,l),vs(d,r),Ps(t.node,d),d}(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=ct(t,s.nodePath);if(null===e&&rt(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Gt.has(e))continue;const r=Kt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new Ho;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 As(i,s);bs(l,a.bindingSession),ms(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in N&&c.push(t);return ts(l,c),vs(l,a.nodes),Ps(t.node,l),l}const Ls=Symbol.for("wcstack.transition-runner");function Os(t){const e=globalThis[Ls];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 Rs=new WeakSet,js=Symbol.for("wcstack.state.view-transition-naming");function Ds(){const t=Os("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Bs(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||Rs.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[js]??={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.`)):(Rs.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 Ws=new WeakMap,zs=new WeakMap,Fs=new WeakMap,Hs=new WeakMap;function Us(t,e,n){!function(t,e,n){let o=zs.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,zs.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function qs(t,e){Ws.set(t,e)}function Gs(t,e){let n=Fs.get(t.node);void 0===n&&(n=[],Fs.set(t.node,n)),n.length<1e3?n.push(e):Es(t.node,e)}function Ks(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 Vs(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function Js(t,n,s){const r=Boolean(s);let i;const a=ks(t.node);i=0===a.size?Ms(t):a.values().next().value;const l=e(),c=t.uuid??"",d=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${Vs(t)}`),$s(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${Vs(t)}`),l){const e=document.createComment(`@@wcs-${d}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);Ss(i,be(t.node),n);const e=Ds();null!==e&&Bs(i,"branch",e)}}const Xs=new WeakMap,Qs=new WeakMap,Ys=new WeakMap,Zs=new WeakMap;function tr(t){return Zs.get(t)??[]}const er=new Set,nr=Symbol.for("wcstack.trustedTypes.policy");function or(){const t=globalThis[nr];return null===t||"object"!=typeof t?null:t}let sr,rr=!1;const ir={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 ar(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],d=r[c];if(d!==s){null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==X(r)&&function(t,e,n){let o=Xs.get(t);o||(o=new Map,Xs.set(t,o)),o.has(e)||o.set(e,n)}(r,c,d);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=or(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(rr)return;if(!function(){if(void 0!==sr)return sr;if(!("trustedTypes"in globalThis))return sr=!1,sr;try{document.createElement("div").innerHTML="<i></i>",sr=!1}catch{sr=!0}return sr}())return;rr=!0;const n="function"==typeof or()?.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=X(t);if(null===n)return null;const o=Y(t)?.get(n);if(void 0===o)return null;const s=tt(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&&Dn(r,c)){const e=Hn(r,c,t.statePathName),o=Un(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??Jn()??Gn(e);if(a.visitedEdges.has(o))null!==_e&&_e({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=Kn(a,o);Xn(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:zn++,writtenValue:n};Qn.push({receipt:i,node:t});try{return r()}finally{Qn.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=ir[c];t?t(r,s):(function(t,e,n){let o=Zs.get(t);o||(o=[],Zs.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,er.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==d)return;d=d[e]}const u=i[i.length-1],h=d[u];if(h!==s){if(Object.isFrozen(d))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 d&&null!==d&&null!==X(r)&&(u in d?function(t,e,n,o){let s=Ys.get(t);s||(s=new Map,Ys.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,u,d[u]):function(t,e,n){let o=Qs.get(t);o||(o=new Map,Qs.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)}(r,c,u));try{d[u]=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 lr=new WeakSet;function cr(t,e,n){}const dr=new WeakMap;function ur(t,e){if(null===t)return!1;const n=dr.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 hr=new WeakMap;function fr(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 pr=new WeakMap,mr=[],gr=new WeakMap;let yr=null;const br=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),wr=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function _r(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 vr(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 Nr={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},Sr={binding:"Bound path",watch:"$watch path"};function $r(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}.${pt}`}function xr(t,e){return`$setAll("${t}") ${e}`}function Ir(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.${pt}`}const Pr=new WeakMap;const kr=new WeakMap,Er=new WeakSet,Cr=new WeakMap;function Ar(t,e){let n=Cr.get(t);void 0===n&&(n=new Set,Cr.set(t,n)),n.add(e),kr.get(t)?.delete(e)}function Tr(t,e,n,o){console.warn(`[@wcstack/state] [${Nr[n]}] ${Sr[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${ft(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${pt}`),null!==_e&&_e({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const Mr=new WeakSet;function Lr(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Or=Object.freeze({[b]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&rt("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[w]: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)},[y]:function(t,e,n){Pn(n)||rt("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=Qo.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||rt('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=X(t);if(null===e)return null;const n=Y(t)?.get(e);return void 0===n&&rt(`Custom element <${e}> is not defined for command binding.`),tt(t)}(r);null===a&&rt(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||rt(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${ft(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),Qo.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 Qo.delete(t);const o=n[i];return"function"!=typeof o&&rt(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),Qo.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Rr={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!lr.has(t.replaceNode)){lr.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=Ve(t),a=Qe(t),l=Ne(a),c=l.length>0&&!zs.has(t.node)?[]:l,d=hs(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);const u=Array.isArray(c)&&c.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(u&&null!==t.node.parentNode){let e=Hs.get(t.node);if(void 0===e){const n=Ws.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),Hs.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let h=zs.get(t.node),f=u?1e3-function(t){return Fs.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==h){for(const e of d.deleteIndexSet){const n=h.get(e);void 0!==n&&(f<=0&&n.tryDestroy()?Es(t.node,n):($s(n),n.unmount(),Gs(t,n),f-=1),u||h.delete(e))}u&&(zs.delete(t.node),h=void 0)}let p=t.node;const m=K(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}(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&p.isConnected&&(b=document.createDocumentFragment(),ze(b,n.rootNode));const w=e(),_=Ds(),v=t.uuid??"",N=Fs.get(t.node);for(const e of d.newIndexes){let o;if(d.addIndexSet.has(e)){const r=cn(m,e);g.createLoopContext(r,r=>{if(o=void 0!==N?N.pop():void 0,void 0===o&&(o=Ms(t)),null!==b)w&&b.appendChild(document.createComment(`@@wcs-for-start:${v}:${s.path}:${e.index}`)),o.appendTo(b),w&&b.appendChild(document.createComment(`@@wcs-for-end:${v}:${s.path}:${e.index}`));else{if(p.nextSibling!==o.firstNode){if(w){const t=document.createComment(`@@wcs-for-start:${v}:${s.path}:${e.index}`);p.parentNode.insertBefore(t,p.nextSibling),p=t}o.mountAfter(p)}if(w){const t=document.createComment(`@@wcs-for-end:${v}:${s.path}:${e.index}`),n=o.lastNode??p;n.parentNode.insertBefore(t,n.nextSibling)}}Ss(o,r,n),null!==_&&Bs(o,"row",_)}),void 0===o&&rt(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=void 0!==h?h.get(e)??null:null,d.changeIndexSet.has(e)){const t=Zo(o);for(const e of t)Hr(e,n)}null===o&&rt(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==y&&y.has(e)&&Ks(p,o.firstNode)||p.nextSibling===o.firstNode||o.mountAfter(p),t){const t=o,s=cn(m,e);g.createLoopContext(s,e=>{Ss(t,e,n)})}}p=o.lastNode||p,void 0===h&&(h=new WeakMap,zs.set(t.node,h)),h.set(e,o)}Ws.set(t.node,p),null!==b&&(t.node.parentNode.insertBefore(b,t.node.nextSibling),ze(b,null))},if:Js,else:Js,elseif:Js,radio:function(t,e,n){const o=t.node,s=Jo(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=Jo(o.value,t.inFilters),r=Array.isArray(n)?n:Xo;o.checked=r.includes(s)}},jr=new WeakMap,Dr=new WeakMap,Br=new WeakMap;function Wr(){}function zr(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===Go.get(t)?.has(e)}(e,n)?cr:function(t,e){return!0===Vo.get(t)?.has(e)}(e,n)?Wr:ar}function Fr(t,e){const n=Jo(function(t,e){const n=un(e);if(n.pathInfo.path in N){const t=be(e.node);return null===t&&rt(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&rt("ListIndex not found for loopContext:");const n=N[e];void 0===n&&rt(`Invalid index name: ${e}`);const o=qe(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&rt(Ir(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Ie](n)}(e.state,t),t.outFilters);if(!0===Dr.get(t))return void e.deferredSelectBindings.push({binding:t,value:n,stateElement:e.stateElement});let o=jr.get(t);if(void 0===o){if(jr.has(t))return o=zr(t),o===cr&&jr.set(t,o),void o(t,e,n);if(o=Rr[t.bindingType],void 0===o){const e=t.propSegments[0];o=Or[e],jr.set(t,o),void 0===o&&(X(t.replaceNode)?(o=zr(t),o===cr&&jr.set(t,o)):(o=ar,jr.set(t,o)))}if(o===ar&&"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 Dr.set(t,!0)}o(t,e,n)}else o(t,e,n)}function Hr(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=Qe(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=qo(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Br.get(t)){const e=X(t.replaceNode);if(e&&void 0===Y(t.replaceNode)?.get(e))return void function(t,e){if(Mr.has(t))return;Mr.add(t);const n=()=>{Mr.delete(t);const e=qo(t);(null===e||e.shouldApplyState(t))&&qr([t])},o=n=>{Mr.delete(t),Lr(e,n)},s=qo(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Mr.delete(t),r()})||(Mr.delete(t),r()))}const r=Y(t.replaceNode);if(null===r)return Mr.delete(t),void Lr(e,new Error("CustomElementRegistry is unavailable."));_o(r).wait(e,()=>{t.replaceNode.isConnected?n():Mr.delete(t)},o)}(t,e);Br.set(t,!0)}if(!0===e.sameRootVerified)return void Fr(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Fe(o),null===o&&rt("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Bi(o);null===n&&rt("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};Fr(t,r)})}else Fr(t,e)}function Ur(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==_e&&_e({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function qr(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 d=c.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Fe(d),null===d&&rt("Root node for fragment not found for binding."));const u=Bi(d);null===u&&rt("No state tree found on this root for binding."),u.createState("readonly",o=>{const h={rootNode:d,stateElement:u,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Hr(c,h)}catch(t){Ur(c,t,u,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{ar(t,{propagationContextByBinding:e},n)}catch(e){Ur(t,e,o??null,l)}for(const[t,e]of r.entries())Se(t,e);for(const[t,e]of i.entries())t.createState("writable",t=>{t[Ae](Array.from(e))});for(const[t,e]of l.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[Te](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 Gr(t,e,n){const[o,s,r]=Vt(t,n),i=Uo(t);for(const t of o)we(t,e);qr(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=Xt(o);0!==t.length&&(we(o.node,e),qr(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const Kr=/\{\{\s*(.+?)\s*\}\}/g,Vr=new Set(["SCRIPT","STYLE"]);function Jr(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&&Vr.has(t.parentElement.tagName)||Xr(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),Jr(e.content)}else Jr(t.content)}function Xr(t){const e=t.data;if(Kr.lastIndex=0,!Kr.test(e))return;Kr.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=Kr.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 Qr;function Yr(){if(Qr)return Qr;const t=[],e=$t("not",t)(Nt);return Qr={filterName:"not",args:t,filterFn:e},Qr}const Zr=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function ti(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 ei(t,e){const n=Zr.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+ti(s,e)+r}function ni(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=ti(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function oi(t,e){return ni(t,e)}function si(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=ei(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=ni(r,e);t!==r&&o.setAttribute(n,t)}}}function ri(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=qt(t);for(const t of n){const n=zt(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:ri(o),parseBindTextResults:n})}return e}function ai(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const li=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),ci=Yr();function di(t,e){const n=e.outFilters;return{...e,outFilters:[...n,ci],bindingType:t}}function ui(t,e,n,o,s,r=!0){ai(e),"string"==typeof o&&si(e,o),hi(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 hi(t,e,n,s){const r=o.commentElsePrefix,i=Ht(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=[],d=[];for(;a.nextNode();){const t=a.currentNode;d.push(t)}for(const e of d){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=oi(i,n));let a=Tt(i)[0];const d=li.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,h=e.content,f=ns();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&rt("'else' binding found without preceding 'if' or 'elseif' binding."),a=di("else",l.parseBindTextResult),p=ui(t,h,a,m,s,!1),Bt(f,t,p);const n=c.at(-1),o=document.createComment(`@@${d}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:ri(o),parseBindTextResults:zt(o)})):e.replaceWith(o)}else if("elseif"===u){null===l&&rt("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=ui(t,h,a,m,s),Bt(f,t,p);const n=document.createComment(`@@${d}:${f}`),o=ns(),i={fragment:document.createDocumentFragment(),parseBindTextResult:di("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ri(n),parseBindTextResults:zt(n)}),Bt(o,t,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(e.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:ri(g),parseBindTextResults:zt(g)})):e.replaceWith(g)}else{p=ui(t,h,a,m,s),Bt(f,t,p);const n=document.createComment(`@@${d}:${f}`);e.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}async function fi(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Y(t);null===s&&rt(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(Ft(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function pi(t){if(t===document)await fi(document),Jr(document),hi(document,document),Gr(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await H(e.host),await fi(e),Jr(e),hi(e,e),Gr(e,null)}}const mi="2.2.0",gi="undefined"==typeof HTMLElement?class{}:HTMLElement,yi=/^@@wcs-(?:for|if|elseif|else):[^-]/,bi=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,wi=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,_i=/^@@wcs-text-start:(.+)$/;function vi(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Ni extends gi{_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=mi.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,o]of Object.entries(e))t.startsWith("$")||"function"==typeof o||(n[t]=o);return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=vi(JSON.stringify(e)),t.appendChild(n);const s=Array.from(Dt.keys());for(const e of s){const n=Wt(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(er);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=tr(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=vi(JSON.stringify(e)),t.appendChild(n)}}er.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(bi.test(t.data)||wi.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;yi.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=_i.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;bi.test(t.data)&&i.push(t)}for(const t of i){const e=bi.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()}Ni.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(yi.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 Si=new Set(["for","if","elseif","else"]);function $i(t){const e=new Ho;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]=Vt(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 xi(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 Ii(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Tt(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,Yr()],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;ai(a),"string"==typeof l&&si(a,l),hi(n,a,l),Bt(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:ii(a)})}}const Pi=Symbol.for("wcstack.binder"),ki=Symbol.for("wcstack.binder.pending"),Ei=Symbol.for("wcstack.binder.taken");function Ci(t){if(Lo(t))return!0;if(!Ai(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Lo(e)}function Ai(t){return 1===t.nodeType}function Ti(t){if(Ci(t))return;Jr(t),hi(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Gr(e&&s?n:t,null)}const Mi=[];function Li(){const t=Mi.splice(0,Mi.length);for(const e of t)Ti(e);!function(){const t=function(){const t=globalThis[Pi];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[ki];return void 0===e&&(e=[],t[ki]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[Ei];return void 0===e&&(e=new WeakSet,t[Ei]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const Oi={protocol:"wcs-binder",version:1,bind:function(t){var e;Ai(t)&&!Ci(t)&&(e=t.getRootNode(),zi.has(e)?Ti(t):Mi.push(t))}},Ri=new WeakMap,ji=new WeakMap,Di=new Set;function Bi(t){return Ri.get(t)??null}function Wi(t){return ji.get(t)??Promise.resolve()}const zi=new WeakSet;function Fi(t){zi.add(t)}function Hi(t,n){const s=Ri.get(t);if(null===n){if(void 0===s)return;Ri.delete(t),Di.delete(s),null!==_e&&_e({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{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 fi(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="${mi}". Falling back to full render.`),Ni.cleanupDom(t),!1}for(const n of e)Ii(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=bi.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 d=t.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.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=Ts(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=$i(o.nodes);bs(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");ms(e,s),vs(e,i);const l=[];for(const t of s)t.statePathName in N&&l.push(t);if(ts(e,l),"for"===o.type&&null!==o.index){const i=xi(t,"for",o.uuid);if(i){const t=rs(null,o.index);Us(i,t,e),qs(i,o.nodes[o.nodes.length-1]),Ps(i,e),Ns(e,cn(K(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=xi(t,o.type,o.uuid);n&&(Ps(n,e),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=xi(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Wt(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Bi(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&ls(e,o)})}}(document.body,n),Ni.removeBlockBoundaryComments(document.body);const s=[];for(const t of e)t.parentNode&&(s.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());Ni.restoreTextBindings(document.body);const[i,a]=Vt(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(we(t,null),e.setAttribute("data-wcs-completed",""))}else we(t,null);const l=[],c=[],d=Uo(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(Si.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=Qe(t),n=Bi(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&Se(e,o)})}qr(l);for(const{el:t,parent:e,next:n}of s)e.insertBefore(t,n);const u=t.querySelectorAll(o.tagNames.ssr);for(const e of u){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 pi(t),Fi(t),Li(),e()}catch(t){n(t)}})});ji.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await pi(t),Fi(t),Li(),e()}catch(t){n(t)}})});ji.set(t,e)}}void 0!==s&&rt('A state tree is already registered on this root — one <wcs-state> per root in v2. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Ri.set(t,n),Di.add(n),function(t,e){const n=gr.get(t);if(void 0===n||0===n.length||null===yr)return;gr.delete(t);const o=yr;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,n),null!==_e&&_e({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}let Ui=0,qi=0;const Gi=[];function Ki(t,e=0){const n=Gi.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Gi.push(o):Gi.splice(n,0,o)}function Vi(t){queueMicrotask(()=>{throw t})}const Ji=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){Ui>qi&&(qi=Ui);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&queueMicrotask(()=>{const t=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(t)})}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!==_e&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&_e({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!==_e&&_e({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=sn(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?qr(o,s):qr(o)};if(e()||0===o.length)t();else{const e=function(t,e){const n=Os(t);if(null!==n)return n.run(e,{source:t,types:void 0});e()}("state",t);void 0!==e&&e.catch(Vi)}}finally{!function(t){for(const e of Gi.slice())e.listener(t)}(new Set(n.keys()))}}};function Xi(){return Ji}const Qi=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Yi(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 Zi="__WCSTACK_DEVTOOLS_HOOK__";const ta=t=>{null!==_e&&_e({type:"state:update-batch",addresses:t})};function ea(t){const e=null!==_e;!function(t){_e=t}(t);const n=null!==t;n&&!e?Ki(ta,0):!n&&e&&function(t){const e=Gi.findIndex(e=>e.listener===t);-1!==e&&Gi.splice(e,1)}(ta)}function na(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 oa(t){return Bi(t)??rt("devtools: no state tree on this root")}let sa=null;function ra(){if(e())return;if(null!==sa)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:mi,getStateElements(){const t=[];for(const e of Di)t.push(na(e));return t},overlays:t=>function(t){const e=fe.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}(oa(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=oa(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 oa(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){oa(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=Wt(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Yi(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=lt(e,Tt(n));for(const o of t)r(Yi(e,o,"attribute",n))}catch{}continue}const e=Qi.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=Wt(s);if(null===a){if(n===o.commentTextPrefix)try{r(Yi(t,jt(s),"comment",s))}catch{}}else r(Yi(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:ea};sa=t,function(){const t=globalThis,e=t[Zi];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[Zi]=n,n}().register(t)}const ia={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",mi),Ni.buildContent(o,Ni.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}},aa="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let la=0;async function ca(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++la}\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 ${aa}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${aa}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function da(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){rt(`Failed to load script file: ${t}`)}}class ua{_loopContextStack=Array(i).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&rt("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=i&&rt("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&&rt("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&&rt("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&&rt(`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 ha=new WeakMap;function fa(t,e){let n=ha.get(t);void 0===n&&(n=new Map,ha.set(t,n));let o=n.get(e);return void 0===o&&(o=new In(e,t),n.set(e,o)),o}const pa=new WeakMap;function ma(t){const e=pa.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 fa(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:fa(t,n)}},set(){rt("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){rt("$command namespace is read-only; deleting from it is not allowed.")}});return pa.set(t,n),n}const ga=Symbol("wcs-stream-last-notified-uncertain"),ya=new WeakMap;function ba(t,e){const n=ya.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function wa(t,e){const n=ya.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:ga,error:Object.is(o.error,null)?null:ga})}const _a=new Set;function va(t){_a.delete(t)}const Na=new WeakMap;function Sa(t){return Na.get(t)??new Map}function $a(t){va(t);const e=Na.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,wa(t,n.name)}const xa=(t,e)=>e,Ia=new Set;const Pa=new WeakMap,ka=new WeakMap;function Ea(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=Sa(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&Sa(t).has(n),ownKeys:()=>Array.from(Sa(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=Sa(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){rt(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){rt(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Ca(t){const e=Pa.get(t);if(void 0!==e)return e;const n=Ea(t,j,t=>t.status);return Pa.set(t,n),n}function Aa(t){const e=ka.get(t);if(void 0!==e)return e;const n=Ea(t,D,t=>t.error);return ka.set(t,n),n}function Ta(t){Pa.delete(t),ka.delete(t)}let Ma=null;function La(t){const e=Sa(t);if(0!==e.size){!function(t){_a.add(t)}(t);for(const n of e.values())Oa(t,n)}}function Oa(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=Ma,r=new Set;let i;Ma=r;try{t.createState("readonly",t=>{i=n(t)})}finally{Ma=o}i instanceof Promise&&rt(`${L} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${j}${s}${e.name}`,l=`${D}${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||rt(`${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&&rt(`${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);t.createState("writable",t=>{t[e.name]=e.definition.initial}),Ra(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(){Ra(t,e,"done",null)},fail(o){Ra(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 Ra(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return ya.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=ya.get(t);void 0===s&&(s=new Map,ya.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${j}${s}${e.name}`),a&&t.$postUpdate(`${D}${s}${e.name}`)}))}Ki(function(t){const e=_a;if(0===e.size)return;const n=[];for(const o of e)for(const e of Sa(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)&&Sa(t).get(o.name)===o)try{Oa(t,o)}catch(n){o.controller?.abort(),e.has(t)&&Sa(t).get(o.name)===o&&Ra(t,o,"error",n)}},20);const ja=new WeakMap,Da=new WeakMap,Ba=new Set,Wa=new Map;function za(t){return ja.get(t)??Wa}const Fa=new Map;function Ha(t){return Da.get(t)??Fa}function Ua(t){0===t.length&&rt(`[wcs/watch-declaration-invalid] ${O} entry name must be a non-empty state path.`),t.startsWith("$")&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not start with "$" (reserved namespace).${pt}`),t.includes("@")&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${pt}`),t in Object.prototype&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=K(t);for(const n of e.segments)0===n.length&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${t}" has an empty path segment.${pt}`);return e.wildcardCount>128&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const qa=new WeakMap;function Ga(t,e,n){let o=qa.get(t);void 0===o&&(o=new Map,qa.set(t,o)),o.set(e,n)}const Ka=new Map;function Va(t){0===za(t).size&&0===Ha(t).size||(function(t){Ba.add(t)}(t),function(t){const e=[];for(const n of za(t).values())Xa(t,n)&&e.push(n);for(const n of Ha(t).values())for(const o of n)Xa(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{Ga(t,Ja(t,o),n[o.path])}catch(e){Ya(t,o.path,"prime",e)}})}(t))}function Ja(t,e){return Be(Le(t,e.pathInfo),null)}function Xa(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Qa={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Ya(t,e,n,o){console.error(`[@wcstack/state] $watch ${Qa[n]} "${e}" threw.`,o),null!==_e&&_e({type:"state:watch-error",phase:n,path:e,error:o})}function Za(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 tl(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Xa(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 Ya(0,n.path,"evaluate",t)}const a=r?function(t,e){return qa.get(t)?.get(e)}(e,o):function(t){return Ka.get(t)}(o);r&&Ga(e,o,i),null!==_e&&_e({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){Ya(0,n.path,"handler",t)}}function el(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 nl(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 ol(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 sl(t){return t.startsWith("$")}function rl(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 il(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 al(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||rt(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||rt(`${e} entries must be non-empty strings.`),t.startsWith("$")&&rt(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&rt(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}Ki(function(t){const e=Ba;try{if(0===e.size)return;const n=function(){const t=qi;return qi=0,t}();if(n>32){const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==_e&&_e({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=za(t).get(s),i=Ha(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=Ge(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Za),function(t){Ui=t+1}(n);try{for(const t of o){if(!e.has(t.stateElement))continue;const n=za(t.stateElement).get(t.entry.path)===t.entry,o=!0===Ha(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&tl(t)}}finally{Ui=0}}finally{Ka.clear()}},10);const ll=new Map;class cl{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=K(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 dl(t){let e;return ll.get(t)??(ll.set(t,e=new cl(t)),e)}function ul(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:qe(n.listIndex,o,n.pathInfo.wildcardCount)}const hl=new WeakMap;function fl(t,e){null===e?hl.delete(t):hl.set(t,e)}function pl(t){const e=hl.get(t);e&&(e.dirty=!0)}function ml(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=Ue(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?qe(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?qe(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}const gl=new WeakMap;class yl{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 cn(K(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(ce(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=ce(t,e),a=de(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a=ce(t,e),l=de(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 ml(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[ce(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)||rt(`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[ce(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 ce(this.record,e),!0}catch{return!1}}}function bl(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=gl.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},gl.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 yl(t,s,e.listIndex,r,n,o))}const wl=new WeakMap,_l=new Set;function vl(t,e,n,o){let s=wl.get(t);if(void 0===s){if(!o)return null;s=new Map,wl.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 Nl(t,e){if(!t.component.isConnected)return!1;const n=be(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 Sl(t,e,n,o){const r=vl(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&&Nl(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?Nl(i,o)&&(null!==l&&rt(`[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 $l(t){const e=t.parentStateElement,n=be(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[xe](n,()=>{t.$postUpdate(o.exportedPath)})})}function xl(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Il(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 Pl(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===A)return Il(ma(s),e.pathInfo.segments);if(i===j)return Il(Ca(s),e.pathInfo.segments);if(i===D)return Il(Aa(s),e.pathInfo.segments);if(!0===s.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const t=ge(s,e.pathInfo.path);if(null!==t)return bl(t,e,n,o)}if(!(e.pathInfo.path in t)){if(null===e.parentAddress&&ur(function(t){return t.rootNode??null}(s),e.pathInfo.path))return;const i=e.parentAddress??rt(function(t,e,n){return`[${Nr.binding}] Path "${t}" does not exist on the state tree.${ft(t,vr(e,"",n))}${pt}`}(e.pathInfo.path,t,s.getterPaths)),a=kl(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=Sl(s,i.pathInfo.path,l,e.listIndex);if(null!==t)return function(t,e,n,o,s){const r=bl(t,cn(K(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??rt(Ir(`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 kl(t,e,n,o){ml(o,e),function(t,e){if(null===Ma)return;const n=Le(t,e.pathInfo);Ma.add(Be(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return xl(s,e)?function(t,e,n,o,s){const r=Be(Le(s,e.pathInfo),e.listIndex),i=function(t){return hl.get(t)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Pl(t,e,n,o,s);return fl(r,{value:a,dirty:!1}),a}(t,e,n,o,s):Pl(t,e,n,o,s)}const El=new WeakMap;function Cl(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const h=o[s]??null;if(null===h)return void u.push(d);const f=cn(h,r),p=El.get(f),m=kl(t,f,e,n),g=hs(r,p,m).newIndexes,y=l[c]??null;if(i.set(f,m),null===y)for(let t=0;t<g.length;t++){const e=g[t];a(o,s+1,e,l,c+1,d.concat(e.index),u)}else{const t=g[y]??rt(`ListIndex not found at index ${y} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,d.concat(t.index),u):u.push(d.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())El.set(t,e);return l}function Al(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=as(kl(t,cn(a,r),e,n));null==l&&rt(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??rt(`ListIndex not found at index ${c} of ${a.path}`)}return r}function Tl(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 Ml(t,e,n,o){"object"==typeof t&&null!==t||rt(`${R} 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&&rt(`${R} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function Ll(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&rt(`${R} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function Ol(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];Ml(a,n,o,i);const l=Ll(a,e,n,o,i);r.has(l)&&rt(`${R} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function Rl(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 jl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=kl(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 Dl=new WeakMap;function Bl(t,e){null===e?Dl.delete(t):Dl.set(t,e)}function Wl(t,e,n){const s=K(t.wildcardParentPaths[e]),r=Le(t.stateElement,s),i=cn(s,n),a=Ne(Be(r,n)),l=t.stateProxy[Ie](i),c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(hs(i.listIndex,a,l),t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)Wl(t,e+1,n)}const zl=[];function Fl(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:zl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:zl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const Hl=[];function Ul(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return Hl;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=K(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??Hl}function ql(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=K(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[Ie](e),a=Ne(Be(Le(t.stateElement,e.pathInfo),e.listIndex)),l=Fl(t,o,0,0,hs(e.listIndex,a,r));for(const e of l.fullRows){const o=cn(s,e);t.result.add(o),n.push(o)}if(null!==l.movedRows){const e=Ul(t,i,s);if(null===e)for(const e of l.movedRows){const o=cn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of l.movedRows)for(const s of e){const e=cn(s,o);t.result.add(e),n.push(e)}}}else{const o=cn(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=K(o),r=[];if(s.wildcardCount>0){const n=Ue(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&rt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=qe(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};Wl(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&rt(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=qe(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=cn(s,e);t.result.add(o),n.push(o)}}}function Gl(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 d=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&&rt(`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),u={ranks:d,stateElement:t,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};return 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,ql(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(u,e,a),Array.from(u.result)}function Kl(t,e,n,o,s){const r=t.watchPaths;null!=r&&s&&r.has(e)&&function(t,e){Ka.has(t)||Ka.set(t,e)}(n,o)}function Vl(t,e,n,s,r){const i=o.enablePropagationContext?Jn()??Gn(-1):null,a=Xi();a.enqueueAbsoluteAddress(e,i),Gl(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=Be(Le(s.stateElement,e.pathInfo),e.listIndex);pl(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function Jl(t,e,n,o,s){s&&(t.getterPaths.has(e)?pl(n):fl(n,{value:o,dirty:!1}))}function Xl(t,e,n,o,s,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const a=kl(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??rt(Ir(`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{Vl(e,n,s,i,a)}}function Ql(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=kl(t,e,o,i),c=function(t,e,n,o){const s=Ol(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=Ol(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===as(o)&&hs(c,null,o);const d=hs(c,o,n.list),u=Yl(t,e,n.list,i,a,l),h=K(l+s+r);for(const e of n.matched){const n=Rl(e.oldRow,e.newRow);if(0===n.length)continue;const o=d.newIndexes[e.position];for(const r of n)void 0!==o?Ql(t,cn(K(h.path+s+r.field),o),r.value,i,a):e.oldRow[r.field]=r.value}return u}(t,e,c,a,o,i)}}return Yl(t,e,n,o,i,null)}function Yl(t,e,n,i,a,l){const c=a.stateElement,d=e.pathInfo.path;if(!0===c.hasGraftedVolumes){const t=function(t,e){const n=hr.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,d);null!==t&&rt(`Cannot replace "${d}" 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 "${d}", instead.`)}const u=!!Yn&&(Yn=!1,!0);if(!(d in t)&&null!==e.parentAddress&&!c.elementPaths.has(d)){const s=kl(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(!u&&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=xl(c,e),g=Be(Le(c,e.pathInfo),e.listIndex);null!==_e&&_e({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:p}),Kl(c,d,g,f,p);let y=!1;try{if(void 0===h&&rt(Ir(`path "${d}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),!0===c.hasMounts&&t!==r&&!(h in s)){const o=Sl(c,e.parentAddress.pathInfo.path,t,e.listIndex);if(null!==o)return y=!0,function(t,e,n,o,s,r){const i=bl(t,cn(K(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{Vl(e,g,i,a,l),y?pl(g):Jl(c,d,g,n,m),Tl(c,e.pathInfo,{value:n})}}}let h,f=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=kl(t,e,i,a);if(jl(t,e,i,a)&&Object.is(o,n))return!0;h=o,f=!0}const p=c.elementPaths.has(e.pathInfo.path),m=xl(c,e),g=Be(Le(c,e.pathInfo),e.listIndex);null!==_e&&_e({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:f}),Kl(c,d,g,h,f);try{return p?function(t,e,n,o,s,r,i){let a=e.parentAddress??rt(`address.parentAddress is undefined path: ${e.pathInfo.path}`),l=function(t){return Dl.get(t)??null}(a);if(null===l){const e=kl(t,a,s,r)??[],n=as(e)??[];l={value:[...e],listIndexes:[...n]},Bl(a,l)}try{return Xl(t,e,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=kl(t,a,s,r)??[],c=Array.isArray(i)?as(i)??[]:[],d=e.listIndex.index,u=-1!==n?l.listIndexes[n]:rs(a.listIndex,-1);if(c[d]=u,new Set(i).size===l.value.length){for(let t=0;t<c.length;t++)c[t].index=t;Bl(a,null)}}}(t,e,g,n,i,a,l):Xl(t,e,g,n,i,a,l)}finally{Jl(c,d,g,n,m),Tl(c,e.pathInfo,{value:n})}}function Zl(t,e,n,o){return(e,s,r)=>{const i=K(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&&rt($r("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=cn(i,Al(t,n,o,i,s));if(void 0===r)return kl(t,a,n,o);Ql(t,a,r,n,o)}}function tc(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return ul(o,s.wildcardPaths.at(-1)??rt(`lastWildcardPath is null: ${e.pathInfo.path}`))??rt(`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]??rt(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=as(kl(t,cn(i,s),n,o))??rt(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??rt(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??rt(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":rt(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}const ec=`${j}${s}`,nc=`${D}${s}`,oc=new WeakMap;function sc(t,e,n,o){const r=N[e];if(void 0!==r){0===o.addressStackLength&&rt(`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&&rt(`ListIndex not found: ${e.toString()}`);let a=r;const l=t.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const t=ge(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=qe(i,a,l.wildcardCount);return c?.index??rt(`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=Zl(t,0,n,o);return(e,r)=>{const i=K(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)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&rt($r("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=ul(o,i.wildcardPaths[t]);if(e){r=Ge(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&&rt(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=Cl(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)=>{const a=K(e);Array.isArray(s)||rt(xr(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&rt($r("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&rt(xr(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&rt(xr(e,"requires an array as the value when { spread: true } is set."));const d=Cl(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&rt(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,d.length,r.length));const u=[];for(let e=0;e<d.length;e++){const s=Al(t,n,o,a,d[e]);u.push(cn(a,s))}let h=0;for(let e=0;e<u.length;e++){const s=u[e];let i;i=c?r(kl(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(Ql(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=dl(e),i=tc(t,r,n,o),a=cn(r.pathInfo,i),l=Be(Le(s,a.pathInfo),a.listIndex),c=Xi();c.enqueueAbsoluteAddress(l),Gl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Be(Le(s,t.pathInfo),t.listIndex);pl(e),c.enqueueAbsoluteAddress(e)}),Tl(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>Zl(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{0===o.addressStackLength&&rt(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??rt("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 A:return ma(o.stateElement);case j:return Ca(o.stateElement);case D:return Aa(o.stateElement)}if(!e.startsWith(ec)&&!e.startsWith(nc))return}const s=dl(e),r=tc(t,s,n,o),i=cn(s.pathInfo,r);return kl(t,i,n,o)}if("symbol"==typeof e){const r=function(t){let e=oc.get(t);return void 0===e&&(e=new Map,oc.set(t,e)),e}(o),i=r.get(e);if(void 0!==i)return i;let a;switch(e){case xe:a=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&rt("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 Ie:a=e=>kl(t,e,n,o);break;case Pe:a=e=>jl(t,e,n,o);break;case ke:a=(e,s)=>Ql(t,e,s,n,o);break;case Ee:a=()=>async function(t,e,n){const o=Reflect.get(t,S);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Ce:a=()=>function(t,e,n){const o=Reflect.get(t,$);"function"==typeof o&&o.call(n)}(t,0,n);break;case Ae:a=e=>function(t,e,n,o){const r=Reflect.get(t,x);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=Ge(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,pr.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=Ge(n.listIndex,l);(a[s]??=[]).push(t)}}if(i.size>0)try{t.callback.call(fr(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 Te: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 rc{_stateElement;_addressStack=Array(i).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Bi(t);null===n&&rt("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&&rt("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=i&&rt(`Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_describeAddressCycle(){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`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&rt(`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 sc(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&rt("This state is readonly."),function(t,e,n,o,s){if("string"==typeof e){const r=dl(e),i=tc(t,r,o,s);return Ql(t,cn(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 ic=new WeakMap;class ac{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=ic.get(t);return n?n.get(e)??null:null}(t,e)??rt("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 lc=t=>()=>t;function cc(t,e,n,o){!function(t,e,n){let o=ic.get(t);o||(o=new Map,ic.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 ac(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:lc(s),enumerable:!0,configurable:!0}),Ko(e,n),dc(e,n)}function dc(t,e){if(P in t){const n=t[P];"function"==typeof n?n.call(t,e).catch(t=>{rt(`Error in ${P}: ${t instanceof Error?t.message:String(t)}`)}):rt(`${P} is not a function.`)}}function uc(t,e){const n=me(e);var o,i;null!==n&&n.stateProp!==t.stateProp&&rt(`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&&Uo(e).dispose(),function(t,e){ue.set(t,e);let n=fe.get(e.parentStateElement);void 0===n&&(n=new Map,fe.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=he.get(e.component);void 0===o&&(o=new Map,he.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&pe.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=Ri.get(t);if(void 0!==n){if(n===e)return;rt("A state tree is already registered on this root.")}Ri.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const i=le.exec(e.statePathName);if(null!==i){const s=function(t,e){return void 0===e?t.delta:K(ce(t,e)).wildcardCount-K(e).wildcardCount}(t,n);o=0===s?e.statePathName:`$${Number(i[1])+s}`}else if(o=ce(t,e.statePathName),"for"===e.bindingType){const n=K(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+s+r,n)}return o===e.statePathName?e:{...e,statePathName:o,statePathInfo:K(o)}}(t,e,n);Jr(e);const o=be(t.component);hi(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),Gr(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=ce(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=K(a);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:r,suffix:i,markerPath:e,exportedPath:a};t.exports.set(a,c),vl(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,a),Ar(t.parentStateElement,a)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=be(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(_l.has(s))continue;const r=K(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[xe](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(_l.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),$l(t),o=e,i=Promise.resolve(),ji.set(o,i),i.then(()=>Fi(o),()=>{})}const hc=new Set;function fc(t,e){hc.has(t)||(hc.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function pc(t){const e=t.rootEntry,n=be(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[xe](n,()=>{o=t[e.outerPathInfo.path]})}),o}function mc(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(fr(t.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function gc(t,e,n){!function(t,e,n){const o=n[O];if(void 0!==o){"object"==typeof o&&null!==o||rt(`${O} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&rt(`${O} entry "${t}" must be a function.`),Ua(t)}const r=n[R];if(void 0!==r){"object"==typeof r&&null!==r||rt(`${R} 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)&&rt(`${R} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+s+n)&&rt(`${R} entry "${e+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&rt(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream 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=K(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;rt(`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;rt(`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=hr.get(t);void 0===n&&(n=new Set,hr.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(fr(e,this))}),"function"==typeof a&&(l.set=function(t){a.call(fr(e,this),t)}),t.defineTreeAccessor(r,l)}!function(t,e,n){const o=n[O];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(fr(e,this),t,n,...o)};n.push({path:o,pathInfo:K(o),handler:c,order:1e6+i++}),r.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(function(t,e){let n=Da.get(t);void 0===n&&(n=new Map,Da.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),Va(t))}const r=n[R];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[x];"function"==typeof i&&(function(t,e){let n=pr.get(t);void 0===n&&(n=[],pr.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(fr(e,t));n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function yc(t,e){let n=null;try{n=gc(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}yr=yc;class bc extends gi{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return Wi(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new ua}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_watchPaths=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&&rt(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){this._commandTokenNames=function(t){const e=new Set,n=t[C];if(void 0===n)return e;Array.isArray(n)||rt(`${C} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||rt(`${C} entries must be non-empty strings.`),t===A&&rt(`${C} entry "${t}" conflicts with the reserved namespace name "${A}".`),e.has(t)&&rt(`${C} entry "${t}" is duplicated.`),e.add(t);return e}(t),this._eventTokenNames=function(t){const e=new Set,n=t[T];if(void 0===n)return e;Array.isArray(n)||rt(`${T} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||rt(`${T} entries must be non-empty strings.`),e.has(t)&&rt(`${T} entry "${t}" is duplicated.`),e.add(t);return e}(t),this.__state=t,this._hasUpdatedCallback=x in t,this._hasErrorCallback=I in t,$n(this),function(t,e,n){const o=e[M];if(void 0!==o){"object"==typeof o&&null!==o||rt(`${M} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||rt(`${M} entry "${e}" is not declared in $eventTokens.${ft(e,n)}`),"function"!=typeof s&&rt(`${M} entry "${e}" must be a function.`),Sn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const n=function(t){const e=new Set,n=new Set,o=rl(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 n.getterPaths)this._getterPaths.add(t);for(const t of n.setterPaths)this._setterPaths.add(t);Ta(this),$a(this),va(this),Na.delete(this),function(t,e){const n=e[L];if(void 0===n)return void ba(t,Ia);"object"==typeof n&&null!==n||rt(`${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&&rt(`${L} entry name must be a non-empty string.`),i.includes(s)&&rt(`${L} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&rt(`${L} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&rt(`${L} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&rt(`${L} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&rt(`${L} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&rt(`${L} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||rt(`${L} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&rt(`${L} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&rt(`${L} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&rt(`${L} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&rt(`${L} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??xa,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){Na.set(t,e)}(t,o),ba(t,new Set(o.keys()))}(this,t),this._listKeys=function(t){const e=t[R];if(void 0===e)return null;"object"==typeof e&&null!==e||rt(`${R} 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&&rt(`${R} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&rt(`${R} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&rt(`${R} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),"function"!=typeof o?("string"!=typeof o&&rt(`${R} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&rt(`${R} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&rt(`${R} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&rt(`${R} 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),function(t){Ba.delete(t),ja.delete(t)}(this),function(t){qa.delete(t)}(this),this._watchPaths=function(t,e){const n=e[O];if(void 0===n)return null;"object"==typeof n&&null!==n||rt(`[wcs/watch-declaration-invalid] ${O} must be an object mapping state paths to handler functions.${pt}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&rt(`[wcs/watch-declaration-invalid] ${O} entry "${e}" must be a function.${pt}`);const n=Ua(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){ja.set(t,e)}(t,o),s.size>0?s:null}(this,t),this._initialized&&null!==this._rootNode&&!e()&&(Va(this),La(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=Ni.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){rt("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 ca(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||rt(`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 da(t);rt(`Unsupported src file type: ${t}`)}}catch(t){rt(`Failed to initialize state: ${t}`)}}async _initializeVolume(){const t=this._rootNode,e=this.getAttribute("mount");try{!function(t){0===t.length&&rt('"mount" requires a non-empty tree path.');const e=K(t);for(const n of e.segments)0===n.length&&rt(`"mount" path "${t}" has an empty segment.`),n===r&&rt(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&rt(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(e),this.hasAttribute("bind-component")&&rt('"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=dr.get(t);void 0===n&&(n=new Set,dr.set(t,n)),n.has(e)&&rt(`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===Bi(t)&&function(t,e){const n=()=>{if(null!==Bi(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){let n=gr.get(t);void 0===n&&(n=[],gr.set(t,n)),n.push(e)}(t,{mountPath:n,volumeState:o,onGrafted:s}):yc(e,{mountPath:n,volumeState:o,onGrafted:s})}(t,Bi(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}await this._loadingPromise,Hi(this.rootNode,this)}_failInitialization(t){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),rt(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?X(a):null;null!==a&&null!==l||rt(`"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&&rt(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const d=this.getAttribute("bind-component");!function(t,e){let n=Vo.get(t);n||(n=new Set,Vo.set(t,n)),n.add(e)}(a,d);const u=Y(a);null===u&&rt(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await H(a),d in a||rt(`Component does not have property "${d}" for state binding.`);let h=a[d];"object"==typeof h&&null!==h||rt(`Component property "${d}" is not an object for state binding.`);const f=function(t,e){const n=Xs.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,d);if(void 0!==f&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=ut(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,d)&&(a[d]=f,h=f),this._boundComponent=a,this._boundComponentStateProp=d,i instanceof ShadowRoot||(ut(a)??[]).some(t=>t.propSegments[0]===d)||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="${d}: path").`),a.hasAttribute(o.bindAttributeName)){const o=(ut(a)??[]).filter(t=>t.propSegments[0]===d);if(o.length>0){const c=Bi(a.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${l}>.`);let u=(n=a,r=d,he.get(n)?.get(r)??null);const f=null!==u;if(null===u&&(function(t,e,n){const o=Ys.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;Ys.get(t).delete(e)}}(a,d,h),u=function(t,e,n,o,r,i=new Set){0===n.length&&rt(`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)&&rt("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 d=++Qt,u=`#m${d}`,{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:d,marker:u,component:t,stateProp:e,parentStateElement:o,entries:a,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+s+u,stateObject:r,getterKeys:h,setterKeys:f,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(a,d,o,c,h,(t=a,e=d,Qs.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){fc(`${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=pc(t),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=t.rootEntry.outerPathInfo.path;fc(`${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.`)}}(u)),this._mountRecord=u,this.parentNode!==i)return;try{uc(u,i instanceof ShadowRoot?i:a)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}if(!f){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=be(t.component);let s;return e[xe](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(ce(t,e))):(n,o,...r)=>{const i=ce(t,n),a=be(t.component)?.listIndex.indexes??[],l=de(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:ce(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:ce(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 ce(t,n),!0}catch{return!1}}})}(u);Object.defineProperty(a,d,{get:()=>t,enumerable:!0,configurable:!0}),Ko(a,d)}return dc(a,d),function(t){const e=Yt.filter(e=>void 0!==t.stateObject[e]);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Zt.has(n)||(Zt.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). See docs/state-mount-design.md §4-6.`))}(u),void te(u,"$connectedCallback")}}cc(this,this._boundComponent,this._boundComponentStateProp,h)}var t,e,n,r}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{S in t&&await t[Ee]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await da(t):rt(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await ca(e,t.tagName.toLowerCase()):rt(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){rt(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||rt(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Y(t);null!==r&&"function"==typeof r.define||rt(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&rt(`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:d,streamBackedBindables:u}=function(t){const e=al(t,k)??[],n=al(t,E)??[],o=rl(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}rt(`${k} entry "${t}" is not declared on the state.${ft(t,il(o,"value"))}`)}"function"==typeof e.value&&rt(`${k} entry "${t}" is a method. Declare it in ${E} instead.`)}for(const t of n){const e=o[t];void 0===e&&rt(`${E} entry "${t}" is not declared on the state.${ft(t,il(o,"method"))}`),"function"!=typeof e.value&&rt(`${E} entry "${t}" is not a method. Declare it in ${k} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||d.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,d):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(B))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=Y(this._shadow);return null!==t&&Z(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 ${k} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=rl(n);for(const[t,e]of Object.entries(g)){if(sl(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=ol(t,o)}else n.get=el(t),n.set=nl(t);Object.defineProperty(m.prototype,t,n)}for(const t of u)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:el(t),set:nl(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=>{$ in t&&t[Ce]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Bi(this._rootNode)===this._volumeGraftInfo.rootStateElement&&mc(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=Uo(e),o=be(t.component);n.forEachActiveBindingNode(t=>we(t,o)),qr(n.rebindAddresses()),$l(t)}(t,e)}),te(t,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||Bi(this._rootNode)===this||Hi(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 t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(B))return this.hasAttribute("bind-component")&&rt(`"bind-component" cannot be used inside a [${B}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(t.host,t);if(this.hasAttribute("mount")){if(this._volumeInitializing)return;return void await this._initializeVolume()}if(await this._initializeBindWebComponent(),null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await Wi(this.rootNode);const t=Ni.extractStateData(this),e=document.createElement(o.tagNames.ssr);e.setAttribute("version",mi),Ni.buildContent(e,t),this.parentNode?.insertBefore(e,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||Va(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||La(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&mc(this._volumeGraftInfo,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._mountRecord)return te(this._mountRecord,"$disconnectedCallback"),$l(this._mountRecord),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Hi(this.rootNode,null),ha.delete(this),function(t){pa.delete(t)}(this),$n(this),$a(this),Ta(this),function(t){Ba.delete(t)}(this),this._rootNode=null}}}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 watchPaths(){return this._watchPaths}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)&&rt(`$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}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 rootNode(){return null===this._rootNode&&rt("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("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+r)),!this._pathSet.has(t)){const e=K(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(ur(t.rootNode??null,n))return;const i=K(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=Pr.get(t);return void 0===n&&(n=new Set,Pr.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;const a=function(t,e,n){if(void 0!==_r(t,e))return wr;const o=K(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!==_r(t,a))return br;if(Object(i)!==i)return br;if(l===r){if(!Array.isArray(i)||0===i.length)return br;i=i[0];continue}const d=_r(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:vr(i,c,n)};if("function"==typeof d.get)return e===o.length-1?wr:br;i=d.value}return wr}(e,n,t.getterPaths);"missing"===a.existence&&(function(t,e){return!0===Cr.get(t)?.has(e)}(t,n)||("binding"!==o?Tr(0,n,o,a):function(t,e,n){let o=kr.get(t);void 0===o&&(o=new Map,kr.set(t,o)),o.set(e,n),Er.has(t)||(Er.add(t),setTimeout(()=>function(t){Er.delete(t);const e=kr.get(t);if(void 0!==e){kr.delete(t);for(const[t,n]of e)Tr(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=K(t.parentPath)}}}_createState(t,e,n){try{const o=function(t,e,n){const o=new rc(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){this._initialized?((this._hasGraftedVolumes||this._hasMounts)&&rt("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):this._resolveSetState?.(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,Ni),t.get(o.tagNames.state)||t.define(o.tagNames.state,bc)}(void 0),function(){const t=globalThis;void 0===t[Pi]&&(t[Pi]=Oi)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=ia)}(),ra()}();const wc={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"},_c=!1,vc=[".html"];function Nc(){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 Sc(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let $c=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const xc={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 Ic(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function Pc(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 kc={static:2,param:1,"catch-all":0};let Ec=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&&Sc(`${wc.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&Sc(`${wc.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+=kc[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(xc).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||Sc(`${wc.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:Ic(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new $c("Navigation cancelled by guard.",o);if(!o)throw new $c("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new $c("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},Cc=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=Nc();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new Ec(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||Sc(`${wc.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):Sc(`${wc.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&&Sc(`${wc.route} with fallback attribute must be a direct child of ${wc.router}.`),t.fallbackRoute&&Sc(`${wc.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 Ac=Symbol.for("wcstack.trustedTypes.policy"),Tc=Symbol.for("wcstack.trustedTypes.internal"),Mc="wcstack";function Lc(){const t=globalThis[Ac];return null===t||"object"!=typeof t?null:t}let Oc=!1;function Rc(t){const e=function(){const t=globalThis,e=t[Tc];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Mc,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof Lc()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Mc}". Allow it in the CSP (\`trusted-types ${Mc};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[Tc]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Lc(),s=o?.createHTML;return"function"==typeof s?(Oc||(Oc=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Mc}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Mc};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const jc=new Map;let Dc=class extends HTMLElement{_uuid=Nc();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||Sc(`${wc.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return jc.set(t,n),n}catch(e){Sc(`${wc.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(`${wc.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)jc.has(t)?n.innerHTML=Rc(jc.get(t)||""):n.innerHTML=Rc(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Rc(t):console.warn(`${wc.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")&&_c}get name(){return this.getAttribute("name")||""}},Bc=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||Sc(`${wc.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")&&_c}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Wc=new Set(["props","states","attr",""]);function zc(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 Fc(t,e){t.hasAttribute("data-bind")||Sc(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Wc.has(n)||Sc(`${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&&zc(t,e,o)}).catch(()=>{Sc(`Failed to define custom element: ${s}`)}):zc(t,e,o)}let Hc=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||Sc(`${wc.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(`${wc.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=>{Fc(e,t)}),e.hasAttribute("data-bind")&&Fc(e,t))}};function Uc(){return document.createElement(wc.layoutOutlet)}const qc="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Gc(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){Sc(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 ${qc}`:`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 ${qc}`}(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 Kc(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 Vc(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===wc.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),Kc(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===wc.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Gc(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===wc.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=Uc();o.layout=n,i=o,a=e}}const c=await Vc(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function Jc(t){const e=new Map;return await Vc(t,t.template.content,[],e)}function Xc(t){return!1!==t.checkVisibility?.()}function Qc(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 d=!1;if("param"===e.type){const t=e.paramType||"any",n=xc[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),d=!0)}else d=null!==e.pattern.exec(c);if(!d){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)Qc(s,e,n,o)}function Yc(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)Qc(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 Zc=null,td=null;function ed(){const t=vc;return 0===t.length?null:(Zc===t&&td||(Zc=t,td=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),td)}function nd(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=ed();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function od(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function sd(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=ed();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function rd(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function id(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=>{Fc(e,t.typedParams)}),n.hasAttribute("data-bind")&&Fc(n,t.typedParams),n.querySelectorAll(wc.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===wc.layoutOutlet&&n.assignParams(t.typedParams)}}function ad(t,e){id(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 ld=Symbol.for("wcstack.transition-runner");const cd=Symbol.for("wcstack.binder");function dd(){const t=globalThis[cd];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const ud=Symbol.for("wcstack.binder.pending"),hd=Symbol.for("wcstack.binder.taken");function fd(){const t=globalThis;let e=t[hd];return void 0===e&&(e=new WeakSet,t[hd]=e),e}function pd(t){const e=dd();return null===e?(function(){const t=globalThis;let e=t[ud];return void 0===e&&(e=[],t[ud]=e),e}().push(t),!1):(fd().add(t),e.bind(t),!0)}const md=new WeakSet,gd="data-wcs";function yd(t,e,n){!md.has(t)&&function(t){return t.hasAttribute(gd)||null!==t.querySelector(`[${gd}]`)}(t)&&(md.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==dd()||(o=t,fd().has(o))||console.warn(`[@wcstack/router] ${e} contains ${gd} 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 bd(t){for(const e of t.childNodeArray)1===e.nodeType&&(pd(e)||yd(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 wd(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 $c)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 _d(t,e,n,o,s=""){const r=od(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=Yc(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:Sc(`${wc.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 wd(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||rd(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=ad(o,e),n.length>0&&!s.has(o)&&bd(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[ld];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(Xc(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(Xc(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 vd(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Nd(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 Sd(t){return"?"===t?"":t}function $d(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 xd(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Id="data-wcs-ssr",Pd="data-wcs-ssr-link",kd="@@wcs-route-ph:",Ed="@@wcs-route-start:",Cd="@@wcs-route-end:",Ad=Object.freeze({});class Td 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=Ad;_typedParams=Ad;_searchParams=Ad;_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 nd(t)}_normalizeBasename(t){return sd(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(wc.outlet))return t;const e=document.createElement(wc.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||Sc(`${wc.router} has no outlet.`),this._outlet}get template(){return this._template||Sc(`${wc.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=Ic(t.search),s=t.data??null,r=this._data!==s,i=!Pc(this._params,e),a=this._routeName!==t.routeName,l=!Pc(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(`${wc.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(`${wc.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=Nd(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Sd(n.search)+n.hash,r=vd();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(od(t,this._basename));await _d(this,this.outlet,t,this._path,Sd(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(od(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await _d(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${wc.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 _d(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=xd();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||Sc(`${wc.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||Sc(`${wc.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await Jc(this),r=!t&&this._outlet.hasAttribute(Id);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&&Sc(`${wc.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(Id);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await _d(this,this.outlet,i,this._path,window.location.search||""),(r||null!==dd())&&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(wc.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(kd)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Ed)){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(Cd)){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 d=od(t,this._basename);let u=Yc(this,d);if(!u){if(null===this._fallbackRoute)return!1;u={routes:[this._fallbackRoute],params:{},typedParams:{},path:d,lastPath:this._path}}if(u.lastPath=this._path,u.routes.length!==r.size)return!1;for(const t of u.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 u.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 u.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(Ed)){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()===wc.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(Id);for(const t of u.routes)id(t,u);return this.outlet.lastRoutes=u.routes,!await wd(this,u)||(this.commitNavigation({params:u.params,typedParams:u.typedParams,routeName:u.routes[u.routes.length-1].name,data:u.data??null,search:window.location.search||"",path:d}),!0)}async _renderForSsr(t){const e=od(t,this._basename),n=Yc(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&Sc(`${wc.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await _d(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${kd}${t.absolutePath}`}),this.outlet.setAttribute(Id,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${Ed}${t.absolutePath}`),s=document.createComment(`${Cd}${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&&pd(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(!$d(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),xd()){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=vd();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&&(vd()?.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 Md=["title","rel","target","download","hreflang","lang","dir"];class Ld extends HTMLElement{static get observedAttributes(){return["to",...Md]}_childNodeArray=[];_uuid=Nc();_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(wc.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(wc.router);if(n)return this._router=n;Sc(`${wc.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 nd(t)}_joinInternalPath(t,e){const n=sd(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}=Nd(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+Sd(o)+s}else try{t.href=new URL(e).toString()}catch{Sc(`[${wc.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){xd()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Pd)?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(Pd),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-")||Md.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,xd())return this._updateActiveState(),void n.setAttribute(Pd,"");vd()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!vd()?.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(){vd()?.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(Md.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}=Nd(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 Od=[],Rd=new Map;let jd=!1;const Dd=new WeakMap;class Bd 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(),jd||(this._captureInitialHead(),jd=!0),Od.push(this),this._reapplyHead()}disconnectedCallback(){const t=Od.indexOf(this);-1!==t&&Od.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||Sc("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Dd.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Dd.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);Rd.has(t)||Rd.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Od)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Rd.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=Od.length-1;e>=0;e--){const o=Od[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Rd.has(n)&&(t=Rd.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),pd(t)||yd(t,`<${t.tagName.toLowerCase()}> inside <${wc.head}>`,`<${wc.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(wc.layout)||t.define(wc.layout,Dc),t.get(wc.layoutOutlet)||t.define(wc.layoutOutlet,Hc),t.get(wc.outlet)||t.define(wc.outlet,Bc),t.get(wc.route)||t.define(wc.route,Cc),t.get(wc.router)||t.define(wc.router,Td),t.get(wc.link)||t.define(wc.link,Ld),t.get(wc.head)||t.define(wc.head,Bd)}(void 0);const Wd="data-fetchtarget",zd={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Fd=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 Hd(t,e){return e.every(e=>"available"===t.availability.get(e))}const Ud=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let qd=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 Fd("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 Hd(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),d=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",u=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:d,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}(Ud,{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(!Hd(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:d="auto",timeout:u=0}=e;let h=null;u>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${u}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)},u));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"===d)s=await n.blob();else if("arrayBuffer"===d)s=await n.arrayBuffer();else if("text"===d)s=await n.text();else if("json"===d)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 u=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,u)),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)}}},Gd=!1;function Kd(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Wd}]`);if(!n)return;const o=n.getAttribute(Wd);if(!o)return;const s=customElements.get(zd.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function Vd(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 Jd=Symbol.for("wcstack.trustedTypes.policy");function Xd(){const t=globalThis[Jd];return null===t||"object"!=typeof t?null:t}let Qd,Yd=!1;let Zd=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...qd.wcBindable,properties:[...qd.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 qd(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(zd.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(zd.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=Xd(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Qd)return Qd;if(!("trustedTypes"in globalThis))return Qd=!1,Qd;try{document.createElement("div").innerHTML="<i></i>",Qd=!1}catch{Qd=!0}return Qd}())return void function(){if(Yd)return;Yd=!0;const t="function"==typeof Xd()?.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(!Vd(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Gd||(Gd=!0,document.addEventListener("click",Kd)),!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 tu extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class eu extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let nu=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 Zd&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(zd.fetch)||t.define(zd.fetch,Zd),t.get(zd.fetchHeader)||t.define(zd.fetchHeader,tu),t.get(zd.fetchBody)||t.define(zd.fetchBody,eu),t.get(zd.infiniteScroll)||t.define(zd.infiniteScroll,nu)}(void 0);const ou="data-storagetarget",su={storage:"wcs-storage"},ru="wcs-storage:value-changed",iu="wcs-storage:loading-changed",au="wcs-storage:error",lu="wcs-storage:error-info-changed",cu="wcs-storage:trigger-changed";let du=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:ru,semantics:"state",getter:t=>t.detail},{name:"loading",event:iu,semantics:"state"},{name:"error",event:au,semantics:"state"},{name:"errorInfo",event:lu,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(iu,{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(au,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(lu,{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(ru,{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)}},uu=!1;function hu(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${ou}]`);if(!n)return;const o=n.getAttribute(ou);if(!o)return;const s=customElements.get(su.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function fu(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 pu=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...du.wcBindable,properties:[...du.wcBindable.properties,{name:"trigger",event:cu,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 du(this),this._internals=this._initInternals(),this._wireStates({[iu]:t=>({loading:!0===t}),[au]: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(cu,{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(!fu(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",uu||(uu=!0,document.addEventListener("click",hu)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(su.storage)||t.define(su.storage,pu)}(void 0);const mu="*",gu="vanilla",yu={scanImportmap:!0,loaders:{[gu]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[mu]:gu},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function bu(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 wu(t,e,n){let o;if(null===e||e===mu||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===mu)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[mu],"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 _u=new Set,vu=new Map;let Nu=new WeakMap;function Su(t){if(t===globalThis.customElements)return vu;let e=Nu.get(t);return void 0===e&&(e=new Map,Nu.set(t,e)),e}const $u=new Map;async function xu(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 $u)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){_u.has(e)||(console.error(`Failed to eager load component '${e}':`,t),_u.add(e))}}function Iu(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 Pu(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&&$u.set(t,e)});const ku=new WeakSet,Eu=new WeakSet;async function Cu(t,e,n){t.shadowRoot&&(ku.has(t)||await async function(t,e,n){ku.add(t),await Lu(t.shadowRoot,e,n)}(t,e,n))}async function Au(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=Su(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=wu("",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),_u.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function Tu(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=Pu(t);void 0===o.get(s.name)?(Eu.has(t)||(Eu.add(t),o.whenDefined(s.name).then(async()=>{await Cu(t,e,n)})),a.has(s.name)||_u.has(s.name)||(a.add(s.name),i.push(s))):await Cu(t,e,n)}let l=0;for(const t of i)await Au(t,e,n,o),l++;return l}async function Mu(t,e,n,o){for(;await Tu(t,e,n,o)>0;);}async function Lu(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 Iu(e)}return Iu(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Mu(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 Mu(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class Ou extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),Ou._instance)throw new Error(`${yu.tagNames.autoloader} can only be instantiated once.`);Ou._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=bu(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=wu(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(xu(s,o,r))}await Promise.all(n)}(n,yu.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 Lu(document,yu,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,Ou._instance===this&&(Ou._instance=null)}}!function(t=customElements){t.get(yu.tagNames.autoloader)||t.define(yu.tagNames.autoloader,Ou)}(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="|",l="prevent",c="stop",d="ro",u="init",h="sync",f="else",p="...",m="on",g="eventToken",y="command",b="class",w="attr",v="style",_={};for(let t=0;t<128;t++)_[`$${t+1}`]=t;const $=Object.freeze(_),N="$connectedCallback",S="$disconnectedCallback",x="$updatedCallback",P="$errorCallback",I="$stateReadyCallback",k="$bindables",A="$commands",E="$commandTokens",C="$command",T="$eventTokens",M="$on",L="$streams",O="$watch",R="$recursion",j="**",D="$listKeys",B="$streamStatus",W="$streamError",z="data-wc-definition",F=new WeakMap,H=new WeakSet;let U=0;async function q(t){const e=function(t){let e,n=F.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++U,promise:o,resolve:e},F.set(t,n),H.has(t)&&n.resolve(),n}(t);await e.promise}function G(t){const e=F.get(t);void 0===e?H.add(t):e.resolve()}function V(t){throw new Error(`[@wcstack/state] ${t}`)}const K=new Map;let J=0;function X(t){let e=K.get(t);return void 0!==e||(-1!==t.indexOf(j)&&V(`[wcs/recursion-unsupported] "${t}" uses "${j}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`),e=Object.freeze(new Q(t)),K.set(t,e)),e}let Q=class{id=++J;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:X(e),n=t.split("."),o=[],s=[],i=[],a={},l=[],c=[],d=[],u=[];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),d.push(e(f)),u.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=d,this.wildcardParentPathInfoSet=new Set(d),this.wildcardPositions=u,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}};const Y=new WeakMap;function Z(t){const e=Y.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{Y.set(t,n)}}function tt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function et(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return tt(e);if(void 0!==n)return tt(n)}return tt(globalThis.customElements)}function nt(t,e){t.upgrade?.(e)}function ot(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=at(s.properties,st);if(null===r)return null;const i=void 0===s.inputs?new Map:at(s.inputs,rt);if(null===i)return null;const a=void 0===s.commands?new Map:at(s.commands,it);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function st(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 rt(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 it(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 at(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 lt(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:X(n),inFilters:[],outFilters:[],bindingType:"prop"}}function ct(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function dt(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&&V("Spread binding requires an element node.");const e=t,o=Z(e);null===o&&V(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=et(e);if(null===a&&V(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||V(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}nt(a,e);const l=ot(e);null===l&&V(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,d=new Set;for(const t of l.knownProperties.keys()){if(d.has(t))continue;d.add(t);const e=lt(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(d.has(t))continue;d.add(t);const e=lt(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=ct(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=ct(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 ut(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 ht=new WeakMap;function ft(t){return ht.get(t)||null}function pt(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 mt(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=pt(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const gt=" Validate statically: npx @wcstack/lint <file>.",yt=new Set(["if","elseif","else","for"]);function bt(t){V(`filter ${t} requires at least one option`)}function wt(t){V(`filter ${t} requires a number as option`)}function vt(t){V(`filter ${t} requires a number value`)}function _t(t){V(`filter ${t} requires a date value`)}function $t(t){return!(!t||isNaN(Number(t)))}const Nt={eq:t=>{const e=t?.[0]??bt("eq");return t=>"number"==typeof t?($t(e)||wt("eq"),t===Number(e)):t===e},ne:t=>{const e=t?.[0]??bt("ne");return t=>"number"==typeof t?($t(e)||wt("ne"),t!==Number(e)):t!==e},not:t=>t=>("boolean"!=typeof t&&V("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??bt("lt");return $t(e)||wt("lt"),t=>("number"!=typeof t&&vt("lt"),t<Number(e))},le:t=>{const e=t?.[0]??bt("le");return $t(e)||wt("le"),t=>("number"!=typeof t&&vt("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??bt("gt");return $t(e)||wt("gt"),t=>("number"!=typeof t&&vt("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??bt("ge");return $t(e)||wt("ge"),t=>("number"!=typeof t&&vt("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??bt("inc");return $t(e)||wt("inc"),t=>("number"!=typeof t&&vt("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??bt("dec");return $t(e)||wt("dec"),t=>("number"!=typeof t&&vt("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??bt("mul");return $t(e)||wt("mul"),t=>("number"!=typeof t&&vt("mul"),t*Number(e))},div:t=>{const e=t?.[0]??bt("div");return $t(e)||wt("div"),t=>("number"!=typeof t&&vt("div"),t/Number(e))},mod:t=>{const e=t?.[0]??bt("mod");return $t(e)||wt("mod"),t=>("number"!=typeof t&&vt("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&vt("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??bt("clamp");$t(e)||wt("clamp");const n=t?.[1]??bt("clamp");$t(n)||wt("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&vt("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return $t(e)||wt("fix"),t=>("number"!=typeof t&&vt("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&vt("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]??bt("slice");$t(n)||wt("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&($t(o)||wt("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??bt("substr");$t(e)||wt("substr");const n=t?.[1]??bt("substr");return $t(n)||wt("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??bt("pad");$t(e)||wt("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??bt("rep");return $t(e)||wt("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??bt("truncate");$t(e)||wt("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)||V("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 $t(e)||wt("round"),t=>{"number"!=typeof t&&vt("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return $t(e)||wt("floor"),t=>{"number"!=typeof t&&vt("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return $t(e)||wt("ceil"),t=>{"number"!=typeof t&&vt("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return $t(e)||wt("percent"),t=>("number"!=typeof t&&vt("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??bt("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||_t("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||_t("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||_t("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||_t("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||_t("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]??bt("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},St=Nt,xt={input:Nt,output:St},Pt=(t,e)=>n=>{const o=n[t];return o||V(`[wcs/filter-unknown] filter not found: ${t}.${mt(t,Object.keys(n))}${gt}`),o(e)};function It(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 kt=new Map;function At(t,e){const n=xt[e];return t.map(t=>{const o=t.indexOf("("),s=t.lastIndexOf(")");if(-1!==o&&-1===s&&V(`Invalid filter format: missing closing parenthesis in "${t}"`),-1!==s&&-1===o&&V(`Invalid filter format: missing opening parenthesis in "${t}"`),-1===o){const o=t.trim(),s=`${o}():${e}`;let r=kt.get(s);return void 0===r&&(r=Pt(o,[])(n),kt.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(It(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=It(n,r,i);return(l||s)&&e.push(l),e}(r),l=`${i}(${a.join(",")}):${e}`;let c=kt.get(l);return void 0===c&&(c=Pt(i,a)(n),kt.set(l,c)),{filterName:i,args:a,filterFn:c}}})}const Et=t=>t.trim(),Ct=new Map,Tt=new Map;function Mt(t){const e=t.indexOf(a);let n="",o=[],s="",r=[];return-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Tt.has(s)?r=Tt.get(s):(o=s.split(a).map(Et),r=At(o,"output"),Tt.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&V(`"${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:X(n),outFilters:r}}function Lt(t){const[...e]=t.split(";").map(Et).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&V(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim();if(n===f){const t=X("#else");return{propName:f,propSegments:[f],propModifiers:[],statePathName:"#else",statePathInfo:t,inFilters:[],outFilters:[],bindingType:"else"}}if(n===p){const e=Mt(o);return e.outFilters.length>0&&V(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&V(`Invalid spread binding "${t}": spread target path is required.`),{propName:p,propSegments:[p],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n||"radio"===n||"checkbox"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Mt(o),bindingType:n};{const t=Mt(o),e=function(t){const e=t.indexOf(a);let n="",o=[],r="",i=[];-1!==e?(n=t.slice(0,e).trim(),r=t.slice(e+1).trim(),Ct.has(r)?i=Ct.get(r):(o=r.split(a).map(Et),i=At(o,"input"),Ct.set(r,i))):n=t.trim();const[l,c]=n.split("#").map(Et),d=l.split(s).map(Et);return{propName:l,propSegments:d,propModifiers:c?c.split(",").map(Et):[],inFilters:i}}(n);return e.propSegments[0]===g||e.propSegments[0].startsWith(m)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>yt.has(t.bindingType))&&V(`[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">).${gt}`),n}const Ot=new WeakMap,Rt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),jt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Dt(t){const e=Ot.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=jt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Rt.has(r)?(Ot.set(t,s[2]),s[2]):null}function Bt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Mt(t),bindingType:"text"}}const Wt=new Map;function zt(t,e,n){if(null===n)Wt.delete(t);else{Wt.set(t,n);const o=Ki(e);null===o&&V("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 Ft(t){return Wt.get(t)||null}function Ht(t){if(t.nodeType===Node.ELEMENT_NODE)return Lt(t.getAttribute(o.bindAttributeName)||"");if(t.nodeType===Node.COMMENT_NODE){const e=Dt(t);null===e&&V("Comment node binding text not found.");const n=Ft(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Bt(e),s=null):s=e,[{...o,uuid:s}]}return[]}function Ut(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function qt(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!Ut(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function Gt(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 Vt(t){const e=[],n=qt(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!==Dt(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&Gt(t,n)||e.push(t)}return e}const Kt=new WeakSet;function Jt(t,e,n,o){const s=dt(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Z(t):null;return null===n&&V("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}Kt.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){ht.set(t,e)}(t,r),G(t),{bindings:r,deferred:null}}function Xt(t,e){const n=Vt(t),o=[],s=[];for(const t of n){if(Kt.has(t))continue;const n=Jt(t,Ht(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function Qt(t){Kt.add(t)}function Yt(t){const{node:e,parseResults:n,transform:o}=t;return function(t){Kt.delete(t)}(e),Jt(e,n,{allowDeferred:!1},o).bindings}let Zt=0;const te=["$watch","$streams","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion"],ee=new Set;function ne(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 oe(t){const e=t.indexOf(s);return-1===e?t:t.slice(0,e)}function se(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 re(t,e){for(const n of t.entries)if(se(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 ie(t,e){return t.markerBasePath+s+e}function ae(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:X(i).wildcardCount-X(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(i),t.addedGetterPaths.add(i))}function le(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 ce(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}.${oe(e)}: path") or declare the key on the component state.`}const de=/^\$(\d+)$/;function ue(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 ae(t,t.markerBasePath,e,e),ie(t,e);if(le(t,n[0]))return ae(t,t.markerBasePath,e,e),ie(t,e);const i=n.slice(0,o+1),a=n.slice(o+1),l=re(t,i);null===l&&V(ce(t,e)),0===a.length&&V(`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 ae(t,c,a.join(s),e),c+s+a.join(s)}(t,e);const o=oe(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return ie(t,e);if(le(t,o))return ie(t,e);const i=re(t,e.split(s));if(null!==i)return i;V(ce(t,e))}function he(t,e,n,o,s){if(void 0===o)return;const r=X(n).wildcardCount-X(e).wildcardCount;return 0===r?o:(s.length<r&&V(`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 fe=new WeakMap,pe=new WeakMap,me=new WeakMap,ge=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 ye(t){return fe.get(t)??null}function be(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=me.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 we=new WeakMap;function ve(t){let e=t;for(;e;){const t=we.get(e);if(t)return t;let n=e.parentNode;null===n&&e instanceof ShadowRoot&&null!==ye(e)&&(n=e.host),e=n}return null}function _e(t,e){null!==e?we.set(t,e):we.delete(t)}let $e=null;const Ne=new WeakMap;function Se(t){return Ne.get(t)??[]}function xe(t,e){Ne.set(t,e)}function Pe(t){return Ne.has(t)}const Ie=new WeakMap;let ke=null,Ae=0;function Ee(t){return Ie.get(t)??[]}function Ce(t,e){null===ke?Ie.set(t,e):ke.set(t,e)}function Te(t){return(ke?.has(t)??!1)||Ie.has(t)}const Me=Symbol("$$setLoopContext"),Le=Symbol("$$getByAddress"),Oe=Symbol("$$hasByAddress"),Re=Symbol("$$setByAddress"),je=Symbol("$$connectedCallback"),De=Symbol("$$disconnectedCallback"),Be=Symbol("$$updatedCallback"),We=Symbol("$$errorCallback"),ze=new WeakMap;function Fe(t,e){if(ze.has(t)){const n=ze.get(t);if(n.has(e))return n.get(e)}else ze.set(t,new WeakMap);const n=Object.freeze(new He(t,e));return ze.get(t).set(e,n),n}class He{pathInfo;stateElement;parentAbsolutePathInfo;constructor(t,e){this.pathInfo=e,this.stateElement=t,null===e.parentPathInfo?this.parentAbsolutePathInfo=null:this.parentAbsolutePathInfo=Fe(t,e.parentPathInfo)}}const Ue=new WeakMap,qe=new WeakMap;class Ge{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=Ve(t,e)}}function Ve(t,e){if(null===e){let e=qe.get(t);return void 0!==e||(e=new Ge(t,null),qe.set(t,e)),e}{let n=Ue.get(e);void 0===n&&(n=new WeakMap,Ue.set(e,n));let o=n.get(t);return void 0!==o||(o=new Ge(t,e),n.set(t,o)),o}}const Ke=new WeakMap;function Je(t,e){null===e?Ke.delete(t):Ke.set(t,e)}function Xe(t){return Ke.get(t)||null}const Qe=new Map;function Ye(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=Qe.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Qe.set(s,r)),r}function Ze(t,e,n){return e<0||e>=n?null:t.at(e-n)}function tn(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const en=new WeakMap;function nn(t){const e=ve(t.node);if(null===e)return null;let n=en.get(e);if(void 0===n)n=new WeakMap,en.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Ye(e.pathInfo,t.statePathInfo);return n>0&&(o=Ze(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const on=new WeakMap;function sn(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Xe(n);null===e?V(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function rn(t,e){let n=null;if(n=on.get(t)||null,null!==n)return n;const o=sn(t,e),s=nn(t),r=Ki(o);return null===r&&V("No state tree found on this root for binding."),n=Ve(Fe(r,t.statePathInfo),s),on.set(t,n),n}function an(t){on.delete(t)}const ln=new WeakMap;function cn(t,e){const n=ln.get(t);void 0===n?ln.set(t,e):n instanceof Set?n.add(e):n!==e&&ln.set(t,new Set([n,e])),null!==$e&&$e({type:"state:binding-added",absoluteAddress:t,binding:e})}function dn(t,e){const n=ln.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&ln.delete(t),null!==$e&&$e({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const un=new WeakMap;function hn(t,e,n){const o=un.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==$e&&$e({type:"state:binding-removed",absoluteAddress:Ve(t,e),binding:n}))}function fn(t){const e=ln.get(t);return void 0!==e?e:null!==t.listIndex?un.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const pn=new WeakMap,mn=new WeakMap;class gn{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=yn(t,e)}}function yn(t,e){if(null===e){let e=mn.get(t);return void 0!==e||(e=new gn(t,null),mn.set(t,e)),e}{let n=pn.get(e);void 0===n&&(n=new WeakMap,pn.set(e,n));let o=n.get(t);return void 0!==o||(o=new gn(t,e),n.set(t,o)),o}}const bn=new WeakMap;function wn(t){let e=null;if(e=bn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=nn(t);null===n&&V(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=yn(t.statePathInfo,n)}else e=yn(t.statePathInfo,null);return bn.set(t,e),e}function vn(t){bn.delete(t)}function _n(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const $n=new Map,Nn=_n();function Sn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function xn(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function Pn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function In(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)Pn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class kn{_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 An extends kn{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==$e&&$e({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const En=new WeakMap;function Cn(t,e){let n=En.get(t);void 0===n&&(n=new Map,En.set(t,n));let o=n.get(e);return void 0===o&&(o=new An(e,t),n.set(e,o)),o}function Tn(t){En.delete(t)}const Mn=new WeakMap;class Ln extends kn{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==$e&&$e({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function On(t){return t instanceof Ln}const Rn=new Map,jn=_n();function Dn(t){const e=t.propModifiers.filter(t=>t===l||t===c).sort().join(",");return`${t.statePathName}::${e}`}function Bn(t){if(!t.propName.startsWith(m))return!1;const e=Dn(t);let n=Rn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(l)&&o.preventDefault(),e.includes(c)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Ki(r);null===i&&V("No state tree found on this root for event handler.");const a=ve(s),d=t.startsWith(C+".");i.createStateAsync("writable",async e=>{const l=e[Me](a,()=>{let l=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=fe.get(n);if(void 0!==t)return t;n=n.parentNode}return fe.get(e)??null}(s,r);if(null!==t){const e=t.indexShiftByLoopElementPath.get(a.pathInfo.path);l=void 0!==e?l-e:0}}const c=null!==a?tn(a.listIndex,l):[];if(d){const s=e[Le](yn(n,null));return On(s)||V(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...c)}const u=e[t];return"function"!=typeof u&&V(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(u,e,[o,...c])});In(l,`"${t}"`)})})(t.statePathName,t.propModifiers,t.statePathInfo),Rn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),jn.add(e,t),!0}const Wn=new Map,zn=_n();function Fn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Hn(t){let e="input";for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}const Un=new Set(["radio","checkbox"]),qn=new Set(["value","valueAsNumber","valueAsDate"]);function Gn(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(Un.has(t)&&"checked"===e)return!0;if(qn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Z(n);if(null!==s){const t=et(n)?.get(s);void 0===t&&V(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=ot(n);if(o?.knownProperties.has(e))return!0}return!1}let Vn=1,Kn=1,Jn=1;const Xn=new WeakMap;function Qn(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=Vn++,o.set(s,r)),r}function Yn(t,e){return"to-element"===e?2*t:2*t+1}const Zn=new Set;function to(t){return{transactionId:Kn++,originBindingId:t,visitedEdges:Zn,hop:0}}function eo(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 no=null;function oo(){return no}function so(t,e){const n=no;no=t;try{return e()}finally{no=n}}const ro=[];let io=!1;const ao=new Map,lo=_n(),co=new WeakMap,uo=t=>t.detail,ho=new WeakMap;function fo(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 po(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Z(t.node);if(null!==n){const o=et(t.node)?.get(n);void 0===o&&V(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=ot(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(m)&&(e=n.slice(2));return e}function mo(t){if(null!==Z(t.node)){const e=ot(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??uo}return null}function go(t){if(null===Z(t.node))return!1;const e=ot(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const yo=new WeakSet;function bo(t){yo.add(t)}function wo(t){return!!yo.has(t)&&(yo.delete(t),!0)}const vo=new WeakSet;function _o(t){vo.add(t)}function $o(t){return!!vo.has(t)&&(vo.delete(t),!0)}let No=0;function So(){No--}function xo(){return No>0}class Po{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 Io=new WeakMap;function ko(t){let e=Io.get(t);return void 0===e&&(e=new Po(t),Io.set(t,e)),e}function Ao(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!==u&&s!==h&&V(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&V(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Eo(t){return t.propModifiers.some(t=>t.includes("="))}const Co=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),To=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Mo(t,e){return"state"===t&&"call"===e?Co:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Lo(t){if(!o.enableDirectionalInitialSync)return Eo(t)&&V("init=/sync= modifiers require enableDirectionalInitialSync."),Co;const e=null===(n=Ao(t,u))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:V(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":V(`Invalid sync modifier value "${t}".`)}(Ao(t,h));if("event"===t.bindingType)return null!==e&&"none"!==e&&V("Event bindings only allow init=none."),"call"===s?To:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===y)return Mo("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&V(`Binding type "${t.bindingType}" does not support init=${e}.`),Mo(e??"state",s);const r=ot(t.node);if(null===r)return Mo(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||V(`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)||V(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||V(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let Oo=0,Ro=0;const jo=new WeakMap,Do=new WeakMap,Bo=new WeakMap,Wo=new WeakMap;function zo(t,e){const n=Wo.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Wo.set(t,new Set([n,e]))):Wo.set(t,e)}function Fo(t){return Wo.has(t)}function Ho(t,e){const n=Wo.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Uo(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Uo(n,e)}function qo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class Go{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)wo(t)||Uo(t,t=>{Ho(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)$o(t)&&!xo()||Uo(t,t=>{Ho(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&ti(o)}}const Vo=new WeakMap;function Ko(t){let e=Vo.get(t);return void 0===e&&(e=new Go(t),Vo.set(t,e)),e}function Jo(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 Qo{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=jo.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(qo(e)&&Ko(e),null===this.rowPlan)for(const n of t){const t=jo.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 Eo(t)&&Lo(t),!0;const e=jo.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=jo.get(t);return e?.session===this?e:null}addTeardown(t,e){const n=jo.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(Xo(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=et(t);null===s&&V(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),zo(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=ko(s).wait(e,()=>{if(a())try{nt(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=jo.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&&(dn(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?rn(n):null;if(null!==e.address?(dn(e.address,n),e.address=null):(hn(e.patternPathInfo,e.patternListIndex,n),e.patternPathInfo=null,e.patternListIndex=null),vn(n),an(n),this.registerAddress(e),null!==o){const t=rn(n);t!==o&&Pe(o)&&xe(t,Se(o)),t!==o&&Te(o)&&Ce(t,Ee(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return qo(e)?e:null}(t);null!==e&&Ko(e)}handleMutations(t,e,n){for(const n of e)Uo(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Uo(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&ti(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=jo.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=Jo(e),Bo.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;zo(n,this);const o=this.knownMapFor(n);let s=Bo.get(t);void 0===s&&(s=Jo(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;zo(a,this),this.addKnownRowBinding(a,r,s),this.optionsByBinding.set(r,n);const l={id:++Oo,info:r,generation:++Ro,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(jo.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=jo.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=++Ro,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:++Oo,info:t,generation:++Ro,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};jo.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]!==g?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=Hn(t),s=Fn(t,o);let r=Wn.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=Ki(o.getRootNode());null===r&&V("No state tree found on this root for two-way binding.");const i=ve(o);r.createState("writable",t=>{t[Me](i,()=>{t[e]=s})})},Wn.set(s,r)),t.node.addEventListener(o,r),zn.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=Hn(t),n=Fn(t,e),o=Wn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==zn.countOf(n)&&(zn.remove(n,t)&&Wn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(d)){const o=xn(t),s=Sn(t,o);let r=$n.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=Ki(o.getRootNode());null===i&&V("No state tree found on this root for two-way binding.");const a=ve(o);i.createState("writable",t=>{t[Me](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]:[]})})},$n.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=xn(t),n=Sn(t,e),o=$n.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Nn.countOf(n)&&(Nn.remove(n,t)&&$n.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Gn(e.node,e.propName)&&-1===e.propModifiers.indexOf(d)){const n=function(t,e,n){let o=co.get(t);void 0===o&&(o=new Map,co.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&&co.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=Z(t.node);if(null!==e){const n=et(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&V(`CustomElementRegistry is unavailable for <${e}>.`))}if(Gn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=po(t),n=mo(t),s=go(t),r=fo(t,e,null!==n,s);let i=ao.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!==uo||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=ho.get(t);void 0===r&&(r=new Set,ho.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 d=co.get(a)?.get(t);if(void 0!==d)for(const t of d)t(c);let u=null;if(o.enablePropagationContext){const n=Qn(a,t,e),s=function(t,e){for(let n=ro.length-1;n>=0;n--){const o=ro[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==$e&&$e({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Yn(n,"to-state"),node:a,member:t}));const r=Yn(n,"to-state"),i=oo();if(null!==i&&i.visitedEdges.has(r))return void(null!==$e&&$e({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));u=eo(i??to(n),r)}const h=Ki(a.getRootNode());null===h&&V("No state tree found on this root for two-way binding.");const f=ve(a),p=()=>{r&&(io=!0);try{h.createState("writable",t=>{t[Me](f,()=>{t[e]=c})})}finally{r&&(io=!1)}};null!==u?so(u,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),ao.set(r,i)),t.node.addEventListener(e,i),lo.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==g)return!1;const e=t.node,n=Z(e),o=et(e);if(null!==n&&void 0===o?.get(n))return null===o&&V(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(Mn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||V('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Z(t)?null:ot(t)}(e);null===r&&V(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&V(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${mt(s,r.knownProperties.keys())}`);const a=i.event,d=t.statePathName,u=t.propModifiers,h=t=>{u.includes(l)&&t.preventDefault(),u.includes(c)&&t.stopPropagation();const n=Ki(e.getRootNode());null===n&&V("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(d)||V(`[wcs/token-undeclared] eventToken "${d}" is not declared in $eventTokens.${mt(d,n.eventTokenNames)}${gt}`);const o=ve(e);n.createStateAsync("writable",async e=>{In(e[Me](o,()=>{const s=null!==o?tn(o.listIndex,o.pathInfo.wildcardCount):[];return Cn(n,d).emit(e,t,...s)}),`$on."${d}"`)})};return e.addEventListener(a,h),Mn.set(t,{eventName:a,handler:h}),!0})(e)&&Xo(t,()=>function(t){if(t.propSegments[0]!==g)return!1;const e=Mn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),Mn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Z(t.info.node);if(null===n)return void e();const o=et(t.info.node);if(null===o&&V(`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=ko(o).wait(n,()=>{if(this.isAlive(t,s))try{nt(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=Ki(t.replaceNode.getRootNode());null===e&&V("No state tree found on this root for binding.");const n=wn(t);let o=!1;return e.createState("readonly",t=>{o=t[Oe](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void No++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,So()),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=Ki(t.node.getRootNode());null===o&&V("No state tree found on this root for initial binding sync.");const s=ve(t.node);o.createState("writable",e=>{e[Me](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=nn(n);if(null!==o){const s=Ki(sn(n,e));null===s&&V("No state tree found on this root for binding.");const r=Fe(s,n.statePathInfo);!function(t,e,n){let o=un.get(t);void 0===o&&(o=new WeakMap,un.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==$e&&$e({type:"state:binding-added",absoluteAddress:Ve(t,e),binding:n})}(r,o,n),t.patternPathInfo=r,t.patternListIndex=o}else{const o=rn(n,e);cn(o,n),t.address=o}if(!t.options.registerPathInfo)return;const s=Ki(n.replaceNode.getRootNode());null===s&&V("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&&jo.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,So());const e=t.info;if(null!==t.address)try{dn(t.address,e),t.address=null,vn(e),an(e)}catch{}else if(null!==t.patternListIndex)try{hn(t.patternPathInfo,t.patternListIndex,e),t.patternPathInfo=null,t.patternListIndex=null,vn(e),an(e)}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=Z(t.node);if(null!==e){const n=et(t.node),o=n?.get(e);if(void 0===o)return}if(Gn(t.node,t.propName)&&-1===t.propModifiers.indexOf(d)){const e=po(t),n=fo(t,e,null!==mo(t),go(t)),o=ao.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),lo.remove(n,t)&&ao.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(m))return!1;const e=Dn(t),n=Rn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);t.node.removeEventListener(o,n),0!==jn.countOf(e)&&jn.remove(e,t)&&Rn.delete(e)}(e)}catch{}}}}function Yo(t){let e=Do.get(t);return void 0===e&&(e=new Qo(t),Do.set(t,e)),e}function Zo(t){return jo.get(t)?.session??null}const ts=new WeakMap;function es(t,e){let n=ts.get(t);n||(n=new Set,ts.set(t,n)),n.add(e)}const ns=new WeakMap;function os(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const ss=Object.freeze([]),rs=new WeakMap,is=new WeakMap;function as(t){return is.get(t)??[]}function ls(t,e){is.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 cs=0;function ds(){return`u${(cs++).toString(36)}`}let us=0;class hs{uuid=ds();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;constructor(t,e){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._index=e,this._version=us}get index(){return this._index}set index(t){this._index=t,this._version=++us,this.indexes[this.position]=t}get version(){return this._version}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=us),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0===this._listIndexes&&(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)]),this._listIndexes}get varName(){return`$${this.position+1}`}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function fs(t,e){return new hs(t,e)}const ps=new WeakMap;function ms(t){return ps.get(t)||null}function gs(t,e){null!==e?ps.set(t,e):ps.delete(t)}const ys=new WeakMap,bs=Object.freeze([]),ws=new Set;function vs(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:bs,s=Array.isArray(n)&&n.length>0?n:bs,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:bs,o=Array.isArray(e)&&e.length>0?e:bs;let s=ys.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=ms(o)||[];let a;try{if(0===s.length)return a={oldIndexes:i,newIndexes:[],changeIndexSet:ws,deleteIndexSet:new Set(i),addIndexSet:ws};let e=ms(s);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=fs(t,n);e.push(o)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:ws,deleteIndexSet:ws,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 a={oldIndexes:i,newIndexes:i,changeIndexSet:ws,deleteIndexSet:ws,addIndexSet:ws};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,l=new Set;for(let o=0;o<s.length;o++){const a=s[o],c=n.get(a),d=c&&c.length>0?c.shift():void 0;if(void 0===d){const n=fs(t,o);e.push(n),l.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return a={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:l}}finally{void 0!==a&&(function(t,e,n){let o=ys.get(t);o||(o=new WeakMap,ys.set(t,o)),o.set(e,n)}(o,s,a),gs(s,a.newIndexes))}}(t,e,n);return function(t){for(let e=0;e<t.length;e++)t[e].index!==e&&(t[e].index=e)}(o.newIndexes),o}const _s=new WeakMap;function $s(t){return _s.get(t)??[]}function Ns(t,e){_s.set(t,e)}const Ss=new WeakMap;function xs(t){return Ss.get(t)??null}function Ps(t,e){Ss.set(t,e)}const Is=new WeakMap;function ks(t){return Is.get(t)??[]}function As(t,e){Is.set(t,e)}function Es(t,e){const n=ks(t);for(const t of n)_e(t,e)}function Cs(t,e,n){Es(t,e);const o=$s(t),s=xs(t);null!==s&&s.activate(o,n.rootNode);for(const t of o)null===s&&cn(rn(t),t),(null===s||s.shouldApplyState(t))&&Yr(t,n)}function Ts(t){if(!t.mounted)return;const e=$s(t),n=xs(t);for(const t of e)null!==n?n.disposeBinding(t):dn(rn(t),t);!function(t){const e=ks(t);for(const t of e)_e(t,null)}(t)}const Ms=new WeakMap,Ls=Object.freeze(new Set);function Os(t,e){const n=Ms.get(t);n?n.add(e):Ms.set(t,new Set([e]))}function Rs(t){const e=Ms.get(t);return void 0!==e?e:Ls}function js(t,e){const n=Ms.get(t);n&&(n.delete(e),0===n.size&&Ms.delete(t))}const Ds=new Set(["if","elseif","else","for"]);class Bs{_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=xs(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRecords();for(const t of this._childNodeArray)bo(t),null!==t.parentNode&&t.parentNode.removeChild(t);const e=$s(this);for(const t of e)if(Ds.has(t.bindingType)){const e=Rs(t.node);for(const t of e)t.tryDestroy()||t.unmount()}return this._mounted=!1,!0}unmount(){xs(this)?.dispose();for(const t of this._childNodeArray)bo(t),null!==t.parentNode&&t.parentNode.removeChild(t);const t=$s(this);for(const e of t){if(Ds.has(e.bindingType)){const t=Rs(e.node);for(const e of t)e.unmount()}vn(e),an(e)}this._mounted=!1}}function Ws(t){const e=document.createDocumentFragment(),n=new Bs(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 zs(t){void 0!==t.uuid&&null!==t.uuid||V("BindingInfo.uuid is null.");const n=Ft(t.uuid);n||V(`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=ut(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===y||s===g)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Z(r))return null;if("prop"===o&&Gn(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 $,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=ut(o,s[t].nodePath);null===e&&V(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),Qt(e),G(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 Qo;return n.initializeRow(t,e),n}(n,a),d=new Bs(o);return Ps(d,c),Ns(d,a),ls(d,l),As(d,r),Os(t.node,d),d}(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=ut(t,s.nodePath);if(null===e&&V(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),Kt.has(e))continue;const r=Jt(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new Qo;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 Bs(i,s);Ps(l,a.bindingSession),Ns(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in $&&c.push(t);return ls(l,c),As(l,a.nodes),Os(t.node,l),l}const Fs=Symbol.for("wcstack.transition-runner");function Hs(t){const e=globalThis[Fs];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}const Us=new WeakSet,qs=Symbol.for("wcstack.state.view-transition-naming");function Gs(){const t=Hs("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Vs(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||Us.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[qs]??={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.`)):(Us.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 Ks=new WeakMap,Js=new WeakMap,Xs=new WeakMap,Qs=new WeakMap;function Ys(t,e,n){!function(t,e,n){let o=Js.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Js.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Zs(t,e){Ks.set(t,e)}function tr(t,e){let n=Xs.get(t.node);void 0===n&&(n=[],Xs.set(t.node,n)),n.length<1e3?n.push(e):js(t.node,e)}function er(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 nr(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function or(t,n,s){const r=Boolean(s);let i;const a=Rs(t.node);i=0===a.size?zs(t):a.values().next().value;const l=e(),c=t.uuid??"",d=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${nr(t)}`),Ts(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${nr(t)}`),l){const e=document.createComment(`@@wcs-${d}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${d}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);Cs(i,ve(t.node),n);const e=Gs();null!==e&&Vs(i,"branch",e)}}const sr=new WeakMap,rr=new WeakMap,ir=new WeakMap,ar=new WeakMap;function lr(t){return ar.get(t)??[]}const cr=new Set,dr=Symbol.for("wcstack.trustedTypes.policy");function ur(){const t=globalThis[dr];return null===t||"object"!=typeof t?null:t}let hr,fr=!1;const pr={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 mr(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],d=r[c];if(d!==s){null!==d&&"object"==typeof d&&null!==s&&"object"==typeof s&&null!==Z(r)&&function(t,e,n){let o=sr.get(t);o||(o=new Map,sr.set(t,o)),o.has(e)||o.set(e,n)}(r,c,d);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=ur(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(fr)return;if(!function(){if(void 0!==hr)return hr;if(!("trustedTypes"in globalThis))return hr=!1,hr;try{document.createElement("div").innerHTML="<i></i>",hr=!1}catch{hr=!0}return hr}())return;fr=!0;const n="function"==typeof ur()?.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=Z(t);if(null===n)return null;const o=et(t)?.get(n);if(void 0===o)return null;const s=ot(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&&Gn(r,c)){const e=Qn(r,c,t.statePathName),o=Yn(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??oo()??to(e);if(a.visitedEdges.has(o))null!==$e&&$e({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=eo(a,o);so(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Jn++,writtenValue:n};ro.push({receipt:i,node:t});try{return r()}finally{ro.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=pr[c];t?t(r,s):(function(t,e,n){let o=ar.get(t);o||(o=[],ar.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,cr.add(a))}return}var a,l;const c=i[0];let d=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==d)return;d=d[e]}const u=i[i.length-1],h=d[u];if(h!==s){if(Object.isFrozen(d))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 d&&null!==d&&null!==Z(r)&&(u in d?function(t,e,n,o){let s=ir.get(t);s||(s=new Map,ir.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,u,d[u]):function(t,e,n){let o=rr.get(t);o||(o=new Map,rr.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)}(r,c,u));try{d[u]=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 gr=new WeakSet;function yr(t,e,n){}const br=new WeakMap;function wr(t,e){if(null===t)return!1;const n=br.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 vr=new WeakMap;function _r(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 $r=new WeakMap,Nr=[],Sr=new WeakMap;let xr=null;const Pr=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Ir=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])});function kr(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 Ar(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 Er={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing"},Cr={binding:"Bound path",watch:"$watch path"};function Tr(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}.${gt}`}function Mr(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 Lr(t,e){return`$setAll("${t}") ${e}`}function Or(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.${gt}`}const Rr=new WeakMap;const jr=new WeakMap,Dr=new WeakSet,Br=new WeakMap;function Wr(t,e){let n=Br.get(t);void 0===n&&(n=new Set,Br.set(t,n)),n.add(e),jr.get(t)?.delete(e)}function zr(t,e,n,o){console.warn(`[@wcstack/state] [${Er[n]}] ${Cr[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${mt(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${gt}`),null!==$e&&$e({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const Fr=new WeakSet;function Hr(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Ur=Object.freeze({[b]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&V("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[w]:function(t,e,n){const o=t.node,s=t.propSegments[1];o.getAttribute(s)!==n&&o.setAttribute(s,n)},[v]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;s[o]!==n&&(s[o]=n)},[y]:function(t,e,n){On(n)||V("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=rs.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||V('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Z(t);if(null===e)return null;const n=et(t)?.get(e);return void 0===n&&V(`Custom element <${e}> is not defined for command binding.`),ot(t)}(r);null===a&&V(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||V(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${mt(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),rs.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 rs.delete(t);const o=n[i];return"function"!=typeof o&&V(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),rs.set(t,{token:o,unsubscribe:c,elementRef:l})}}),qr={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!gr.has(t.replaceNode)){gr.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=nn(t),a=rn(t),l=Se(a),c=l.length>0&&!Js.has(t.node)?[]:l,d=vs(i,c,o);n.newListValueByAbsAddress.set(a,Array.isArray(o)?o:[]);const u=Array.isArray(c)&&c.length===d.deleteIndexSet.size&&d.deleteIndexSet.size>0;if(u&&null!==t.node.parentNode){let e=Qs.get(t.node);if(void 0===e){const n=Ks.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),Qs.set(t.node,e)}if(e){const e=t.node.parentNode;e.textContent="",e.appendChild(t.node)}}let h=Js.get(t.node),f=u?1e3-function(t){return Xs.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==h){for(const e of d.deleteIndexSet){const n=h.get(e);void 0!==n&&(f<=0&&n.tryDestroy()?js(t.node,n):(Ts(n),n.unmount(),tr(t,n),f-=1),u||h.delete(e))}u&&(Js.delete(t.node),h=void 0)}let p=t.node;const m=X(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}(d);let b=null;d.newIndexes.length==d.addIndexSet.size&&d.newIndexes.length>0&&p.isConnected&&(b=document.createDocumentFragment(),Je(b,n.rootNode));const w=e(),v=Gs(),_=t.uuid??"",$=Xs.get(t.node);for(const e of d.newIndexes){let o;if(d.addIndexSet.has(e)){const r=yn(m,e);g.createLoopContext(r,r=>{if(o=void 0!==$?$.pop():void 0,void 0===o&&(o=zs(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)}}Cs(o,r,n),null!==v&&Vs(o,"row",v)}),void 0===o&&V(`Content not found for ListIndex: ${e.index} at path "${s.path}"`)}else{if(o=void 0!==h?h.get(e)??null:null,d.changeIndexSet.has(e)){const t=as(o);for(const e of t)Yr(e,n)}null===o&&V(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==y&&y.has(e)&&er(p,o.firstNode)||p.nextSibling===o.firstNode||o.mountAfter(p),t){const t=o,s=yn(m,e);g.createLoopContext(s,e=>{Cs(t,e,n)})}}p=o.lastNode||p,void 0===h&&(h=new WeakMap,Js.set(t.node,h)),h.set(e,o)}Ks.set(t.node,p),null!==b&&(t.node.parentNode.insertBefore(b,t.node.nextSibling),Je(b,null))},if:or,else:or,elseif:or,radio:function(t,e,n){const o=t.node,s=os(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=os(o.value,t.inFilters),r=Array.isArray(n)?n:ss;o.checked=r.includes(s)}},Gr=new WeakMap,Vr=new WeakMap,Kr=new WeakMap;function Jr(){}function Xr(t){const e=t.replaceNode,n=t.propSegments[0];return function(t,e){return!0===ts.get(t)?.has(e)}(e,n)?yr:function(t,e){return!0===ns.get(t)?.has(e)}(e,n)?Jr:mr}function Qr(t,e){const n=os(function(t,e){const n=wn(e);if(n.pathInfo.path in $){const t=ve(e.node);return null===t&&V(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&V("ListIndex not found for loopContext:");const n=$[e];void 0===n&&V(`Invalid index name: ${e}`);const o=Ze(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&V(Or(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Le](n)}(e.state,t),t.outFilters);if(!0===Vr.get(t))return void e.deferredSelectBindings.push({binding:t,value:n,stateElement:e.stateElement});let o=Gr.get(t);if(void 0===o){if(Gr.has(t))return o=Xr(t),o===yr&&Gr.set(t,o),void o(t,e,n);if(o=qr[t.bindingType],void 0===o){const e=t.propSegments[0];o=Ur[e],Gr.set(t,o),void 0===o&&(Z(t.replaceNode)?(o=Xr(t),o===yr&&Gr.set(t,o)):(o=mr,Gr.set(t,o)))}if(o===mr&&"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 Vr.set(t,!0)}o(t,e,n)}else o(t,e,n)}function Yr(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=rn(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=Zo(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Kr.get(t)){const e=Z(t.replaceNode);if(e&&void 0===et(t.replaceNode)?.get(e))return void function(t,e){if(Fr.has(t))return;Fr.add(t);const n=()=>{Fr.delete(t);const e=Zo(t);(null===e||e.shouldApplyState(t))&&ti([t])},o=n=>{Fr.delete(t),Hr(e,n)},s=Zo(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Fr.delete(t),r()})||(Fr.delete(t),r()))}const r=et(t.replaceNode);if(null===r)return Fr.delete(t),void Hr(e,new Error("CustomElementRegistry is unavailable."));ko(r).wait(e,()=>{t.replaceNode.isConnected?n():Fr.delete(t)},o)}(t,e);Kr.set(t,!0)}if(!0===e.sameRootVerified)return void Qr(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Xe(o),null===o&&V("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Ki(o);null===n&&V("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};Qr(t,r)})}else Qr(t,e)}function Zr(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==$e&&$e({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function ti(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 d=c.replaceNode.getRootNode();d instanceof DocumentFragment&&!(d instanceof ShadowRoot)&&(d=Xe(d),null===d&&V("Root node for fragment not found for binding."));const u=Ki(d);null===u&&V("No state tree found on this root for binding."),u.createState("readonly",o=>{const h={rootNode:d,stateElement:u,state:o,appliedBindingSet:s,newListValueByAbsAddress:r,updatedAbsAddressSetByStateElement:i,deferredSelectBindings:a,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Yr(c,h)}catch(t){Zr(c,t,u,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{mr(t,{propagationContextByBinding:e},n)}catch(e){Zr(t,e,o??null,l)}for(const[t,e]of r.entries())xe(t,e),Ce(t,e);for(const[t,e]of i.entries())t.createState("writable",t=>{t[Be](Array.from(e))});for(const[t,e]of l.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[We](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 ei(t,e,n){const[o,s,r]=Xt(t,n),i=Yo(t);for(const t of o)_e(t,e);ti(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=Yt(o);0!==t.length&&(_e(o.node,e),ti(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const ni=/\{\{\s*(.+?)\s*\}\}/g,oi=new Set(["SCRIPT","STYLE"]);function si(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&&oi.has(t.parentElement.tagName)||ri(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),si(e.content)}else si(t.content)}function ri(t){const e=t.data;if(ni.lastIndex=0,!ni.test(e))return;ni.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=ni.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 ii;function ai(){if(ii)return ii;const t=[],e=Pt("not",t)(St);return ii={filterName:"not",args:t,filterFn:e},ii}const li=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function ci(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 di(t,e){const n=li.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+ci(s,e)+r}function ui(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=ci(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function hi(t,e){return ui(t,e)}function fi(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=di(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=ui(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 mi(t){const e=[],n=Vt(t);for(const t of n){const n=Ht(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 gi(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const yi=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),bi=ai();function wi(t,e){const n=e.outFilters;return{...e,outFilters:[...n,bi],bindingType:t}}function vi(t,e,n,o,s,r=!0){gi(e),"string"==typeof o&&fi(e,o),_i(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:mi(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 _i(t,e,n,s){const r=o.commentElsePrefix,i=qt(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=[],d=[];for(;a.nextNode();){const t=a.currentNode;d.push(t)}for(const e of d){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=hi(i,n));let a=Lt(i)[0];const d=yi.get(a.bindingType);if(void 0===d)continue;const u=a.bindingType,h=e.content,f=ds();let p=null;const m="for"===u?a.statePathName:n;if("else"===u){null===l&&V("'else' binding found without preceding 'if' or 'elseif' binding."),a=wi("else",l.parseBindTextResult),p=vi(t,h,a,m,s,!1),zt(f,t,p);const n=c.at(-1),o=document.createComment(`@@${d}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:pi(o),parseBindTextResults:Ht(o)})):e.replaceWith(o)}else if("elseif"===u){null===l&&V("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=vi(t,h,a,m,s),zt(f,t,p);const n=document.createComment(`@@${d}:${f}`),o=ds(),i={fragment:document.createDocumentFragment(),parseBindTextResult:wi("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:pi(n),parseBindTextResults:Ht(n)}),zt(o,t,i);const u=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==u?(e.remove(),u.fragment.appendChild(g),u.nodeInfos.push({nodePath:pi(g),parseBindTextResults:Ht(g)})):e.replaceWith(g)}else{p=vi(t,h,a,m,s),zt(f,t,p);const n=document.createComment(`@@${d}:${f}`);e.replaceWith(n)}"if"===u?(c.length=0,l=p):"elseif"===u?l=p:"else"===u&&(l=null,c.length=0)}}async function $i(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=et(t);null===s&&V(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(Ut(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function Ni(t){if(t===document)await $i(document),si(document),_i(document,document),ei(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await q(e.host),await $i(e),si(e),_i(e,e),ei(e,null)}}const Si="2.3.0",xi="undefined"==typeof HTMLElement?class{}:HTMLElement,Pi=/^@@wcs-(?:for|if|elseif|else):[^-]/,Ii=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,ki=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Ai=/^@@wcs-text-start:(.+)$/;function Ei(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Ci extends xi{_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=Si.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=Ei(JSON.stringify(e)),t.appendChild(n);const s=Array.from(Wt.keys());for(const e of s){const n=Ft(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(cr);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=lr(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=Ei(JSON.stringify(e)),t.appendChild(n)}}cr.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(Ii.test(t.data)||ki.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;Pi.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=Ai.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;Ii.test(t.data)&&i.push(t)}for(const t of i){const e=Ii.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()}Ci.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(Pi.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 Ti=new Set(["for","if","elseif","else"]);function Mi(t){const e=new Qo;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]=Xt(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 Li(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 Oi(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Lt(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,ai()],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;gi(a),"string"==typeof l&&fi(a,l),_i(n,a,l),zt(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:mi(a)})}}const Ri=Symbol.for("wcstack.binder"),ji=Symbol.for("wcstack.binder.pending"),Di=Symbol.for("wcstack.binder.taken");function Bi(t){if(Fo(t))return!0;if(!Wi(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(`[${o.bindAttributeName}]`);return null!==e&&Fo(e)}function Wi(t){return 1===t.nodeType}function zi(t){if(Bi(t))return;si(t),_i(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);ei(e&&s?n:t,null)}const Fi=[];function Hi(){const t=Fi.splice(0,Fi.length);for(const e of t)zi(e);!function(){const t=function(){const t=globalThis[Ri];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[Di];return void 0===e&&(e=new WeakSet,t[Di]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const Ui={protocol:"wcs-binder",version:1,bind:function(t){var e;Wi(t)&&!Bi(t)&&(e=t.getRootNode(),Xi.has(e)?zi(t):Fi.push(t))}},qi=new WeakMap,Gi=new WeakMap,Vi=new Set;function Ki(t){return qi.get(t)??null}function Ji(t){return Gi.get(t)??Promise.resolve()}const Xi=new WeakSet;function Qi(t){Xi.add(t)}function Yi(t,n){const s=qi.get(t);if(null===n){if(void 0===s)return;qi.delete(t),Vi.delete(s),null!==$e&&$e({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{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 $i(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="${Si}". Falling back to full render.`),Ci.cleanupDom(t),!1}for(const n of e)Oi(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=Ii.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 d=t.nextSibling;const u=`@@wcs-${o}-end:${s}`;for(;d&&(d.nodeType!==Node.COMMENT_NODE||d.data!==u);)c.push(d),d=d.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=Ws(o.nodes),{bindingInfos:s,subscriberNodes:i,bindingSession:a}=Mi(o.nodes);Ps(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");Ns(e,s),As(e,i);const l=[];for(const t of s)t.statePathName in $&&l.push(t);if(ls(e,l),"for"===o.type&&null!==o.index){const i=Li(t,"for",o.uuid);if(i){const t=fs(null,o.index);Ys(i,t,e),Zs(i,o.nodes[o.nodes.length-1]),Os(i,e),Es(e,yn(X(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=Li(t,o.type,o.uuid);n&&(Os(n,e),a.initialize(s,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}))}}for(const[e,o]of n){const n=Li(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=Ft(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Ki(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&gs(e,o)})}}(document.body,n),Ci.removeBlockBoundaryComments(document.body);const s=[];for(const t of e)t.parentNode&&(s.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());Ci.restoreTextBindings(document.body);const[i,a]=Xt(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(_e(t,null),e.setAttribute("data-wcs-completed",""))}else _e(t,null);const l=[],c=[],d=Yo(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(Ti.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=rn(t),n=Ki(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&(xe(e,o),Ce(e,o))})}ti(l);for(const{el:t,parent:e,next:n}of s)e.insertBefore(t,n);const u=t.querySelectorAll(o.tagNames.ssr);for(const e of u){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 Ni(t),Qi(t),Hi(),e()}catch(t){n(t)}})});Gi.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await Ni(t),Qi(t),Hi(),e()}catch(t){n(t)}})});Gi.set(t,e)}}void 0!==s&&V('A state tree is already registered on this root — one <wcs-state> per root in v2. Mount additional states onto the tree instead: <wcs-state mount="...">.'),qi.set(t,n),Vi.add(n),function(t,e){const n=Sr.get(t);if(void 0===n||0===n.length||null===xr)return;Sr.delete(t);const o=xr;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,n),null!==$e&&$e({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}let Zi=0,ta=0;const ea=[];function na(t,e=0){const n=ea.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?ea.push(o):ea.splice(n,0,o)}function oa(t){queueMicrotask(()=>{throw t})}const sa=new class{_queueUpdateRecords=[];constructor(){}enqueueAbsoluteAddress(t,e=null){Zi>ta&&(ta=Zi);const n=0===this._queueUpdateRecords.length;this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&(Ae++,null===ke&&(ke=new Map),queueMicrotask(()=>{const t=this._queueUpdateRecords;this._queueUpdateRecords=[],this._applyChange(t)}))}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!==$e&&null!=t&&null!==e.context&&t.transactionId!==e.context.transactionId&&$e({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!==$e&&$e({type:"propagation:hop-limit",absoluteAddress:t,transactionId:e.transactionId,hop:e.hop});continue}const n=fn(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?ti(o,s):ti(o)};if(e()||0===o.length)t();else{const e=function(t,e){const n=Hs(t);if(null!==n)return n.run(e,{source:t,types:void 0});e()}("state",t);void 0!==e&&e.catch(oa)}}finally{!function(){if(0!==Ae&&(Ae--,!(Ae>0||null===ke))){for(const[t,e]of ke)Ie.set(t,e);ke=null}}(),function(t){for(const e of ea.slice())e.listener(t)}(new Set(n.keys()))}}};function ra(){return sa}const ia=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function aa(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 ca=t=>{null!==$e&&$e({type:"state:update-batch",addresses:t})};function da(t){const e=null!==$e;!function(t){$e=t}(t);const n=null!==t;n&&!e?na(ca,0):!n&&e&&function(t){const e=ea.findIndex(e=>e.listener===t);-1!==e&&ea.splice(e,1)}(ca)}function ua(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 ha(t){return Ki(t)??V("devtools: no state tree on this root")}let fa=null;function pa(){if(e())return;if(null!==fa)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Si,getStateElements(){const t=[];for(const e of Vi)t.push(ua(e));return t},overlays:t=>function(t){const e=me.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}(ha(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=ha(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 ha(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){ha(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=Ft(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(aa(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=dt(e,Lt(n));for(const o of t)r(aa(e,o,"attribute",n))}catch{}continue}const e=ia.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=Ft(s);if(null===a){if(n===o.commentTextPrefix)try{r(aa(t,Bt(s),"comment",s))}catch{}}else r(aa(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:da};fa=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 ma={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",Si),Ci.buildContent(o,Ci.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}},ga="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let ya=0;async function ba(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++ya}\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 ${ga}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${ga}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function wa(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){V(`Failed to load script file: ${t}`)}}class va{_loopContextStack=Array(i).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&V("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=i&&V("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&&V("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&&V("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&&V(`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 _a=new WeakMap;function $a(t,e){let n=_a.get(t);void 0===n&&(n=new Map,_a.set(t,n));let o=n.get(e);return void 0===o&&(o=new Ln(e,t),n.set(e,o)),o}const Na=new WeakMap;function Sa(t){const e=Na.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 $a(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:$a(t,n)}},set(){V("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){V("$command namespace is read-only; deleting from it is not allowed.")}});return Na.set(t,n),n}const xa=Symbol("wcs-stream-last-notified-uncertain"),Pa=new WeakMap;function Ia(t,e){const n=Pa.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function ka(t,e){const n=Pa.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:xa,error:Object.is(o.error,null)?null:xa})}const Aa=new Set;function Ea(t){Aa.delete(t)}const Ca=new WeakMap;function Ta(t){return Ca.get(t)??new Map}function Ma(t){Ea(t);const e=Ca.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,ka(t,n.name)}const La=(t,e)=>e,Oa=new Set;function Ra(t,e){"string"==typeof e&&0!==e.length||V(`[wcs/recursion-declaration-invalid] ${R} ${t} must be a non-empty string.`);const n=e.split(s);n.some(t=>0===t.length)&&V(`[wcs/recursion-declaration-invalid] ${R} ${t} "${e}" must not contain empty path segments.`),n.length<2&&V(`[wcs/recursion-declaration-invalid] ${R} ${t} "${e}" must name a list element: a property path ending with "${s}${r}" (for example "nodes${s}${r}").`),n[n.length-1]!==r&&V(`[wcs/recursion-declaration-invalid] ${R} ${t} "${e}" must end with "${s}${r}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&V(`[wcs/recursion-declaration-invalid] ${R} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&V(`[wcs/recursion-declaration-invalid] ${R} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===r&&V(`[wcs/recursion-declaration-invalid] ${R} ${t} "${e}" must have exactly one "${r}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===j&&V(`[wcs/recursion-declaration-invalid] ${R} ${t} "${e}" must not contain "${j}" — the declaration is what gives "${j}" its meaning.`),isNaN(Number(n[o]))||V(`[wcs/recursion-declaration-invalid] ${R} ${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 ja(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 Da(t){return-1!==t.indexOf(j)}function Ba(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(Da(o))return null;const i=o.slice(1).split(s);return i[0]===r||i.some(t=>0===t.length)?null:o}function Wa(t){return 0===t.length?t:s+Ha(t.slice(1))}function za(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 Fa(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(s,o-1))if(za(t,e,n.slice(0,o)))return!0;return!1}function Ha(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 Ua(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 qa(t,e,n){n<0&&V(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=s+t.repeat;const i=o+e;let a=0;for(const t of i.split(s))t===r&&a++;return a>128&&V(`[wcs/recursion-depth-exceeded] Recursion on "${t.anchor}" reached depth ${n} ("${i}"), which needs ${a} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),i}function Ga(t,e){return qa(t,"",e)}function Va(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 Ka=new WeakMap;function Ja(t,e){null===e?Ka.delete(t):Ka.set(t,e)}function Xa(t){const e=Ka.get(t);e&&(e.dirty=!0)}const Qa=new WeakSet;function Ya(t){return"function"==typeof t.get&&Qa.has(t.get)}const Za="[wcs/recursion-declaration-invalid]";class tl{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=ja(e);for(const[e,o]of Object.entries(n)){if(!Da(e))continue;"function"==typeof o.set&&V(`${Za} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&V(`${Za} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=Ba(t,e);null===n&&V(Mr(e,t.recursiveAnchor)),0===n.length&&V(`${Za} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${s}total"), not the node.`),Ua(t,Wa(n))&&V(`${Za} "${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(Da(e)||Ya(n))continue;const t=this._matchExpansion(e);null!==t&&V(`${Za} "${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++)za(this.spec,t[e].suffix,t[n].suffix)&&V(`${Za} "${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(Fa(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=Ha(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!==Va(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=Va(this.spec,t.suffix,e);null!==n&&(null!==o&&V(`"${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||Ya(s)||V(`"${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,Qa.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(Ga(t,o)+s+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){!function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&Ya(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=X(o),s=Fe(t,n),r=n.wildcardParentPathInfos,i=(t,e,n)=>{if(n===r.length)return void Ja(Ve(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=ms(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,new Set(this._accessors.keys()))}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=qa(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 el=new WeakMap,nl=new WeakMap;function ol(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=Ta(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&Ta(t).has(n),ownKeys:()=>Array.from(Ta(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=Ta(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){V(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){V(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function sl(t){const e=el.get(t);if(void 0!==e)return e;const n=ol(t,B,t=>t.status);return el.set(t,n),n}function rl(t){const e=nl.get(t);if(void 0!==e)return e;const n=ol(t,W,t=>t.error);return nl.set(t,n),n}function il(t){el.delete(t),nl.delete(t)}let al=null;function ll(t){const e=Ta(t);if(0!==e.size){!function(t){Aa.add(t)}(t);for(const n of e.values())cl(t,n)}}function cl(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=al,r=new Set;let i;al=r;try{t.createState("readonly",t=>{i=n(t)})}finally{al=o}i instanceof Promise&&V(`${L} entry "${e.name}" args must be synchronous (it returned a Promise).`);const a=`${B}${s}${e.name}`,l=`${W}${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||V(`${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&&V(`${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);t.createState("writable",t=>{t[e.name]=e.definition.initial}),dl(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(){dl(t,e,"done",null)},fail(o){dl(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 dl(t,e,n,o){e.status=n,e.error=o;const r=function(t,e){return Pa.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=Pa.get(t);void 0===s&&(s=new Map,Pa.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{i&&t.$postUpdate(`${B}${s}${e.name}`),a&&t.$postUpdate(`${W}${s}${e.name}`)}))}na(function(t){const e=Aa;if(0===e.size)return;const n=[];for(const o of e)for(const e of Ta(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)&&Ta(t).get(o.name)===o)try{cl(t,o)}catch(n){o.controller?.abort(),e.has(t)&&Ta(t).get(o.name)===o&&dl(t,o,"error",n)}},20);const ul=new WeakMap,hl=new WeakMap,fl=new Set,pl=new Map;function ml(t){return ul.get(t)??pl}const gl=new Map;function yl(t){return hl.get(t)??gl}function bl(t){0===t.length&&V(`[wcs/watch-declaration-invalid] ${O} entry name must be a non-empty state path.`),t.startsWith("$")&&V(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not start with "$" (reserved namespace).${gt}`),t.includes("@")&&V(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${gt}`),t in Object.prototype&&V(`[wcs/watch-declaration-invalid] ${O} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=X(t);for(const n of e.segments)0===n.length&&V(`[wcs/watch-declaration-invalid] ${O} entry "${t}" has an empty path segment.${gt}`);return e.wildcardCount>128&&V(`[wcs/watch-declaration-invalid] ${O} entry "${t}" exceeds the maximum wildcard depth (128).`),e}const wl=new WeakMap;function vl(t,e,n){let o=wl.get(t);void 0===o&&(o=new Map,wl.set(t,o)),o.set(e,n)}const _l=new Map;function $l(t){0===ml(t).size&&0===yl(t).size||(function(t){fl.add(t)}(t),function(t){const e=[];for(const n of ml(t).values())Sl(t,n)&&e.push(n);for(const n of yl(t).values())for(const o of n)Sl(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{vl(t,Nl(t,o),n[o.path])}catch(e){Pl(t,o.path,"prime",e)}})}(t))}function Nl(t,e){return Ve(Fe(t,e.pathInfo),null)}function Sl(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const xl={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Pl(t,e,n,o){console.error(`[@wcstack/state] $watch ${xl[n]} "${e}" threw.`,o),null!==$e&&$e({type:"state:watch-error",phase:n,path:e,error:o})}function Il(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 kl(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Sl(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 Pl(0,n.path,"evaluate",t)}const a=r?function(t,e){return wl.get(t)?.get(e)}(e,o):function(t){return _l.get(t)}(o);r&&vl(e,o,i),null!==$e&&$e({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){Pl(0,n.path,"handler",t)}}function Al(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 El(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 Cl(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 Tl(t){return t.startsWith("$")}function Ml(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 Ll(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||V(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||V(`${e} entries must be non-empty strings.`),t.startsWith("$")&&V(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&V(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}na(function(t){const e=fl;try{if(0===e.size)return;const n=function(){const t=ta;return ta=0,t}();if(n>32){const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==$e&&$e({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=ml(t).get(s),i=yl(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=tn(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(Il),function(t){Zi=t+1}(n);try{for(const t of o){if(!e.has(t.stateElement))continue;const n=ml(t.stateElement).get(t.entry.path)===t.entry,o=!0===yl(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&kl(t)}}finally{Zi=0}}finally{_l.clear()}},10);const Ol=new Map;class Rl{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=X(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 jl(t){let e;return Ol.get(t)??(Ol.set(t,e=new Rl(t)),e)}function Dl(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:Ze(n.listIndex,o,n.pathInfo.wildcardCount)}function Bl(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=Ye(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?Ze(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?Ze(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}const Wl=new WeakMap;class zl{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 yn(X(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(ue(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=ue(t,e),a=he(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a=ue(t,e),l=he(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 Bl(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[ue(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)||V(`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[ue(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 ue(this.record,e),!0}catch{return!1}}}function Fl(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=Wl.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Wl.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 zl(t,s,e.listIndex,r,n,o))}const Hl=new WeakMap,Ul=new Set;function ql(t,e,n,o){let s=Hl.get(t);if(void 0===s){if(!o)return null;s=new Map,Hl.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 Gl(t,e){if(!t.component.isConnected)return!1;const n=ve(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 Vl(t,e,n,o){const r=ql(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&&Gl(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?Gl(i,o)&&(null!==l&&V(`[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 Kl(t){const e=t.parentStateElement,n=ve(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[Me](n,()=>{t.$postUpdate(o.exportedPath)})})}function Jl(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function Xl(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 Ql(t,e,n,o,s){const i=e.pathInfo.segments[0];if(i===C)return Xl(Sa(s),e.pathInfo.segments);if(i===B)return Xl(sl(s),e.pathInfo.segments);if(i===W)return Xl(rl(s),e.pathInfo.segments);if(!0===s.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const t=be(s,e.pathInfo.path);if(null!==t)return Fl(t,e,n,o)}if(!(e.pathInfo.path in t)){if(null===e.parentAddress&&wr(function(t){return t.rootNode??null}(s),e.pathInfo.path))return;const i=e.parentAddress??V(function(t,e,n){return`[${Er.binding}] Path "${t}" does not exist on the state tree.${mt(t,Ar(e,"",n))}${gt}`}(e.pathInfo.path,t,s.getterPaths)),a=Yl(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=Vl(s,i.pathInfo.path,l,e.listIndex);if(null!==t)return function(t,e,n,o,s){const r=Fl(t,yn(X(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??V(Or(`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 Yl(t,e,n,o){Bl(o,e),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,e.pathInfo),function(t,e){if(null===al)return;const n=Fe(t,e.pathInfo);al.add(Ve(n,e.listIndex))}(o.stateElement,e);const s=o.stateElement;return Jl(s,e)?function(t,e,n,o,s){const r=Ve(Fe(s,e.pathInfo),e.listIndex),i=function(t){return Ka.get(t)??null}(r);if(null!==i&&!1===i.dirty)return i.value;const a=Ql(t,e,n,o,s);return Ja(r,{value:a,dirty:!1}),a}(t,e,n,o,s):Ql(t,e,n,o,s)}function Zl(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,d,u)=>{const h=o[s]??null;if(null===h)return void u.push(d);const f=yn(h,r),p=Ve(Fe(n.stateElement,h),r),m=Ee(p),g=Yl(t,f,e,n),y=vs(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,d.concat(e.index),u)}else{const t=y[b]??V(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,d.concat(t.index),u):u.push(d.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Ce(t,Array.isArray(e)?e:[]);return l}function tc(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=ms(Yl(t,yn(a,r),e,n));null==l&&V(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??V(`ListIndex not found at index ${c} of ${a.path}`)}return r}function ec(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 nc(t,e,n,o){"object"==typeof t&&null!==t||V(`${D} 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&&V(`${D} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function oc(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&V(`${D} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function sc(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];nc(a,n,o,i);const l=oc(a,e,n,o,i);r.has(l)&&V(`${D} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function rc(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 ic(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const i=Yl(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 ac=new WeakMap;function lc(t,e){null===e?ac.delete(t):ac.set(t,e)}function cc(t,e,n){const s=X(t.wildcardParentPaths[e]),r=Fe(t.stateElement,s),i=yn(s,n),a=Ve(r,n),l=Ee(a),c=t.stateProxy[Le](i),d=vs(i.listIndex,l,c);t.observedListValueByAbsAddress.set(a,Array.isArray(c)?c:[]);const u=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}`),[]}}(d,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...u);else for(const n of u)cc(t,e+1,n)}const dc=[];function uc(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:dc,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:dc,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const hc=[];function fc(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return hc;let r=null;const i=e+s;for(const t of o){if(t!==e&&!t.startsWith(i))continue;const o=X(t);if(o.wildcardCount!==n.wildcardCount)return null;(r??=[]).push(o)}return r??hc}function pc(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const i of s){const s=X(i);if(t.listPathSet.has(o)&&s.lastSegment===r){const r=t.stateProxy[Le](e),a=Ve(Fe(t.stateElement,e.pathInfo),e.listIndex),l=Ee(a),c=vs(e.listIndex,l,r);t.observedListValueByAbsAddress.set(a,Array.isArray(r)?r:[]);const d=uc(t,o,0,0,c);for(const e of d.fullRows){const o=yn(s,e);t.result.add(o),n.push(o)}if(null!==d.movedRows){const e=fc(t,i,s);if(null===e)for(const e of d.movedRows){const o=yn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of d.movedRows)for(const s of e){const e=yn(s,o);t.result.add(e),n.push(e)}}}else{const o=yn(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=X(o),r=[];if(s.wildcardCount>0){const n=Ye(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&V(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=Ze(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};cc(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&V(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=Ze(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=yn(s,e);t.result.add(o),n.push(o)}}}function mc(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 d=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&&V(`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),u={ranks:d,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,pc(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(u,e,a);for(const[t,e]of u.observedListValueByAbsAddress)Ce(t,e);return Array.from(u.result)}function gc(t,e,n,o,s){const r=t.watchPaths;null!=r&&s&&r.has(e)&&function(t,e){_l.has(t)||_l.set(t,e)}(n,o)}function yc(t,e,n,s,r){const i=o.enablePropagationContext?oo()??to(-1):null,a=ra();a.enqueueAbsoluteAddress(e,i),mc(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=Ve(Fe(s.stateElement,e.pathInfo),e.listIndex);Xa(n),a.enqueueAbsoluteAddress(n,i)},{listExpansion:"diff",keyedMergePath:r})}function bc(t,e,n,o,s){s&&(t.getterPaths.has(e)?Xa(n):Ja(n,{value:o,dirty:!1}))}function wc(t,e,n,o,s,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const a=Yl(t,n,s,i),l=e.pathInfo.segments[e.pathInfo.segments.length-1];if(l===r){const t=e.listIndex?.index??V(Or(`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{yc(e,n,s,i,a)}}function vc(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=Yl(t,e,o,i),c=function(t,e,n,o){const s=sc(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=sc(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===ms(o)&&vs(c,null,o);const d=vs(c,o,n.list),u=_c(t,e,n.list,i,a,l),h=X(l+s+r);for(const e of n.matched){const n=rc(e.oldRow,e.newRow);if(0===n.length)continue;const o=d.newIndexes[e.position];for(const r of n)void 0!==o?vc(t,yn(X(h.path+s+r.field),o),r.value,i,a):e.oldRow[r.field]=r.value}return u}(t,e,c,a,o,i)}}return _c(t,e,n,o,i,null)}function _c(t,e,n,i,a,l){const c=a.stateElement,d=e.pathInfo.path;if(!0===c.hasGraftedVolumes){const t=function(t,e){const n=vr.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,d);null!==t&&V(`Cannot replace "${d}" 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 "${d}", instead.`)}if(!0===c.hasRecursion){const t=c.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);null!==t&&V(`[wcs/recursion-readonly] "${d}" 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 u=!!io&&(io=!1,!0);if(!(d in t)&&null!==e.parentAddress&&!c.elementPaths.has(d)){const s=Yl(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(!u&&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=Jl(c,e),g=Ve(Fe(c,e.pathInfo),e.listIndex);null!==$e&&$e({type:"state:write",absoluteAddress:g,value:n,oldValue:f,hasOldValue:p}),gc(c,d,g,f,p);let y=!1;try{if(void 0===h&&V(Or(`path "${d}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),!0===c.hasMounts&&t!==r&&!(h in s)){const o=Vl(c,e.parentAddress.pathInfo.path,t,e.listIndex);if(null!==o)return y=!0,function(t,e,n,o,s,r){const i=Fl(t,yn(X(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{yc(e,g,i,a,l),y?Xa(g):bc(c,d,g,n,m),ec(c,e.pathInfo,{value:n})}}}let h,f=!1;if(!u&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=Yl(t,e,i,a);if(ic(t,e,i,a)&&Object.is(o,n))return!0;h=o,f=!0}const p=c.elementPaths.has(e.pathInfo.path),m=Jl(c,e),g=Ve(Fe(c,e.pathInfo),e.listIndex);null!==$e&&$e({type:"state:write",absoluteAddress:g,value:n,oldValue:h,hasOldValue:f}),gc(c,d,g,h,f);try{return p?function(t,e,n,o,s,r,i){let a=e.parentAddress??V(`address.parentAddress is undefined path: ${e.pathInfo.path}`),l=function(t){return ac.get(t)??null}(a);if(null===l){const e=Yl(t,a,s,r)??[],n=ms(e)??[];l={value:[...e],listIndexes:[...n]},lc(a,l)}try{return wc(t,e,n,o,s,r,i)}finally{const n=l.value.indexOf(o),i=Yl(t,a,s,r)??[],c=Array.isArray(i)?ms(i)??[]:[],d=e.listIndex.index,u=-1!==n?l.listIndexes[n]:fs(a.listIndex,-1);if(c[d]=u,new Set(i).size===l.value.length){for(let t=0;t<c.length;t++)c[t].index=t;lc(a,null)}}}(t,e,g,n,i,a,l):wc(t,e,g,n,i,a,l)}finally{bc(c,d,g,n,m),ec(c,e.pathInfo,{value:n})}}function $c(t,e,n,o){return(e,s,r)=>{const i=X(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&&V(Tr("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=yn(i,tc(t,n,o,i,s));if(void 0===r)return Yl(t,a,n,o);vc(t,a,r,n,o)}}function Nc(t,e,n){const o=t.recursionRegistry,r=Ba(o.spec,n);null===r&&V(Mr(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&&V(`[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 Sc(t,e,n,o,r){const i=o.spec,a=[],l=new Map,c=[],d=i.repeatList,u=i.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void a.push(yn(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=yn(o,s),c=Ve(Fe(n.stateElement,o),s),u=Yl(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)&&V(`[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)&&V(`[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 "${d}" array.`),o})(o.path,u,r),p=vs(s,Ee(c),u);return l.set(c,Array.isArray(u)?u:[]),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 u=(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:X(n),childListPathInfo:X(i+s+d)};return c[t]=a,a})(t),y=l;h.add(y);const b=u.concretePathInfo.wildcardCount===t+1;for(let e=0;e<i.length;e++){const n=i[e];b?a.push(yn(u.concretePathInfo,n)):p(u.concretePathInfo,t+1,n),g(t+1,u.childListPathInfo,n)}h.delete(y)};g(0,X(u),null);for(const[t,e]of l)Ce(t,e);return a}function xc(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Dl(o,s.wildcardPaths.at(-1)??V(`lastWildcardPath is null: ${e.pathInfo.path}`))??V(`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]??V(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=ms(Yl(t,yn(i,s),n,o))??V(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??V(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??V(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":V(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}const Pc=/^\$\d+$/,Ic=`${B}${s}`,kc=`${W}${s}`,Ac=new WeakMap;function Ec(t,e,n,o){const r=$[e];if(void 0===r&&"string"==typeof e&&36===e.charCodeAt(0)&&Pc.test(e)&&V(`[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&&V(`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&&V(`ListIndex not found: ${e.toString()}`);let a=r;const l=t.pathInfo;if(!0===o.stateElement?.hasMounts&&-1!==l.path.indexOf("#")){const t=be(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=Ze(i,a,l.wildcardCount);return c?.index??V(`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=$c(t,0,n,o);return(e,r)=>{if(!0===o.stateElement.hasRecursion&&Da(e)){if(void 0!==r)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=Ba(r.spec,o);null===i&&V(Mr(o,r.spec.recursiveAnchor)),Array.isArray(s)||V(`[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&&V(`[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=Sc(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(Yl(t,a[o],e,n));return l}(t,n,o,e,r);e=Nc(o.stateElement,o,e)}const i=X(e);if(void 0===r||Array.isArray(r)||V(`$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&&V(Tr("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Dl(o,i.wildcardPaths[t]);if(e){r=tn(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&&V(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=Zl(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&&Da(e))return function(t,e,n,o,s,r,i){const a=n.stateElement.recursionRegistry,l=Ba(a.spec,o);null===l&&V(Mr(o,a.spec.recursiveAnchor));const c=Wa(l);Array.isArray(s)||V(Lr(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&V(`[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&&V(Lr(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&V(Lr(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){Ua(t,n)&&V(`[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 d=a.conflictingRecursiveGetter(c);null!==d&&V(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${d}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const u=Sc(t,e,n,a,l);let h=0;for(let o=0;o<u.length;o++)void 0!==r&&(vc(t,u[o],r,e,n),h++);return h}(t,n,o,e,s,r,i);const a=X(e);Array.isArray(s)||V(Lr(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&V(Tr("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&V(Lr(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&V(Lr(e,"requires an array as the value when { spread: true } is set."));const d=Zl(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==d.length&&V(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,d.length,r.length));const u=[];for(let e=0;e<d.length;e++){const s=tc(t,n,o,a,d[e]);u.push(yn(a,s))}let h=0;for(let e=0;e<u.length;e++){const s=u[e];let i;i=c?r(Yl(t,s,n,o),...d[e]):l?r[e]:r,void 0!==i&&(vc(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=jl(e),i=xc(t,r,n,o),a=yn(r.pathInfo,i),l=Ve(Fe(s,a.pathInfo),a.listIndex),c=ra();c.enqueueAbsoluteAddress(l),mc(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Ve(Fe(s,t.pathInfo),t.listIndex);Xa(e),c.enqueueAbsoluteAddress(e)}),ec(s,a.pathInfo)}}(t,0,n,o)(e);case"$resolve":return(e,s,r)=>$c(t,0,n,o)(e,s,r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{Da(t)&&V(`[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&&V(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??V("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 C:return Sa(o.stateElement);case B:return sl(o.stateElement);case W:return rl(o.stateElement)}if(!e.startsWith(Ic)&&!e.startsWith(kc))return}const s=jl(!0===o.stateElement?.hasRecursion&&Da(e)?Nc(o.stateElement,o,e):e),r=xc(t,s,n,o),i=yn(s.pathInfo,r);return Yl(t,i,n,o)}if("symbol"==typeof e){const r=function(t){let e=Ac.get(t);return void 0===e&&(e=new Map,Ac.set(t,e)),e}(o),i=r.get(e);if(void 0!==i)return i;let a;switch(e){case Me:a=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&V("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case Le:a=e=>Yl(t,e,n,o);break;case Oe:a=e=>ic(t,e,n,o);break;case Re:a=(e,s)=>vc(t,e,s,n,o);break;case je:a=()=>async function(t,e,n){const o=Reflect.get(t,N);"function"==typeof o&&await o.call(n)}(t,0,n);break;case De:a=()=>function(t,e,n){const o=Reflect.get(t,S);"function"==typeof o&&o.call(n)}(t,0,n);break;case Be:a=e=>function(t,e,n,o){const r=Reflect.get(t,x);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=tn(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,$r.get(l)??Nr):[];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=tn(n.listIndex,l);(a[s]??=[]).push(t)}}if(i.size>0)try{t.callback.call(_r(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 We:a=(e,o)=>function(t,e,n,o){const s=Reflect.get(t,P);"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 Cc{_stateElement;_addressStack=Array(i).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Ki(t);null===n&&V("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&&V("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=i&&(this._hasRepeatedAddress()&&V(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),V(`[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&&V(`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 Ec(t,e,n,this)}set(t,e,n,o){return"readonly"===this._mutability&&V("This state is readonly."),function(t,e,n,o,s){if("string"==typeof e){const r=jl(e),i=xc(t,r,o,s);return vc(t,yn(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 Tc=new WeakMap;class Mc{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=Tc.get(t);return n?n.get(e)??null:null}(t,e)??V("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 Lc=t=>()=>t;function Oc(t,e,n,o){!function(t,e,n){let o=Tc.get(t);o||(o=new Map,Tc.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 Mc(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:Lc(s),enumerable:!0,configurable:!0}),es(e,n),Rc(e,n)}function Rc(t,e){if(I in t){const n=t[I];"function"==typeof n?n.call(t,e).catch(t=>{V(`Error in ${I}: ${t instanceof Error?t.message:String(t)}`)}):V(`${I} is not a function.`)}}function jc(t,e){const n=ye(e);var o,i;null!==n&&n.stateProp!==t.stateProp&&V(`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&&Yo(e).dispose(),function(t,e){fe.set(t,e);let n=me.get(e.parentStateElement);void 0===n&&(n=new Map,me.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=pe.get(e.component);void 0===o&&(o=new Map,pe.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&ge.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=qi.get(t);if(void 0!==n){if(n===e)return;V("A state tree is already registered on this root.")}qi.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const i=de.exec(e.statePathName);if(null!==i){const s=function(t,e){return void 0===e?t.delta:X(ue(t,e)).wildcardCount-X(e).wildcardCount}(t,n);o=0===s?e.statePathName:`$${Number(i[1])+s}`}else if(o=ue(t,e.statePathName),"for"===e.bindingType){const n=X(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+s+r,n)}return o===e.statePathName?e:{...e,statePathName:o,statePathInfo:X(o)}}(t,e,n);si(e);const o=ve(t.component);_i(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),ei(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=ue(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=X(a);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:r,suffix:i,markerPath:e,exportedPath:a};t.exports.set(a,c),ql(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,a),Wr(t.parentStateElement,a)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=ve(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(Ul.has(s))continue;const r=X(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[Me](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Ul.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),Kl(t),o=e,i=Promise.resolve(),Gi.set(o,i),i.then(()=>Qi(o),()=>{})}const Dc=new Set;function Bc(t,e){Dc.has(t)||(Dc.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Wc(t){const e=t.rootEntry,n=ve(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Me](n,()=>{o=t[e.outerPathInfo.path]})}),o}function zc(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(_r(t.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function Fc(t,e,n){!function(t,e,n){const o=n[O];if(void 0!==o){"object"==typeof o&&null!==o||V(`${O} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&V(`${O} entry "${t}" must be a function.`),bl(t)}const r=n[D];if(void 0!==r){"object"==typeof r&&null!==r||V(`${D} 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)&&V(`${D} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+s+n)&&V(`${D} entry "${e+s+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&V(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n[R]&&V(`Volume "${e}" declares ${R}, 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(ja(n)))-1!==t.indexOf(j)&&V(`Volume "${e}" declares "${t}", which uses "${j}". 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=X(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(a)return;V(`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;V(`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=vr.get(t);void 0===n&&(n=new Set,vr.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(_r(e,this))}),"function"==typeof a&&(l.set=function(t){a.call(_r(e,this),t)}),t.defineTreeAccessor(r,l)}!function(t,e,n){const o=n[O];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(_r(e,this),t,n,...o)};n.push({path:o,pathInfo:X(o),handler:c,order:1e6+i++}),r.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(function(t,e){let n=hl.get(t);void 0===n&&(n=new Map,hl.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),$l(t))}const r=n[D];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[x];"function"==typeof i&&(function(t,e){let n=$r.get(t);void 0===n&&(n=[],$r.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(_r(e,t));n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function Hc(t,e){let n=null;try{n=Fc(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}xr=Hc;class Uc extends xi{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return Ji(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!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;_watchPaths=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&&V(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){const n=this.__state,o=function(t){const e=t[R];if(void 0===e)return null;"object"==typeof e&&null!==e||V(`[wcs/recursion-declaration-invalid] ${R} 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&&V(`[wcs/recursion-declaration-invalid] ${R} must declare exactly one anchor; it is empty.`),n.length>1&&V(`[wcs/recursion-declaration-invalid] ${R} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,i]=n[0];Ra("anchor",o),"string"!=typeof i&&V(`[wcs/recursion-declaration-invalid] ${R} entry "${o}" must map to the repeating sub-path as a string (for example "children${s}${r}").`),Ra("repeating sub-path",i);const a=o.slice(0,o.lastIndexOf(s)),l=i.slice(0,i.lastIndexOf(s)),c=a+s+j;return Object.freeze({anchor:o,repeat:i,recursiveAnchor:c,anchorList:a,repeatList:l})}(t),i=null===o?null:new tl(o,t),a=function(t){const e=new Set,n=t[E];if(void 0===n)return e;Array.isArray(n)||V(`${E} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||V(`${E} entries must be non-empty strings.`),t===C&&V(`${E} entry "${t}" conflicts with the reserved namespace name "${C}".`),e.has(t)&&V(`${E} entry "${t}" is duplicated.`),e.add(t);return e}(t),l=function(t){const e=new Set,n=t[T];if(void 0===n)return e;Array.isArray(n)||V(`${T} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||V(`${T} entries must be non-empty strings.`),e.has(t)&&V(`${T} entry "${t}" is duplicated.`),e.add(t);return e}(t);null!==this._recursionRegistry&&this._recursionRegistry.forgetGenerated(this,n),this._recursionRegistry=i,this._commandTokenNames=a,this._eventTokenNames=l,this.__state=t,this._hasUpdatedCallback=x in t,this._hasErrorCallback=P in t,Tn(this),function(t,e,n){const o=e[M];if(void 0!==o){"object"==typeof o&&null!==o||V(`${M} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||V(`${M} entry "${e}" is not declared in $eventTokens.${mt(e,n)}`),"function"!=typeof s&&V(`${M} entry "${e}" must be a function.`),Cn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const c=function(t){const e=new Set,n=new Set,o=ja(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 c.getterPaths)this._getterPaths.add(t);for(const t of c.setterPaths)this._setterPaths.add(t);il(this),Ma(this),Ea(this),Ca.delete(this),function(t,e){const n=e[L];if(void 0===n)return void Ia(t,Oa);"object"==typeof n&&null!==n||V(`${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&&V(`${L} entry name must be a non-empty string.`),i.includes(s)&&V(`${L} entry "${i}" must be a flat property name ("${s}" is not allowed).`),i.includes(r)&&V(`${L} entry "${i}" must be a flat property name ("${r}" is not allowed).`),i.startsWith("$")&&V(`${L} entry "${i}" must not start with "$" (reserved namespace).`),i in Object.prototype&&V(`${L} entry "${i}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(i)&&V(`${L} entry "${i}" conflicts with a getter declared on the state.`),t.setterPaths.has(i)&&V(`${L} entry "${i}" conflicts with a setter declared on the state.`),"object"==typeof a&&null!==a||V(`${L} entry "${i}" must be an object ({ args?, source, fold?, initial? }).`);const n=a;"function"!=typeof n.source&&V(`${L} entry "${i}" source must be a function.`);const l=void 0!==n.fold;l&&"function"!=typeof n.fold&&V(`${L} entry "${i}" fold must be a function.`),l&&!("initial"in n)&&V(`${L} entry "${i}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&V(`${L} entry "${i}" args must be a function.`);const c={name:i,definition:{args:n.args??null,source:n.source,fold:n.fold??La,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){Ca.set(t,e)}(t,o),Ia(t,new Set(o.keys()))}(this,t),this._listKeys=function(t){const e=t[D];if(void 0===e)return null;"object"==typeof e&&null!==e||V(`${D} 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&&V(`${D} entry path must be a non-empty string.`);const e=t.split(s);e.some(t=>0===t.length)&&V(`${D} entry "${t}" must not contain empty path segments.`),e[e.length-1]===r&&V(`${D} entry "${t}" must be the list path itself, not the element path (drop the trailing "${s}${r}").`),-1!==t.indexOf(j)&&V(`[wcs/recursion-unsupported] ${D} entry "${t}" uses "${j}", which ${D} 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&&V(`${D} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&V(`${D} entry "${t}" key field name must be a non-empty string.`),(o.includes(s)||o.includes(r))&&V(`${D} entry "${t}" key field name "${o}" must be a flat property name ("${s}" / "${r}" are not allowed).`),o in Object.prototype&&V(`${D} 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),null!==o&&this._listPaths.add(o.anchorList),function(t){fl.delete(t),ul.delete(t)}(this),function(t){wl.delete(t)}(this),this._watchPaths=function(t,e){const n=e[O];if(void 0===n)return null;"object"==typeof n&&null!==n||V(`[wcs/watch-declaration-invalid] ${O} must be an object mapping state paths to handler functions.${gt}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&V(`[wcs/watch-declaration-invalid] ${O} entry "${e}" must be a function.${gt}`);const n=bl(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){ul.set(t,e)}(t,o),s.size>0?s:null}(this,t),this._initialized&&null!==this._rootNode&&!e()&&($l(this),ll(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=Ci.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){V("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 ba(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||V(`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 wa(t);V(`Unsupported src file type: ${t}`)}}catch(t){V(`Failed to initialize state: ${t}`)}}async _initializeVolume(){const t=this._rootNode,e=this.getAttribute("mount");try{!function(t){0===t.length&&V('"mount" requires a non-empty tree path.');const e=X(t);for(const n of e.segments)0===n.length&&V(`"mount" path "${t}" has an empty segment.`),n===r&&V(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&V(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(e),this.hasAttribute("bind-component")&&V('"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=br.get(t);void 0===n&&(n=new Set,br.set(t,n)),n.has(e)&&V(`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===Ki(t)&&function(t,e){const n=()=>{if(null!==Ki(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){let n=Sr.get(t);void 0===n&&(n=[],Sr.set(t,n)),n.push(e)}(t,{mountPath:n,volumeState:o,onGrafted:s}):Hc(e,{mountPath:n,volumeState:o,onGrafted:s})}(t,Ki(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}await this._loadingPromise,Yi(this.rootNode,this)}_failInitialization(t){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),V(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?Z(a):null;null!==a&&null!==l||V(`"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&&V(`"bind-component" cannot be combined with ${c.join(", ")}. The component's "${this.getAttribute("bind-component")}" property is the only state source.`);const d=this.getAttribute("bind-component");!function(t,e){let n=ns.get(t);n||(n=new Set,ns.set(t,n)),n.add(e)}(a,d);const u=et(a);null===u&&V(`CustomElementRegistry is unavailable for <${l}>.`),await u.whenDefined(l.toLowerCase()),a.hasAttribute(o.bindAttributeName)&&await q(a),d in a||V(`Component does not have property "${d}" for state binding.`);let h=a[d];"object"==typeof h&&null!==h||V(`Component property "${d}" is not an object for state binding.`);const f=function(t,e){const n=sr.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(a,d);if(void 0!==f&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=ft(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(a,d)&&(a[d]=f,h=f),this._boundComponent=a,this._boundComponentStateProp=d,i instanceof ShadowRoot||(ft(a)??[]).some(t=>t.propSegments[0]===d)||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="${d}: path").`),a.hasAttribute(o.bindAttributeName)){const o=(ft(a)??[]).filter(t=>t.propSegments[0]===d);if(o.length>0){const c=Ki(a.getRootNode())??this._failInitialization(`No state tree found on this root for mount host <${l}>.`);let u=(n=a,r=d,pe.get(n)?.get(r)??null);const f=null!==u;if(null===u&&(function(t,e,n){const o=ir.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;ir.get(t).delete(e)}}(a,d,h),u=function(t,e,n,o,r,i=new Set){0===n.length&&V(`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)&&V("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 d=++Zt,u=`#m${d}`,{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:d,marker:u,component:t,stateProp:e,parentStateElement:o,entries:a,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?u:c.outerPathInfo.path+s+u,stateObject:r,getterKeys:h,setterKeys:f,injectedKeys:i,privateSnapshot:p,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(a,d,o,c,h,(t=a,e=d,rr.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){Bc(`${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=Wc(t),i=!0),"object"!=typeof r||null===r||!(a in r))continue;const l=t.rootEntry.outerPathInfo.path;Bc(`${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.`)}}(u)),this._mountRecord=u,this.parentNode!==i)return;try{jc(u,i instanceof ShadowRoot?i:a)}catch(t){throw this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),t}if(!f){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=ve(t.component);let s;return e[Me](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(ue(t,e))):(n,o,...r)=>{const i=ue(t,n),a=ve(t.component)?.listIndex.indexes??[],l=he(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:ue(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:ue(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 ue(t,n),!0}catch{return!1}}})}(u);Object.defineProperty(a,d,{get:()=>t,enumerable:!0,configurable:!0}),es(a,d)}return Rc(a,d),function(t){const e=te.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(j)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;ee.has(n)||(ee.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.`))}(u),void ne(u,"$connectedCallback")}}Oc(this,this._boundComponent,this._boundComponentStateProp,h)}var t,e,n,r}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{N in t&&await t[je]()})}async _initializeDCC(t,e){let n;try{if(this.hasAttribute("src")){const t=this.getAttribute("src");t.endsWith(".js")?n=await wa(t):V(`DCC: Unsupported src type: ${t}`)}else{const e=this.querySelector('script[type="module"]');e?n=await ba(e,t.tagName.toLowerCase()):V(`DCC: No state source found for "${t.tagName.toLowerCase()}".`)}}catch(t){V(`DCC: Failed to load state: ${t}`)}!function(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||V(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=et(t);null!==r&&"function"==typeof r.define||V(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&V(`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:d,streamBackedBindables:u}=function(t){const e=Ll(t,k)??[],n=Ll(t,A)??[],o=ja(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}V(`${k} entry "${t}" is not declared on the state.${mt(t,Ml(o,"value"))}`)}"function"==typeof e.value&&V(`${k} entry "${t}" is a method. Declare it in ${A} instead.`)}for(const t of n){const e=o[t];void 0===e&&V(`${A} entry "${t}" is not declared on the state.${mt(t,Ml(o,"method"))}`),"function"!=typeof e.value&&V(`${A} entry "${t}" is not a method. Declare it in ${k} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||d.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,d):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(z))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=et(this._shadow);return null!==t&&nt(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 ${k} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=ja(n);for(const[t,e]of Object.entries(g)){if(Tl(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=Cl(t,o)}else n.get=Al(t),n.set=El(t);Object.defineProperty(m.prototype,t,n)}for(const t of u)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:Al(t),set:El(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=>{S in t&&t[De]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initialized){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&Ki(this._rootNode)===this._volumeGraftInfo.rootStateElement&&zc(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=Yo(e),o=ve(t.component);n.forEachActiveBindingNode(t=>_e(t,o)),ti(n.rebindAddresses()),Kl(t)}(t,e)}),ne(t,"$connectedCallback"),void this._resolveConnectedCallback?.()}this._dcc||Ki(this._rootNode)===this||Yi(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 t=this.parentNode;if(t instanceof ShadowRoot&&t.host.hasAttribute(z))return this.hasAttribute("bind-component")&&V(`"bind-component" cannot be used inside a [${z}] host. DCC state comes from the template, not from a component property.`),void await this._initializeDCC(t.host,t);if(this.hasAttribute("mount")){if(this._volumeInitializing)return;return void await this._initializeVolume()}if(await this._initializeBindWebComponent(),null!==this._mountRecord)return this._initialized=!0,this._resolveInitialize?.(),this._resolveLoading?.(),void this._resolveConnectedCallback?.();await this._initialize(),this._initialized=!0,this._resolveInitialize?.()}if(this.hasAttribute("enable-ssr")&&!e()||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await Ji(this.rootNode);const t=Ci.extractStateData(this),e=document.createElement(o.tagNames.ssr);e.setAttribute("version",Si),Ci.buildContent(e,t),this.parentNode?.insertBefore(e,this)}catch(t){throw this._rejectConnectedCallback?.(t),t}e()||null===this._rootNode||t!==this._connectGeneration||$l(this),e()||null===this._rootNode||t!==this._connectGeneration||this._streamsStartedGeneration===t||ll(this),this._resolveConnectedCallback?.()}disconnectedCallback(){if(this.hasAttribute("mount"))return null!==this._volumeGraftInfo&&zc(this._volumeGraftInfo,"$disconnectedCallback"),void(this._rootNode=null);if(null!==this._mountRecord)return ne(this._mountRecord,"$disconnectedCallback"),Kl(this._mountRecord),void(this._rootNode=null);if(null!==this._rootNode){if(!this._initialized)return void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{Yi(this.rootNode,null),_a.delete(this),function(t){Na.delete(t)}(this),Tn(this),Ma(this),il(this),function(t){fl.delete(t)}(this),this._rootNode=null}}}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 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)&&V(`$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 kr(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 rootNode(){return null===this._rootNode&&V("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("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+r)),!this._pathSet.has(t)){const e=X(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(wr(t.rootNode??null,n))return;const i=X(n).segments;if("binding"===o&&i.length<2)return;if(function(t,e){let n=Rr.get(t);return void 0===n&&(n=new Set,Rr.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!==kr(t,e))return Ir;const o=X(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!==kr(t,a))return Pr;if(Object(i)!==i)return Pr;if(l===r){if(!Array.isArray(i)||0===i.length)return Pr;i=i[0];continue}const d=kr(i,l);if(void 0===d)return{existence:"missing",missingSegment:l,candidates:Ar(i,c,n)};if("function"==typeof d.get)return e===o.length-1?Ir:Pr;i=d.value}return Ir}(e,n,t.getterPaths);"missing"===a.existence&&(function(t,e){return!0===Br.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),Dr.has(t)||(Dr.add(t),setTimeout(()=>function(t){Dr.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=X(t.parentPath)}}}_createState(t,e,n){try{const o=function(t,e,n){const o=new Cc(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){this._initialized?((this._hasGraftedVolumes||this._hasMounts)&&V("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):this._resolveSetState?.(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,Ci),t.get(o.tagNames.state)||t.define(o.tagNames.state,Uc)}(void 0),function(){const t=globalThis;void 0===t[Ri]&&(t[Ri]=Ui)}(),function(){const e=globalThis;void 0===e[t]&&(e[t]=ma)}(),pa()}();const qc={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"},Gc=!1,Vc=[".html"];function Kc(){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 Jc(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let Xc=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const Qc={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 Yc(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function Zc(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 td={static:2,param:1,"catch-all":0};let ed=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&&Jc(`${qc.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&Jc(`${qc.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+=td[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(Qc).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||Jc(`${qc.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:Yc(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new Xc("Navigation cancelled by guard.",o);if(!o)throw new Xc("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new Xc("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},nd=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=Kc();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new ed(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||Jc(`${qc.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):Jc(`${qc.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&&Jc(`${qc.route} with fallback attribute must be a direct child of ${qc.router}.`),t.fallbackRoute&&Jc(`${qc.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 od=Symbol.for("wcstack.trustedTypes.policy"),sd=Symbol.for("wcstack.trustedTypes.internal"),rd="wcstack";function id(){const t=globalThis[od];return null===t||"object"!=typeof t?null:t}let ad=!1;function ld(t){const e=function(){const t=globalThis,e=t[sd];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(rd,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof id()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${rd}". Allow it in the CSP (\`trusted-types ${rd};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[sd]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=id(),s=o?.createHTML;return"function"==typeof s?(ad||(ad=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${rd}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${rd};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const cd=new Map;let dd=class extends HTMLElement{_uuid=Kc();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||Jc(`${qc.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return cd.set(t,n),n}catch(e){Jc(`${qc.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(`${qc.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)cd.has(t)?n.innerHTML=ld(cd.get(t)||""):n.innerHTML=ld(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=ld(t):console.warn(`${qc.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")&&Gc}get name(){return this.getAttribute("name")||""}},ud=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||Jc(`${qc.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")&&Gc}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const hd=new Set(["props","states","attr",""]);function fd(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 pd(t,e){t.hasAttribute("data-bind")||Jc(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";hd.has(n)||Jc(`${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&&fd(t,e,o)}).catch(()=>{Jc(`Failed to define custom element: ${s}`)}):fd(t,e,o)}let md=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||Jc(`${qc.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(`${qc.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=>{pd(e,t)}),e.hasAttribute("data-bind")&&pd(e,t))}};function gd(){return document.createElement(qc.layoutOutlet)}const yd="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function bd(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){Jc(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 ${yd}`:`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 ${yd}`}(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 wd(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 vd(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===qc.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),wd(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===qc.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&bd(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===qc.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=gd();o.layout=n,i=o,a=e}}const c=await vd(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function _d(t){const e=new Map;return await vd(t,t.template.content,[],e)}function $d(t){return!1!==t.checkVisibility?.()}function Nd(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 d=!1;if("param"===e.type){const t=e.paramType||"any",n=Qc[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),d=!0)}else d=null!==e.pattern.exec(c);if(!d){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)Nd(s,e,n,o)}function Sd(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)Nd(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 xd=null,Pd=null;function Id(){const t=Vc;return 0===t.length?null:(xd===t&&Pd||(xd=t,Pd=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Pd)}function kd(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=Id();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Ad(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function Ed(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=Id();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function Cd(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function Td(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=>{pd(e,t.typedParams)}),n.hasAttribute("data-bind")&&pd(n,t.typedParams),n.querySelectorAll(qc.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===qc.layoutOutlet&&n.assignParams(t.typedParams)}}function Md(t,e){Td(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 Ld=Symbol.for("wcstack.transition-runner");const Od=Symbol.for("wcstack.binder");function Rd(){const t=globalThis[Od];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const jd=Symbol.for("wcstack.binder.pending"),Dd=Symbol.for("wcstack.binder.taken");function Bd(){const t=globalThis;let e=t[Dd];return void 0===e&&(e=new WeakSet,t[Dd]=e),e}function Wd(t){const e=Rd();return null===e?(function(){const t=globalThis;let e=t[jd];return void 0===e&&(e=[],t[jd]=e),e}().push(t),!1):(Bd().add(t),e.bind(t),!0)}const zd=new WeakSet,Fd="data-wcs";function Hd(t,e,n){!zd.has(t)&&function(t){return t.hasAttribute(Fd)||null!==t.querySelector(`[${Fd}]`)}(t)&&(zd.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==Rd()||(o=t,Bd().has(o))||console.warn(`[@wcstack/router] ${e} contains ${Fd} 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 Ud(t){for(const e of t.childNodeArray)1===e.nodeType&&(Wd(e)||Hd(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 qd(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 Xc)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 Gd(t,e,n,o,s=""){const r=Ad(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=Sd(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:Jc(`${qc.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 qd(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||Cd(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=Md(o,e),n.length>0&&!s.has(o)&&Ud(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[Ld];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($d(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if($d(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 Vd(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Kd(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 Jd(t){return"?"===t?"":t}function Xd(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 Qd(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Yd="data-wcs-ssr",Zd="data-wcs-ssr-link",tu="@@wcs-route-ph:",eu="@@wcs-route-start:",nu="@@wcs-route-end:",ou=Object.freeze({});class su 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=ou;_typedParams=ou;_searchParams=ou;_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 kd(t)}_normalizeBasename(t){return Ed(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(qc.outlet))return t;const e=document.createElement(qc.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||Jc(`${qc.router} has no outlet.`),this._outlet}get template(){return this._template||Jc(`${qc.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=Yc(t.search),s=t.data??null,r=this._data!==s,i=!Zc(this._params,e),a=this._routeName!==t.routeName,l=!Zc(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(`${qc.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(`${qc.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=Kd(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Jd(n.search)+n.hash,r=Vd();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(Ad(t,this._basename));await Gd(this,this.outlet,t,this._path,Jd(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(Ad(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await Gd(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${qc.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 Gd(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=Qd();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||Jc(`${qc.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||Jc(`${qc.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await _d(this),r=!t&&this._outlet.hasAttribute(Yd);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&&Jc(`${qc.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(Yd);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await Gd(this,this.outlet,i,this._path,window.location.search||""),(r||null!==Rd())&&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(qc.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(tu)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(eu)){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(nu)){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 d=Ad(t,this._basename);let u=Sd(this,d);if(!u){if(null===this._fallbackRoute)return!1;u={routes:[this._fallbackRoute],params:{},typedParams:{},path:d,lastPath:this._path}}if(u.lastPath=this._path,u.routes.length!==r.size)return!1;for(const t of u.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 u.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 u.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(eu)){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()===qc.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(Yd);for(const t of u.routes)Td(t,u);return this.outlet.lastRoutes=u.routes,!await qd(this,u)||(this.commitNavigation({params:u.params,typedParams:u.typedParams,routeName:u.routes[u.routes.length-1].name,data:u.data??null,search:window.location.search||"",path:d}),!0)}async _renderForSsr(t){const e=Ad(t,this._basename),n=Sd(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&Jc(`${qc.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await Gd(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${tu}${t.absolutePath}`}),this.outlet.setAttribute(Yd,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${eu}${t.absolutePath}`),s=document.createComment(`${nu}${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&&Wd(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(!Xd(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),Qd()){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=Vd();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&&(Vd()?.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 ru=["title","rel","target","download","hreflang","lang","dir"];class iu extends HTMLElement{static get observedAttributes(){return["to",...ru]}_childNodeArray=[];_uuid=Kc();_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(qc.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(qc.router);if(n)return this._router=n;Jc(`${qc.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 kd(t)}_joinInternalPath(t,e){const n=Ed(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}=Kd(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+Jd(o)+s}else try{t.href=new URL(e).toString()}catch{Jc(`[${qc.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){Qd()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Zd)?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(Zd),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-")||ru.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,Qd())return this._updateActiveState(),void n.setAttribute(Zd,"");Vd()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Vd()?.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(){Vd()?.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(ru.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}=Kd(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 au=[],lu=new Map;let cu=!1;const du=new WeakMap;class uu 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(),cu||(this._captureInitialHead(),cu=!0),au.push(this),this._reapplyHead()}disconnectedCallback(){const t=au.indexOf(this);-1!==t&&au.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||Jc("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=du.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return du.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);lu.has(t)||lu.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of au)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of lu.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=au.length-1;e>=0;e--){const o=au[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&lu.has(n)&&(t=lu.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),Wd(t)||Hd(t,`<${t.tagName.toLowerCase()}> inside <${qc.head}>`,`<${qc.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(qc.layout)||t.define(qc.layout,dd),t.get(qc.layoutOutlet)||t.define(qc.layoutOutlet,md),t.get(qc.outlet)||t.define(qc.outlet,ud),t.get(qc.route)||t.define(qc.route,nd),t.get(qc.router)||t.define(qc.router,su),t.get(qc.link)||t.define(qc.link,iu),t.get(qc.head)||t.define(qc.head,uu)}(void 0);const hu="data-fetchtarget",fu={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let pu=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 mu(t,e){return e.every(e=>"available"===t.availability.get(e))}const gu=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let yu=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 pu("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 mu(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),d=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",u=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:d,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}(gu,{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(!mu(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:d="auto",timeout:u=0}=e;let h=null;u>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${u}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)},u));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"===d)s=await n.blob();else if("arrayBuffer"===d)s=await n.arrayBuffer();else if("text"===d)s=await n.text();else if("json"===d)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 u=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,u)),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)}}},bu=!1;function wu(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${hu}]`);if(!n)return;const o=n.getAttribute(hu);if(!o)return;const s=customElements.get(fu.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function vu(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 _u=Symbol.for("wcstack.trustedTypes.policy");function $u(){const t=globalThis[_u];return null===t||"object"!=typeof t?null:t}let Nu,Su=!1;let xu=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...yu.wcBindable,properties:[...yu.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 yu(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(fu.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(fu.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=$u(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Nu)return Nu;if(!("trustedTypes"in globalThis))return Nu=!1,Nu;try{document.createElement("div").innerHTML="<i></i>",Nu=!1}catch{Nu=!0}return Nu}())return void function(){if(Su)return;Su=!0;const t="function"==typeof $u()?.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(!vu(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",bu||(bu=!0,document.addEventListener("click",wu)),!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 Pu extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class Iu extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let ku=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 xu&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(fu.fetch)||t.define(fu.fetch,xu),t.get(fu.fetchHeader)||t.define(fu.fetchHeader,Pu),t.get(fu.fetchBody)||t.define(fu.fetchBody,Iu),t.get(fu.infiniteScroll)||t.define(fu.infiniteScroll,ku)}(void 0);const Au="data-storagetarget",Eu={storage:"wcs-storage"},Cu="wcs-storage:value-changed",Tu="wcs-storage:loading-changed",Mu="wcs-storage:error",Lu="wcs-storage:error-info-changed",Ou="wcs-storage:trigger-changed";let Ru=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Cu,semantics:"state",getter:t=>t.detail},{name:"loading",event:Tu,semantics:"state"},{name:"error",event:Mu,semantics:"state"},{name:"errorInfo",event:Lu,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(Tu,{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(Mu,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(Lu,{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(Cu,{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)}},ju=!1;function Du(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Au}]`);if(!n)return;const o=n.getAttribute(Au);if(!o)return;const s=customElements.get(Eu.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function Bu(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 Wu=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Ru.wcBindable,properties:[...Ru.wcBindable.properties,{name:"trigger",event:Ou,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 Ru(this),this._internals=this._initInternals(),this._wireStates({[Tu]:t=>({loading:!0===t}),[Mu]: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(Ou,{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(!Bu(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",ju||(ju=!0,document.addEventListener("click",Du)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(Eu.storage)||t.define(Eu.storage,Wu)}(void 0);const zu="*",Fu="vanilla",Hu={scanImportmap:!0,loaders:{[Fu]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[zu]:Fu},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function Uu(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 qu(t,e,n){let o;if(null===e||e===zu||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===zu)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[zu],"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 Gu=new Set,Vu=new Map;let Ku=new WeakMap;function Ju(t){if(t===globalThis.customElements)return Vu;let e=Ku.get(t);return void 0===e&&(e=new Map,Ku.set(t,e)),e}const Xu=new Map;async function Qu(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 Xu)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){Gu.has(e)||(console.error(`Failed to eager load component '${e}':`,t),Gu.add(e))}}function Yu(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 Zu(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&&Xu.set(t,e)});const th=new WeakSet,eh=new WeakSet;async function nh(t,e,n){t.shadowRoot&&(th.has(t)||await async function(t,e,n){th.add(t),await ih(t.shadowRoot,e,n)}(t,e,n))}async function oh(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=Ju(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=qu("",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),Gu.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function sh(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=Zu(t);void 0===o.get(s.name)?(eh.has(t)||(eh.add(t),o.whenDefined(s.name).then(async()=>{await nh(t,e,n)})),a.has(s.name)||Gu.has(s.name)||(a.add(s.name),i.push(s))):await nh(t,e,n)}let l=0;for(const t of i)await oh(t,e,n,o),l++;return l}async function rh(t,e,n,o){for(;await sh(t,e,n,o)>0;);}async function ih(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 Yu(e)}return Yu(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await rh(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 rh(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class ah extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),ah._instance)throw new Error(`${Hu.tagNames.autoloader} can only be instantiated once.`);ah._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=Uu(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=qu(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(Qu(s,o,r))}await Promise.all(n)}(n,Hu.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 ih(document,Hu,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,ah._instance===this&&(ah._instance=null)}}!function(t=customElements){t.get(Hu.tagNames.autoloader)||t.define(Hu.tagNames.autoloader,ah)}(void 0);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|