wcstack 4.0.0-rc.2 → 4.0.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -3
- 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
|
-
var e=class{constructor(e,n,r){this.u=[],this.getter=null,this.Z=null,this.ke=!1,this.at=[],this.Ae=[],this.ct=null,this.A=-1,this.ee=t,this.Fe=null,this.xt=null,this.Rt=null,this.H=null,this.Pt=new Set,this.t=e,this.w=r,this.l=n;let i=null===r?[null]:r.c.slice(),s="*"===n;s&&i.push(r),this.n=i.length-1,this._=s?[]:null===r?[n]:[...r._,n],this.c=i}Ln(e){this.Pt.has(e)||(this.Pt.add(e),this.at.push(e),e.Ae.push(this))}Po(){this.getter=null,this.Z=null,this.A=-1,this.ee=t,this.at.length=0,this.Pt.clear(),this.Ae.length=0,this.ct=null,this.Fe=null,this.xt=null,this.Rt=null,this.H=null}G(e){let t=this;for(;null!==t;){if(t===e)return!0;t=t.w}return!1}},t=Symbol("unset"),n=Symbol("dirty"),r=Symbol("failed"),i=class{constructor(e=null){this.Tt=new Map,this.Bn=e}At(e){return this.Tt.get(e)}get(t){let n=this.Tt.get(t);if(void 0!==n)return n;let r=t.lastIndexOf("."),i=r<0?null:this.get(t.slice(0,r));return n=new e(t,t.slice(r+1),i),this.Bn?.(n),this.Tt.set(t,n),i&&i.u.push(n),n}all(){return this.Tt.values()}},s=new Map;function o(e){let t=s.get(e);if(void 0!==t)return t;let n=!0,r=e.split("."),i=[];for(let e=0;e<r.length;e++){let t=r[e],s=t.charCodeAt(0);e>0&&s>=48&&s<=57?(n=!1,i.push(Number(t)),r[e]="*"):"*"===t&&i.push(-1)}if(!n)return{o:r.join("."),indexes:i};let o={o:e,indexes:null};return s.set(e,o),o}var l=class{constructor(e,t,n){this.ut=null,this.$=null,this.de=null,this.H=null,this.u=null,this.d=!0,this.s=e,this.b=t,this.O=n}},a=class{constructor(e,t){this.Y=null,this.was=null,this.f=[],this.$=null,this.j=null,this.J=!1,this.Ft=!1,this.Ge=!1,this.o=e,this.te=t,this.n=e.n+1}},u=[],c={};function h(e,t){return null==e?t:(...n)=>{e(...n),t(...n)}}function d(e,t,n){return null==t?n:(...r)=>{let i=t(...r);return e(i)?i:n(...r)}}var f=e=>!0===e,p=e=>void 0!==e,m=e=>null!=e,g=new Set;function y(e){let t=e.$features;if(null!=c.Ct&&Array.isArray(t)){let e=t.filter(e=>!g.has(e));if(e.length>0)return c.Ct(e)}}function b(e,t){if(!g.has(e))throw new Error(`[@wcstack/state] [wcs/feature-not-installed] ${t} needs the add-on @wcstack/state/features/${e}`)}function v(e,t,n){throw new Error(`[@wcstack/state] ${e}${c.Ao?.(e,t,n)??""}`)}var w=["","binding-syntax","template-syntax","binding-path-missing","binding-type-expectation","filter-unknown","filter-arity","getter-cycle","getter-depth-exceeded","index-arity","index-param-range","recursion-unsupported","token-misconfigured","token-undeclared","wildcard-rank","spread-no-bindable","declaration-alias","name-alias"],_=e=>{let t=w[e/100|0];return t?`[wcs/${t}] `:""};function $(e,t=[]){return c.Fo?.(e,t)??`${_(e)}#${e}${t.map(e=>` ${"string"==typeof e?JSON.stringify(e):String(e)}`).join("")}`}function k(e,t,n,r){v($(e,t),n,r)}var S=class{constructor(e){this.dt=new Set,this.name=e}get size(){return this.dt.size}subscribe(e){return this.dt.add(e),()=>{this.dt.delete(e)}}unsubscribe(e){return this.dt.delete(e)}emit(...e){let t=[];for(let n of this.dt)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[@wcstack/state] ${$(17,[this.name])}`,e)}return t}};function N(e,t,n){if(void 0===e)return[];Array.isArray(e)||k(18,[t]);let r=new Set;for(let i of e)("string"!=typeof i||""===i)&&k(19,[t]),i===n&&k(20,[t,i,n]),r.has(i)&&k(21,[t,i]),r.add(i);return e}var E=Symbol.for("wcstack.transition-runner");function A(e){let t=globalThis[E];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run||"function"!=typeof t.accepts||!t.accepts(e)?null:t}function C(e,t,n){let r=A(e);if(null!==r)return r.run(t,{source:e,types:n});t()}var x="else",T="eventToken",P=/^\$[1-9]\d{0,2}$/,O=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function M(e){let t=[],n=[],r="",i=null,s=!1,o=-1,l=-1,a=e=>{let i=function(e,t,n){let r=-1===t?e.length:t,i=-1===n?0:n;return e.slice(r-e.slice(0,r).trimStart().length,i+e.slice(i).trimEnd().length)}(r,o,l);(!e||i||s)&&(t.push(i),n.push(function(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:O.test(e)?Number(e):e)}(i,s))),r="",s=!1,o=-1,l=-1};for(let t=0;t<e.length;t++){let n=e[t];i?n===i?i=null:(-1===o&&(o=r.length),r+=n,l=r.length):'"'===n||"'"===n?(i=n,s=!0):","===n?a():r+=n}return null!==i&&k(107,[i,e]),a(!0),{args:t,literals:n}}var L=e=>e.trim();function I(e,t){let n=[],r=null;for(let i=0;i<e.length;i++){let s=e[i];null!==r?s===r&&(r=null):"'"===s||'"'===s?r=s:s===t&&n.push(i)}return n}var j=(e,t)=>I(e,t)[0]??-1;function R(e,t){let n=[],r=0;for(let i of I(e,t))n.push(e.slice(r,i)),r=i+1;return n.push(e.slice(r)),n}function H(e,t,n){let r=j(e,"|");if(-1===r)return[e.trim(),[]];let i=e.slice(r+1).trim(),s=n.get(i);return void 0===s&&(s=function(e,t,n){let r=n??e.join("|");return e.map(e=>{let n=j(e,"("),i=(e=>I(e,")").pop()??-1)(e);if(-1===i&&(i=e.lastIndexOf(")")),-1!==n&&-1===i&&k(108,[e]),-1!==i&&-1===n&&k(109,[e]),-1!==i&&i<n&&k(110,[e]),-1!==i&&e.slice(i+1).trim().length>0){let t=e.slice(i+1).trim();k(111,[e,t])}let s=(-1===n?e:e.substring(0,n)).trim();if(0===s.length&&k(112,[r]),s.includes("#")){let[,e]=s.split("#");k("input"===t?113:114,[s,e])}return-1===n?{Dn:s,args:[],literals:[]}:{Dn:s,...M(e.substring(n+1,i))}})}(R(i,"|").map(L),t,e),n.set(i,s)),[e.slice(0,r).trim(),s]}var W=new Map;function z(e){k(1101,[e])}function D(e){let[t,n]=H(e,"output",W);t.includes("@")&&k(32,[t]);let r=t,i=r.startsWith("."),s=i?r.slice(1):r;return(s.length>0&&s.split(".").some(e=>0===e.length)||!i&&0===s.length)&&k(119,[e]),function(e){e.includes("**")&&z(e);let t=e.split(".").length;t>512&&k(117,[e,t])}(r),{Ye:r,Je:n}}var U=[["$streams","$stream"],["$updatedCallback","$renderedCallback"]],F=[["$watch","temporal"],["$stream","temporal"],["$listKeys","list-keys"],["$recursion","recursion"]],q=["enableMustache","sameValueGuard","enableDirectionalInitialSync"];function B(e){return e.includes("**")&&z(e),e}var K=0;function G(e,t,n){let r=e.get(t);return void 0===r&&e.set(t,r=n()),r}var V=()=>new Set,J=()=>[];function Q(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}function X(e,t){return e===t||e!=e&&t!=t}function Y(e,t,n){let r=e.H?.get(t);void 0!==r&&r.delete(n)&&0===r.size&&e.H.delete(t)}function Z(e,t){for(let n=0;n<t.length;n++){if(null==e)return;e=e[t[n]]}return e}function ee(e,t){for(;null!==e&&e.s.n>t;)e=e.s.te;return null!==e&&e.s.n===t?e:null}function te(e,t,n){let r=ee(e,n);return null!==r&&r.s.o===t.c[n]?r:null}var ne=class{constructor(e,t){this.Oe=0,this.h=null,this.Ce=0,this.ft=new Set,this.root=null,this.Qe=new Map,this.Mn=Symbol("wcs.block"),this.element=null,this.pt=[],this.Ie=null,this.Wn=[],this.Bt=0,this.V=null,this.oe=new Map,this.re=new Map,this.je=[],this.Le=[],this.Be=[],this.mt=!1,this.un=!1,this.dn=new WeakMap,this.B=0,this.Dt=0,this.fn=!1,this.Mt=!1,this.Wt=!1,this.Ee=0,this._n=()=>{this.B=0,this.fn=!1},this.Hn=()=>{this.Ee--},this.rp=null,this.rr=null,this.Oo=()=>this._t(),this.Co=(e,t)=>e(this.proxy,...t),this.Vn=[],this.Io={$untracked:e=>{let t=this.V;if(null===t)return e();t.fe++;try{return e()}finally{t.fe--}},$eqIndex:(e,t=1)=>{let n=ee(this.h,t);null===n&&k(7,[e]);let r=this.o(e);if(null!==r.getter||r.ke)return this.watchIndex(t),n.b===this.read(r,null);let i=this.V;if(null!==i){let e=i.getter,n=r.Fe??(r.Fe=[]);if(!n.some(n=>n.getter===e&&n.Un===t)){n.push({getter:e,Un:t});let i=e.c[t];(i.xt??(i.xt=[])).push({source:r,getter:e})}}return n.b===this.v(r,null)},$eq:(e,t)=>this.eq(e,t),$eqPath:(e,t)=>{let n=this.o(t);return this.eq(e,this.v(n,ee(this.h,n.n)))},$dependOn:e=>{this.resolve(B(e),this.h),null!==this.V&&0===this.V.fe&&this.qn(this.rp,this.rr,this.V)},$getAll:(e,t)=>this.getAll(e,t),$setAll:(e,t,n,r)=>this.pn(e,t,n,r),$resolve:(...e)=>{let t=B(e[0]),n=e[1]??[],r=this.o(t);this.mn("$resolve",t,r,n,!0);let i=this.Kn(r,n,null);if(e.length<3)return this.read(r,i);this.P(r,i,e[2])},$postUpdate:e=>{this.resolve(B(e),this.h);let t=this.rp,n=this.rr;"*"===t.l&&null!==n&&(n.O=n.s.Y[n.b],this.R.Ht(n)),this.hn(t,n),null!==n&&n.s.Ge&&this.zn(n,t,void 0,n.O,!1),0===t.n&&this.Xn(t,void 0,void 0,!0),this.Vt(t,n,void 0,void 0,!1)}},this.R=t,this.L=new i(e=>this.Ze(e)),this.Gn(e);let n=this;this.proxy=new Proxy(e,{get(e,t,r){let i=n.target;if("symbol"==typeof t)return Reflect.get(i,t);if(36===t.charCodeAt(0))return n.Ut(t);if(t.indexOf(".")<0){let e=n.L.At(t);if(void 0===e||null===e.getter){let e=i[t];if("function"==typeof e)return r===n.proxy&&n.U?.(e)||e}if(void 0!==e&&0===e.n)return n.read(e,null)}return n.resolve(t,n.h),n.read(n.rp,n.rr)},set:(e,t,r)=>"symbol"==typeof t?Reflect.set(n.target,t,r):(n.resolve(B(t),n.h),n.P(n.rp,n.rr,r),!0)})}o(e){return this.L.get(e)}Yn(e){let t=new Set;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n)){if(t.has(e))continue;t.add(e);let r=Object.getOwnPropertyDescriptor(n,e);if(void 0===r.get&&void 0===r.set)continue;let i=this.o(e);i.getter=r.get??null,i.Z=r.set??null,null!==i.getter&&i.n>0&&(i.A=this.Oe++)}for(let e of this.L.all())this.Ze(e)}Ze(e){e.t.includes("**")&&z(e.t),("__proto__"===e.l||"prototype"===e.l)&&k(120,[e.t]);let t=e.w;e.ke=null!==t&&"*"!==e.l&&t.n===e.n&&(null!==t.getter||t.ke),null===e.getter&&this.jo(e)}jo(e){let t=e.t,n=e.l;if(P.test(n))e.getter=function(){return this[n]};else{let n=t.split("."),r=n.findIndex((e,t)=>t>0&&e.charCodeAt(0)>=48&&e.charCodeAt(0)<=57);if(r<0||n.indexOf("*",r)>=0)return;let i=n.slice(0,r).join("."),s=n.slice(r);e.getter=function(){let e=this[t];return void 0!==e?e:Z(this[i],s)},e.Z=function(e){this[t]=e}}e.n>0&&(e.A=this.Oe++)}De(e,t){let n=null===e?this.oe:e.u??=new Map,r=n.get(t);return void 0===r&&n.set(t,r=new a(t,e)),this.q(r),r}Jn(e){try{this.q(e)}catch(t){this.qt(t,e.o.t,e.$?.S??null,"for")}}q(e){let t=this.v(e.o,e.te),n=e.Y;if(t===n)return;e.was=n,this.Qn(e);let r=function(e,t,n){let r=Array.isArray(t)?t:u;if(r===e.Y)return null;let i=e.f,s=r.length,o=i.length,a=new Array(s),c=0;for(;c<s&&c<o&&i[c].O===r[c];)a[c]=i[c],c++;let h=o-1,d=s-1;for(;h>=c&&d>=c&&i[h].O===r[d];)a[d]=i[h],h--,d--;if(c>h)for(let t=c;t<=d;t++)a[t]=new l(e,t,r[t]);else if(c>d)for(let e=c;e<=h;e++)n.Ot(i[e]);else{let t=new Map;for(let e=c;e<=h;e++){let n=i[e],r=t.get(n.O);void 0===r?t.set(n.O,n):Array.isArray(r)?r.push(n):t.set(n.O,[r,n])}for(let n=c;n<=d;n++){let i,s=r[n],o=t.get(s);void 0!==o&&(Array.isArray(o)?(i=o.shift(),0===o.length&&t.delete(s)):(i=o,t.delete(s))),a[n]=i??new l(e,n,s)}for(let e of t.values())if(Array.isArray(e))for(let t of e)n.Ot(t);else n.Ot(e)}for(let e=c;e<s;e++){let t=a[e];t.b!==e&&(t.b=e,n.To(t))}return e.f=a,e.Y=r,i}(e,t,this);if(null===r)return;if(e.Y===t){let i=G(this.dn,t,J);if(i.push(e),i.length>1){for(let e of i)e.Ge=!0;if(i.some(e=>e.was!==n)){let t=this.o(`${e.o.t}.*`);for(let e of r)e.d&&this.$e(t,e)}}}c.Kt?.(this,e,r),(null!==e.$||null!==e.j)&&!e.J&&(e.J=!0,this.Le.push(e),this.Ne());let i=e.o.xt;if(null!==i)for(let{source:t,getter:n}of i){let i=this.v(t,null),s=r[i],o=e.f[i];s!==o&&(void 0!==s&&s.d&&this.gn(n,s),void 0!==o&&this.gn(n,o))}}To(e){this.R.Lo(this,e)}Ot(e){e.d=!1;let t=e.H;if(null!==t){for(let e of t)Y(e.source,e.key,e.sub);e.H=null}if(null!==e.u)for(let t of e.u.values()){this.Qn(t);for(let e of t.f)this.Ot(e)}}Qn(e){let t=this.dn.get(e.Y);void 0!==t&&(t.splice(t.indexOf(e)>>>0,1),e.Ge=!1,1===t.length&&(t[0].Ge=!1))}resolve(e,t){let n=o(e),r=this.o(n.o),i=n.indexes;this.rr=0===r.n?null:null===i?te(t,r,r.n):this.Kn(r,i,t),this.rp=r}Kn(e,t,n){let r=null;for(let i=1;i<=e.n;i++){let s=e.c[i],o=this.De(r,s),l=t[i-1];if(-1===l&&(l=te(n,e,i)?.b??-1),r=o.f[l]??null,null===r)break}return r}zt(e,t){return 0===e.n?Z(this.target,e._):null===t?void 0:Z(t.O,e._)}read(e,t){let n=this.V;if(null!==n&&0===n.fe&&this.qn(e,t,n),null!==e.getter)return this.R.Bo(this,e,t);if(e.ke){let n=this.read(e.w,t);return n?.[e.l]}return null===e.w&&!(e.l in this.target)&&!this.ft.has(e.l)&&"then"!==e.l&&"toJSON"!==e.l&&k(301,[e.t],e.l,Object.keys(this.target)),this.zt(e,t)}v(e,t){let n=this.V;if(null===n)return this.read(e,t);n.fe++;try{return this.read(e,t)}finally{n.fe--}}qn(e,t,n){let r=n.getter;e.Ln(r),e.n>0&&r.n>0&&ee(t,Math.min(e.n,r.n))!==ee(n.r,Math.min(e.n,r.n))&&(r.ct??(r.ct=new Set)).add(e)}Do(e,t){for(let n=0;n<this.Bt;n++){let r=this.Wn[n];r.getter===e&&r.r===t&&k(701,[e.t])}this.Bt>=128&&k(801,[e.t]);let n=this.Bt++;this.Ce++;let r=this.Wn[n]??={getter:e,r:t,fe:0,Me:0};r.getter=e,r.r=t,r.fe=0,r.Me=++K;let i=this.V;this.V=r;let s=this.h;this.h=t;try{return e.getter.call(this.proxy)}finally{this.Ce--,this.Bt--,this.V=i,this.h=s,r.r=null}}watchIndex(e){let t=this.V;if(null!==t&&0===t.fe){let n=t.getter,r=n.c[e];if(r){let e=r.Rt??(r.Rt=[]);e.includes(n)||e.push(n)}}}Ut(e){let t=e.charCodeAt(1);if(t>=48&&t<=57){let n=2===e.length?t-48:P.test(e)?+e.slice(1):0;return(n<1||n>128)&&k(1001,[e]),this.watchIndex(n),ee(this.h,n)?.b}let n=this.Io[e];if(void 0!==n)return n;switch(e){case"$trackDependency":return k(1701,[e,"$dependOn"]);case"$untrackDependency":return k(1701,[e,"$untracked"]);case"$stateElement":return this.element;case"$command":return this.commands}return c.Ut?.(this,e)}eq(e,t){this.resolve(e,this.h);let n=this.rp,r=this.rr;if(null!==n.getter||n.ke||n.n>0)return X(this.read(n,r),t);let i=this.V;return null!==i&&0===i.fe&&this.Mo(n,t,i),X(this.v(n,null),t)}Mo(e,t,n){let r=n.getter,i=n.r,s=null===i?this.Vn:i.H??(i.H=[]);for(let i=0;i<s.length;i++){let o=s[i];if(o.sub.getter===r&&o.source===e){if(X(o.key,t))return void(o.Me=n.Me);o.Me!==n.Me&&(Y(e,o.key,o.sub),s.splice(i--,1))}}let o={getter:r,r:i};G(e.H??=new Map,t,V).add(o),s.push({source:e,key:t,sub:o,Me:n.Me})}Xn(e,t,n,r){this.Xt(e,i=>{let s=i.H;if(null===s&&null===i.Fe)return;let o=i===e?[]:i.t.slice(e.t.length+1).split("."),l=Z(t,o),a=Z(n,o);if(null!==i.Fe&&this.Wo(i,l,a,r),null!==s)for(let e of r?s.keys():[l,a]){let t=s.get(e);if(void 0!==t)for(let n of t)null===n.r||n.r.d?this.R.xe(this,n.getter,n.r):Y(i,e,n)}})}P(e,t,n,r=!1,i=!1){if(this.Ce>0&&k(8),i||this.Ee>0?this.Mt=!0:this.Wt=!0,c.Re?.(this,e,t,n,i))return;if(null!==e.Z){try{this.yn(e.Z,t,[n])}finally{this.Vt(e,t,void 0,void 0,!1)}return}null!==e.getter&&k(2,[e.t]),e.n>0&&null===t&&k(3,[e.t]);let s=e.ke?this.v(e,t):this.zt(e,t);if(r||!this.jt||!Object.is(s,n)||Object(n)===n){if("*"===e.l){let e=t;e.s.Y[e.b]=n,e.O=n,this.R.Ht(e)}else{let r=1===e._.length?0===e.n?this.target:t.O:this.v(e.w,t);null==r&&k(4,[e.t,r]),r[e.l]=n}this.wn(e,t),null!==t&&t.s.Ge&&this.zn(t,e,s,n),0===e.n&&this.Xn(e,s,n),this.Vt(e,t,s,n,!0)}}Zn(e){return(this.dn.get(e.Y)??[]).filter(t=>t.Y===e.Y&&(null===t.te||t.te.d))}zn(e,t,n,r,i=!0){let s=e.s,o=t.t.slice(s.o.t.length+2);for(let t of this.Zn(s)){if(t===s)continue;let l=t.f[e.b];if(void 0===l)continue;let a=this.o(`${t.o.t}.*${o}`);""===o&&(l.O=r,this.R.Ht(l)),i?this.wn(a,l):this.hn(a,l),this.Vt(a,l,n,r,i)}}hn(e,t){this._o(e,t,e=>{this.q(e);for(let t of e.Ge?this.Zn(e):[e]){let e=this.o(`${t.o.t}.*`);for(let n of t.f)this.ht(e,n),this.hn(e,n)}})}wn(e,t){let n=null===t?this.oe:t.u;if(null!==n)for(let t of n.values())t.o.G(e)&&this.q(t)}_o(e,t,n){let r=null===t?this.oe:t.u;if(null!==r)for(let t of r.values())t.o.G(e)&&n(t)}Wo(e,t,n,r){for(let{getter:i,Un:s}of e.Fe)this.eo(i.c[s],e=>{for(let s of r?e.f.keys():[t,n]){let t="number"==typeof s?e.f[s]:void 0;void 0!==t&&this.gn(i,t)}})}gn(e,t){t.s.n===e.n?this.R.xe(this,e,t):this.Gt(t,e,t=>this.R.xe(this,e,t))}Vt(e,t,n,r,i){c.pe?.(this,e,t,n,r,i),this.$e(e,t)}$e(e,t){this.R.Ho(this,e,t),this.Ne()}to(e){let t=this.Qe.get(e);if(void 0!==t)return t;let n=Symbol(`wcs.on${e}`);this.Qe.set(e,n);let r=this.root,i=this.Mn;return r.addEventListener(e,t=>{for(let s=t.target;null!==s&&s!==r;s=s.parentNode){let r=s[n];if(void 0!==r&&(r(t),t.cancelBubble))return;let o=s[i];if(void 0!==o&&o.d&&o.Vo(e,t))return}}),n}reset(e){let t=this.target;this.Gn(e);let n=this.ft;for(let e in t)"$"!==e[0]&&n.add(e);for(let t of n)t in e&&n.delete(t);for(let e of this.re.values())for(let t of e)this.Yt(t);for(let e of this.oe.values())this.no(e);this.Ie=null;try{this._t()}finally{this.bn()}c.element?.(this,"reset")}Gn(e){for(let[t,n]of F)void 0!==e[t]&&b(n,t);void 0!==e.$scan&&k(1);for(let[t,n]of U)void 0!==e[t]&&k(1601,[t,n]);let t=e.$features;if(void 0!==t){Array.isArray(t)||k(46);for(let e of t)b(e,"$features")}let n=void 0===e.$behavior?{}:e.$behavior;("object"!=typeof n||!n||Array.isArray(n))&&k(44,["state","$behavior"]);for(let e in n)(!q.includes(e)||"boolean"!=typeof n[e])&&k(44,["$behavior",e]);let[r,i,s]=q.map(e=>n[e]??!0);void 0!==this.target&&(r!==this.It||i!==this.jt||s!==this.Lt)&&k(45);let o=function(e,t){let n={};for(let r of N(e.$commandTokens,"$commandTokens","$command"))n[r]=t?.[r]??new S(r);return Object.freeze(n)}(e,this.commands),l=function(e,t){let n=new Map;for(let t of N(e.$eventTokens,"$eventTokens"))n.set(t,new S(t));let r=e.$on;if(void 0===r)return n;(null===r||"object"!=typeof r)&&k(22);for(let[e,i]of Object.entries(r)){let r=n.get(e);void 0===r&&k(23,[e]),"function"!=typeof i&&k(24,[e]),r.subscribe((...e)=>t(i,e))}return n}(e,this.Co);this.It=r,this.jt=i,this.Lt=s,c.ie?.(this,e),this.target=e,this.Oe=0;for(let e of this.L.all())e.Po();this.Vn.length=0,this.Yn(e),this.commands=o,this.Se=l}no(e){this.Jn(e);let t=this.o(`${e.o.t}.*`);for(let n of e.f)if(n.ut=null,n.H=null,this.ht(t,n),null!==n.u)for(let e of n.u.values())this.no(e)}D(e){let t=[];for(let n=e;null!==n;n=n.s.te)t.unshift(n.b);return t}Uo(e,t,n){let r=this.Se.get(e);void 0===r&&k(1301,[e],e,this.Se.keys()),r.emit(t,...this.D(n))}command(e){let t=this.commands[e];return void 0===t&&k(1302,[e],e,Object.keys(this.commands)),t}qo(e,t,n){this.command(e).emit(t,...this.D(n))}Ko(e,t,n){let r=e.includes(".")?this.v(this.o(e),null):this.target[e];return"function"!=typeof r&&k(5,[e]),this.yn(r,n,[t,...this.D(n)])}yn(e,t,n){let r=this.h;this.h=t;try{return e.apply(this.proxy,n)}finally{this.h=r}}ht(e,t){if(null!==e.getter){let n=null===t?this.oe:t.u;if(null!==n)for(let t of n.values())!t.Ft&&t.o.G(e)&&(t.Ft=!0,this.Be.push(t))}if(null===t)return void this.Xt(e,e=>{let t=this.re.get(e);if(void 0!==t)for(let e of t)this.Yt(e)});let n=t.de;if(null!==n)for(let t=0;t<n.length;t++)n[t].o.G(e)&&this.Yt(n[t]);let r=t.$;null!==r&&null!==r.se&&r.oo(this,e);let i=t.s.j;if(null!==i)for(let n of i){let r=n.map.get(t);void 0!==r&&null!==r.se&&r.oo(this,e)}}vn(e,t,n){this.Xt(e,e=>{let r=e.at;for(let i=0;i<r.length;i++){let s=r[i];if(0===s.n)this.et(s,null,n);else if(null===t||0===e.n||s.c[1]!==e.c[1]||null!==s.ct&&s.ct.has(e))this.Jt(s.c[s.n],e=>this.et(s,e,n));else if(s.n<=e.n){let e=ee(t,s.n);null!==e&&this.et(s,e,n)}else this.Gt(t,s,e=>this.et(s,e,n))}})}et(e,t,n){n(e,t)&&(c.me?.(this,e,t),this.ht(e,t),this.vn(e,t,n))}Xt(e,t){t(e);let n=e.u;for(let e=0;e<n.length;e++)this.Xt(n[e],t)}Jt(e,t){this.eo(e,e=>{for(let n of e.f)t(n)})}eo(e,t){if(0===e.n){let n=this.oe.get(e);return void(void 0!==n&&t(n))}this.Jt(e.c[e.n],n=>{let r=n.u?.get(e);void 0!==r&&t(r)})}Gt(e,t,n){if(e.s.n===t.n)return n(e);let r=e.u?.get(t.c[e.s.n+1]);if(void 0!==r)for(let e of r.f)this.Gt(e,t,n)}zo(e){let t=e.r;null===t?G(this.re,e.o,V).add(e):(t.de??(t.de=[])).push(e)}kn(e){let t=e.r;if(null===t)return void this.re.get(e.o)?.delete(e);let n=t.de;t.d&&null!==n&&n.splice(n.indexOf(e)>>>0,1)}Yt(e){e.J||(e.J=!0,this.je.push(e),this.Ne())}Ne(){this.mt||(this.mt=!0,queueMicrotask(this.Oo))}Sn(){for(let e of this.je)e.J=!1;for(let e of this.Le)e.J=!1;for(let e of this.Be)e.Ft=!1;this.je=[],this.Le=[],this.Be=[],this.R.ft(this)}io(e,t){let n=[...new Set([...this.je,...this.Le,...this.Be].map(e=>e.o.t))];console.error(`[@wcstack/state] ${$(e)}`,n),c.tt?.(this,{type:"state:render-chain-limit",maxDepth:t,paths:n}),this.Sn()}_t(){this.mt=!1;let e=this.Dt;this.Dt=0;let t=0;if(!this.Mt||this.Wt?this._n():e>0?t=e:1===(t=++this.B)&&setTimeout(this._n,0),this.Mt=this.Wt=!1,t>100)101===t?this.io(41,100):this.Sn();else{this.un=!0;try{for(let e=0;this.je.length>0||this.Le.length>0||this.Be.length>0;e++){if(e>=32){this.fn?this.Sn():this.io(11,32),this.fn=!0;break}let n=this.Be;if(n.length>0){this.Be=[];for(let e of n)e.Ft=!1,this.Jn(e)}let r=this.Le,i=this.je;this.Le=[],this.je=[];let s=C("state",()=>{for(let e of r){e.J=!1;for(let t of[e.$,...e.j??[]])if(null!==t&&t.d)try{t.yt()}catch(n){this.qt(n,e.o.t,t.S,"for")}}for(let e=0;e<i.length;e++){let t=i[e];t.J&&(t.J=!1,(null===t.En||t.En.d)&&this.We(t))}this.un||(this.Qt(),this.mt&&(this.Dt=t+1))});void 0!==s&&s.then(void 0,e=>console.error(e))}}finally{this.un=!1}this.Mt=this.Wt=!1,this.Qt(),c.Pe?.(this),e>0&&this.mt&&(this.Dt=t+1)}}wt(e,t){this.pt.push([e,t])}qt(e,t,n,r){this.wt(e,{o:{t:t},a:n,Zt:()=>r})}We(e){try{e.apply()}catch(t){return void this.pt.push([t,e])}null!==this.Ie&&this.so(e.o,e.r)}so(e,t){let n=G(this.Ie,e.t,J);null!==t&&n.push(this.D(t))}bn(){this.Ie="function"==typeof this.target.$renderedCallback?new Map:null}Qt(){let e=this.Ie;if(null!==e&&e.size>0){this.Ie=new Map;let t,n=[...e.keys()],r={};for(let[t,n]of e)n.length>0&&(r[t]=n);this.Ee++;try{t=this.ae("$renderedCallback",[n,r])}catch(e){console.error(e)}Q(t)?t.then(this.Hn,e=>{this.Hn(),console.error(e)}):this.Ee--}if(0===this.pt.length)return;let t=this.pt;this.pt=[];let n=this.target.$errorCallback;for(let[r,i]of t){c._e?.(this,r,i);let t=i.o.t,s=i.Zt();if("function"==typeof n)try{let e=this.ae("$errorCallback",[r,{path:t,bindingType:s,node:i.a}]);Q(e)&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}else console.error(`[@wcstack/state] ${$(12,[s,t])}`,r)}}ae(e,t=[]){let n=this.target[e];return"function"==typeof n?this.yn(n,null,t):void 0}lo(e,t,n){if(0===e.n)return void n(null,[]);let r=[],i=(s,o)=>{let l=e.c[s];this.read(l,o);let a=this.De(o,l),u=t=>{r.push(t.b),s===e.n?n(t,r):i(s+1,t),r.pop()};for(let e of s-1<t.length?[a.f[t[s-1]]]:a.f)void 0!==e&&u(e)};i(1,null)}getAll(e,t){let n=this.o(e);void 0!==t&&this.mn("$getAll",e,n,t,!1);let r=t;if(void 0===r){r=[];let t=this.h;if(null!==t&&n.n>0){for(let e=1;e<=n.n;e++){let i=te(t,n,e);if(null===i)break;r.push(i.b)}0===r.length&&k(6,[e])}}let i=[];return this.lo(n,r,e=>i.push(this.read(n,e))),i}pn(e,t,n,r){Array.isArray(t)||k(9,[e]),this.Ce>0&&k(8);let i=this.o(e);this.mn("$setAll",e,i,t,!1);let s=[];this.lo(i,t,(e,t)=>s.push([e,t.slice()]));let o=!0===r?.spread;o&&(!Array.isArray(n)||n.length!==s.length)&&k(10,[e,s.length]);let l=0;for(let e=0;e<s.length;e++){let[t,r]=s[e],a="function"==typeof n?n(this.v(i,t),...r):o?n[e]:n;void 0!==a&&(this.P(i,t,a),l++)}return l}mn(e,t,n,r,i){let s=r.length;(s>n.n||i&&s<n.n)&&k(i?901:902,[e,t,n.n,s])}},re={bindAttributeName:"data-wcs",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:typeof document<"u"&&document.documentElement?.lang||"en"},ie=new Map,se=new Set(["if","elseif","else","for"]),oe=new Set([x,"if","elseif","for","..."]),le=new Set(["class","attr","style","command",T,"state"]);function ae(e){let t=function(e){return R(e,";")}(e).map(L).filter(e=>e.length>0).map(e=>{let t=j(e,":");-1===t&&k(101,[e]);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim(),i=n.split("#")[0].split("|")[0].trim();if(oe.has(i)){let t;return i!==n&&k(102,[e,i]),i===x?(r.length>0&&k(103,[e]),t={Ye:"#else",Je:[]}):"..."===i?(0===r.length&&k(104,[e]),t=D(r),t.Je.length>0&&k(105,[e])):(t=D(r),"for"===i&&t.Je.length>0&&k(121,[e])),{he:i,ye:[i],en:[],C:[],...t,y:"..."===i?"spread":i}}let s=D(r),o=function(e){let[t,n]=H(e,"input",ie),r=t.split("#").map(L);r.length>2&&k(115,[t]);let[i,s]=r,o=i.split(".").map(L);return!(o.length>1&&""===o[0])&&(0===i.length||o.some(e=>0===e.length))&&k(116,[e]),{he:i,ye:o,en:s?s.split(",").map(L):[],C:n}}(n),[l]=o.ye;if(""===l&&o.ye.length>1){let e=o.ye.slice(1);return(e.includes("")||le.has(e[0]))&&k(106,[n]),{...o,he:e.join("."),ye:e,...s,y:"prop"}}return{...o,...s,y:"radio"===i||"checkbox"===i?i:l===T||l.startsWith("on")?"event":"prop"}});return t.length>1&&t.some(e=>se.has(e.y))&&k(201,[e]),t}var ue=["toFixed","locale","upper","lower","capitalize","trim","slice","padStart","padEnd","repeat","reverse","truncate","join","round","floor","ceil","percent","unit","date","time","datetime","ymd","hms"],ce=new Map,he=new Map;function de(e){for(let t of Object.keys(e))ce.set(t,{...e[t]});he.clear()}function fe(e){return ce.has(e)}function pe(e){k(26,[e])}function me(e){k(27,[e])}function ge(e){k(28,[e])}function ye(e){k(29,[e])}function be(e){return!(!e||isNaN(Number(e)))}function ve(e,t){return be(e)||me(t),Number(e)}function we(e,t,n){return ve(e?.[t]??pe(n),n)}function _e(e,t){return void 0!==t&&t.length>0?t[0]:e}var $e=(e,t)=>({factory:n=>{let r=we(n,0,e);return n=>("number"!=typeof n&&ge(e),t(n,r))},arity:[1,1]}),ke={eq:{factory:(e,t)=>{let n=e?.[0]??pe("eq"),r=_e(n,t);return e=>"number"==typeof e?"string"!=typeof r?e===r:(be(n)||me("eq"),e===Number(n)):"string"==typeof e?e===n:e===r},arity:[1,1]},ne:{factory:(e,t)=>{let n=e?.[0]??pe("ne"),r=_e(n,t);return e=>"number"==typeof e?"string"!=typeof r?e!==r:(be(n)||me("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==r},arity:[1,1]},not:{factory:()=>e=>!e,arity:[0,0]},lt:$e("lt",(e,t)=>e<t),le:$e("le",(e,t)=>e<=t),gt:$e("gt",(e,t)=>e>t),ge:$e("ge",(e,t)=>e>=t),add:$e("add",(e,t)=>e+t),sub:$e("sub",(e,t)=>e-t),mul:$e("mul",(e,t)=>e*t),div:$e("div",(e,t)=>e/t),mod:$e("mod",(e,t)=>e%t),abs:{factory:()=>e=>("number"!=typeof e&&ge("abs"),Math.abs(e)),arity:[0,0]},clamp:{factory:e=>{let t=we(e,0,"clamp"),n=we(e,1,"clamp");return e=>("number"!=typeof e&&ge("clamp"),Math.min(Math.max(e,t),n))},arity:[2,2]},int:{factory:()=>e=>parseInt(String(e),10),arity:[0,0]},float:{factory:()=>e=>parseFloat(String(e)),arity:[0,0]},falsy:{factory:()=>e=>!e,arity:[0,0]},truthy:{factory:()=>e=>!!e,arity:[0,0]},defaults:{factory:(e,t)=>{let n=_e(e?.[0]??pe("defaults"),t);return e=>e||n},arity:[1,1]},coalesce:{factory:(e,t)=>{let n=_e(e?.[0]??pe("coalesce"),t);return e=>e??n},arity:[1,1]},boolean:{factory:()=>e=>!!e,arity:[0,0]},number:{factory:()=>e=>Number(e),arity:[0,0]},string:{factory:()=>e=>String(e),arity:[0,0]},nullIfEmpty:{factory:()=>e=>""===e?null:e,arity:[0,0]}},Se=!1;function Ne(e,t){if(null!==e)for(let n=0;n<e.length;n++)t=e[n](t);return t}function Ee(e){return 0===e.length?null:(Se||(Se=!0,de(ke)),e.map(e=>function(e,t,n){let r=`${e}${function(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}(t,n)}`,i=he.get(r);if(typeof i<"u")return i;let s=ce.get(e);void 0===s&&function(e,t){ue.includes(e)&&v(`[wcs/filter-unknown] filter not found: ${e}. "${e}" is in the formats add-on — install it with installFeatures([formats]) from "@wcstack/state/features/formats".`,e,t),k(501,[e],e,t)}(e,ce.keys());let[o,l]=s.arity;t.length<o&&k(601,[e,o,t.length]),t.length>l&&k(602,[e,l,t.length]);let a=s.factory(t,n);return he.set(r,a),a}(e.Dn,e.args,e.literals)))}var Ae=Symbol.for("wcstack.trustedTypes.policy");function Ce(){let e=globalThis[Ae];return null!==e&&"object"==typeof e?e:null}function xe(e){return"innerHTML"===e||"outerHTML"===e||"srcdoc"===e}function Te(e){if(globalThis.trustedTypes?.isHTML(e))return e;let t=null==e?"":String(e),n=Ce(),r=n?.createHTML;return"function"==typeof r?r.call(n,t):t}var Pe=Symbol.for("wcstack.state.view-transition-naming"),Oe=new WeakSet;function Me(){let e=A("state");return null!==e&&"auto"===e.naming?e.namingLimit:-1}var Le=new WeakMap,Ie=e=>e.customElementRegistry??customElements;function je(e,t,n,r,i,s=!1){let o=n.localName;if(!o.includes("-"))return i(null);let l=Ie(n);if(!s&&!n.isConnected&&void 0===l.get(o)&&"customElementRegistry"in n)return void queueMicrotask(()=>je(e,t,n,r,i,!0));let a=()=>{let e=l.get(o);l.upgrade(n),i(e?function(e){if(Le.has(e))return Le.get(e);let t=e.wcBindable,n=null;if(null!==t&&"object"==typeof t&&"wc-bindable"===t.protocol&&Number.isInteger(t.version)&&t.version>=1){n={properties:new Map,inputs:new Map,commands:new Set};for(let e of t.properties??[])n.properties.set(e.name,{event:e.event,getter:"function"==typeof e.getter?e.getter:null,ao:"event"===e.semantics});for(let e of t.inputs??[])n.inputs.set(e.name,{attribute:"string"==typeof e.attribute?e.attribute:null});for(let e of t.commands??[])null!==e&&"object"==typeof e&&"string"==typeof e.name&&n.commands.add(e.name)}return Le.set(e,n),n}(e):null)};if(!s&&void 0!==l.get(o))return a();null!==r&&!r.d||function(e,t,n){let r=n;null!==t&&(t.bt??=[]).push(()=>{r=null}),e.then(()=>r?.())}(l.whenDefined(o),r,()=>{try{a()}catch(r){Ue(e,r,t,n)}e.Ne()})}function Re(e,t,n,r,i=t.o,s,o,l){let a=l.properties.get(r)??null,u=l.inputs.get(r),h=e.Lt;h&&null===a&&void 0===u&&k(38,[r]);let d=t.M;(null===a?"element"===d||"auto"===d:void 0===u&&("state"===d||"auto"===d))&&k(39,[d,r]),"connect"===t.q&&null===a&&k(40,[r]);let f=h&&null!==a&&void 0===u,p=new Be(e,ze,n,r,i,s,o,t.N,void 0);p.C=t.C,p.attribute=u?.attribute??null,Ze(e,p,!f),null!==a&&!t.ro&&n.addEventListener(a.event,t=>{let i;null!==a.getter?i=a.getter(t):(i=t.detail,a.ao||c.detail?.(n,r,i)),(!p.$n||!Object.is(i,p.value))&&(i=Ne(p.C,i),null===p.N&&(p.value=i),e.P(p.o,p.r,i,a.ao,!0))});let m=d??(f?"element":"state");if("state"===m)f||e.We(p);else if("element"===m||"auto"===m){let i=()=>{if(null!==o&&!o.d)return;if("auto"===m&&void 0!==e.v(p.o,p.r))return void(f||e.We(p));let t=n[r];null===p.N&&(p.value=t),e.P(p.o,p.r,t,!1,!0)};"connect"!==t.q||n.isConnected?i():Promise.resolve().then(i)}return p}function He(e,t,n){k(e,[t.localName,n])}var We=new Set(["click","dblclick","input","change","submit","keydown","keyup","mousedown","mouseup","pointerdown","pointerup"]),ze=11,De=["text","prop","prop","prop","prop","event","for","if","prop","radio","checkbox","prop","prop","event","spread"],Ue=(e,t,n,r)=>e.qt(t,n.o?.t??n.vt,r,De[n.i]),Fe=Symbol();function qe(e,t,n){let r=t.M;return null===r||"state"===r||"auto"===r&&void 0!==e.v(t.o,n)?t.W:Fe}var Be=class{constructor(e,t,n,r,i,s,o,l,a,u=null){this.J=!1,this.C=null,this.attribute=null,this.$n=!1,this.engine=e,this.i=t,this.a=n,this.name=r,this.o=i,this.r=s,this.En=o,this.N=l,this.value=a,this.B=u}Zt(){return De[this.i]}apply(){if(null!==this.B)return void this.B.yt();let e=Ne(this.N,this.engine.read(this.o,this.r));if(e===this.value&&("object"!=typeof e||null===e||this.i===ze||8===this.i||xe(this.name)))return;if(this.value===Fe)return void(this.value=e);let t=this.a;if(this.i!==ze)9===this.i?t.checked=void 0!==e&&this.tn()===e:10===this.i?t.checked=Array.isArray(e)&&e.includes(this.tn()):Ge(this.i,t,this.name,e),this.value=e;else{if(void 0===e)return void(this.value=e);this.value=e,this.$n=!0;try{t[this.name]!==e&&(t[this.name]=e)}finally{this.$n=!1}null!==this.attribute&&function(e,t,n){try{if(null==n)e.removeAttribute(t);else{let r=n;if("object"==typeof n)try{r=JSON.stringify(n)}catch{}e.setAttribute(t,String(r))}}catch{}}(t,this.attribute,e)}}tn(){return Ne(this.C,this.a.value)}Xo(){let e,t=this.a,n=this.engine;if(9===this.i){if(!t.checked)return;e=this.tn()}else if(10===this.i){let r=this.tn(),i=n.v(this.o,this.r),s=Array.isArray(i)?i:[],o=s.includes(r);if(t.checked?o:!o)return;e=o?s.filter(e=>e!==r):[...s,r]}else e=Ne(this.C,t[this.name]);n.P(this.o,this.r,e,!1,!0)}},Ke=e=>"textContent"===e||"innerText"===e||"innerHTML"===e;function Ge(e,t,n,r){switch(e){case 0:return void(t.data=null==r?"":String(r));case 1:return void(Ke(n)?t[n]="innerHTML"===n?Te(r):null==r?"":String(r):xe(n)?null==r&&"srcdoc"===n?t.removeAttribute(n):void 0!==r&&(t[n]=Te(r)):void 0!==r&&(t[n]!==r&&!("value"===n&&t.value===String(r))&&(t[n]=r),("value"===n||"selectedIndex"===n)&&"select"===t.localName&&(t[Ve]=[n,r])));case 8:return void(t.innerHTML=Te(r));case 2:return null!=r&&"boolean"!=typeof r&&k(401,[n,typeof r]),void t.classList.toggle(n,!0===r);case 3:return void(null==r?t.removeAttribute(n):t.setAttribute(n,String(r)));case 4:return void(null==r?t.style.removeProperty(n):t.style.setProperty(n,String(r)))}}var Ve=Symbol();function Je(e){let t="optgroup"===e.localName?e.parentNode:e,n=t?.[Ve];void 0!==n&&(t[n[0]]=n[1])}var Qe=class{constructor(e,t,n,r){this.d=!0,this.de=null,this.u=null,this.bt=null,this.xn=null,this.r=e,this.He=t,this.I=n,this.T=r}Vo(e,t){let n=t.target,r=this.T,i=[],s=null;for(let t of r.Se){if(t.name!==e)continue;let o=r.Rn[t.a],l=at(null===this.I?this.He:this.I[o[0]],o,1);l.contains(n)&&(l!==s&&i.unshift([]),i[0].push(t),s=l)}for(let e of i){for(let n of e)n.Nn(t,this.r);if(t.cancelBubble)return!0}return!1}get l(){return null===this.I?this.He:this.I[this.I.length-1]}Ve(){let e=this.xn;return(null===e?null:e.Pn(this.He))??this.He}insertBefore(e,t){let n=this.l;for(let r=this.Ve();;){let i=r.nextSibling;if(e.insertBefore(r,t),r===n)return;r=i}}fo(){null===this.I?this.He.remove():ut(this.Ve(),this.l)}be(e){if(this.d=!1,null!==this.bt)for(let e of this.bt)e();let t=this.de;if(null!==t)for(let n=0;n<t.length;n++)e.kn(t[n]);if(null!==this.u)for(let e of this.u)e.be()}},Xe=class extends Qe{constructor(e,t,n,r){super(e,t,n,r),this.po=0,this.U=null,this.se=0===r.Ue.length?null:new Array(2*r.Ue.length)}mo(e,t){let n=this.U??=new Array(this.T.Ue.length),r=n[t];if(void 0===r){let i=this.T.Ue[t],s=this.se;r=n[t]=new Be(e,i.i,s[2*t],i.name,i.o,this.r,this,i.N,s[2*t+1])}return r}oo(e,t){let n=this.T.Ue;for(let r=0;r<n.length;r++)n[r].o.G(t)&&e.Yt(this.mo(e,r))}be(e){let t=this.r;t.$===this&&(t.$=null),super.be(e)}};function Ye(e,t,n,r){let i=ee(n,t.n);try{return e.De(i,t)}catch(n){return e.qt(n,t.t,r,"for"),null===i?e.oe.get(t):i.u.get(t)}}function Ze(e,t,n){n&&e.zo(t);let r=t.En;null!==r&&(r.de??=[]).push(t)}var et=null;function tt(){let e=et;return et=null,e}var nt=-1;function rt(e,t,n,r,i=null){let s,o=t.Rn,l=t.build,a=t.ho,u=null,h=c.Te?.(t,null===r?i:r.S,null!==r),d=!h&&t.Tn,f=h?document.createDocumentFragment():(d?t.root:t.nn).cloneNode(!0);if(!h)for(let e=0;e<l.length;e++){let t=l[e];a[t]=at(f,o[t],d?1:0)}d?s=f:(u=h||[...f.childNodes],s=u[0]);let p,m=null;if(null!==r?(p=m=new Xe(n,s,u,t),null===r.map?n.$=m:r.map.set(n,m)):p=new Qe(n,s,u,t),nt>=0&&function(e,t,n,r){let i=null;if(null===t)i=1===e.nodeType?e:null;else for(let e=0;e<t.length&&null===i;e++)1===t[e].nodeType&&(i=t[e]);let s=i?.style;if(null===i||void 0===s||Oe.has(i))return;let o=globalThis[Pe]??={counter:0,assigned:0,warned:!1};o.assigned>=r?o.warned||(o.warned=!0,console.warn(`[@wcstack/state] ${$(25,[r])}`)):(Oe.add(i),o.assigned++,s.setProperty("view-transition-name",`wcs-${n}-${++o.counter}`),s.setProperty("view-transition-class",`wcs-${n}`))}(s,u,null!==r?"row":"branch",nt),t.Se.length>0){let t=e.Mn;if(null===u)s[t]=p;else for(let e of u)1===e.nodeType&&(e[t]=p)}let g=t.Go,y=e.Ie,b=t.Yo?a.slice(0,o.length):a,v=null===m?null:m.se;if(null!==v){let e=t.Ue;for(let t=0;t<e.length;t++)v[2*t]=b[e[t].a],v[2*t+1]=e[t].W}for(let r=0;r<g.length;r++){let i=g[r],o=b[i.a],l=i.A;if(l>=0&&null!==v){let r=m.U?.[l];if(void 0!==r){r.J=!1,e.We(r);continue}try{let t=Ne(i.N,e.read(i.o,n));t!==i.W&&(Ge(i.i,o,i.name,t),v[2*l+1]=t),null!==y&&e.so(i.o,n)}catch(t){e.wt(t,m.mo(e,l))}continue}switch(i.i){case 6:{let t=new lt(e,i.T,Ye(e,i.o,n,o),o);(p.u??=[]).push(t),o===s&&(p.xn=t),t.yt();break}case 7:{let t=st(e,i.K.map(e=>({T:e.T,o:e.o,N:e.N,S:b[e.a]})),n,p);(p.u??=[]).push(t),o===s&&(p.xn=t);break}default:try{it(e,i,o,n,p)}catch(t){Ue(e,t,i,o)}}}return et=p,f}function it(e,t,n,r,i){let s=n;switch(t.i){case 5:return void function(e,t,n,r,i){let s=n.Nn,o=e=>s(e,r);if(n.Qe){let r=e.to(n.name),i=t[r];t[r]=void 0===i?o:e=>{i(e),o(e)},n.we&&t.addEventListener(n.name,e=>e.bubbles||o(e))}else t.addEventListener(n.name,o),n.uo&&null!==i&&(i.bt??=[]).push(()=>t.removeEventListener(n.name,o))}(e,n,t,r,i);case 12:return void je(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name,o=e.command(t.vt.slice(9));null===i&&He(1202,n,`command.${s}`),i.commands.has(s)||k(1203,[n.localName,s]);let l=new WeakRef(n),a=o.subscribe((...e)=>{let t=l.deref();if(void 0!==t)return t.isConnected?t[s](...e):void 0;a()});null!==r&&(r.bt??=[]).push(a)}(e,t,s,i,n));case 13:return void je(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name;null===i&&He(1202,n,`eventToken.${s}`);let o=i.properties.get(s);void 0===o&&k(1204,[n.localName,s]);let l=t.vt;n.addEventListener(o.event,n=>{t.kt&&n.preventDefault(),t.St&&n.stopPropagation();try{e.Uo(l,n,r)}catch(e){console.error(e)}})}(e,t,s,r,n))}let o=t.o,l=ee(r,o.n);if(14===t.i)return void je(e,t,s,i,n=>function(e,t,n,r,i,s){null===s&&He(1501,n,`"...: ${t.o.t}"`);let o=new Set([...s.properties.keys(),...s.inputs.keys()]);for(let l of o){if(t.co?.includes(l))continue;let o=e.o(`${t.o.t}.${l}`),a=0===o.n?null:r;Re(e,{...t,M:null,q:null},n,l,o,a,i,s)}}(e,t,s,l,i,n));if(t.we&&1===t.i)return void je(e,t,s,i,n=>function(e,t,n,r,i,s){if(null!==s)return void Re(e,t,n,t.name,t.o,r,i,s);let o=new Be(e,1,n,t.name,t.o,r,i,t.N,qe(e,t,r));o.C=t.C,!c.Jo?.(o,t.ro)&&(Ze(e,o,!0),e.We(o))}(e,t,s,l,i,n));let a=new Be(e,t.i,n,t.name,o,l,i,t.N,qe(e,t,l));a.C=t.C,Ze(e,a,!0),e.We(a),null!==t.Et&&n.addEventListener(t.Et,()=>a.Xo())}function st(e,t,n,r){let i=new ot(e,t,n),s=null;for(let o of t){if(null===o.o)continue;let t=o.o,l=new Be(e,7,o.S,"if",t,ee(n,t.n),r,null,void 0,i);Ze(e,l,!0),null===r&&i.re.push(l),s??=l}return e.We(s),i}var ot=class{constructor(e,t,n){this.d=!0,this.F=null,this.b=-1,this.re=[],this.engine=e,this.K=t,this.r=n}Pn(e){return null!==this.F&&this.K[this.b].S===e?this.F.Ve():null}yt(){let e=this.engine,t=-1;for(let n=0;n<this.K.length;n++){let r=this.K[n];if(null===r.o||Ne(r.N,e.read(r.o,ee(this.r,r.o.n)))){t=n;break}}if(t!==this.b&&(nt=Me(),null!==this.F&&(this.F.fo(),this.F.be(e),this.F=null),this.b=t,t>=0)){let n=this.K[t],r=rt(e,n.T,this.r,null,n.S);this.F=tt();let i=n.S.parentNode;i.insertBefore(r,n.S),Je(i)}}be(){this.d=!1;for(let e of this.re)this.engine.kn(e);null!==this.F&&this.F.be(this.engine)}},lt=class{constructor(e,t,n,r){this.d=!0,this.ve=[],this.engine=e,this.T=t,this.s=n,this.S=r,null===n.$?(n.$=this,this.map=null):((n.j??=[]).push(this),this.map=new Map)}Pn(e){return 0===this.ve.length?null:this.ve[0].Ve()}$t(e){return null===this.map?e.$:this.map.get(e)??null}go(e){let t=this.map;null!==t&&t.get(e.r)===e&&t.delete(e.r),e.be(this.engine)}yt(){let e=this.engine,t=this.s.f,n=this.ve;nt=Me();let r=t.length,i=n.length,s=this.S,o=s.parentNode;if(0===r){if(i>0){ut(n[0].Ve(),n[i-1].l);for(let e=0;e<i;e++)this.go(n[e])}return void(this.ve=[])}let l=new Array(r),a=0;for(;a<r&&a<i&&this.$t(t[a])===n[a];)l[a]=n[a],a++;let u=i-1,c=r-1;for(;u>=a&&c>=a&&this.$t(t[c])===n[u];)l[c]=n[u],u--,c--;for(let e=a;e<=u;e++){let t=n[e],r=t.r;r.d&&this.$t(r)===t?t.po=e:(t.fo(),this.go(t))}if(a<=c){let n=c-a+1,u=new Int32Array(n),h=!1;if(i>0)for(let e=0;e<n;e++){let n=this.$t(t[a+e]);null!==n&&n.d?(u[e]=n.po,h=!0):u[e]=-1}let d=c+1<r?l[c+1].Ve():s;if(h){let r=function(e){let t=e.length,n=new Uint8Array(t),r=new Int32Array(t).fill(-1),i=[];for(let n=0;n<t;n++){let t=e[n];if(t<0)continue;let s=0,o=i.length;for(;s<o;){let n=s+o>>1;e[i[n]]<t?s=n+1:o=n}s>0&&(r[n]=i[s-1]),i[s]=n}let s=i.length>0?i[i.length-1]:-1;for(;s>=0;)n[s]=1,s=r[s];return n}(u),i=d;for(let s=n-1;s>=0;s--){let n=t[a+s],u=this.$t(n);null!==u&&u.d?0===r[s]&&u.insertBefore(o,i):(o.insertBefore(rt(e,this.T,n,this),i),u=tt()),l[a+s]=u,i=u.Ve()}}else{let n=document.createDocumentFragment();for(let r=a;r<=c;r++)n.appendChild(rt(e,this.T,t[r],this)),l[r]=tt();o.insertBefore(n,d)}}this.ve=l,Je(o)}be(){this.d=!1;let e=this.s;if(e.$===this)e.$=null;else if(null!==e.j){let t=e.j.indexOf(this);t>=0&&e.j.splice(t,1),0===e.j.length&&(e.j=null)}for(let e of this.ve)e.be(this.engine);this.map?.clear()}};function at(e,t,n){for(;n<t.length;n++){e=e.firstChild;for(let r=t[n];r>0;r--)e=e.nextSibling}return e}function ut(e,t){let n=document.createRange();n.setStartBefore(e),n.setEndAfter(t),n.deleteContents()}var ct=()=>re.bindAttributeName;function ht(){return{a:0,i:1,name:"",o:null,N:null,W:t,Nn:null,T:null,K:null,C:null,Et:null,we:!1,M:null,q:null,ro:!1,kt:!1,St:!1,vt:null,co:null,A:-1,Qe:!1,uo:!1}}var dt=["state","element","auto","none"],ft=["call","connect"],pt="$command.";function mt(e,t,n){P.test(t)&&(null===n&&k(1401,[t,Number(t.slice(1))]),t=`${n.t}.*.${t}`);let r=e.o(function(e,t){return 46!==e.charCodeAt(0)?e:(null===t&&k(1402,[e]),"."===e?`${t.t}.*`:`${t.t}.*${e}`)}(t,n)),i=null===n?0:n.n+1;r.n>i&&k(1401,[r.t,r.n,i]);for(let e=1;e<=r.n;e++){let t=e===i?n:n.c[e];r.c[e]!==t&&k(1403,[r.t,r.c[e].t,t.t])}return c.yo?.(e,r),r}var gt=e=>1===e.i&&("outerHTML"===e.name||"outerText"===e.name),yt=e=>8===e.i||gt(e)||1===e.i&&Ke(e.name);function bt(e){k(202,[e])}function vt(e,t,n,r,i){let s=ae(t).map(t=>function(e,t,n,r,i){let s=function(e,t){let n=t.find(e=>e.startsWith("on")),r=null,i=null;for(let n of t){let t=n.indexOf("=");if(t<0)continue;e.Lt||k(31);let s=n.slice(0,t).trim(),o=n.slice(t+1).trim(),l="init"===s;!l&&"sync"!==s&&k(33,[s,n]),null!==(l?r:i)&&k(34,[s]),(l?dt:ft).includes(o)||k(35,[s,o]),l?r=o:i=o}return{ro:t.includes("ro"),kt:t.includes("prevent"),St:t.includes("stop"),event:n?n.slice(2):null,M:r,q:i}}(e,t.en),o=r.localName.includes("-"),l=t.ye,a=t.Ye;if("event"===t.y){if(null!==s.M&&"none"!==s.M&&k(36),"eventToken"===l[0])return{...ht(),a:i,i:13,name:l.slice(1).join("."),vt:a,we:o,kt:s.kt,St:s.St};let n=a.startsWith(pt)?a.slice(9):null,{kt:r,St:u}=s,c=t.he.slice(2),h=t.en.includes("direct"),d=!h&&We.has(c);return d&&e.to(c),{...ht(),a:i,i:5,name:c,Qe:d,we:o,uo:h,Nn(t,i){r&&t.preventDefault(),u&&t.stopPropagation();try{if(null!==n)e.qo(n,t,i);else{let n=e.Ko(a,t,i);Q(n)&&n.then(void 0,e=>console.error(e))}}catch(e){console.error(e)}}}}if("spread"===t.y)return{...ht(),a:i,i:14,o:mt(e,a,n),we:o};if("command"===l[0]&&l.length>1)return a.startsWith(pt)||k(1201,[t.he,a]),{...ht(),a:i,i:12,name:l.slice(1).join("."),vt:a,we:o};let u=mt(e,a,n),c={...ht(),a:i,i:1,name:t.he,o:u,N:Ee(t.Je),C:Ee(t.C),ro:s.ro,M:s.M,q:s.q};if("radio"===t.y||"checkbox"===t.y)return("element"===s.M||"auto"===s.M)&&k(37,[t.y,s.M]),c.i="radio"===t.y?9:10,s.ro||(c.Et=s.event??"input"),c;if(l.length>1){let e=l.slice(1).join("."),t=l[0];if("class"===t||"attr"===t||"style"===t)return c.M=null,c.name=e,"class"===t?(c.i=2,c.W=r.classList.contains(e)):c.i="attr"===t?"srcdoc"===e&&"iframe"===r.localName?1:3:4,c}return"html"===t.he?(c.i=8,c):(c.name="text"===t.he?"textContent":t.he,c.we=o&&!xe(c.name),!o&&!s.ro&&function(e,t){let n=e.localName;if("input"===n){let n=(e.getAttribute("type")||"text").toLowerCase();return"button"!==n&&(("radio"===n||"checkbox"===n)&&"checked"===t||"value"===t||"valueAsNumber"===t||"valueAsDate"===t)}return("select"===n||"textarea"===n)&&"value"===t}(r,c.name)&&(c.Et=s.event??("select"===r.localName?"change":"input")),c)}(e,t,n,r,i));for(let e=0;e<s.length;e++)14===s[e].i&&(s[e].co=s.slice(e+1).filter(e=>1===e.i).map(e=>e.name));return s}var wt=/\{\{([\s\S]+?)\}\}/g;function _t(e){let t=e.data,n=[],r=0;wt.lastIndex=0;for(let i=wt.exec(t);null!==i;i=wt.exec(t)){let s=wt.lastIndex-i[0].length;s>r&&e.before(t.slice(r,s));let o=e.ownerDocument.createTextNode("");e.before(o),n.push({a:o,Qo:i[1].trim()}),r=wt.lastIndex}return 0===n.length||(r<t.length&&e.before(t.slice(r)),e.remove()),n}function $t(e,t,n,r){let i=function(e){return{he:"textContent",ye:["textContent"],en:[],C:[],...D(e),y:"text"}}(t);return{...ht(),a:r,i:0,o:mt(e,i.Ye,n),N:Ee(i.Je),W:""}}function kt(e){let t=e.getAttribute(ct());if(null===t)return null;let n=ae(t)[0];return void 0===n||"for"!==n.y&&"if"!==n.y&&"elseif"!==n.y&&"else"!==n.y?null:n}var St=(e,t)=>0===e?re.commentIfPrefix:null===t.o?re.commentElsePrefix:re.commentElseIfPrefix;function Nt(e,t,n){let r=(t,r)=>({el:t,o:"else"===r.y?null:mt(e,r.Ye,n),N:"else"===r.y?null:Ee(r.Je)}),i=[r(t,kt(t))];for(let e=t.nextSibling;null!==e;e=e.nextSibling){if(3===e.nodeType&&""===e.data.trim()||8===e.nodeType)continue;if(1!==e.nodeType||"template"!==e.localName)break;let t=kt(e);if(null===t||"elseif"!==t.y&&"else"!==t.y||(i.push(r(e,t)),"else"===t.y))break}return i}var Et=new WeakSet;function At(e,t,n,r,i,s,o,l){let a=(t,n)=>{let i=document.createComment(n);return t.replaceWith(i),r&&c.An?.(e,i,t),i},u=t=>{for(let h=0;h<t.length;h++){let d=t[h];if(null!==d.parentNode)if(1===d.nodeType){let t=d,l=t.localName;if(r){if("script"===l||"style"===l||Et.has(t))continue;if(Et.add(t),l===re.tagNames.state){u([...t.childNodes]);continue}}let h="template"===l?kt(t):null;if(null!==h){if("for"===h.y){let r=mt(e,h.Ye,n),s=Tt(e,t,r,!0);i(a(t,re.commentForPrefix),r,s)}else"if"===h.y?s(Nt(e,t,n).map((t,r)=>({T:Tt(e,t.el,n,!1),o:t.o,N:t.N,S:a(t.el,St(r,t))}))):bt(h.y);continue}let f=t.getAttribute(ct()),p=null===f?null:vt(e,f,n,t,0),m="noscript"!==l&&"iframe"!==l&&!p?.some(yt)&&!c.wo?.(t);try{r&&m&&u([...t.childNodes])}finally{null!==p&&o(t,p)}!r&&m&&u([...t.childNodes])}else if(3===d.nodeType&&e.It&&d.data.includes("{{")&&!Et.has(d))for(let{a:e,Qo:t}of _t(d))l(e,t);else if(8===d.nodeType){let e=Ct.exec(d.data),t=e&&d.parentNode.localName;if(null!==t&&"textarea"!==t&&"title"!==t){let t=document.createTextNode("");d.replaceWith(t),l(t,e[1])}}}};u(t)}var Ct=/^\s*@@\s*(?:wcs-text)?\s*:\s*([\s\S]+?)\s*$/,xt=e=>{let t=document.createRange();return t.selectNodeContents(e),e.content??t.cloneContents()};function Tt(e,t,n,r){let i=document.importNode(xt(t),!0),s=[],o=[],l=e=>s.push(e)-1;At(e,[...i.childNodes],n,!1,(e,t,n)=>{o.push({...ht(),a:l(e),i:6,o:t,T:n})},e=>{let t=e.map(e=>({a:l(e.S),T:e.T,o:e.o,N:e.N}));o.push({...ht(),a:t[0].a,i:7,K:t})},(e,t)=>{let n=l(e);for(let e of t)gt(e)&&k(203,[e.name]),e.a=n;o.push(...t),e.removeAttribute(ct())},(t,r)=>{o.push($t(e,r,n,l(t)))}),Lt(i,new Set(s),!0);let a=s.map(e=>function(e,t){let n=[];for(let r=t;r!==e;r=r.parentNode){let e=0;for(let t=r.previousSibling;null!==t;t=t.previousSibling)e++;n.unshift(e)}return n}(i,e)),u=1===i.childNodes.length&&8!==i.firstChild.nodeType,c=o.some(e=>6===e.i||7===e.i),h=[],d=new Set,f=[],p=[],m=r?n.n+1:-1;for(let e of o){if(5===e.i&&e.Qe&&!e.we&&!Pt(s[e.a],i)){f.push(e);continue}p.push(e);let t=e.o;if(null!==t&&t.n===m&&t.c[m]===n&&Ot(e)&&(e.A=h.push(e)-1),7===e.i)for(let t of e.K)d.add(t.a);else d.add(e.a)}let g=[...d].sort((e,t)=>e-t);return{nn:i,root:u?i.firstChild:null,Rn:a,build:g,Se:f,Go:p,Tn:u,Yo:c,ho:[],Ue:h}}function Pt(e,t){for(;e.parentNode!==t;e=e.parentNode){if(e.parentNode.localName.includes("-"))return!0;for(let t=e.previousSibling;t;t=t.previousSibling)if(8===t.nodeType)return!0}return!1}function Ot(e){if(null!==e.M)return!1;switch(e.i){case 0:case 2:case 3:case 4:case 8:return!0;case 1:return!e.we&&null===e.Et;default:return!1}}var Mt=new Set(["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","datalist"]);function Lt(e,t,n){for(let r=e.firstChild;null!==r;){let e=r.nextSibling;3===r.nodeType?n&&!t.has(r)&&""===r.data.trim()&&r.remove():1===r.nodeType&&Lt(r,t,Mt.has(r.localName)),r=e}}var It=new WeakMap;function jt(e,t){let n=9===t.nodeType?t.body:t;e.root=t,It.set(t,e),Rt(e,[...n.childNodes]),e.Qt()}function Rt(e,t){At(e,t,null,!0,(t,n,r)=>{new lt(e,r,Ye(e,n,null,t),t).yt()},t=>{st(e,t,null,null)},(t,n)=>{c.An?.(e,t,n);for(let r of n)it(e,r,t,null,null)},(t,n)=>{c.An?.(e,t,n),it(e,$t(e,n,null,0),t,null,null)})}var Ht=Symbol.for("wcstack.binder"),Wt=Symbol.for("wcstack.binder.pending"),zt=Symbol.for("wcstack.binder.taken"),Dt=new Set;function Ut(e,t){if(1!==e.nodeType||!e.isConnected)return;let n=It.get(e.getRootNode());void 0===n||!1===n.element?.isConnected?Dt.add(e):function(e,t,n){try{let r="template"===t.localName?kt(t):null;null!==r&&!n&&k(204,[r.y]),Rt(e,[t])}catch(e){console.error(e)}e.Qt()}(n,e,t?.range)}function Ft(){let e=[...Dt];Dt.clear();for(let t of e)Ut(t);!function(){let e=function(){let e=globalThis[Ht];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;let t=function(){let e=globalThis,t=e[Wt];return void 0===t&&(t=[],e[Wt]=t),t}();if(0===t.length)return;let n=t.splice(0,t.length),r=function(){let e=globalThis,t=e[zt];return void 0===t&&(t=new WeakSet,e[zt]=t),t}();for(let t of n)r.add(t),e.bind(t)}()}var qt=class{constructor(){this.name="dirty",this.nt=(e,r)=>{if(0===e.n){let r=e.ee;return r!==t&&r!==n&&(e.ee=n,!0)}let i=null===r?null:r.ut;if(null===i)return!1;let s=i[e.A];return s!==t&&s!==n&&(i[e.A]=n,!0)}}Ho(e,t,n){null!==t.getter&&this.nt(t,n),e.ht(t,n),e.vn(t,n,this.nt)}Lo(e,t){let n=t.s.o.Rt;if(null!==n)for(let r of n)r.n===t.s.n?e.et(r,t,this.nt):e.Gt(t,r,t=>e.et(r,t,this.nt))}xe(e,t,n){this.nt(t,n),c.me?.(e,t,n),e.ht(t,n),e.vn(t,n,this.nt)}Bo(e,i,s){let o=0===i.n;if(!o&&null===s)return;let l=o?null:s.ut??=new Array(e.Oe).fill(t),a=null===l?i.ee:l[i.A];if(a!==t&&a!==n&&a!==r&&(null===l||i.A in l))return a;a=r;try{return a=e.Do(i,null===l?null:s)}finally{null===l?i.ee=a:l[i.A]=a}}Ht(e){e.ut=null}ft(e){for(let t of e.L.all())null!==t.getter&&(0===t.n?t.ee===n&&(t.ee=r):e.Jt(t.c[t.n],e=>{let i=e.ut;null!==i&&i[t.A]===n&&(i[t.A]=r)}))}},Bt=0,Kt=new WeakMap;function Gt(e){let t=e.getRootNode();Kt.set(t,[...(Kt.get(t)??[]).filter(t=>t.isConnected&&t!==e),e])}function Vt(e){let t=Kt.get(e)??[],n=t.filter(t=>t.getRootNode()===e);return Promise.any(n.map(e=>e.initializePromise.then(()=>e.U||e.connectedCallbackPromise))).then(()=>{},r=>n.length?Kt.get(e)!==t?Vt(e):Promise.reject(r.errors[0]):void 0)}var Jt=typeof HTMLElement>"u"?class{}:HTMLElement,Qt=class extends Jt{constructor(){super(),this.engine=null,this.Fn=!1,this._e=!1,this.W=null,this.qe=null,this.loaded=!1,this.sn=null,this.connectedCallbackPromise=new Promise((e,t)=>{this.rn=e,this.bo=t}),this.connectedCallbackPromise.catch(()=>{}),this.initializePromise=new Promise(e=>{this.on=e})}static{this.getBindingsReady=Vt}static{this.hasConnectedCallbackPromise=!0}connectedCallback(){if(this.Fn){if(null!==this.qe)return void this.qe.Ke();Gt(this);let e=this.engine;return void(null!==e&&Promise.resolve(e.ae("$connectedCallback")).then(()=>{this.isConnected&&c.element?.(e,"connected")},e=>console.error(e)))}this.Fn=!0;let e=this.getRootNode(),t=c.ot?.(this,e);if(t)return this.qe=t,!t.vo&&this.parentNode instanceof ShadowRoot&&Gt(this),void(void 0===t.Ct?this.ko():t.Ct()).then(e=>(this.loaded=!0,t.start(e,()=>this.So()))).then(()=>{this.on(),this.rn()},e=>this.wt(e,t.vo));this.start(e),Gt(this)}disconnectedCallback(){if(null!==this.qe)return void this.qe.On();let e=this.engine;null!==e&&(e.ae("$disconnectedCallback"),c.element?.(e,"disconnected"))}setInitialState(e){if(this._e&&k(14),this.loaded)this.qe.reset(e);else if(null===this.engine)if(null!==this.sn){let t=this.sn;this.sn=null,t(e)}else this.W=e;else this.engine.reset(e)}createState(e,t){let n=this.engine;null===n&&k(15),"readonly"===e&&n.Ce++;try{t(n.proxy)}finally{"readonly"===e&&n.Ce--}}async createStateAsync(e,t){let n=this.engine;null===n&&k(15),await t("writable"===e?n.proxy:new Proxy(n.proxy,{get(e,t,n){let r=Reflect.get(e,t,n);return"$setAll"===t||"$resolve"===t?(...e)=>(e.length>2&&k(8),r(...e)):r},set(){k(8)}}))}async ko(){await 0;let e=this.getAttribute("state");if(null!==e){let t=t=>[...t.querySelectorAll('script[type="application/json"]')].find(t=>t.id===e),n=t(this.getRootNode())??t(document);return void 0===n?Promise.reject(new Error(`[@wcstack/state] ${$(16,[e])}`)):Promise.resolve(JSON.parse(n.textContent||"{}"))}let t=this.getAttribute("src");if(null!==t)return async function(e){let t=new URL(e,document.baseURI).href;if(/\.json(?:[?#]|$)/.test(t)){let n=await fetch(t);return n.ok||k(13,[e,n.status]),await n.json()}return(await(import(t))).default??{}}(t);let n=this.getAttribute("json");if(null!==n)return Promise.resolve(JSON.parse(n));let r=this.querySelector('script[type="module"]');return null!==r?async function(e){let t=!1,n=e=>{e.effectiveDirective.startsWith("script-src")&&(t=!0)};document.addEventListener("securitypolicyviolation",n);let r="function"==typeof URL.createObjectURL,i=r?URL.createObjectURL(new Blob([e.text],{type:"application/javascript"})):"data:text/javascript;charset=utf-8,"+encodeURIComponent(`${e.text}\n//${++Bt}`);try{return(await(import(i))).default??{}}catch(e){throw await new Promise(e=>setTimeout(e)),new Error(`[@wcstack/state] ${t?$(42):$(43,[e instanceof Error?e.message:String(e)])}`,{cause:e})}finally{document.removeEventListener("securitypolicyviolation",n),r&&URL.revokeObjectURL(i)}}(r):null!==this.W?Promise.resolve(this.W):new Promise(e=>{this.sn=e})}async start(e){try{let t=e.host;(this.hasAttribute("mount")||this.hasAttribute("bind-component")||t?.hasAttribute("data-wc-definition"))&&b("scopes","<wcs-state>");let n=await this.ko(),r=y(n);if(r&&await r,this.getRootNode()!==e)return this.W=n,this.Fn=!1,void(this.isConnected&&this.connectedCallback());this.hasAttribute("enable-ssr")&&b("ssr","enable-ssr");let i=It.get(e)?.element;i?.isConnected&&(i.U||i.qe)&&k(47);let s=new ne(n,new qt);s.element=this,this.engine=s,c.element?.(s,"mounting"),jt(s,e),Ft(),s.bn(),this.So(),await s.ae("$connectedCallback"),this.isConnected&&c.element?.(s,"connected"),this.rn()}catch(e){this._e=!this.U,this.wt(e)}}So(){this.U=!0,this.on()}wt(e,t){let n=["mount","bind-component","state","src"].flatMap(e=>this.hasAttribute(e)?[e,this.getAttribute(e)]:[]);console.error(`[@wcstack/state] ${$(this.U?50:49,[this.localName,...n])}`,e),this.on(),t?this.rn():this.bo(e)}},Xt=[];function Yt(){return(Xt=Xt.filter(e=>e.deref())).map(e=>e.deref())}var Zt,en=e=>t=>{let n=e(t);return e=>null==e?e:n(e)},tn="en";function nn(){if(re.locale!==Zt){Zt=re.locale;try{tn=Intl.getCanonicalLocales(Zt)[0]}catch{console.warn(`[@wcstack/state] ${$(48,[Zt])}`),tn="en"}}return tn}var rn={toFixed:{factory:e=>{let t=ve(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&ge("toFixed"),e.toFixed(t))},arity:[0,1]},locale:{factory:e=>{let t=e?.[0];return e=>("number"!=typeof e&&ge("locale"),e.toLocaleString(t??nn()))},arity:[0,1]},upper:{factory:en(()=>e=>String(e).toUpperCase()),arity:[0,0]},lower:{factory:en(()=>e=>String(e).toLowerCase()),arity:[0,0]},capitalize:{factory:en(()=>e=>{let t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),arity:[0,0]},trim:{factory:en(()=>e=>String(e).trim()),arity:[0,0]},slice:{factory:en(e=>{let t=[we(e,0,"slice")],n=e?.[1];return typeof n<"u"&&t.push(ve(n,"slice")),e=>String(e).slice(...t)}),arity:[1,2]},padStart:{factory:en(e=>{let t=we(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),arity:[1,2]},padEnd:{factory:en(e=>{let t=we(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),arity:[1,2]},repeat:{factory:en(e=>{let t=we(e,0,"repeat");return e=>String(e).repeat(t)}),arity:[1,1]},reverse:{factory:en(()=>e=>String(e).split("").reverse().join("")),arity:[0,0]},truncate:{factory:en(e=>{let t=we(e,0,"truncate"),n=e?.[1]??"…";return e=>{let r=String(e);return r.length<=t?r:r.slice(0,t)+n}}),arity:[1,2]},join:{factory:e=>{let t=e?.[0]??", ";return e=>(Array.isArray(e)||k(30,["join"]),e.join(t))},arity:[0,1]},round:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","round"));return e=>("number"!=typeof e&&ge("round"),Math.round(e*t)/t)},arity:[0,1]},floor:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&ge("floor"),Math.floor(e*t)/t)},arity:[0,1]},ceil:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&ge("ceil"),Math.ceil(e*t)/t)},arity:[0,1]},percent:{factory:e=>{let t=ve(e?.[0]??"0","percent");return e=>("number"!=typeof e&&ge("percent"),`${(100*e).toFixed(t)}%`)},arity:[0,1]},unit:{factory:en(e=>{let t=e?.[0]??pe("unit");return e=>String(e)+t}),arity:[1,1]},date:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("date"),e.toLocaleDateString(t??nn()))},arity:[0,1]},time:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("time"),e.toLocaleTimeString(t??nn()))},arity:[0,1]},datetime:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("datetime"),e.toLocaleString(t??nn()))},arity:[0,1]},ymd:{factory:e=>{let t=e?.[0]??"-";return e=>{e instanceof Date||ye("ymd");let n=e.getFullYear().toString(),r=(e.getMonth()+1).toString().padStart(2,"0"),i=e.getDate().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]},hms:{factory:e=>{let t=e?.[0]??":";return e=>{e instanceof Date||ye("hms");let n=e.getHours().toString().padStart(2,"0"),r=e.getMinutes().toString().padStart(2,"0"),i=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]}},sn=!1,on={name:"formats",install:function(){sn||(sn=!0,de(rn))}};function ln(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;let r=new Array(t.length+1),i=new Array(t.length+1);for(let e=0;e<=t.length;e++)r[e]=e;for(let n=1;n<=e.length;n++){i[0]=n;for(let s=1;s<=t.length;s++){let o=e[n-1]===t[s-1]?0:1;i[s]=Math.min(r[s]+1,i[s-1]+1,r[s-1]+o)}for(let e=0;e<=t.length;e++)r[e]=i[e]}return r[t.length]}function an(e,t){if(0===e.length)return"";let n=e.toLowerCase(),r=null,i=3;for(let e of t){let t=ln(n,e.toLowerCase(),2);t<i&&(r=e,i=t)}return null!==r?` Did you mean "${r}"?`:""}var un=" Validate statically: npx @wcstack/lint <file>.",cn=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],hn=(e,t)=>`<${e}${t.map((e,t)=>t%2?`="${e}"`:` ${e}`).join("")}>`,dn="https://github.com/wcstack/wcstack/blob/main/docs/csp.md",fn={1:()=>"$scan was removed (use $watch or $on)",2:e=>`"${e}" is a getter without a setter`,3:e=>`no row for "${e}"`,4:(e,t)=>`cannot write "${e}": its parent is ${t}`,5:e=>`"${e}" is not a method`,6:e=>`$getAll("${e}"): no loop level in common with the context`,7:e=>`$eqIndex("${e}") needs a list row scope.`,8:()=>"This state is readonly.",9:e=>`$setAll("${e}") needs indexes ([] for every match)`,10:(e,t)=>`$setAll("${e}", …, { spread: true }) needs an array of ${t} values`,11:()=>"updates did not settle after 32 passes",41:()=>"render chain depth limit exceeded (100 drains that rendering itself started); bindings for this batch were not applied.",12:(e,t)=>`binding "${e}: ${t}" failed to apply.`,13:(e,t)=>`failed to load "${e}": ${t}`,14:()=>"this <wcs-state> failed to initialize; create a new one",15:()=>"state is not initialized",16:e=>`no <script> with id "${e}"`,42:()=>`The inline <script> of <wcs-state> was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src="./state.js") needs neither. See ${dn}`,43:e=>`Failed to evaluate the inline <script> of <wcs-state>: ${e}. If this page sets a Content-Security-Policy, see ${dn}`,17:e=>`a subscriber of token "${e}" threw.`,18:e=>`${e} must be an array of strings.`,19:e=>`${e} entries must be non-empty strings.`,20:(e,t,n)=>`${e} entry "${t}" conflicts with the reserved namespace name "${n}".`,21:(e,t)=>`${e} entry "${t}" is duplicated.`,22:()=>"$on must be an object of handlers.",23:e=>`$on entry "${e}" is not declared in $eventTokens.`,24:e=>`$on entry "${e}" must be a function.`,25:e=>`view-transition naming-limit (${e}) reached.`,26:e=>`filter ${e} requires at least one option`,27:e=>`filter ${e} requires a number as option`,28:e=>`filter ${e} requires a number value`,29:e=>`filter ${e} requires a date value`,30:e=>`filter ${e} requires an array value`,31:()=>"init=/sync= modifiers require enableDirectionalInitialSync.",33:(e,t)=>`Unknown binding modifier "${e}" in "${t}".`,34:e=>`Binding modifier "${e}" may only be specified once.`,35:(e,t)=>`Invalid ${e} modifier value "${t}".`,36:()=>"Event bindings only allow init=none.",37:(e,t)=>`Binding type "${e}" does not support init=${t}.`,38:e=>`Property "${e}" is not declared by wcBindable.`,39:(e,t)=>`init=${e} is incompatible with wcBindable member "${t}".`,40:e=>`sync=connect requires observable property "${e}".`,44:(e,t)=>`${e}: "${t}" is not one of its options, or not of the option's type.${"bootstrapState"===e&&cn.includes(t)?" 4.0 moved it to the state's $behavior.":""}`,45:()=>"a re-set state may not change $behavior: create the element again.",47:()=>'a second <wcs-state> on the same root: there is one state tree per root — graft a subtree with <wcs-state mount="path"> (v1\'s name="…" is gone: read the mounted state by its path).',48:e=>`the locale "${e}" (<html lang> or bootstrapState's locale) is not a language tag Intl takes (en-US, not en_US): the locale filters use "en".`,46:()=>'$features must be an array of add-on names (["temporal", "formats"]).',49:(e,...t)=>`${hn(e,t)} failed to initialize.`,50:(e,...t)=>`${hn(e,t)} $connectedCallback failed.`,101:e=>`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`,102:(e,t)=>`"${e}": "${t}" takes no modifiers or filters on its left side — write "${t}:".`,103:e=>`"${e}": "else" takes no value — write "else:".`,104:e=>`Invalid spread binding "${e}": spread target path is required.`,105:e=>`Invalid spread binding "${e}": filters are not allowed on spread targets.`,106:e=>`"${e}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (class, attr, style, command, eventToken, state).`,107:(e,t)=>`unterminated ${e} quote in the filter arguments "(${t})". Close the quote.`,108:e=>`Invalid filter format: missing closing parenthesis in "${e}".`,109:e=>`Invalid filter format: missing opening parenthesis in "${e}".`,110:e=>`Invalid filter format: ")" comes before "(" in "${e}".`,111:(e,t)=>`"${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,e.lastIndexOf(")")+1)}|${t}").`,112:e=>`an empty filter in "${e}" — remove the extra "|" or name the filter.`,113:(e,t)=>`"${e}" is not a filter name: a modifier list "#${t}" comes before the input filters, not inside one`,114:e=>`"${e}" is not a filter name: "#" cannot appear in one.`,115:e=>`"${e}": a binding takes one modifier list after a single "#"`,116:e=>`"${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).`,117:(e,t)=>`"${e}" has ${t} path segments — the limit is 512.`,32:e=>`"${e}": 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.`,120:e=>`"${e}": a state path cannot go through "__proto__" or "prototype" (it would reach every object's prototype).`,121:e=>`"${e}": "for:" takes no filters — a row is "<path>.<index>", so the rows of a filtered list would name other elements. Declare a getter that returns the filtered list and loop over it ("for: <getter>").`,119:e=>`"${e}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).`,201:e=>`Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`,202:e=>`"${e}:" must follow an "if:" template`,204:e=>`a "${e}:" template at the top of inserted content was not rendered, as it would render beside itself out of the inserter's reach: wrap it in an element.`,203:e=>`"${e}:" replaces its element, so it cannot be used inside a "for" / "if" template (a row or branch keeps its nodes by position): bind innerHTML: on a wrapper element instead.`,301:e=>`Path "${e}" does not exist on the state tree.`,401:(e,t)=>`class.${e} needs a boolean, got ${t}.`,501:e=>`filter not found: ${e}.`,601:(e,t,n)=>`filter "${e}" requires at least ${t} argument(s) (${n} given).`,602:(e,t,n)=>`filter "${e}" accepts at most ${t} argument(s) (${n} given).`,701:e=>`"${e}" depends on itself`,801:e=>`"${e}"`,901:(e,t,n,r)=>`${e}("${t}") takes ${n} index(es), got ${r}.`,902:(e,t,n,r)=>`${e}("${t}") takes at most ${n} index(es), got ${r}.`,1001:e=>`"${e}": list index parameters run from $1 to $128.`,1101:e=>`"${e}" uses "**", which is not accepted here.`,1201:(e,t)=>`"${e}: ${t}": the right-hand side must be $command.<name>`,1202:(e,t)=>`<${e}> declares no static wcBindable (${t}).`,1203:(e,t)=>`<${e}> declares no command "${t}".`,1204:(e,t)=>`<${e}> declares no property "${t}".`,1301:e=>`eventToken "${e}" is not declared in $eventTokens.`,1302:e=>`"$command.${e}" is not declared in $commandTokens.`,1401:(e,t,n=0)=>`"${e}" needs ${t} enclosing loop level(s); the scope provides ${n}.`,1402:e=>`"${e}" is relative: it needs an enclosing "for" template`,1403:(e,t,n)=>`"${e}" ranges over the rows of "${t}", but the enclosing "for" template at that level renders "${n}".`,1501:(e,t)=>`<${e}> declares no static wcBindable (${t}).`,1601:(e,t)=>`${e} was removed: write ${t}.`,1701:(e,t)=>`${e} was removed: write ${t}.`};function pn(e,t){let n=fn[e];return void 0===n?`${_(e)}#${e} ${t.join(" ")}`:_(e)+n(...t)}var mn=new Set(["binding-syntax","template-syntax","filter-unknown","filter-arity","index-arity","wildcard-rank","token-undeclared","binding-path-missing","index-param-range"]),gn=[[/no loop level in common with the context/,"; pass indexes ([] for all)."],[/"([^"#]+)#([^"]*)" is not a filter name: a modifier list .* comes before the input filters/,' — write "<property>#$2|$1".'],[/\[wcs\/recursion-unsupported\]/," 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."],[/must be single binding/,' Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).'],[/\[wcs\/wildcard-rank\] .* needs \d+ enclosing/,' Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.'],[/\[wcs\/wildcard-rank\] .* ranges over the rows of/,' A "*" in a binding is the row of the loop around it: read a row of another list in a getter, with $resolve(path, indexes).'],[/\[wcs\/binding-type-expectation\] class\.([^ ]+)/,' Write "class.$1: path|truthy" to toggle on truthiness.'],[/path segments — the limit/," Every prefix of a path is interned, so the cost grows with the square of the depth."],[/\[wcs\/index-arity\] \$resolve/,' $resolve takes one index per "*"; $getAll / $setAll take at most that many (fewer expands the rest).'],[/"([^"#]+)#[^"]*" is not a filter name: "#" cannot appear in one/,' Modifiers belong on the left side of the binding, before the ":" — write "$1" here.']],yn={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function bn(e,t,n){let r=(void 0!==t&&e.includes("[wcs/filter-unknown]")?function(e){if("substr"===e)return' "substr" was removed in 4.0 — write slice(start, start + length): slice takes the end index, not a length.';let t=Object.hasOwn(yn,e)?yn[e]:null;return null===t?null:` "${e}" was renamed "${t}" in 3.2 and removed in 4.0 — write "${t}".`}(t):null)??(void 0!==t&&void 0!==n?an(t,n):"");for(let[t,n]of gn){let i=t.exec(e);null!==i&&(r+=n.replace(/\$(\d)/g,(e,t)=>i[Number(t)]))}let i=/"([^"#]+)#([^"]+)": a binding takes one modifier list/.exec(e);null!==i&&(r+=` — write "${i[1]}#${i[2].split("#").join(",")}".`),e.includes("[wcs/filter-unknown]")&&(e.includes("formats add-on")?r+=' On a split auto page: features="formats" on the root, or "$features": ["formats"].':ue.some(fe)||(r+=' No formatting filters are installed — add the formats add-on: installFeatures([formats]) from "@wcstack/state/features/formats" (a split auto page: features="formats", or "$features").'));let s=/\[wcs\/([\w-]+)\]/.exec(e);return null!==s&&mn.has(s[1])&&!/ path segments — the limit is |inserted content was not rendered|formats add-on/.test(e)&&(r+=un),r}var vn=new WeakMap,wn=new WeakMap,_n=new WeakSet,$n=new WeakSet;function kn(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function Sn(e){let t=new Set;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"$"!==e[0]&&"constructor"!==e&&t.add(e);return[...t]}function Nn(e,t){let n=[];for(let e=t;null!==e;e=e.w)n.unshift(e);let r=e.target,i=t=>null===t?null:function(e,t){let n=t.t.split("."),r=n.findIndex((e,t)=>t>0&&/^\d/.test(e));return r<0||n.indexOf("*",r)>=0||void 0!==kn(e.target,t.t)?.get?t:e.L.At(o(t.t).o)}(e,t);for(let t of n){if(null!=i(t)?.getter||null===r||"object"!=typeof r)return null;if("*"===t.l){if(!Array.isArray(r)||0===r.length)return null;r=r[0];continue}if(Array.isArray(r)&&/^\d+$/.test(t.l)){if(Number(t.l)>=r.length)return null;r=r[Number(t.l)];continue}let n=kn(r,t.l);if(void 0===n&&null===t.w&&e.ft.has(t.l))return null;if(void 0===n){let n=Sn(r),s=i(t.w);for(let t of e.L.all())t.w===s&&null!==t.getter&&n.push(t.l);return{seg:t.l,names:n}}if(void 0!==n.get||void 0!==n.set)return null;r=n.value}return null}function En(e){_n.has(e)||(_n.add(e),setTimeout(()=>function(e){_n.delete(e);let t=vn.get(e);if(void 0===t)return;let n=wn.get(e);void 0===n&&wn.set(e,n=new Set);for(let[r,i]of t){if(n.has(r))continue;n.add(r);let t=Nn(e,r);if(null===t)continue;let s=[...e.root?.querySelectorAll(`${re.tagNames.state}[mount]`)??[]].find(e=>!$n.has(e)&&(r.t+".").startsWith(e.getAttribute("mount")+"."));if(void 0!==s){n.delete(r),s.initializePromise.then(()=>{$n.add(s),En(e)});continue}let[l,a]=i?["watch-path-missing","$watch path"]:["binding-path-missing","Bound path"];c.tt?.(e,{type:"state:path-unresolved",source:i?"watch":"binding",path:r.t,missingSegment:t.seg});let u=e.L.At(o(r.t).o),h="";if(void 0!==u&&u!==r&&null!==u.getter){let e=u.c.slice(1).map((e,t)=>`for: ${0===t?e.t:e.t.slice(u.c[t].t.length+2)}`);h=` The getter "${u.t}" is declared for the rows of ${e.join(" → ")}; a list named by an index has rows of its own.`}console.warn(`[@wcstack/state] [wcs/${l}] ${a} "${r.t}" does not resolve on the state tree: "${t.seg}" is not declared.${an(t.seg,t.names)}${h} Updates to this path will be silently dropped.${un}`)}}(e),0))}function An(e,t,n=!1){if("$"===t.t[0]||t.t.includes("#")||!n&&null===t.w)return;let r=vn.get(e);void 0===r&&vn.set(e,r=new Map),r.has(t)||r.set(t,n),En(e)}var Cn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),xn=!1;function Tn(e,t,n){let r="html"===n.name?"innerHTML":n.name;if(xn||!(t instanceof TypeError)||!xe(r)||!("trustedTypes"in globalThis))return;xn=!0;let i="function"==typeof Ce()?.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 "${r}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${i}\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:n.a,property:r})}var Pn=new WeakMap;function On(e,t,n){let r=e[t],i=void 0===n?void 0===r?null:`the event carried no detail (undefined) while element.${t} is ${typeof r}`:null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==r&&"object"==typeof r?null:`the event's detail is an object with a "${t}" key while element.${t} is ${typeof r}`;if(null===i)return;let s=Pn.get(e);void 0===s&&Pn.set(e,s=new Set),!s.has(t)&&(s.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.localName}> "${t}": ${i}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}var Mn={name:"diagnostics",install(){c.Ao=bn,c.Fo=pn,c.yo=An,c.detail=On,c._e=h(c._e,Tn),c.ie=h(c.ie,(e,t)=>{(function(e){let t=e.$recursion;if(null===t||"object"!=typeof t)return;let n=Object.entries(t);if(1!==n.length||"string"!=typeof n[0][1])return;let[r,i]=n[0];if(!r.endsWith(".*")||!i.endsWith(".*"))return;let s=r.slice(0,-2),o=i.slice(0,-2),l=`.${i}`,a=`${s}.**`,u=Sn(e),c=u.filter(e=>e.startsWith(a)).map(e=>e.slice(a.length)),h=e=>v(`[wcs/recursion-declaration-invalid] ${e}`);for(let e of c){(e===`.${o}`||e.startsWith(`.${o}.`))&&h(`"${a}${e}" names the recursion structure itself (the "${o}" lists): recursive getters compute values over the nodes.`);for(let t of c)t.length>e.length&&t.endsWith(e)&&new RegExp(`^(?:${Cn(l)})+$`).test(t.slice(0,t.length-e.length))&&h(`"${a}${e}" and "${a}${t}" expand to the same concrete path at different depths (they differ by whole repetitions of "${i}"). Rename one of them.`);let t=new RegExp(`^${Cn(r)}(?:${Cn(l)})*${Cn(e)}$`);for(let n of u)!n.includes("**")&&t.test(n)&&h(`"${n}" is already defined on the state, so the recursive getter "${a}${e}" cannot expand to it.`)}})(t),function(e){wn.delete(e),vn.has(e)&&En(e)}(e)})}},Ln={},In=/\.\d/,jn=new Set(Object.getOwnPropertyNames(Object.prototype)),Rn=0,Hn=!1,Wn=null,zn=()=>{Hn=!1,Rn++};function Dn(){if(null===Wn)if("function"==typeof MessageChannel){let e=new MessageChannel;e.port1.onmessage=zn,e.port1.unref?.(),Wn=()=>e.port2.postMessage(0)}else Wn=()=>setTimeout(zn,0);return Hn||(Hn=!0,Wn()),Rn}function Un(e,t){let n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(!n.has(e)){n.add(e);for(let n of e.Ae){for(let r of t)if(n.G(r)&&(n.n===r.n||!(r.n<e.n&&e.c[r.n+1].G(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var Fn=class{constructor(e,t){this.active=!1,this.ze=new Map,this.n=0,this.$o=-1,this.Cn=new Set,this.$e=null,this.engine=e,this.rt=t}Zo(){let e=this.engine;this.ze.clear();for(let t of this.rt)t.getter=null!==t.p.getter||t.p.ke,t.l=new WeakMap,this.prime(t,()=>{0===t.p.n?t.getter&&t.l.set(Ln,e.v(t.p,null)):this.In(t.p,1,null,n=>{t.getter&&this.prime(t,()=>t.l.set(n,e.v(t.p,n)))})});this.active=!0}prime(e,t){try{t()}catch(t){console.error(`[@wcstack/state] $watch initial evaluation of "${e.t}" threw.`,t),c.tt?.(this.engine,{type:"state:watch-error",phase:"prime",path:e.t,error:t})}}No(){this.active=!1,this.ze.clear()}In(e,t,n,r){let i=this.engine.De(n,e.c[t]);for(let n of i.f)t===e.n?r(n):this.In(e,t+1,n,r)}ln(e,t,n,r){let i=this.ze.get(e);void 0===i&&this.ze.set(e,i=new Map);let s=i.get(t);void 0===s?i.set(t,[n,this.n,r]):(s[1]<this.n&&(s[1]=this.n),s[2]||=r)}pe(e,t,n,r,i){if(this.active){(this.$e??=new Set).add(e);for(let s of this.rt){let o=s.p;o.n!==e.n||!o.G(e)||this.ln(s,t,s.getter?s.l.get(t??Ln):o===e&&i&&this.engine.jt&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}}me(e,t){if(this.active)for(let n of this.rt)(n.getter||=null!==n.p.getter||n.p.ke)&&n.p.n===e.n&&n.p.G(e)&&this.ln(n,t,n.l.get(t??Ln),!1)}Kt(e,t){if(!this.active)return;let n=null;for(let r of this.rt){let i=r.p;if(!(i.n<e.n||i.c[e.n]!==e.o)){n??=new Set(t);for(let t of e.f)n.has(t)||(i.n===e.n?this.ln(r,t,void 0,!0):this.In(i,e.n+1,t,e=>this.ln(r,e,void 0,!0)))}}}Pe(){let e=this.$e;if(this.$e=null,!this.active||0===this.ze.size)return;let t=this.ze;this.ze=new Map;let n=this.engine,r=[];for(let i of this.rt){let s=t.get(i);if(void 0===s)continue;let o,l=[...s].filter(([e])=>null===e||e.d);l.length>1&&l.sort((e,t)=>Bn(e[0],t[0]));for(let[t,[s,a,u]]of l){let l,h="evaluate",d=n.h;this.n=a+1,n.Ee++;try{if(l=n.v(i.p,t),i.getter&&(i.l.set(t??Ln,l),Object.is(l,s)&&(In.test(i.t)||null!==t&&!u&&!(o??=null!==e&&Un(qn(i.p),e)))))continue;if(a>32){r.includes(i.t)||r.push(i.t);continue}n.h=t,c.tt?.(n,{type:"state:watch-fired",path:i.t}),h="handler",i.handler.call(n.proxy,l,s,...n.D(t))}catch(e){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,e),c.tt?.(n,{type:"state:watch-error",phase:h,path:i.t,error:e})}finally{n.h=d,this.n=0,n.Ee--}}}r.length>0&&this.xo(r)}xo(e){let t=Dn();t!==this.$o&&(this.$o=t,this.Cn.clear());let n=e.filter(e=>!this.Cn.has(e));if(0!==n.length){for(let e of n)this.Cn.add(e);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),c.tt?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:n})}}};function qn(e){for(;null===e.getter&&null!==e.w;)e=e.w;return e}function Bn(e,t){let n=[],r=[];for(let t=e;null!==t;t=t.s.te)n.unshift(t.b);for(let e=t;null!==e;e=e.s.te)r.unshift(e.b);for(let e=0;e<n.length&&e<r.length;e++)if(n[e]!==r[e])return n[e]-r[e];return n.length-r.length}var Kn="$streamStatus",Gn="$streamError",Vn=new Set(Object.getOwnPropertyNames(Object.prototype)),Jn=!1;function Qn(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return void 0!==e.get||void 0!==e.set||"function"==typeof e.value}return!1}var Xn=class{constructor(e,t,n){this.jn=0,this.engine=e,this.entries=t,this.X=n}set(e,t,n){Jn=!0;try{this.engine.P(this.engine.o(`${e}.${t}`),null,n)}finally{Jn=!1}}er(){for(let e of this.entries)this.start(e,!0)}tr(){for(let e of this.entries)e.it=!1,e.z?.abort(),e.z=null}nr(){for(let e of this.entries)e.it=!1,null!==e.z&&(e.z.abort(),e.z=null),this.set(Kn,e.name,"idle")}me(e){let t=Math.max(this.X.n,this.jn);for(let n of this.entries)n.g===e&&(n.n=n.it?Math.max(n.n,t):t,n.it=!0)}Pe(){let e=this.engine,t=this.X,n=[];for(let i of this.entries){if(!i.it)continue;let s=i.n;if(i.it=!1,s>32)n.push(i.name),i.g.ee=r;else{t.n=s+1,e.Ee++;try{this.start(i,!1)}finally{e.Ee--,t.n=0}}}n.length>0&&t.xo(n)}start(e,t){let n,i=this.engine;if(null!==e.z&&e.z.abort(),e.z=null,null!==e.g){let s=e.g;s.getter=e.args;let o=s.Ae.slice();Yn(s);try{n=i.read(s,null),function(e,t,n){null!==n&&"function"==typeof n?.then&&v(`$stream "${e}": args must be synchronous (it returned a Promise).`);for(let n of t.Ae)n.n>0&&v(`$stream "${e}": args must not read a wildcard path ("${n.t}").`),(n.t===e||n.t===`${Kn}.${e}`||n.t===`${Gn}.${e}`)&&v(`$stream "${e}": args must not read the stream itself ("${n.t}").`)}(e.name,s,n)}catch(n){Yn(s);for(let e of o)e.Ln(s);if(s.ee=r,t)throw n;return this.set(Gn,e.name,n),void this.set(Kn,e.name,"error")}}let s=new AbortController;e.z=s,i.P(i.o(e.name),null,e.W),this.set(Gn,e.name,null),this.set(Kn,e.name,"active"),this.or(e,s,n)}async or(e,t,n){let r=this.engine,i=t.signal,s=()=>!i.aborted&&e.z===t,o=r.o(e.name),l=this.X.n,a=Dn(),u=e.W;try{let t=await e.source(n,i);if(!s())return;let c=t=>{u=void 0!==e.Ro?e.Ro(u,t):t,this.jn=Dn()===a?l:0;try{r.P(o,null,u)}finally{this.jn=0}};if(null!==t&&"function"==typeof t?.getReader){let e=t.getReader();for(i.addEventListener("abort",()=>{e.cancel().catch(()=>{})});;){let t=await e.read();if(!s())return;if(t.done)break;c(t.value)}}else{if(null===t||"function"!=typeof t?.[Symbol.asyncIterator])throw new TypeError(`$stream "${e.name}": source must return an async iterable or a ReadableStream`);{let e=t[Symbol.asyncIterator]();for(i.addEventListener("abort",()=>{e.return?.()});;){let t=await e.next();if(!s())return;if(t.done)break;c(t.value)}}}if(!s())return;e.z=null,this.set(Kn,e.name,"done")}catch(n){if(!s())return;e.z=null,t.abort(),this.set(Gn,e.name,n),this.set(Kn,e.name,"error")}}};function Yn(e){for(let t of e.Ae){let n=t.at.indexOf(e);n>=0&&t.at.splice(n,1),t.Pt.delete(e)}e.Ae.length=0,e.ee=t}var Zn=new WeakMap;function er(e){let t=Zn.get(e);return t?.target===e.target?t:void 0}function tr(e,t){let n=new Fn(e,function(e,t){if(void 0===t)return[];(null===t||"object"!=typeof t)&&v("$watch must be an object mapping paths to handler functions.");let n=[];for(let r of Object.keys(t)){let i=t[r];(""===r||"$"===r[0]||r.includes("@")||jn.has(r))&&v(`$watch path "${r}" is not a path of the state tree.`),"function"!=typeof i&&v(`$watch entry "${r}" must be a function.`);let s=e.o(r);c.yo?.(e,s,!0),n.push({t:r,p:s,handler:i,getter:!1,l:new WeakMap})}return n}(e,t.$watch)),r=new Xn(e,function(e,t){let n=t.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&v("$stream must be an object mapping stream names to definitions.");let r=[],i={},s={};for(let o of Object.keys(n)){let l=n[o];(""===o||"$"===o[0]||/[.*]/.test(o)||Vn.has(o))&&v(`$stream entry "${o}" must be a flat property name.`),(null===l||"object"!=typeof l)&&v(`$stream entry "${o}" must be an object.`);let a=l.source,u=l.fold,c=l.args,h=l.initial;"function"!=typeof a&&v(`$stream entry "${o}" needs a source function.`),void 0!==u&&"function"!=typeof u&&v(`$stream entry "${o}": fold must be a function.`),void 0!==u&&!("initial"in l)&&v(`$stream entry "${o}": fold needs an initial value.`),void 0!==c&&"function"!=typeof c&&v(`$stream entry "${o}": args must be a function.`),Qn(t,o)&&v(`$stream entry "${o}" collides with a getter, setter or method of the state.`),void 0===t[o]&&(t[o]=h),i[o]="idle",s[o]=null,r.push({name:o,source:a,Ro:u,W:h,z:null,it:!1,n:0,g:void 0===c?null:e.o(`$streamArgs.${o}`),args:void 0===c?null:function(){return c(this)}})}return t[Kn]=i,t[Gn]=s,r}(e,t),n),i=Zn.get(e);void 0!==i&&(i.X.No(),i.Nt.tr()),Zn.set(e,{X:n,Nt:r,Ke:i?.Ke??!1,target:t})}function nr(e,t){let n=Zn.get(e);if(void 0!==n&&"mounting"!==t&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==t&&(n.Ke="connected"===t),n.target===e.target)){if("disconnected"===t)return n.X.No(),void n.Nt.nr();n.Ke&&(n.X.Zo(),n.Nt.er())}}var rr=["$streamStatus","$streamError"],ir={name:"temporal",install(){c.ie=h(c.ie,tr),c.element=h(c.element,nr),c.pe=h(c.pe,(e,t,n,r,i,s)=>er(e)?.X.pe(t,n,r,i,s)),c.me=h(c.me,(e,t,n)=>{let r=er(e);void 0!==r&&(r.X.me(t,n),r.Nt.me(t))}),c.Kt=h(c.Kt,(e,t,n)=>er(e)?.X.Kt(t,n)),c.Pe=h(c.Pe,e=>{let t=er(e);void 0!==t&&(t.X.Pe(),t.Nt.Pe())}),c.Ut=d(p,c.Ut,(e,t)=>{let n=t.split(".",1)[0];if(rr.includes(n))return n===t?e.target[t]:e.read(e.o(t),null)}),c.Re=d(f,c.Re,(e,t)=>(!Jn&&36===t.t.charCodeAt(0)&&rr.includes(t.t.split(".",1)[0])&&v(`"${t.t}" is read-only (the stream runtime owns it).`),!1))}},sr=new WeakMap,or=!1,lr=/^(?!prototype$)[^\d.*$][^.*]*$/;function ar(e,t){let n=t.$listKeys,r=new Map;if(void 0!==n){(null===n||"object"!=typeof n)&&v("$listKeys must be an object mapping list paths to a key field or function.");for(let t of Object.keys(n)){let i=n[t];"string"==typeof i?r.set(e.o(t),e=>e[i]):"function"==typeof i?r.set(e.o(t),i):v(`$listKeys "${t}" must be a field name or a function.`)}}sr.set(t,r)}function ur(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function cr(e,t,n){let r=new Map;for(let i of t){ur(i)||v(`$listKeys "${e}": rows must be plain objects.`);let t=n(i);null==t&&v(`$listKeys "${e}": a row has no key.`),r.has(t)&&v(`$listKeys "${e}": duplicate key ${JSON.stringify(t)}.`),r.set(t,i)}return r}function hr(e,t,n,r){if(or||!Array.isArray(r))return!1;let i=sr.get(e.target)?.get(t);if(void 0===i)return!1;let s=e.zt(t,n);if(!Array.isArray(s)||s===r)return!1;let o=cr(t.t,s,i);cr(t.t,r,i);let l=[],a=[],u=s.length===r.length;for(let e=0;e<r.length;e++){let t=r[e],n=o.get(i(t));l.push(n??t),void 0!==n&&a.push([e,n,t]),l[e]!==s[e]&&(u=!1)}let c=[];for(let[e,t,n]of a){for(let r of Object.keys(n))Object.is(t[r],n[r])||c.push([e,r,n[r]]);for(let r of Object.keys(t))!(r in n)&&null!==t[r]&&c.push([e,r,null])}if(u&&0===c.length)return!0;if(!u){or=!0;try{e.P(t,n,l)}finally{or=!1}}if(c.length>0){let r=e.De(0===t.n?null:n,t);for(let[n,i,s]of c){if("__proto__"===i)continue;let o=r.f[n],l=lr.test(i)?e.o(`${t.t}.*.${i}`):null;null===l?.getter?e.P(l,o,s):(o.O[i]=s,e.P(e.o(`${t.t}.*`),o,o.O,!0))}}return!0}var dr={name:"list-keys",install(){c.ie=h(c.ie,ar),c.Re=d(f,c.Re,hr)}},fr=new WeakMap,pr=new WeakMap,mr=new WeakMap,gr="will not graft: the root state failed to initialize.",yr=new WeakSet,br=new WeakMap,vr=["$stream","$streams","$scan","$recursion","$watch","$listKeys","$renderedCallback","$updatedCallback","$behavior","$features"],wr=["$commandTokens","$eventTokens","$on","$errorCallback"],_r=e=>`[@wcstack/state] <${re.tagNames.state} mount="${e}">`,$r=new Set(["$getAll","$setAll","$resolve","$postUpdate","$dependOn","$eq","$eqIndex"]),kr=e=>e?.element?.isConnected?e:void 0;function Sr(e){let t=mr.get(e);return void 0!==t&&!Array.isArray(t)&&t.isConnected}function Nr(e,t){fr.set(t,e);let n=mr.get(t);if(mr.delete(t),Array.isArray(n))for(let t of n)Cr(t,e)}function Er(e,t){console.error(`${_r(e.t)} ${t}`),function(e){let t=pr.get(e.root);t?.get(e.t)===e&&t.delete(e.t)}(e),e.Xe?.(),e.Xe=null}function Ar(e,t){let n=e.state?.[t];if("function"==typeof n)try{let t=n.call(e.chroot);null!==t&&"object"==typeof t&&"function"==typeof t.then&&t.then(void 0,e=>console.error(e))}catch(e){console.error(e)}}function Cr(e,t){if(yr.has(t))return Er(e,"will not graft: its component is wired to its host.");let n=e.state,r=t.target,i=e.t.split("."),s=r;for(let e of i)s=s?.[e];if(void 0!==s&&!0!==t.hydrated)return Er(e,`will not graft: the root state already has "${e.t}".`);let o=function(e,t){let n=e=>`${t}.${e}`;return new Proxy({},{get(t,r){if("symbol"==typeof r)return;if(36!==r.charCodeAt(0))return e.proxy[n(r)];let i=e.proxy[r];return"$eqPath"===r?(e,t)=>i(n(e),n(t)):$r.has(r)&&"function"==typeof i?(e,...t)=>i(n(e),...t):i},set:(t,r,i)=>"symbol"!=typeof r&&(e.proxy[n(r)]=i,!0)})}(t,e.t);e.chroot=o;let l={},a={},u=new Set;for(let t=n;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let n of Object.getOwnPropertyNames(t)){if(u.has(n)||"constructor"===n)continue;u.add(n);let{get:r,set:i,value:s}=Object.getOwnPropertyDescriptor(t,n);if(void 0!==r||void 0!==i)a[`${e.t}.${n}`]={get:r&&function(){return r.call(o)},set:i&&function(e){i.call(o,e)}};else{if("$"===n[0])continue;if("function"==typeof s){let t=s.bind(o);a[`${e.t}.${n}`]={get:()=>t}}else l[n]=s}}if(void 0===s){for(let e=1;e<i.length;e++){let n=t.o(i.slice(0,e).join("."));null==t.zt(n,null)&&t.P(n,null,{})}t.P(t.o(e.t),null,l)}t.Yn(Object.defineProperties({},a));for(let e in a)t.$e(t.o(e),null);e.engine=t;let c=br.get(t);void 0===c&&br.set(t,c=[]),c.push(e.t),e.el.isConnected&&Ar(e,"$connectedCallback"),e.Xe?.(),e.Xe=null}function xr(e,t){let n=mr.get(e);if(Array.isArray(n))for(let e of n)Er(e,gr);mr.set(e,t)}var Tr=new WeakMap;function Pr(e,t){let n=e.getAttribute("mount");if(null===n)return null;let r={el:e,root:t,t:n,state:null,engine:null,chroot:null,Xe:null},i=null;if(function(e){return""!==e&&e.split(".").every(e=>""!==e&&!/[*$#@\s]/.test(e))}(n))if(e.hasAttribute(re.bindAttributeName))i='injections (data-wcs="state.<key>: …") are not supported — read the root path in a root getter.';else{let e=pr.get(t);void 0===e&&pr.set(t,e=new Map);let s=e.get(n);if(void 0!==s&&s!==r&&(null===s.engine?s.el.isConnected:kr(s.engine)))i=`will not graft: another volume already holds "${n}".`;else{if(null===s?.engine){let e=mr.get(t);Array.isArray(e)&&mr.set(t,e.filter(e=>e!==s)),s.Xe?.(),s.Xe=null}e.set(n,r)}}else i='has an invalid mount path: it must be a static path (no "*", "$", "#", "@").';return{vo:!0,start(e){if(null!==i)return Er(r,i);if(pr.get(t).get(n)===r){for(let t of vr)if(void 0!==e[t])return Er(r,`${t} is not run in a volume — declare it on the root state.`);for(let t of wr)void 0!==e[t]&&console.warn(`${_r(n)} ${t} is not run in a volume (it belongs to the root).`);return r.state=e,new Promise(e=>{r.Xe=e;let n=kr(fr.get(t))??kr(It.get(t)),i=mr.get(t);void 0!==n?Cr(r,n):Sr(t)?Er(r,gr):mr.set(t,[...Array.isArray(i)?i:[],r])})}},Ke(){null!==r.engine&&Ar(r,"$connectedCallback")},On(){null!==r.engine&&Ar(r,"$disconnectedCallback")},reset(){v(`re-setting a volume is not supported: its data was copied into the root tree at "${n}" — write the paths under it on the root instead.`)}}}var Or=new WeakMap,Mr=new WeakMap;function Lr(e,t){let n=e[t];if(void 0===n)return[];Array.isArray(n)||v(`${t} must be an array of state member names.`);let r=new Set;for(let e of n)("string"!=typeof e||""===e)&&v(`${t} entries must be non-empty strings.`),"$"===e[0]&&v(`${t} entry "${e}": internal ($) members are never exposed.`),r.has(e)&&v(`${t} entry "${e}" is duplicated.`),r.add(e);return n}function Ir(e,t){let n=t.host;if(void 0===n||!n.hasAttribute("data-wc-definition"))return null;let r=document.createDocumentFragment();for(let e of[...t.childNodes])r.appendChild(e.cloneNode(!0));let i=t.mode;return{start(t){e.hasAttribute("bind-component")&&v("DCC: a <wcs-state bind-component> cannot define a component (use one mechanism)."),function(e,t,n,r){e.includes("-")||v(`DCC: <${e} data-wc-definition> is not a valid custom element name.`),void 0!==customElements.get(e)&&v(`DCC: <${e}> is already defined.`);let i=function(e){let t=new Map;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"constructor"===e||"$"===e[0]||t.has(e)||t.set(e,Object.getOwnPropertyDescriptor(n,e));let n=e.$stream;if(null!==n&&"object"==typeof n)for(let e of Object.keys(n))t.has(e)||t.set(e,{value:void 0});return t}(r),s=Lr(r,"$bindables"),o=Lr(r,"$commands");for(let e of s){let t=i.get(e);void 0===t&&v(`$bindables entry "${e}" does not exist on the state.`),"function"==typeof t.value&&v(`$bindables entry "${e}" is a method: list it in $commands.`)}for(let e of o){let t=i.get(e);void 0===t&&v(`$commands entry "${e}" does not exist on the state.`),"function"!=typeof t.value&&v(`$commands entry "${e}" is not a method: list it in $bindables.`)}let l={tag:e,bindables:s},a=new WeakMap,u=new WeakMap,c=r=>{if(a.has(r))return a.get(r);if(r.hasAttribute("data-wc-definition"))return null;let i=r.attachShadow({mode:n});i.appendChild(t.cloneNode(!0));let o=i.querySelector(re.tagNames.state);return a.set(r,o),Or.set(r,l),null===o&&s.length>0&&console.warn(`[@wcstack/state] DCC: <${e}> declares $bindables but its content has no <${re.tagNames.state}>: no change events.`),o},h=e=>c(e)?.engine??null,d=e=>Promise.resolve(c(e)?.initializePromise).then(()=>{let t=u.get(e);u.delete(e);let n=h(e);if(void 0!==t&&null!==n)for(let[e,r]of t)n.proxy[e]=r});class f extends HTMLElement{static{this.wcBindable=0===s.length&&0===o.length?null:{protocol:"wc-bindable",version:1,properties:s.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:s.map(e=>({name:e})),...0===o.length?{}:{commands:o.map(e=>({name:e,async:!0}))}}}connectedCallback(){null!==c(this)&&d(this)}get stateElement(){return c(this)}}for(let[e,t]of i)"function"==typeof t.value?Object.defineProperty(f.prototype,e,{configurable:!0,value(...t){return d(this).then(()=>{let n=h(this);return null===n?void 0:n.proxy[e].apply(n.proxy,t)})}}):Object.defineProperty(f.prototype,e,{configurable:!0,get(){return h(this)?.proxy[e]},set(t){let n=h(this);if(null!==n)n.proxy[e]=t;else{let n=u.get(this);void 0===n&&u.set(this,n=[]),n.push([e,t])}}});customElements.define(e,f)}(n.localName,r,i,t)},Ke(){},On(){},reset(){v("re-setting a DCC definition is not supported: each instance loads its own state.")}}}var jr=new WeakMap,Rr=new WeakSet,Hr=new WeakMap,Wr=new WeakMap,zr="data-wcs-wired",Dr=new WeakMap,Ur=new WeakMap,Fr=new WeakMap,qr=0,Br=new Set,Kr={},Gr=["$watch","$stream","$renderedCallback"],Vr=e=>e.split(".",1)[0];function Jr(e,t){let n=0;return e.split(".").map(e=>"*"===e?String(t[n++]):e).join(".")}function Qr(e,t){let n=e.a,r=Vr(e.name);if(!0!==document.documentElement?.hasAttribute("data-wcs-server"))n.removeAttribute(zr);else if(!Yr(n,r)){let e=n.getAttribute(zr)?.split(" ")??[];e.includes(r)||n.setAttribute(zr,[...e,r].join(" "))}Dr.get(n)?.ce===r&&v(`<${n.localName}>.${r} has loaded its state: the wiring "${e.name}" added afterwards cannot reach it — bind the host's wiring before the component loads.`);let i=jr.get(n);void 0===i&&jr.set(n,i=[]),i.push(e),t&&Rr.add(e);let s=Hr.get(n);return void 0===s&&Hr.set(n,s=new Map),s.has(r)||s.set(r,n[r]),Wr.get(n)?.(),!1}function Xr(e){return e.localName.includes("-")&&null!==e.querySelector(`:scope > ${re.tagNames.state}[bind-component]`)}function Yr(e,t){let n=e.getAttribute(re.bindAttributeName);return null!==n&&new RegExp(`(^|;)\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[.#:]`).test(n)}var Zr=new Set;function ei(e,t){Zr.has(e)||(Zr.add(e),console.warn(`[@wcstack/state] ${t}`))}var ti=(e,t)=>t in e.state;function ni(e,t){let n=ri(e.state,t);return void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)}function ri(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function ii(e,t,n){if(null!==n.getter)return;let r,i=e.host,s=i.engine,o=Vr(n.t),l=i.entries.find(e=>e.E===n.t);if(void 0===l&&null!==n.w)return function(e,t){let n,r=t.w;for(;null!==r&&void 0===(n=e.st.get(r));)r=r.w;if(null===r||void 0===n)return;let i=e.x,s=e.host.engine,o=s.o(n.p.t+t.t.slice(r.t.length));if(null===o.getter)return;let l=n,a=()=>{let n=si(e,l.r);return 0===t.n?n:(s.resolve(Jr(o.t,[...s.D(n),...i.D(ee(i.h,t.n))]),null),s.rr)};t.getter=()=>{let e=a();return o.n>0&&null===e?void 0:s.v(o,e)},null!==o.Z&&(t.Z=n=>{let r=a();oi(e,l.e,()=>s.P(o,r,n)),e.an=t}),t.n>0&&(t.A=i.Oe++),e.st.set(t,{e:l.e,p:o,r:l.r})}(e,n);if(0!==n.n)return;if(void 0!==l){if(l.E!==o?ti(i,o):ni(i,o))return;r=l.ue}else{if(null===t||null!==n.w||"$"===o[0]||ti(i,o))return;l=t,r=s.o(`${t.ue.t}.${o}`)}let a=l.r,u=l;n.getter=()=>s.v(r,si(e,a)),n.Z=t=>{oi(e,u,()=>s.P(r,a,t)),e.an=n},e.st.set(n,{e:l,p:r,r:a})}function si(e,t){return null!==t&&!t.d&&v(`The host row of <${e.host.el.localName}> was removed.`),t}function oi(e,t,n){let r=Br.has(e.x);Br.add(e.x),e.from=t;try{n()}finally{r||Br.delete(e.x),e.from=null}}var li=(e,t)=>t||!Br.has(e.m.x)||null!==e.m.from&&e.m.from!==e.e;function ai(e,t){if(e.cn===t||null===e.host.engine)return;e.cn=t,qr+=t?1:-1;let n=e.host.engine,r=Fr.get(n);void 0===r&&Fr.set(n,r=new Map);for(let n of e.se){let e=r.get(n.e.ue);void 0===e&&r.set(n.e.ue,e=new Map);let i=e.get(n.e.r);void 0===i&&e.set(n.e.r,i=new Set),t?i.add(n):(i.delete(n),0===i.size&&e.delete(n.e.r))}let i=e.host.entries.find(e=>""===e.E);if(void 0!==i){null===e.Q&&function(e,t){let n=e.host,r=n.engine;e.Q=new Map;let i=new Set;for(let s=n.state;null!==s&&s!==Object.prototype;s=Object.getPrototypeOf(s))for(let o of Object.getOwnPropertyNames(s)){if(i.has(o))continue;i.add(o);let l=Object.getOwnPropertyDescriptor(s,o);if(void 0===l.get&&void 0===l.set||"$"===o[0]||o.includes("*"))continue;let a=Vr(o);if(o!==a&&!ti(n,a))continue;let u=r.o(`${t.ue.t}.${o}`);if(null===u.getter)hi(r,u,t.ue);else if(!ui.has(u.getter))continue;e.Q.set(u,e.x.o(o))}}(e,i);for(let r of e.Q.keys())t&&null===r.getter&&hi(n,r,i.ue),n.R.xe(n,r,i.r);e.Q.size>0&&n.Ne(),t&&function(e,t){let n=e.host.engine;for(let[r,i]of e.Q){let s=n.v(r.w,t.r);if(null===s||"object"!=typeof s||!(r.l in s))continue;let o=e.host.el.localName;ei(`${o}|${r.t}`,`[wcs/mount-export-shadowed] <${o}>.${e.host.ce}.${i.t} is exported at "${r.t}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`)}}(e,i)}}var ui=new WeakSet;function ci(e,t,n,r){let i=Fr.get(e)?.get(t)?.get(n);if(void 0===i)return null;let s=null;for(let e of i)""!==e.e.E||!0!==e.m.Q?.has(r)||e.m===s||(null!==s&&v(`[wcs/mount-export-ambiguous] "${r.t}" is exported by two mounted components on the same instance: <${s.host.el.localName}> and <${e.m.host.el.localName}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),s=e.m);return s}function hi(e,t,n){let r=t.w,i=t.l,s=()=>{let t=e.read(r,e.h);return null!==t&&"object"==typeof t&&i in t?t:null};t.getter=()=>{let r=s();if(null!==r)return r[i];let o=ci(e,n,e.h,t);return null===o?void 0:o.x.read(o.Q.get(t),null)},ui.add(t.getter),t.Z=o=>{let l=null===s()?ci(e,n,e.h,t):null;if(null===l){let t=e.read(r,e.h);return void(null!==t&&"object"==typeof t&&(t[i]=o))}let a=l.Q.get(t);void 0===ri(l.host.state,a.t)?.set&&v(`Cannot write to "${a.t}" on mounted <${l.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),l.x.P(a,null,o)},t.n>0&&(t.A=e.Oe++)}function di(e,t,n,r,i,s){if(null!==t.getter)return e.R.xe(e,t,n),void e.Ne();if("*"===t.l){if(null===n)return;if(n.O=n.s.Y[n.b],e.R.Ht(n),null!==n.u)for(let t of n.u.values())e.q(t)}else e.wn(t,n);c.pe?.(e,t,n,r,i,s),e.$e(t,n)}function fi(e){let t=e.m.x;for(let[n,r]of e.m.st)r.e===e.e&&(0===n.n?t.R.xe(t,n,null):t.Jt(n.c[n.n],e=>t.R.xe(t,n,e)));t.Ne()}function pi(e,t,n,r,i,s,o){let l=n.t.slice(t.t.length);if(""===l)return fi(e);let a,u=e.m,c=u.x;if(""===e.e.E){a=l.slice(1);let e=Vr(a);if("$"===e[0]||ti(u.host,e)||u.host.entries.some(e=>""!==e.E&&(a===e.E||a.startsWith(`${e.E}.`))))return}else a=e.e.E+l;let h=[];for(let e=t.n+1;e<=n.n;e++)h.push(ee(r,e).b);c.resolve(Jr(a,h),null);let d=c.rp,f=c.rr;d.n>0&&null===f||di(c,d,f,i,s,o)}function mi(e,t,n,r,i,s,o){if(0===qr)return;let l=Br.has(e);Br.add(e);try{let l=Ur.get(e);!o&&void 0!==l&&l.cn&&!Br.has(l.host.engine)&&function(e,t,n,r,i,s){let o,l=t;for(;null!==l&&void 0===(o=e.st.get(l));)l=l.w;if(null===l||void 0===o)return;let a=e.host.engine;if(l===t&&e.an===t)return void(e.an=null);if(null!==o.r&&!o.r.d)return;let u=[...a.D(o.r),...e.x.D(n)];a.resolve(Jr(o.p.t+t.t.slice(l.t.length),u),null);let c=a.rp,h=a.rr;c.n>0&&null===h||oi(e,o.e,()=>di(a,c,h,r,i,s))}(l,t,n,r,i,s),o&&void 0!==l&&l.cn&&null!==l.Q&&function(e,t){let n=e.host.entries.find(e=>""===e.E),r=e.host.engine;for(let[i,s]of e.Q)s===t&&(r.R.xe(r,i,n.r),r.Ne())}(l,t);let a=Fr.get(e);if(void 0===a)return;for(let[e,l]of a)if(t.G(e)){let a=l.get(0===e.n?null:ee(n,e.n));if(void 0!==a)for(let l of[...a])li(l,o)&&pi(l,e,t,n,r,i,s)}else if(e.G(t))for(let[e,r]of[...l])if(0===t.n||ee(e,t.n)===n)for(let e of[...r])li(e,o)&&fi(e)}finally{l||Br.delete(e)}}async function gi(e,t){ai(e,!0);for(let t of e.se)fi(t);t?.(),!e.broken&&(await e.x.ae("$connectedCallback"),null===e.host.engine&&e.el.isConnected&&c.element?.(e.x,"connected"))}function yi(e,t){let n=e.getAttribute("bind-component");if(null===n)return function(e,t){return e.connectedCallbackPromise.catch(()=>{let n=It.get(t)?.element;if(!(e.U||void 0!==n&&n!==e&&n.isConnected)){xr(t,e);for(let e of Tr.get(t)??[])e()}}),null}(e,t);let r=e.parentNode,i=r instanceof ShadowRoot,s=i?r.host:r instanceof Element?r:null,o=()=>{let t=null===s?void 0:Dr.get(s)?.F;return t?.el===e?t:null},l=t=>{throw i&&xr(r,e),t};return{Ct:()=>(null!==s&&s.localName.includes("-")?async function(e,t,n,r){let i=n.localName;(["state","src","json"].some(t=>e.hasAttribute(t))||null!==e.querySelector('script[type="module"]'))&&v(`<${re.tagNames.state} bind-component> takes its state from <${i}>.${t}: it cannot also load one (state / src / json / an inline script).`),await Ie(n).whenDefined(i);let s=Dr.get(n);if(void 0!==s)return s.ce!==t&&v(`<${i}> already has a <${re.tagNames.state} bind-component="${s.ce}">.`),s.state;let o=()=>(jr.get(n)??[]).filter(e=>Vr(e.name)===t);if(0===o().length&&(Yr(n,t)||((e,t)=>!0===e.getAttribute(zr)?.split(" ").includes(t))(n,t))){let e;await new Promise((r,s)=>{Wr.set(n,r),e=function(e,t){Sr(e)&&t();let n=Tr.get(e)??new Set;return Tr.set(e,n.add(t)),()=>n.delete(t)}(n.getRootNode(),()=>s(new Error(`[@wcstack/state] <${i}>.${t} will not mount: the root state failed to initialize.`)))}).finally(()=>e())}Wr.delete(n);let l=o(),a=Hr.get(n),u=void 0!==a&&a.has(t)?a.get(t):n[t];if((null===u||"object"!=typeof u)&&v(`"bind-component": <${i}>.${t} must be an object (the component's state), got ${null===u?"null":typeof u}.`),0===l.length&&r){let e=new Error(`[@wcstack/state] A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${i}>, or mount it from the host (${re.bindAttributeName}="${t}: path").`);return queueMicrotask(()=>{throw e}),Kr}let c=[];for(let e of l){let r=e.name===t?"":e.name.slice(t.length+1);c.some(e=>e.E===r)&&v(`<${i}> maps "${e.name}" twice.`);let s=r.split(".").indexOf("*");if(s>=0){let n=r.split(".").slice(0,s).join(".");v(`<${i}> maps "${e.name}": the component-side path of a mount cannot contain "*"${""===n?"":` — map the list itself ("${t}.${n}: <the host's list>")`}.`)}c.push({E:r,ue:e.o,r:e.r,ro:Rr.has(e)}),e.engine.kn(e),""!==r&&delete n[e.name]}let h=0===l.length?function(e){let t=Object.getOwnPropertyDescriptors(e),n=Object.isFrozen(e);for(let e of Object.values(t))"value"in e&&!1===e.writable&&(e.writable=!0,n=!0);return n?Object.create(Object.getPrototypeOf(e),t):e}(u):u;return Dr.set(n,s={el:n,ce:t,state:h,engine:0===l.length?null:l[0].engine,entries:c,F:null}),h}(e,n,s,!i):Promise.reject(new Error(`[@wcstack/state] "bind-component" requires <${re.tagNames.state}> to be a direct child of a custom element.`))).catch(l),async start(t,n){let a=!1;await async function(e,t,n,r,i){if(r===Kr)return;let s=y(r);s&&await s;let o=Dr.get(t);o.engine&&r.$recursion&&v(`[wcs/mount-dollar-declaration] <${t.localName}>: $recursion is not run in a mounted component — declare it on the root state.`);let l=o.F;if(null!==l&&l.el!==e&&l.el.isConnected&&v(`<${t.localName}> already has a connected <${re.tagNames.state} bind-component="${o.ce}">.`),null!==l&&ai(l,!1),null!==l&&function(e,t,n){let r=e.x,i=`[${re.bindAttributeName}]`,s=e=>1===e.nodeType&&(e.matches(i)||null!==e.querySelector(i)),o=new Set,l=e=>{for(;null!==e&&e.parentNode!==n;)e=e.parentNode;null!==e&&o.add(e)},a=(e,t)=>{for(let n=e.Pn(t);null!==n&&n!==t;n=n.nextSibling)l(n);l(t)};for(let e of r.re.values())for(let t of e)if(null===t.B)l(t.a);else for(let e of t.B.K)a(t.B,e.S);for(let e of r.oe.values())for(let t of[e.$,...e.j??[]])null!==t&&a(t,t.S);for(let t of e.I)t.parentNode===n&&s(t)&&o.add(t);if(0===o.size)return!1;let u=[...n.childNodes].filter(n=>n!==t&&!o.has(n)&&!e.I.includes(n)&&(s(n)||r.It&&n.textContent.includes("{{")));return u.length>0&&console.warn(`[@wcstack/state] <${e.host.el.localName}>: ${u.length} node(s) added beside the content taken over are not bound.`),!0}(l,e,n))return async function(e,t,n,r){e.el.engine=null,e.el=t,e.x.element=t,t.engine=e.x,e.I=e.I.filter(e=>e.parentNode===n),t.isConnected?await gi(e,r):r()}(l,e,n,i);let a=new ne(r,new qt);a.element=e,e.engine=a,function(e,t){let n=new Map;for(let e=t;null!==e&&e!==Object.prototype;e=Object.getPrototypeOf(e))for(let t of Object.getOwnPropertyNames(e)){let r=Object.getOwnPropertyDescriptor(e,t).value;"function"==typeof r&&"constructor"!==t&&n.set(r,null)}let r=(t,n,r)=>Reflect.apply(t,e.proxy,r);e.U=e=>{let t=n.get(e);return null===t&&n.set(e,t=new Proxy(e,{apply:r})),t}}(a,r);let u={el:e,I:[],x:a,host:o,se:[],st:new Map,cn:!1,an:null,from:null,Q:null};for(let e of o.entries)u.se.push({m:u,e:e});o.F=u,Ur.set(a,u);let h=null===o.engine;h?c.element?.(a,"mounting"):(function(e){let t=e.x,n=e.host,r=n.engine,i=n.el.localName,s=n.entries.find(e=>""===e.E)??null;for(let e of n.entries){if(""===e.E)continue;let t=Vr(e.E);ti(n,t)&&(e.E!==t||ni(n,t))&&ei(`${i}.${e.E}`,`[wcs/mount-own-key-shadow] <${i}>: "${n.ce}.${e.E}" is hidden by the component's own "${t}"; rename one side.`)}if(null!==s){let e=r.v(s.ue,s.r);if(null!==e&&"object"==typeof e)for(let t of Object.keys(n.state))"$"!==t[0]&&t in e&&!n.entries.some(e=>e.E===t)&&ei(`${i}.${t}`,`[wcs/mount-own-key-shadow] <${i}>: its own "${t}" hides "${s.ue.t}.${t}" — remove the default to read the tree, or rename it to keep it private.`)}let o=Gr.filter(e=>void 0!==n.state[e]);o.length>0&&ei(`${i}.${n.ce}$`,`[wcs/mount-dollar-declaration] <${i}>: ${o.join(", ")} ${1===o.length?"is":"are"} not run in a mounted component — declare it on the root state.`);let l=t.Ze;t.Ze=n=>{ii(e,s,n),l.call(t,n)};let a=[...t.L.all()];for(let t of a)ii(e,s,t);for(let e of a)l.call(t,e);let u=n.entries.filter(e=>null!==e.r);if(u.length>0){let e=t._t;t._t=()=>{u.every(e=>e.r.d)&&e.call(t)}}}(u),ai(u,!0),yr.add(a),Nr(a,n));let d=c.ir?.(n);jt(a,n),d?.(),u.I=[...n.childNodes],Ft(),h&&a.bn(),Object.defineProperty(t,o.ce,{configurable:!0,enumerable:!0,get:()=>a.proxy});let f=t.$stateReadyCallback;if("function"==typeof f)try{let e=f.call(t,o.ce);null!==e&&"object"==typeof e&&"function"==typeof e.then&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}i(),e.isConnected?(await a.ae("$connectedCallback"),h&&e.isConnected&&c.element?.(a,"connected")):ai(u,!1)}(e,s,i?r:s,t,()=>{a=!0,n()}).catch(e=>{let t=o();return!a&&null!==t&&(t.broken=!0),l(e)})},Ke(){let e=o();null!==e&&gi(e).catch(e=>console.error(e))},On(){let e=o();null!==e&&(ai(e,!1),!e.broken&&(e.x.ae("$disconnectedCallback"),null===e.host.engine&&c.element?.(e.x,"disconnected")))},reset(){v(`re-setting a component's state is not supported: write <${s?.localName}>.${n} instead.`)}}}var bi={name:"scopes",install(){c.ot=d(m,c.ot,Pr),c.ot=d(m,c.ot,Ir),c.ot=d(m,c.ot,yi),c.Jo=Qr,c.wo=Xr,c.element=h(c.element,(e,t)=>{if("mounting"!==t)return;let n=e.element.getRootNode();Nr(e,n),function(e,t){let n=t.host,r=void 0===n?void 0:Or.get(n);void 0!==r&&Mr.set(e,{host:n,def:r})}(e,n)}),c.pe=h(c.pe,(e,t,n,r,i,s)=>{(function(e,t,n,r){let i=Mr.get(e);if(void 0===i)return;let s=t.t.split(".",1)[0];if(!i.def.bindables.includes(s))return;let o=r&&t.t===s;i.host.dispatchEvent(new CustomEvent(`${i.def.tag}:${s}-changed`,{detail:o?n:void 0,bubbles:!0}))})(e,t,i,s),mi(e,t,n,r,i,s,!1)}),c.me=h(c.me,(e,t,n)=>mi(e,t,n,void 0,void 0,!1,!0)),c.Re=d(f,c.Re,(e,t,n,r,i)=>(function(e,t){let n=br.get(e);if(void 0!==n&&0===t.n)for(let e of n)e.startsWith(`${t.t}.`)&&v(`writing "${t.t}" would replace the volume grafted at "${e}"; write the paths under it instead.`)}(e,t),function(e,t,n){let r,i=Ur.get(e);if(void 0===i)return!1;for(let e=t;null!==e&&void 0===r;e=e.w)r=i.st.get(e);if(void 0===r)return!1;let s=r.e;return!((null===s.r||s.r.d)&&!s.ro)&&(!!n||(si(i,s.r),void v(`[wcs/mount-readonly] <${i.host.el.localName}> cannot write "${t.t}": it is mounted read-only ("${i.host.ce}${""===s.E?"":`.${s.E}`}#ro: ${s.ue.t}"). Write it on the host, or drop #ro from the mount.`)))}(e,t,i)));let e=c.ie;c.ie=(t,n)=>{let r=br.get(t);void 0!==r&&r.length>0&&v(`re-setting a root state with grafted volumes (${r.join(", ")}) is not supported: their data is part of the tree.`),function(e){let t=Fr.get(e);if(void 0===t)return!1;for(let e of t.values())if(e.size>0)return!0;return!1}(t)&&v("re-setting a root state with mounted components is not supported: they read its data."),e?.(t,n)}}},vi="$recursion",wi=new WeakMap,_i=new WeakSet,$i=new WeakSet,ki=0,Si=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ni=e=>`[wcs/recursion-${e}]`;function Ei(e,t){let n=n=>v(`${Ni("declaration-invalid")} ${vi} ${e} "${String(t)}" ${n}`);("string"!=typeof t||""===t)&&v(`${Ni("declaration-invalid")} ${vi} ${e} must be a non-empty string.`);let r=t.split(".");(r.length<2||"*"!==r[r.length-1])&&n('must end with ".*" (a list element).');for(let e=0;e<r.length-1;e++){let t=r[e];""===t&&n("must not contain empty path segments."),("*"===t||"**"===t||/^\d/.test(t))&&n('must have exactly one "*", at the end.'),t.includes("#")&&n('must not contain "#".')}return"$"===t[0]&&n('must not start with "$".'),t}var Ai=(e,t)=>`${e.s}.*${e.step.repeat(t)}`;function Ci(e,t){let n=`${e.s}.**`,r=t.slice(n.length);return(!t.startsWith(n)||""!==r&&"."!==r[0]||r.includes("**"))&&v(`[wcs/recursion-anchor] "${t}" does not start at the recursion anchor "${e.s}.*".`),r}function xi(e,t,n){let r=Ci(e,t),i=function(e,t){for(let n=t;null!==n;n=n.s.te){let t=e.nodeList.exec(n.s.o.t);if(null!==t)return{k:t[1].length/(e.key.length+3),r:n}}return null}(e,n);return null===i&&v(`[wcs/recursion-context] "${t}" uses "**", which is bound to the depth of the row it is evaluated in; there is none here — use $getAll("${t}", []) for every depth.`),Ai(e,i.k)+r}function Ti(e,t,n){let r=new Set,i=new Set,s=(e,n,s)=>!(!Array.isArray(e)||0===e.length||(r.has(e)&&v(`${Ni("cycle")} "${n}" is reachable from itself: the data under "${t.s}" must be a tree.`),i.has(e)&&v(`${Ni("shared-list")} "${n}" is the same array instance as a list reached before: the data under "${t.s}" must be a tree.`),s+1>128&&v(`${Ni("depth-exceeded")} Recursion on "${t.s}.*" reached depth ${s+1} (the limit is 128).`),i.add(e),0)),o=(i,l)=>{for(let a of i){n(l,a);let i=e.o(`${Ai(t,l)}.${t.key}`),u=e.read(i,a);s(u,i.t,l+1)&&(r.add(u),o(e.De(a,i).f,l+1),r.delete(u))}},l=e.o(t.s),a=e.read(l,null);s(a,t.s,0)&&(r.add(a),o(e.De(null,l).f,0))}function Pi(e,t){let n=function(e){let t=e[vi],n=[],r=new Set;for(let t=e;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let e of Object.getOwnPropertyNames(t))!r.has(e)&&e.includes("**")&&n.push([e,Object.getOwnPropertyDescriptor(t,e)]),r.add(e);if(void 0===t)return n.length>0&&z(n[0][0]),null;(null===t||"object"!=typeof t||Array.isArray(t))&&v(`${Ni("declaration-invalid")} ${vi} must be an object mapping one anchor path to its repeating sub-path.`);let i=Object.entries(t);1!==i.length&&v(`${Ni("declaration-invalid")} ${vi} must declare exactly one anchor (it declares ${i.length}).`);let s=Ei("anchor",i[0][0]),o=Ei("repeat",i[0][1]),l=s.slice(0,-2),a=o.slice(0,-2),u=`.${o}`,c=new Map,h=[],d=`${l}.**`;for(let[e,t]of n){let n=e.slice(d.length);(!e.startsWith(d)||""!==n&&"."!==n[0]||n.includes("**"))&&v(`[wcs/recursion-anchor] "${e}": a recursive key is "${d}" followed by a path (the anchor is "${s}").`),(""===n||n.split(".").slice(1).some(e=>""===e))&&v(`[wcs/recursion-anchor] "${e}" needs a path after "**".`),(void 0===t.get||void 0!==t.set)&&v(`${Ni("declaration-invalid")} "${e}": a recursive key is a getter without a setter.`),c.set(n,t.get),h.push([new RegExp(`^${Si(s)}((?:${Si(u)})*)${Si(n)}$`),n])}return{s:l,step:u,key:a,families:c,matchers:h,owners:new Map,nodeList:new RegExp(`^${Si(l)}((?:${Si(`.*.${a}`)})*)$`)}}(t),r=wi.has(e);null!==n?(r||ki++,wi.set(e,n),$i.add(e),_i.has(e)||function(e){_i.add(e);let t=e,n=t.Ze;t.Ze=r=>{let i=wi.get(e);if(r.t.includes("**")){let t=e.L.At(r.t)===r;return void($i.has(e)||void 0===i&&t?r.getter=()=>z(r.t):t||n.call(e,r))}if(void 0!==i&&null===r.getter)for(let[e,n]of i.matchers)if(e.test(r.t)){r.getter=i.families.get(n),r.n>0&&(r.A=t.Oe++),i.owners.set(r,i.s+".**"+n);break}n.call(e,r)};let r=t.resolve;t.resolve=(t,n)=>{let i=wi.get(e);return r.call(e,void 0!==i&&t.includes("**")?xi(i,t,n):t,n)};let i=t.getAll;t.getAll=(n,r)=>{let s=wi.get(e);if(void 0===s||!n.includes("**"))return i.call(e,n,r);if(void 0===r)return i.call(e,xi(s,n,t.h));(!Array.isArray(r)||r.length>0)&&v(`${Ni("getall-form")} $getAll("${n}", indexes) with "**" takes either no indexes (this depth) or [] (every depth).`);let o=Ci(s,n),l=[];return Ti(e,s,(t,n)=>{for(let r of i.call(e,Ai(s,t)+o,e.D(n)))l.push(r)}),l};let s=t.pn;t.pn=(n,r,i,o)=>{let l=wi.get(e);if(void 0===l||!n.includes("**"))return s.call(e,n,r,i,o);Array.isArray(r)||k(9,[n]),r.length>0&&v(`${Ni("setall-form")} $setAll("${n}", indexes, …) with "**" takes no partial prefix: pass [] to write every node.`),("function"==typeof i||!0===o?.spread)&&v(`${Ni("setall-form")} $setAll("${n}", [], value) with "**" takes a plain value (no mapper, no spread).`),t.Ce>0&&k(8);let a=Ci(l,n),u=a.replace(/\.\d+(?=\.|$)/g,".*");for(;u.startsWith(l.step);)u=u.slice(l.step.length);let c=l.key.split(".");(""===u||u===`.${l.key}.length`||c.some((e,t)=>u===`.${c.slice(0,t+1).join(".")}`))&&v(`${Ni("structural-write")} "${n}" writes the recursion structure itself (a node, its "${l.key}" list or that list's length, or an object on the way to it).`);for(let e of l.families.keys()){let t=e;for(;t.startsWith(l.step);)t=t.slice(l.step.length);(u===t||u.startsWith(`${t}.`))&&v(`${Ni("readonly")} "${n}" writes into the recursive getter "${l.s}.**${e}".`)}let h=[];Ti(e,l,(e,t)=>h.push([e,t]));let d=0;for(let[t,n]of h)d+=s.call(e,Ai(l,t)+a,e.D(n),i);return d}}(e)):r&&(wi.delete(e),ki--)}function Oi(e,t){if(0===ki)return!1;let n=wi.get(e);if(void 0===n)return!1;for(let e=t;null!==e;e=e.w){let r=n.owners.get(e);void 0!==r&&v(`${Ni("readonly")} "${t.t}" writes into the recursive getter "${r}".`)}return!1}var Mi={name:"recursion",install(){c.ie=h(c.ie,Pi),c.element=h(c.element,(e,t)=>{("mounting"===t||"reset"===t)&&function(e){$i.delete(e)}(e)}),c.Re=d(f,c.Re,Oi)}},Li="4.0.0-rc.2",Ii=e=>e.split(".").slice(0,2).join("."),ji=class extends Jt{static find(e){return e.querySelector?.(re.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return Ii(this.version)===Ii(Li)}};function Ri(e){let t=re.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends ji{})}var Hi=()=>re.tagNames.ssr,Wi=Symbol.for("wcstack.ssr.snapshotBuilder"),zi=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),Di=e=>document.createComment(e),Ui=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,Fi=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),qi=new WeakMap,Bi=new WeakMap,Ki=new WeakMap,Gi=new WeakSet,Vi=new WeakMap;function Ji(e,t){let n=[];for(let r=e;null!==r&&(n.push(r),r!==t);r=r.nextSibling);return n}function Qi(e,t,...n){for(let n of Array.from(e.attributes))t.setAttribute(n.name,n.value);return(t.content??t).append(...n),t}var Xi=e=>null===e.I?e.He:e.I[e.I.length-1];function Yi(e,t,n){let r=[Di(null===n?"wcs-[":`wcs-[:${n}`)];for(let e of t)null===n&&r.push(Di("wcs-|")),r.push(...Ji(e.He,Xi(e)));r.push(Di("wcs-]")),e.after(...r);for(let e of r)Gi.add(e)}function Zi(e){if(e instanceof lt){Yi(e.S,e.ve,null);for(let t of e.ve)es(t);return}let t=e.F;null!==t&&(Yi(e.K[e.K.length-1].S,[t],e.b),es(t))}function es(e){if(null!==e.u)for(let t of e.u)Zi(t)}var ts=new Set(["script","style","template","textarea","title"]),ns="data-wcs-raw",rs=e=>ts.has(e.localName)||e.localName===Hi();function is(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(Di("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(Di("wcs-s")):1===t.nodeType&&!rs(t)&&is(t)}var ss=0;function os(e,t){let n=e.getRootNode(),r=[t];for(let e of Bi.get(n)??[])e!==t&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let i=new Map;for(let e of r){let t=qi.get(e);if(void 0===t)continue;let n=new Map;for(let t of e.oe.values())if(null!==t.$&&n.set(t.$.S,t.$),null!==t.j)for(let e of t.j)n.set(e.S,e);for(let t of e.re.values())for(let e of t)if(null!==e.B)for(let t of e.B.K)n.set(t.S,e.B);let r=new Set;for(let[e,s]of t){i.set(e,s);let t=n.get(e);void 0!==t&&!r.has(t)&&e.isConnected&&(r.add(t),Zi(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=Ki.get(e);if(void 0!==t){let n=document.createTreeWalker(e,133,{acceptNode:e=>Gi.has(e)||1===e.nodeType&&t.has(e)&&hs(e)?2:1}),r=[];for(let e=n.nextNode();null!==e;e=n.nextNode()){let n=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(rs(e.parentNode)?Vi.has(e):t.has(n)&&Fi(n,"wcs-t:"))&&(Vi.has(e)||t.get(e)!==e.data):!t.has(e))&&r.push(e)}for(let e of r)e.remove()}let n=Array.from(e.childNodes);rs(e)&&n.some(e=>Vi.has(e))&&e.setAttribute(ns,n.map(e=>Vi.has(e)?`{{ ${Vi.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}is(9===n.nodeType?n.body:n);let s=document.createElement(Hi());s.setAttribute("version",Li);let o=document.createElement("script");o.type="application/json",o.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let n of Object.keys(e)){if("$"===n[0])continue;let r=Object.getOwnPropertyDescriptor(e,n);void 0!==r.get||void 0!==r.set||"function"==typeof r.value||(t[n]=r.value)}return t}(t.target)),s.append(o);for(let[e,t]of i){if(!e.isConnected)continue;let n=e.parentNode;for(;null!==n&&"svg"!==n.localName&&"foreignObject"!==n.localName;)n=n.parentElement;let r="svg"===n?.localName,i=`wcs-${r?"s":"t"}${ss++}`;e.replaceWith(Di(`wcs-p:${i}`));let o=document.importNode(xt(t),!0);for(let e of Array.from(o.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(Qi(e,document.createElement("template"),...e.childNodes));if(r){let e=document.createElementNS(n.namespaceURI,"svg");e.append(o),o=e}let l=document.createElement("template");l.id=i,s.append(Qi(t,l,o))}e.before(s)}function ls(e){!function(e){if(null!==e.querySelector(re.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>Vi.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${re.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===Hi())continue;let e=t.engine;null!=e&&os(t,e)}}var as=Symbol.for("wcstack.state.ssr.impl"),us=new Map,cs=new WeakMap,hs=e=>!0===c.wo?.(e),ds=e=>1===e.nodeType&&!rs(e)&&!hs(e),fs=e=>e.f.flat().concat(e._??[]),ps=e=>{for(let t of fs(e))t.remove()};function ms(e,t,n){let r=/^wcs-\[(?::(\d+))?/.exec(e.data),i=e.previousSibling,s=e.parentNode,o=[],l=e.nextSibling;for(e.remove();null!==l&&!Ui(l,"wcs-]");){let e=l.nextSibling;if(Ui(l,"wcs-|"))o.push([]),l.remove();else{0===o.length&&o.push([]);let n=o[o.length-1];Fi(l,"wcs-[")?e=ms(l,t,n):(n.push(l),ds(l)&&gs(l,t))}l=e}let a={branch:void 0===r[1]?null:Number(r[1]),f:o,_:l??s.appendChild(Di("wcs-]"))},u=fs(a);l=a._.nextSibling;for(let e of u)n?.push(e),t&&Et.add(e);return t&&null!==i?us.set(i,a):ps(a),l}function gs(e,t){for(let n=e.firstChild;null!==n;)Fi(n,"wcs-[")?n=ms(n,t):(ds(n)&&gs(n,t),n=n.nextSibling)}function ys(e,t,n){let r=e=>{for(let i of Array.from(e.childNodes))if(i.parentNode===e)if(8===i.nodeType){let e=i.data;try{if("wcs-s"===e)i.remove();else if("wcs-e"===e)i.replaceWith("");else if(e.startsWith("wcs-t:")){let t=Di(`@@:${decodeURIComponent(e.slice(6))}`),n=i.nextSibling;for(;null!==n&&!Ui(n,"wcs-/t");){let e=n.nextSibling;n.remove(),n=e}n?.remove(),i.replaceWith(t)}else if(e.startsWith("wcs-p:")){let n=t.querySelector(`template[id="${e.slice(6)}"]`);if(null!==n){let t=i.parentNode,r="s"===e[10]?Qi(n,document.createElementNS(t.namespaceURI,"template"),...document.importNode(n.content.firstChild,!0).childNodes):document.importNode(n,!0);r.removeAttribute("id"),t.replaceChild(r,i)}}}catch{}}else 1===i.nodeType&&!rs(i)&&(hs(i)?cs.set(i,{ssr:t,Te:n}):r(i))};r(e),function(e){for(let t of Array.from(e.querySelectorAll("table > tbody"))){let e=[];for(let n=t.previousSibling;null!==n&&(8===n.nodeType||Ss(n)||"template"===n.localName);n=n.previousSibling)e.unshift(n);let n=0,r=0;if(e.forEach((e,t)=>{Fi(e,"wcs-[")?r++:Ui(e,"wcs-]")&&--r<0&&(r=0,n=t+1)}),0===r)continue;let i=0;for(let r=t.firstChild;null!==r;r=r.nextSibling)if(Fi(r,"wcs-["))i++;else if(Ui(r,"wcs-]")&&0===i--){t.prepend(...e.slice(n));break}}}(e),gs(e,n)}function bs(e){let t=cs.get(e);if(void 0===t||(cs.delete(e),ys(e,t.ssr,t.Te),!t.Te))return null;let n=c.Te;return c.Te=As,()=>{c.Te=n,vs()}}function vs(){for(let e of us.values())ps(e);us.clear()}function ws(e){let t=[];for(let n=document.createTreeWalker(e,128);n.nextNode();)t.push(n.currentNode);return t}function _s(e,t,n,r){let i=null;for(let r of e){let e=r[n];null!==e&&(""===e||t===e||t.startsWith(`${e}.`))&&(null===i||e.length>i[n].length)&&(i=r)}let s=i?.[r];if(null==s)return null;let o=i[n],l=""===o?t:t.slice(o.length+1);return""===s?l:""===l?s:`${s}.${l}`}function $s(e,t,n){if(zi()){if(n instanceof Array){for(let e=n.length;e-- >0;)gt(n[e])&&n.splice(e,1);let e=t;if(n.some(yt))Gi.add(e);else if(e.localName.includes("-")&&!hs(e)){let t=new Map;for(let n=document.createTreeWalker(e,133);n.nextNode();)t.set(n.currentNode,n.currentNode.data);Ki.set(e,t)}return}if("string"==typeof n){if(Vi.set(t,n),rs(t.parentNode))return;let e=Di(`wcs-t:${encodeURIComponent(n)}`),r=Di("wcs-/t");return t.before(e),void t.after(r)}let r=qi.get(e);void 0===r&&qi.set(e,r=new Map),r.set(t,n);let i=t.getRootNode(),s=Bi.get(i);return void 0===s&&Bi.set(i,s=new Set),void s.add(e)}if("string"!=typeof n&&us.size>0){let e=us.get(n);void 0!==e&&(us.delete(n),us.set(t,e))}}var ks=e=>null!==e&&8===e.nodeType&&[re.commentIfPrefix,re.commentElseIfPrefix,re.commentElsePrefix].includes(e.data),Ss=e=>3===e.nodeType&&""===e.data.trim(),Ns=e=>(us.get(e)?._??e).nextSibling;function Es(e,t){if(t.length!==e.nn.childNodes.length)return!1;let n=e.Rn;for(let r=0;r<n.length;r++){let i=n[r],s=e.nn,o=t[i[0]];for(let e=0;;){if(s=s.childNodes[i[e]],o?.nodeName!==s.nodeName)return!1;if(++e===i.length)break;o=o.firstChild;for(let t=i[e];t>0&&null!==o;t--)o=Ns(o)}e.ho[r]=o}return!0}function As(e,t,n){if(0===us.size)return null;let r=t,i=0;if(!n){let e=re.commentIfPrefix;if(!Ui(t,e))for(let n=t.previousSibling;null!==n&&(ks(n)||Ss(n))&&(ks(n)&&i++,!Ui(n,e));n=n.previousSibling);for(let n=t.nextSibling;!us.has(r)&&null!==n&&!Ui(n,e)&&(ks(n)||Ss(n));n=n.nextSibling)ks(n)&&(r=n)}let s=us.get(r);if(void 0===s)return null;if(!n&&s.branch!==i)return us.delete(r),ps(s),null;let o=s.f.shift();if(0===s.f.length&&us.delete(r),s._?.replaceWith(...Ji(t,r)),s._=null,void 0===o)return null;let l=[];for(let e=0;e<o.length;e++){let t=us.get(o[e]);if(l.push(o[e]),void 0!==t)for(;e<o.length&&o[e]!==t._;)e++}if(!Es(e,l)){let n=(e.Tn?e.root:e.nn).cloneNode(!0);l=e.Tn?[n]:[...n.childNodes],Es(e,l),(o[0]??s.f.find(e=>e.length>0)?.[0]??t).before(n);for(let e of o)e.remove()}return l}var Cs={name:"ssr",install(){c.An=$s,c.ir=bs;let e=c.element;c.element=(t,n)=>{"mounting"===n&&function(e){let t=e.element;if(!t.hasAttribute("enable-ssr")||zi())return;let n=t.previousElementSibling,r=n?.localName===Hi(),i=r?n.getAttribute("version"):null,s=null===i||Ii(i)===Ii(Li);if(s){let t=e,n=t.ae;t.ae=(t,r)=>"$connectedCallback"===t?void 0:n.call(e,t,r)}if(!r)return;let o=!s&&parseInt(i)<4,l=/^3\.(\d+)\.(\d+)$/.exec(i),a=null!==l&&(+l[1]-5||+l[2]-3)>=0;s||console.warn(`[@wcstack/state] <${Hi()} version="${i}"> does not match ${Li}: its snapshot is discarded, and the page renders on the client from its own state.${o&&!a?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let u=s?n.querySelector('script[type="application/json"]'):null;if(null!==u){let t=JSON.parse(u.textContent||"{}"),n=e.target;for(let e of Object.keys(t)){let r=Object.getOwnPropertyDescriptor(n,e);void 0!==r&&(void 0!==r.get||void 0!==r.set||"function"==typeof r.value)||(n[e]=t[e])}e.hydrated=!0}let h=t.getRootNode();for(let e of Array.from(h.querySelectorAll(`[${ns}]`)))e.textContent=e.getAttribute(ns),e.removeAttribute(ns);let d=9===h.nodeType?h.body:h;o?function(e,t,n){let r=new Map,i=e=>{let t=e.parentElement;for(;null!==t&&!hs(t);)t=t.parentElement;if(null===t)return null;let n=r.get(t);if(void 0===n){let e=i(t),s=t.querySelector(`:scope > ${re.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,n=[]);for(let r of ae(t.getAttribute(re.bindAttributeName)??"")){let t=r.Ye;r.ye[0]===s&&n.push([e?_s(e,t,1,0):t,r.ye.slice(1).join("."),e&&t])}}return n},s=(e,t,n)=>{let r=i(e);if(null===r)return t;let s=/^([^|]*)#m\d+\.([^|]*)$/.exec(t);if(null===s)return n?t:_s(r,t,0,1)??t;let o=s[1].replace(/#m\d+\./g,"").slice(0,-1);return r.some(e=>""===e[1]&&(e[0]===o||e[2]===o))?s[2]:_s(r,s[2],2,1)??s[2]};for(let t of ws(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let r=t.nextSibling;for(;null!==r&&!Ui(r,`@@wcs-${e[1]}-end:${e[2]}`);)r=r.nextSibling;if(null!==r){for(;t.nextSibling!==r;)t.nextSibling.remove();r.remove(),t.replaceWith(..."text"===e[1]?[Di(`@@:${s(t,e[2],n)}`)]:[])}}let o=(e,n)=>{for(let r of ws(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(r.data)?.[1],i=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===i)continue;let l=document.importNode(i,!0),a=re.bindAttributeName;l.removeAttribute("id"),l.setAttribute(a,l.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,i)=>t+s(n??r,i))),o(l.content,n??r);let u=l.content.firstChild;r.replaceWith(.../^\s*elseif\s*:/.test(u?.getAttribute?.(a)??"")?l.content.childNodes:[l])}};o(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(d,n,a):ys(d,n,s),n.remove(),s&&(c.Te=As,queueMicrotask(()=>{vs(),c.Te=null}))}(t),e?.(t,n)},function(){let e=globalThis;e[as]={build:ls,reset(){ss=0}},void 0===e[Wi]&&(e[Wi]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[as].build(t),reset:()=>e[as].reset()})}(),c.Eo=h(c.Eo,Ri);for(let e of Yt())Ri(e)}},xs="__WCSTACK_DEVTOOLS_HOOK__",Ts=null,Ps=new Set,Os=(e,t,n)=>({absolutePathInfo:{pathInfo:{path:t.t},stateElement:e.element},listIndex:null===n?null:{indexes:e.D(n)}}),Ms=new WeakMap,Ls=0,Is=new WeakMap;function js(e){if(null===Ts)return;let t=Is.get(e),n=Ps.has(e)?function(e,t){let n=new Map,r=new Set,i=(r,i,s,o,l,a)=>{if(5===r)return;let u=function(e,t){return 0===e?"textContent":2===e?`class.${t}`:3===e?`attr.${t}`:4===e?`style.${t}`:t}(r,i),c=0===o.n?null:l,h=`${(e=>{let t=Ms.get(e);return void 0===t&&Ms.set(e,t=++Ls),t})(s)}|${u}|${o.t}|${null===c?"":e.D(c).join(",")}`;if(n.has(h))return;let d=t?.get(h);n.set(h,d??{binding:{propName:u,statePathName:o.t,bindingType:a,node:s,replaceNode:s},absoluteAddress:Os(e,o,c)})},s=e=>i(e.i,e.name,e.a,e.o,e.r,e.Zt()),o=e=>{if(!r.has(e)){if(r.add(e),null!==e.de)for(let t of e.de)s(t);if(e instanceof Xe&&null!==e.se){let t=e.T.Ue;for(let n=0;n<t.length;n++){let r=e.U?.[n];void 0!==r?s(r):i(t[n].i,t[n].name,e.se[2*n],t[n].o,e.r,0===t[n].i?"text":"prop")}}if(null!==e.u)for(let t of e.u)l(t)}},l=e=>{if(!r.has(e))if(r.add(e),e instanceof lt){i(-1,"for",e.S,e.s.o,e.s.te,"for");for(let t of e.ve)o(t)}else null!==e.F&&o(e.F)};for(let t of e.re.values())for(let e of t)s(e),null!==e.B&&l(e.B);for(let t of e.oe.values())if(null!==t.$&&l(t.$),null!==t.j)for(let e of t.j)l(e);return n}(e,t):new Map;if(void 0!==t)for(let[e,r]of t)n.has(e)||Ts({type:"state:binding-removed",...r});for(let[e,r]of n)(void 0===t||!t.has(e))&&Ts({type:"state:binding-added",...r});Is.set(e,n)}function Rs(e){let t=It.get(e);if(void 0===t)throw new Error("[@wcstack/state] devtools: no state tree on this root");return t}function Hs(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let s of e.L.all()){for(let e=1;e<=s.n;e++)t.add(s.c[e].t);"*"===s.l&&n.add(s.t),null!==s.getter&&r.add(s.t),null!==s.Z&&i.add(s.t)}let s=e.target;return{rootNode:e.root,element:e.element,paths:{list:t,element:n,getter:r,setter:i},commandTokenNames:new Set(Object.keys(e.commands)),eventTokenNames:new Set(e.Se.keys()),staticDependency:new Map,dynamicDependency:new Map,watchPaths:null!==s.$watch&&"object"==typeof s.$watch?new Set(Object.keys(s.$watch)):null,keyedListPaths:null!==s.$listKeys&&"object"==typeof s.$listKeys?new Set(Object.keys(s.$listKeys)):null}}var Ws=new WeakSet,zs=new WeakMap;function Ds(e,t){if(("mounting"===t||"reset"===t)&&function(e){let t=(t,n)=>{if(Ws.has(t))return;Ws.add(t);let r=t.emit;t.emit=(...i)=>(null!==Ts&&Ts({type:"state:token-emit",kind:n,tokenName:t.name,args:i,subscriberCount:t.size,stateElement:e.element}),r.apply(t,i))};for(let n of Object.values(e.commands))t(n,"command");for(let n of e.Se.values())t(n,"event")}(e),"connected"===t){if(Ps.has(e))return;Ps.add(e),Ts?.({type:"state:element-registered",rootNode:e.root,element:e.element}),js(e)}else"disconnected"===t&&(Ps.delete(e),js(e),Ts?.({type:"state:element-unregistered",rootNode:e.root,element:e.element}))}function Us(e,t,n,r,i,s){if(null===Ts)return;let o=Os(e,t,0===t.n?null:n),l=zs.get(e);void 0===l&&zs.set(e,l=new Set),l.add(o),s&&Ts({type:"state:write",absoluteAddress:o,value:i,oldValue:r,hasOldValue:!0})}function Fs(e){if(null===Ts)return;let t=zs.get(e);zs.delete(e),void 0!==t&&Ts({type:"state:update-batch",addresses:t}),js(e)}function qs(e,t,n){Ts?.({type:"state:binding-apply-error",path:n.o.t,bindingType:n.Zt(),error:t})}!function(e){for(let t of e)g.has(t.name)||(g.add(t.name),t.install())}([on,Mn,ir,dr,bi,Mi,Cs,{name:"devtools",install(){c.element=h(c.element,Ds),c.pe=h(c.pe,Us),c.Pe=h(c.Pe,Fs),c._e=h(c._e,qs),function(){if(typeof document>"u"||document.documentElement?.hasAttribute("data-wcs-server"))return;let e=globalThis,t=e[xs]??(e[xs]=function(){let e=new Map,t=new Set,n=e=>{0===t.size?e._setSink(null):e._setSink(n=>{for(let r of t)r.onEvent?.(e.id,n)})};return{version:2,sources:e,register(r){if(!e.has(r.id)){e.set(r.id,r),n(r);for(let e of t)e.onSourceRegistered?.(r)}},unregister(n){let r=e.get(n);if(void 0!==r){r._setSink(null),e.delete(n);for(let e of t)e.onSourceUnregistered?.(n)}},addListener(r){t.add(r);for(let t of e.values())n(t),r.onSourceRegistered?.(t);return()=>{if(t.delete(r))for(let t of e.values())n(t)}}}}());2!==t.version&&console.warn(`[@wcstack/state] devtools hook registry version ${t.version}, expected 2: keeping the existing one.`),t.register({id:`state:${Math.random().toString(36).slice(2,10)}`,kind:"state",packageVersion:Li,getStateElements:()=>[...Ps].map(Hs),overlays:()=>[],keyedSubscriptions:e=>function(e){let t=[];for(let n of e.L.all()){let r=n.H,i=n.Fe?.length??0;if((null===r||0===r.size)&&0===i)continue;let s,o=0;if(null!==r)for(let e of r.values())o+=e.size;try{s=0===n.n?e.v(n,null):void 0}catch{s=void 0}t.push({path:n.t,tracked:!1,rows:o,keys:null===r?0:r.size,lists:i,lastValue:s})}return t}(Rs(e)),keys(e){let t=Rs(e).target;return Object.keys(t).filter(e=>{if(e.includes("*")||"$"===e[0])return!1;let n=Object.getOwnPropertyDescriptor(t,e);return void 0!==n.get||"function"!=typeof n.value})},read(e,t,n){let r;return Rs(e).element.createState("readonly",e=>{r=e.$resolve(t,n??[])}),r},write(e,t,n,r){Rs(e).element.createState("writable",e=>{e.$resolve(t,r??[],n)})},_setSink(e){let t=null===Ts&&null!==e;Ts=e,null===e&&(Is=new WeakMap),c.tt=e&&((e,t)=>Ts?.({...t,stateElement:e.element})),t&&queueMicrotask(()=>{for(let e of Ps)js(e)})}})}()}}]),function(e=customElements){(function(){let e=globalThis;void 0===e[Ht]&&(e[Ht]={protocol:"wcs-binder",version:1,bind:Ut})})(),Yt().includes(e)||Xt.push(new WeakRef(e));let t=re.tagNames.state;void 0===e.get(t)&&e.define(t,class extends Qt{}),c.Eo?.(e)}();const Bs={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"},Ks=!1,Gs=[".html"];function Vs(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function Js(e,t){if(t&&"cause"in t)throw new Error(`[@wcstack/router] ${e}`,{cause:t.cause});throw new Error(`[@wcstack/router] ${e}`)}let Qs=class extends Error{fallbackPath;constructor(e,t){super(e),this.fallbackPath=t}};const Xs={int:{typeName:"int",pattern:/^-?\d+$/,parse(e){if(this.pattern.test(e))return parseInt(e,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(e){if(this.pattern.test(e))return parseFloat(e)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(e){if(this.pattern.test(e))return"true"===e||"1"===e}},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(e){if(this.pattern.test(e))return e}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(e){if(this.pattern.test(e))return e}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(e){if(!this.pattern.test(e))return;const[t,n,r]=e.split("-").map(Number),i=new Date(t,n-1,r);return i.getFullYear()===t&&i.getMonth()===n-1&&i.getDate()===r?i:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(e){if(this.pattern.test(e))return e}}};function Ys(e){const t={};for(const[n,r]of new URLSearchParams(e))t[n]=r;return Object.freeze(t)}function Zs(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const r of n){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(e[r]!==t[r])return!1}return!0}const eo={static:2,param:1,"catch-all":0};let to=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(e){super(),this._target=e??this}get parentCore(){return this._parentCore}set parentCore(e){this._parentCore=e}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(e,t){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&Js(`${Bs.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&Js(`${Bs.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):t()}get absolutePath(){return this._checkParentCore(e=>{const t=e.absolutePath;return t.endsWith("/")?t+this._path:t+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(e=>[...e.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 e=[];for(const t of this._segmentInfos)t.paramName&&e.push(t.paramName);this._paramNames=e}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(e=>[...e.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let e=0;for(const t of this._segmentInfos)e+=eo[t.type];this._weight=e}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(e=>e.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let e=0;for(const t of this._segmentInfos)"catch-all"!==t.type&&e++;this._segmentCount=""===this._path?0:e}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(e=>e.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(e,t={}){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=e,this._name=t.name||"",this._isFallbackRoute=t.isFallback||!1,t.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=e.split("/");for(let e=0;e<n.length;e++){const r=n[e];if(!(""===r&&e===n.length-1&&e>0)){if("*"===r){this._segmentInfos.push({type:"catch-all",segmentText:r,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(r.startsWith(":")){const e=r.match(/^:([^()]+)(\(([^)]+)\))?$/);let t,n="any";e?(t=e[1],e[3]&&Object.keys(Xs).includes(e[3])&&(n=e[3])):t=r.substring(1),this._segmentInfos.push({type:"param",segmentText:r,paramName:t,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===r&&t.isIndex||this._segmentInfos.push({type:"static",segmentText:r,paramName:null,pattern:new RegExp(`^${r}$`)})}}this._hasGuard=t.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=t.guardFallback||"/",this._waitForSetGuardHandler=new Promise(e=>{this._resolveSetGuardHandler=e}))}setParams(e,t){const n=this._active;this._params=e,this._typedParams=t,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:e,typedParams:t},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const e=this._active;this._params={},this._typedParams={},this._active=!1,e&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(e){for(const t of this.paramNames)if(this._params[t]!==e[t])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||Js(`${Bs.route} has no guardHandler.`),this._guardHandler}set guardHandler(e){this._guardHandler=e,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(e){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const t=e.path,n=e.lastPath,r=await this._guardHandler(t,n,function(e){return Object.freeze({params:Object.freeze({...e.params}),typedParams:Object.freeze({...e.typedParams}),searchParams:Ys(e.search??""),routeName:e.routes[e.routes.length-1]?.name??""})}(e));if("string"==typeof r&&""!==r)throw new Qs("Navigation cancelled by guard.",r);if(!r)throw new Qs("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof r?r:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new Qs("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const no="data-wcs-ssr",ro="data-wcs-ssr-link",io="@@wcs-route-ph:",so="@@wcs-route-start:",oo="@@wcs-route-end:";let lo=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=Vs();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new to(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||Js(`${Bs.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${oo}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(e,t){for(this._childNodeArray=[...e],t&&(this._endMarker=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(e){this._core.guardHandler=e}setParams(e,t){this._core.setParams(e,t)}clearParams(){this._core.clearParams()}shouldChange(e){return this._core.shouldChange(e)}async guardCheck(e){return this._core.guardCheck(e)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(e){let t=this._routeParentNode;for(;t;){if(t===e)return!0;t=t.routeParentNode}return!1}initialize(e,t){if(this._initialized)return;let n;this._initialized=!0;let r=!1,i=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",r=!0):this.hasAttribute("fallback")?(n="",i=!0):Js(`${Bs.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=t;const s=t||e;s.routeChildNodes.push(this),this._childIndex=s.routeChildNodes.length-1,i&&(t&&Js(`${Bs.route} with fallback attribute must be a direct child of ${Bs.router}.`),e.fallbackRoute&&Js(`${Bs.router} can have only one fallback route.`),e.fallbackRoute=this),t&&(this._core.parentCore=t._core),this._core.parsePath(n,{isIndex:r,isFallback:i,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const ao=Symbol.for("wcstack.trustedTypes.policy"),uo=Symbol.for("wcstack.trustedTypes.internal"),co="wcstack";function ho(){const e=globalThis[ao];return null===e||"object"!=typeof e?null:e}let fo=!1;function po(e){const t=function(){const e=globalThis,t=e[uo];if(void 0!==t)return t;const n=globalThis.trustedTypes;let r=null;if(n&&"function"==typeof n.createPolicy)try{r=n.createPolicy(co,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){"function"!=typeof ho()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${co}". Allow it in the CSP (\`trusted-types ${co};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,e)}return e[uo]=r,r}(),n=t?.createHTML;if("function"==typeof n)return n.call(t,e);if(!("trustedTypes"in globalThis))return e;const r=ho(),i=r?.createHTML;return"function"==typeof i?(fo||(fo=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${co}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${co};\` in the CSP to avoid this. See docs/csp.md section 7.`)),i.call(r,e)):e}const mo=new Map;let go=class extends HTMLElement{_uuid=Vs();constructor(){super()}async _loadTemplateFromSource(e){try{const t=await fetch(e);t.ok||Js(`${Bs.layout} failed to fetch layout from source: ${e}, status: ${t.status}`);const n=await t.text();return mo.set(e,n),n}catch(t){Js(`${Bs.layout} failed to load layout from source: ${e}, error: ${t}`,{cause:t})}}_loadTemplateFromDocument(e){const t=document.getElementById(`${e}`);return t&&t instanceof HTMLTemplateElement?t.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),t=this.getAttribute("layout");e&&t&&console.warn(`${Bs.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)mo.has(e)?n.innerHTML=po(mo.get(e)||""):n.innerHTML=po(await this._loadTemplateFromSource(e)||"");else if(t){const e=this._loadTemplateFromDocument(t);e?n.innerHTML=po(e):console.warn(`${Bs.layout} could not find template with id "${t}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Ks}get name(){return this.getAttribute("name")||""}};class yo extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||Js(`${Bs.outlet} has no routesNode.`),this._routesNode}set routesNode(e){this._routesNode=e}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(e){this._lastRoutes=[...e]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Ks}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const bo=new Set(["props","states","attr",""]);function vo(e,t,n){for(const[r,i]of Object.entries(t))switch(n){case"props":e.props={...e.props,[r]:i};break;case"states":e.states={...e.states,[r]:i};break;case"attr":null==i?e.removeAttribute(r):e.setAttribute(r,String(i));break;case"":e[r]=i}}function wo(e,t){e.hasAttribute("data-bind")||Js(`${e.tagName} has no 'data-bind' attribute.`);const n=e.getAttribute("data-bind")||"";bo.has(n)||Js(`${e.tagName} has invalid 'data-bind' attribute: ${n}`);const r=n,i=function(e){const t=e.tagName.toLowerCase();if(t.includes("-"))return t;const n=e.getAttribute("is");return n&&n.includes("-")?n:null}(e);i&&void 0===customElements.get(i)?customElements.whenDefined(i).then(()=>{e.isConnected&&vo(e,t,r)}).catch(()=>{Js(`Failed to define custom element: ${i}`)}):vo(e,t,r)}const _o=Symbol.for("wcstack.binder");function $o(){const e=globalThis[_o];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}const ko=Symbol.for("wcstack.binder.pending"),So=Symbol.for("wcstack.binder.taken");function No(){const e=globalThis;let t=e[So];return void 0===t&&(t=new WeakSet,e[So]=t),t}function Eo(e,t){const n=$o();return null===n?(function(){const e=globalThis;let t=e[ko];return void 0===t&&(t=[],e[ko]=t),t}().push(e),!1):(No().add(e),n.bind(e,t),!0)}const Ao={range:!0};function Co(e,t){for(const n of e.routeChildNodes)t.add(n.placeHolder).add(n.endMarker),Co(n,t);return t}function xo(e){const t=e.placeHolder,n=e.endMarker,r=null!==n.parentNode&&n.parentNode===t.parentNode&&!!(4&t.compareDocumentPosition(n)),i=r?null:Co(e,new Set),s=[];let o=0;for(let l=t.nextSibling;null!==l&&l!==n&&(null===i||8!==l.nodeType||!/^@@(route:|wcs-route-)/.test(l.data)||i.has(l));l=l.nextSibling)s.push(l),(r||e.childNodeArray.includes(l))&&(o=s.length);return s.length=o,s}let To=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||Js(`${Bs.layoutOutlet} has no layout.`),this._layout}set layout(e){this._layout=e,this.setAttribute("name",e.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 e=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(e.content.cloneNode(!0));for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),this.appendChild(e)}else{const t=e.content.cloneNode(!0),n=new Map;t.querySelectorAll("slot").forEach(e=>{const t=e.getAttribute("name")||"";n.has(t)?console.warn(`${Bs.layoutOutlet} duplicate slot name "${t}" in layout template.`):n.set(t,e)});const r=new Map,i=document.createDocumentFragment();for(const e of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(e),e instanceof Element){const t=e.getAttribute("slot")||"";if(t.length>0&&n.has(t)){r.has(t)||r.set(t,document.createDocumentFragment()),r.get(t)?.appendChild(e);continue}}i.appendChild(e)}for(const[e,t]of n){const n=r.get(e);n&&t.replaceWith(n)}const s=n.get("");s&&s.replaceWith(i),this.appendChild(t)}!function(e){if(null!==$o())for(const t of e)1===t.nodeType&&Eo(t,Ao)}(Array.from(this.childNodes))}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(e){for(const t of this._layoutChildNodes)t instanceof Element&&(t.querySelectorAll("[data-bind]").forEach(t=>{wo(t,e)}),t.hasAttribute("data-bind")&&wo(t,e))}};function Po(){return document.createElement(Bs.layoutOutlet)}const Oo="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Mo(e,t){(async function(e,t){let n=null,r=null;const i=t.uuid||"",s=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=e.text+s;let l=!1;const a=e=>{e.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",a);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),i=URL.createObjectURL(t);try{n=await(import(i))}catch(e){r=e}finally{URL.revokeObjectURL(i)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await(import(`data:application/javascript;base64,${t}`))}catch(e){await new Promise(e=>setTimeout(e)),Js(function(e,t,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${Oo}`:`loadGuardHandler: failed to import guard script. data: URL error: ${e?.message??String(e)}`+(t?`. Blob URL error: ${t?.message??String(t)}`:"")+`. If this page sets a Content-Security-Policy, see ${Oo}`}(e,r,l),{cause:r??e})}}}finally{document.removeEventListener("securitypolicyviolation",a)}return n&&"function"==typeof n.default?n.default:null})(e,t).then(e=>{e?t.guardHandler=e:t.notifyGuardHandlerLoadFailed()}).catch(e=>{console.error("loadGuardHandler failed:",e),t.notifyGuardHandlerLoadFailed()})}function Lo(e,t){let n=e.get(t.absolutePath);n||(n=[]);for(const e of n)if(!t.testAncestorNode(e)){console.warn(`Duplicate route path detected: '${t.absolutePath}' (defined as '${t.path}')`);break}n.push(t),1===n.length&&e.set(t.absolutePath,n)}async function Io(e,t,n,r){const i=n.length>0?n[n.length-1]:null,s=document.createDocumentFragment(),o=Array.from(t.childNodes);for(const t of o)if(t.nodeType===Node.ELEMENT_NODE){let o=t,l=t;const a=l.tagName.toLowerCase();if(a===Bs.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const s=document.importNode(l,!0);customElements.upgrade(s),s.appendChild(t);const a=s;a.initialize(e,i),Lo(r,a),n.push(a),o=a.placeHolder,l=a}else{if(a===Bs.guardHandler){if(n.length>0){const e=n[n.length-1],t=l.querySelector('script[type="module"]');t&&Mo(t,e)}continue}if("template"===a){s.appendChild(l);continue}if(a===Bs.layout){const e=document.createDocumentFragment();for(const t of Array.from(l.childNodes))e.appendChild(t);const t=document.importNode(l,!0);customElements.upgrade(t),t.appendChild(e);const n=t,r=Po();r.layout=n,o=r,l=t}}const u=await Io(e,l,n,r);l.replaceChildren(),l.appendChild(u),s.appendChild(o)}else s.appendChild(t);return s}async function jo(e){const t=new Map;return await Io(e,e.template.content,[],t)}function Ro(e){return!1!==e.checkVisibility?.()}function Ho(e,t,n,r){const i=function(e,t,n){const r={},i={};let s=!0,o=!1,l=0,a=0;for(;l<e.absoluteSegmentInfos.length;){const t=e.absoluteSegmentInfos[l];if(t.isIndex){l++;continue}if(0===l&&""===t.segmentText&&"static"===t.type){l++;continue}const u=n[a];if(void 0===u){s=!1;break}let c=!1;if("param"===t.type){const e=t.paramType||"any",n=Xs[e].parse(u);void 0!==n&&(t.paramName&&(r[t.paramName]=u,i[t.paramName]=n),c=!0)}else c=null!==t.pattern.exec(u);if(!c){s=!1;break}if("catch-all"===t.type){const e=n.slice(a).join("/");r["*"]=e,i["*"]=e,o=!0;break}l++,a++}let u=!1;return s&&(o||l===e.absoluteSegmentInfos.length&&a===n.length)&&(u=!0),u?{path:t,routes:e.routes,params:r,typedParams:i,lastPath:""}:null}(e,t,n);i&&r.push(i);for(const i of e.routeChildNodes)Ho(i,t,n,r)}function Wo(e,t){const n=e.routeChildNodes,r=[],i=t.split("/"),s=i.filter((e,t)=>!(0===t&&""===e||t===i.length-1&&""===e&&i.length>1));for(const e of n)Ho(e,t,s,r);return r.sort((e,t)=>{const n=e.routes.at(-1),r=t.routes.at(-1),i=n.absoluteSegmentCount-r.absoluteSegmentCount;if(0!==i)return-i;const s=n.absoluteWeight-r.absoluteWeight;return 0!==s?-s:n.childIndex-r.childIndex}),r.length>0?r[0]:null}let zo=null,Do=null;function Uo(){const e=Gs;return 0===e.length?null:(zo===e&&Do||(zo=e,Do=new RegExp(`\\/[^/]+(?:${e.map(e=>e.replace(/\./g,"\\.")).join("|")})$`,"i")),Do)}function Fo(e){let t=e||"/";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=Uo();return n&&(t=t.replace(n,"")),""===t&&(t="/"),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function qo(e,t){let n=e;return""!==t&&(e===t?n="":e.startsWith(t+"/")&&(n=e.slice(t.length))),""===n?"/":n}function Bo(e){let t=e||"";if(!t)return"";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=Uo();return n&&(t=t.replace(n,"")),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),"/"===t?"":t}function Ko(e){if(null!==e.held)return;const t=xo(e),n=new Set(t),r=[...t,...e.childNodeArray];let i=null;for(const s of e.childNodeArray)n.has(s)?i=s:null===s.parentNode||r.some(e=>e!==s&&e.contains(s))||(t.splice(null===i?0:t.indexOf(i)+1,0,s),n.add(s),i=s);const s=document.createDocumentFragment();!function(e,t){const n=t.map(e=>e.parentNode);for(let r=0;r<t.length;r++)t[r].parentNode===n[r]&&e.appendChild(t[r])}(s,t),s.appendChild(e.endMarker),e.held=s}function Go(e){e.clearParams(),Ko(e)}function Vo(e,t){const n={},r={};for(const i of e.paramNames)n[i]=t.params[i],r[i]=t.typedParams[i];e.setParams(n,r);for(const t of e.childNodeArray)if(t.nodeType===Node.ELEMENT_NODE){const n=t;n.querySelectorAll("[data-bind]").forEach(t=>{wo(t,e.typedParams)}),n.hasAttribute("data-bind")&&wo(n,e.typedParams),n.querySelectorAll(Bs.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===Bs.layoutOutlet&&n.assignParams(e.typedParams)}}const Jo=new WeakSet;function Qo(e){const t=e.placeHolder;null!==t.parentNode&&(Jo.has(e)||null!==e.endMarker.parentNode?(Ko(e),t.after(e.held),e.held=null):t.after(...e.childNodeArray,e.endMarker),Jo.add(e))}const Xo=Symbol.for("wcstack.transition-runner");const Yo=new WeakSet,Zo="data-wcs";function el(e,t,n){!Yo.has(e)&&function(e){return e.hasAttribute(Zo)||null!==e.querySelector(`[${Zo}]`)}(e)&&(Yo.add(e),function(e){"complete"===document.readyState?e():window.addEventListener("load",e,{once:!0})}(()=>{var r;null!==$o()||(r=e,No().has(r))||console.warn(`[@wcstack/router] ${t} contains ${Zo} 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 tl(e){for(const t of e.childNodeArray)if(1===t.nodeType){if(t.isConnected){if(Eo(t,Ao))continue}else if(null!==$o())continue;el(t,`<${t.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 nl(e,t){try{let e=null;for(const n of t.routes){const r=await n.guardCheck(t);r&&(e=null===e?r:Object.assign({},e,r))}t.data=e}catch(t){if(t instanceof Qs)return console.warn(`Navigation cancelled: ${t.message}. Redirecting to ${t.fallbackPath}`),queueMicrotask(()=>{e.navigate(t.fallbackPath).catch(e=>{console.error("Fallback navigation failed:",e)})}),!1;throw t}return!0}async function rl(e,t,n,r,i=""){const s=qo(n,e.basename);if(e.isSameMatch(s))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:i,path:s}),!0;let o=Wo(e,s);o||(e.fallbackRoute?o={routes:[e.fallbackRoute],params:{},typedParams:{},path:s,lastPath:r}:Js(`${Bs.router} No route matched for path: ${s}`)),o.lastPath=r,o.search=i;const l=t.lastRoutes,a=await async function(e,t,n){if(!await nl(e,t))return!1;const r=new Set(t.routes),i=new Set(n),s=()=>{for(const e of n)r.has(e)||Go(e);const e=[];for(const n of t.routes)(e.length>0||!i.has(n)||n.shouldChange(t.params))&&(e.push(n),Vo(n,t));let s=!1;for(const t of e){const e=i.has(t);e&&s||Qo(t),s||=e,n.length>0&&!e&&tl(t)}};let o;return 0===n.length?s():o=function(e,t,n){const r=function(e){const t=globalThis[Xo];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}(e);if(null!==r)return r.run(t,{source:e,types:n});t()}("router",s),void 0!==o&&await o,!0}(e,o,l);return!!a&&(e.commitNavigation({params:o.params,typedParams:o.typedParams,routeName:o.routes[o.routes.length-1]?.name??"",data:o.data??null,search:i,path:s}),t.lastRoutes=o.routes,l.length>0&&function(e,t){if("title"===e.announcePolicy){const t=e.a11yRegion;null!==t&&(t.textContent=document.title)}if("heading"===e.focusPolicy){const e=function(e){for(const t of e){if(t.nodeType!==Node.ELEMENT_NODE)continue;const e=t;if(/^H[1-6]$/.test(e.tagName)){if(Ro(e))return e}else for(const t of e.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(Ro(t))return t}return null}(t.routes[t.routes.length-1].childNodeArray);if(null!==e)e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus();else{const e=document.querySelector("[autofocus]");null!==e?e.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(e,o),!0)}function il(){const e=window.navigation;return e?"function"!=typeof e.addEventListener||"function"!=typeof e.removeEventListener?null:e:null}function sl(e){let t=e,n="";const r=t.indexOf("#");r>=0&&(n=t.slice(r),t=t.slice(0,r));let i="";const s=t.indexOf("?");return s>=0&&(i=t.slice(s),t=t.slice(0,s)),{pathname:t,search:i,hash:n}}function ol(e){return"?"===e?"":e}function ll(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}function al(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const ul=Object.freeze({});class cl 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:e=>e.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:e=>e.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=ul;_typedParams=ul;_searchParams=ul;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),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 e=document.createElement("div");e.setAttribute("role","status"),e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",e.style.clipPath="inset(50%)",e.style.whiteSpace="nowrap",this.appendChild(e),this._a11yRegion=e}_normalizePathname(e){return Fo(e)}_normalizeBasename(e){return Bo(e)}_joinInternalPath(e,t){const n=this._normalizeBasename(e);let r=t.startsWith("/")?t:"/"+t;return r=this._normalizePathname(r),n?"/"===r?n+"/":n+r:r}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let e=new URL(document.baseURI).pathname||"/";return"/"===e?"":this._normalizeBasename(e)}get basename(){return this._basename}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(Bs.outlet))return e;const t=document.createElement(Bs.outlet);return this.parentNode?this.parentNode.insertBefore(t,this.nextSibling):document.body.appendChild(t),t}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||Js(`${Bs.router} has no outlet.`),this._outlet}get template(){return this._template||Js(`${Bs.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(e){const t=this._path!==e;this._path=e,t&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:e,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(e){return!!this._hasCommitted&&this._path===e}commitNavigation(e){const t=Object.freeze({...e.params}),n=Object.freeze({...e.typedParams}),r=Ys(e.search),i=e.data??null,s=this._data!==i,o=!Zs(this._params,t),l=this._routeName!==e.routeName,a=!Zs(this._searchParams,r),u=this._path!==e.path;s&&(this._data=i),o&&(this._params=t,this._typedParams=n),l&&(this._routeName=e.routeName),a&&(this._searchParams=r),this._path=e.path,this._hasCommitted=!0,s&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),o&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:e.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(e){this._fallbackRoute=e}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{console.error(`${Bs.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{console.error(`${Bs.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(e){await this._performNavigation(e,!1)}async replace(e){await this._performNavigation(e,!0)}async _performNavigation(e,t){const n=sl(e),r=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,i=r+ol(n.search)+n.hash,s=il();if(s?.navigate){const e=t?s.navigate(i,{history:"replace"}):s.navigate(i);await(e?.finished)}else{t?history.replaceState(null,"",i):history.pushState(null,"",i);const e=this._normalizePathname(r),s=this.isSameMatch(qo(e,this._basename));await rl(this,this.outlet,e,this._path,ol(n.search))&&!s&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(e){return""===this._basename||e===this._basename||e.startsWith(this._basename+"/")}_onNavigateFunc(e){if(!e.canIntercept||e.hashChange||null!==e.downloadRequest)return;const t=new URL(e.destination.url),n=this._normalizePathname(t.pathname);if(!this._isOwnPath(n))return;const r=this.isSameMatch(qo(n,this._basename)),i=r&&("push"===e.navigationType||"replace"===e.navigationType),s=t.search,o=this;e.intercept({handler:async()=>{try{await rl(o,o.outlet,n,o.path,s)}catch(e){throw console.error(`${Bs.router} applyRoute failed:`,e),e}},scroll:i?"manual":"after-transition",focusReset:r||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const e=this._normalizePathname(window.location.pathname);this._isOwnPath(e)&&(await rl(this,this.outlet,e,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=al();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const t=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||t||"/"===n.pathname||Js(`${Bs.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||Js(`${Bs.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await jo(this),s=!e&&this._outlet.hasAttribute(no);if(s||this._outlet.rootNode.appendChild(i),null!==r){const e=this._template.content;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(r)}0===this.routeChildNodes.length&&Js(`${Bs.router} has no route definitions.`),e||this._ensureA11yRegion();const o=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(o),void(this._initialized=!0);if(s){if(await this._hydrateFromSsr(o))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(no);const e=this._outlet.rootNode;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(i)}await rl(this,this.outlet,o,this._path,window.location.search||""),(s||null!==$o())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const t=this.outlet.rootNode,n=new Map;let r=!1;if(this._forEachRoute(e=>{n.has(e.absolutePath)?r=!0:n.set(e.absolutePath,e)}),r)return!1;if(null!==t.querySelector(Bs.layoutOutlet))return!1;const i=new Map,s=new Map,o=new Map,l=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);let a=0;for(;l.nextNode();){const e=l.currentNode,t=e.data;if(a++,t.startsWith(io)){const r=t.slice(15);if(i.has(r)||!n.has(r))return!1;i.set(r,e)}else if(t.startsWith(so)){const r=t.slice(18);if(s.has(r)||!n.has(r))return!1;s.set(r,{comment:e,index:a})}else if(t.startsWith(oo)){const r=t.slice(16);if(o.has(r)||!n.has(r))return!1;o.set(r,{comment:e,index:a})}}if(s.size!==o.size)return!1;const u=[];for(const[e,t]of s){const n=o.get(e);if(!n)return!1;if(n.comment.parentNode!==t.comment.parentNode)return!1;if(n.index<=t.index)return!1;u.push({start:t.index,end:n.index})}for(const e of u)for(const t of u)if(e.start<t.start&&t.start<e.end&&e.end<t.end)return!1;const c=qo(e,this._basename);let h=Wo(this,c);if(!h){if(null===this._fallbackRoute)return!1;h={routes:[this._fallbackRoute],params:{},typedParams:{},path:c,lastPath:this._path}}if(h.lastPath=this._path,h.routes.length!==s.size)return!1;for(const e of h.routes)if(!s.has(e.absolutePath))return!1;const d=new Set;for(const e of this.routeChildNodes)d.add(e.absolutePath);for(const e of h.routes)for(const t of e.routeChildNodes)d.add(t.absolutePath);if(i.size!==d.size)return!1;for(const e of d)if(!i.has(e))return!1;for(const[e,t]of i){const r=n.get(e);t.parentNode.replaceChild(r.placeHolder,t)}for(const e of h.routes){const t=s.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,r=[],i=new Set;let l=t.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const e=l.data;if(e.startsWith(so)){const t=e.slice(18);l=o.get(t).comment.nextSibling;continue}}if(i.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===Bs.link){const e=l.anchorElement;null!==e&&i.add(e)}r.push(l),l=l.nextSibling}}e.adoptChildNodes(r,n)}for(const{comment:e}of s.values())e.remove();this.outlet.removeAttribute(no);for(const e of h.routes)Vo(e,h);return this.outlet.lastRoutes=h.routes,!await nl(this,h)||(this.commitNavigation({params:h.params,typedParams:h.typedParams,routeName:h.routes[h.routes.length-1].name,data:h.data??null,search:window.location.search||"",path:c}),!0)}async _renderForSsr(e){const t=qo(e,this._basename),n=Wo(this,t),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&Js(`${Bs.router} No route matched for path: ${t}`),!r.some(e=>e.hasGuard)){await rl(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(e=>{e.placeHolder.data=`${io}${e.absolutePath}`}),this.outlet.setAttribute(no,"");for(const e of this.outlet.lastRoutes)e.placeHolder.after(document.createComment(`${so}${e.absolutePath}`))}}_offerInitialContentToBinder(){for(const e of this.outlet.lastRoutes)for(const t of e.childNodeArray)t.nodeType===Node.ELEMENT_NODE&&t.isConnected&&Eo(t,Ao)}_forEachRoute(e,t=this){for(const n of t.routeChildNodes)e(n),this._forEachRoute(e,n)}async connectedCallback(){if(function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!ll(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),al()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const e=il();e&&!this._listeningNavigate&&(e.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),e||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(il()?.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 hl=["title","rel","target","download","hreflang","lang","dir"];class dl extends HTMLElement{static get observedAttributes(){return["to",...hl]}_childNodeArray=[];_uuid=Vs();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const e=this.closest(Bs.router);if(e)return this._router=e;const t=this.getRootNode(),n=t.querySelector?.(Bs.router);if(n)return this._router=n;Js(`${Bs.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(e){return Fo(e)}_joinInternalPath(e,t){const n=Bo(e),r=t.startsWith("/")?t:"/"+t,i=this._normalizePathname(r);return n?"/"===i?n+"/":n+i:i}_isInternalTarget(e){return e.startsWith("/")||e.startsWith("?")}_setAnchorHref(e,t){if(this._isInternalTarget(t)){const{pathname:n,search:r,hash:i}=sl(t),s=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);e.href=s+ol(r)+i}else try{e.href=new URL(t).toString()}catch{Js(`[${Bs.link}] Invalid URL in 'to' attribute: ${t}`)}}connectedCallback(){al()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const e=this.nextElementSibling;return null!==e&&"A"===e.tagName&&e.hasAttribute(ro)?e:null}_connect(){this._initialized||this._initialize();const e=this.parentNode;if(!e)return;const t=this._findSsrAnchor();let n;if(null!==t)n=t,n.removeAttribute(ro),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const t=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const e of Array.from(this.attributes))(e.name.startsWith("aria-")||hl.includes(e.name))&&n.setAttribute(e.name,e.value);for(const e of this._childNodeArray)n.appendChild(e);t?e.insertBefore(n,t):e.appendChild(n)}if(this._anchorElement=n,al())return this._updateActiveState(),void n.setAttribute(ro,"");il()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!il()?.navigate&&(this._onClick=async e=>{e.defaultPrevented||0===e.button&&(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||this._isInternalTarget(this._path)&&(e.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){il()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const e=this._anchorElement;e&&(this._onClick&&(e.removeEventListener("click",this._onClick),this._onClick=void 0),e.remove(),this._anchorElement=null);for(const t of this._childNodeArray)e&&t.parentNode===e&&e.removeChild(t);this._router=null}attributeChangedCallback(e,t,n){if("to"===e&&t!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(hl.includes(e)){const t=this._anchorElement;t&&(null===n?t.removeAttribute(e):t.setAttribute(e,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const e=this._normalizePathname(new URL(window.location.href).pathname),{pathname:t}=sl(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t):t);this._anchorElement&&(e===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 fl=[],pl=new Map;let ml=!1;const gl=new WeakMap;class yl 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 e of this._childElementArray)this.removeChild(e)}}connectedCallback(){this._initialize(),ml||(this._captureInitialHead(),ml=!0),fl.push(this),this._reapplyHead()}disconnectedCallback(){const e=fl.indexOf(this);-1!==e&&fl.splice(e,1),this._reapplyHead()}get childElementArray(){return this._initialized||Js("Head component is not initialized yet."),this._childElementArray}_getKey(e){const t=gl.get(e);if(void 0!==t)return t;const n=this._computeKey(e);return gl.set(e,n),n}_computeKey(e){const t=e.tagName.toLowerCase();if("title"===t)return"title";if("meta"===t)return`meta:${e.getAttribute("name")||""}:${e.getAttribute("property")||""}:${e.getAttribute("http-equiv")||""}:${e.hasAttribute("charset")?"charset":""}:${e.getAttribute("media")||""}`;if("link"===t)return`link:${e.getAttribute("rel")||""}:${e.getAttribute("href")||""}:${e.getAttribute("media")||""}:${e.getAttribute("hreflang")||""}`;if("base"===t)return"base";if("script"===t){const t=e.getAttribute("src")||"",n=e.getAttribute("id")||"",r=e.getAttribute("type")||"";return t||n?`script:${t}:${n}:${r}`:`script::${r}:${e.outerHTML.slice(0,100)}`}if("style"===t){const t=e.getAttribute("id")||"",n=e.getAttribute("media")||"";return t?`style:${t}:${n}`:`style::${n}:${e.outerHTML.slice(0,100)}`}return`${t}:${e.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const e=new Map;for(const t of Array.from(document.head.children)){const n=this._getKey(t);e.has(n)||e.set(n,t)}return e}_captureInitialHead(){const e=document.head;for(const t of Array.from(e.children)){const e=this._getKey(t);pl.has(e)||pl.set(e,t.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of fl)for(const n of t._childElementArray)e.add(this._getKey(n));for(const t of pl.keys())e.add(t);const t=this._buildHeadElementMap();for(const n of t.keys())e.add(n);for(const n of e){let e=null;for(let t=fl.length-1;t>=0;t--){const r=fl[t];for(const t of r._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}!e&&pl.has(n)&&(e=pl.get(n).cloneNode(!0));const r=t.get(n)??null;e?(r?r.replaceWith(e):document.head.appendChild(e),t.set(n,e),Eo(e)||el(e,`<${e.tagName.toLowerCase()}> inside <${Bs.head}>`,`<${Bs.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.`)):(r?.remove(),t.delete(n))}}}await void function(e=customElements){e.get(Bs.layout)||e.define(Bs.layout,go),e.get(Bs.layoutOutlet)||e.define(Bs.layoutOutlet,To),e.get(Bs.outlet)||e.define(Bs.outlet,yo),e.get(Bs.route)||e.define(Bs.route,lo),e.get(Bs.router)||e.define(Bs.router,cl),e.get(Bs.link)||e.define(Bs.link,dl),e.get(Bs.head)||e.define(Bs.head,yl)}(void 0);const bl="data-fetchtarget",vl={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let wl=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(e,t,n={}){this.laneKey=e,this.policy=t,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 e;switch(this.policy){case"latest":e=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const t=this._nextOperationId++,n={operationId:t,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:e};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=t;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=t);break;case"overlap":this._activeOperationIds.add(t)}this._inFlightCount+=1,this._attempts.set(t,1);const r=this._makeAttempt(t,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:t,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:r}}retry(e){if(e.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(e.operationId))return null;const t=this._attempts.get(e.operationId);if(void 0===t)return null;const n=t+1;this._attempts.set(e.operationId,n),this._releaseController(e.operationId);const r=this._makeAttempt(e.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:e.operationId,laneKey:this.laneKey,attempt:n}),r}canCommit(e){if(e.ownerGeneration!==this._ownerGeneration)return!1;const t=this._terminal.get(e.operationId);return(void 0===t||"committing"===t)&&this._isEligible(e)}claimTerminal(e,t){return e.ownerGeneration===this._ownerGeneration&&!this._terminal.has(e.operationId)&&!!this._isEligible(e)&&(this._terminal.set(e.operationId,"committing"),this._claimedOutcome.set(e.operationId,t),!0)}claimedOutcome(e){return this._claimedOutcome.get(e.operationId)}finalize(e){const t=e.operationId,n=this._terminal.get(t);if(void 0!==n&&"committing"!==n)return;let r;r="committing"===n?this._claimedOutcome.get(t)??"stale":"stale",this._terminal.set(t,r),this._claimedOutcome.delete(t),this._releaseController(t),this._attempts.delete(t),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(t),void 0!==this._trace&&("stale"===r?this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:t,laneKey:this.laneKey,outcome:r}))}signalOf(e){return this._controllers.get(e.operationId)?.signal}abort(e){this._abortController(e.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const e of this._activeOperationIds)this._abortController(e)}disposeOwner(){this._ownerGeneration+=1;for(const e of Array.from(this._controllers.keys()))this._abortController(e),this._releaseController(e);for(const e of Array.from(this._attempts.keys()))this._terminal.has(e)||this._terminal.set(e,"stale"),this._claimedOutcome.delete(e),this._attempts.delete(e),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(e,t){let n;if(this._withSignal&&"function"==typeof AbortController){const t=new AbortController;this._controllers.set(e,t),n=t.signal}return{operationId:e,attempt:t,signal:n}}_isEligible(e){switch(this.policy){case"latest":return e.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===e.operationId;case"overlap":return this._activeOperationIds.has(e.operationId)}}_advanceBookkeeping(e){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===e&&(this._activeOperationId=void 0);break;case"queue":{const t=this._queue.filter(t=>t.operationId!==e);this._queue.length=0,this._queue.push(...t),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(e)}}_abortController(e){const t=this._controllers.get(e);void 0===t||t.signal.aborted||t.abort()}_releaseController(e){this._controllers.delete(e)}};function _l(e,t){return t.every(t=>"available"===e.availability.get(t))}const $l=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let kl=class e extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:e=>e.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:e=>e.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:e=>e.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 wl("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(e){super(),this._target=e??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 _l(this.platformAssessment,e.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(e,t){const n=new Map,r=t=>{const n=e.get(t);return void 0===n?"unknown":n.probe()?"available":"missing"};let i=!0;for(const e of t.required){const t=r(e);n.set(e,t),"available"!==t&&(i=!1)}let s=!0;for(const e of t.optional??[]){const t=r(e);n.set(e,t),"available"!==t&&(s=!1)}const o=i?s?"ready":"degraded":"idle",l=[...t.required,...t.optional??[]],a=l.some(t=>!0===e.get(t)?.requiresSecureContext),u=l.some(t=>!0===e.get(t)?.requiresUserActivation),c=a?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",h=u?"required":"not-applicable";return{availability:n,permission:t.permission??"not-applicable",readiness:o,activity:t.activity??"inactive",preconditions:{secureContext:c,userActivation:h},epoch:t.epoch??0,lastError:t.lastError}}($l,{required:e.REQUIRED_CAPABILITIES,optional:e.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(e,t,n,r,i){this._commitErrorInfo({code:e,phase:t,recoverable:n,message:r,...void 0===i?{}:{capabilityId:i}})}_commitErrorInfo(e){this._errorInfo!==e&&(this._errorInfo=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:e,bubbles:!0})))}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:e,bubbles:!0}))}_setError(e){this._error!==e&&(this._error=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:e,bubbles:!0})))}_setResponse(e,t,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=e,this._status=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:e,status:t,objectURL:n},bubbles:!0}))}_createObjectURL(e){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(e):null}_revokeObjectURL(e){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(e)}abort(){this._lane.abortActive()}_commitStep(e,t){this._lane.canCommit(e)&&t()}async fetch(t,n={}){if(!t)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const r=this.platformAssessment;if(!_l(r,e.REQUIRED_CAPABILITIES)){const t=e.REQUIRED_CAPABILITIES.find(e=>"available"!==r.availability.get(e));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const i=this._doFetch(t,n);return this._promise=i,i}async _doFetch(e,t){const n=this._lane.begin(),{ticket:r,attempt:i}=n,s=i.signal;this._commitStep(r,()=>this._setLoading(!0)),this._commitStep(r,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:o="GET",body:l=null,contentType:a=null,forceText:u=!1,responseType:c="auto",timeout:h=0}=t;let d=null;h>0&&(d=setTimeout(()=>{if(!this._lane.claimTerminal(r,"timeout"))return;const e=`Request timed out after ${h}ms.`;this._commitStep(r,()=>{this._setErrorInfo("timeout","execute",!0,e),this._setError({name:"TimeoutError",message:e})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),this._lane.abort(r),this._lane.finalize(r)},h));const f={...t.headers??{}};try{a&&!f["Content-Type"]&&(f["Content-Type"]=a);const t={method:o,headers:f,signal:s};"GET"!==o&&"HEAD"!==o&&null!==l&&(t.body=l);const n=await globalThis.fetch(e,t);let i=null;if("HEAD"===o);else if(n.ok)if(u)i=await n.text();else if("blob"===c)i=await n.blob();else if("arrayBuffer"===c)i=await n.arrayBuffer();else if("text"===c)i=await n.text();else if("json"===c)i=await n.json();else{const e=n.headers.get("Content-Type")||"";i=e.includes("application/json")?await n.json():await n.text()}if(!n.ok){const e=await n.text().catch(()=>""),t={status:n.status,statusText:n.statusText,body:e};return this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(t)}),this._commitStep(r,()=>this._setResponse(null,n.status)),this._commitStep(r,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(r,"success"))return null;const h=i instanceof Blob?this._createObjectURL(i):null;return this._commitStep(r,()=>this._setResponse(i,n.status,h)),this._commitStep(r,()=>this._setLoading(!1)),this._value}catch(e){return e&&"AbortError"===e.name?(this._lane.claimTerminal(r,"aborted")&&this._commitStep(r,()=>this._setLoading(!1)),null):this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{const t=String(e?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,t),this._setError(e??{message:t})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),null):null}finally{null!==d&&clearTimeout(d),this._lane.finalize(r)}}},Sl=!1;function Nl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${bl}]`);if(!n)return;const r=n.getAttribute(bl);if(!r)return;const i=customElements.get(vl.fetch),s=document.getElementById(r);if(!(i&&s instanceof i))return;const o=s;o.url&&(e.preventDefault(),o.fetch())}function El(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}const Al=Symbol.for("wcstack.trustedTypes.policy");function Cl(){const e=globalThis[Al];return null===e||"object"!=typeof e?null:e}let xl,Tl=!1;let Pl=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...kl.wcBindable,properties:[...kl.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":e=>({loading:!0===e}),"wcs-fetch:error":e=>({error:null!=e})}),this._core=new kl(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[n,r]of Object.entries(e))this.addEventListener(n,e=>{const n=this.hasAttribute("debug-states");for(const[i,s]of Object.entries(r(e.detail))){try{s?t.add(i):t.delete(i)}catch{}n&&this.toggleAttribute(`data-wcs-state-${i}`,s)}})}get url(){return this.getAttribute("url")||""}set url(e){null==e?this.removeAttribute("url"):this.setAttribute("url",e)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(e){null==e?this.removeAttribute("method"):this.setAttribute("method",e)}get target(){return this.getAttribute("target")}set target(e){null==e?this.removeAttribute("target"):this.setAttribute("target",e)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(e){null==e?this.removeAttribute("response-type"):this.setAttribute("response-type",e)}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(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(e){this._body=e??null}get trigger(){return this._trigger}set trigger(e){if(e){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 e={},t=this.querySelectorAll(vl.fetchHeader);for(const n of t){const t=n.headerName,r=n.headerValue;t&&(e[t]=r)}return e}_isNativeBodyInit(e){return e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||e instanceof ArrayBuffer||ArrayBuffer.isView(e)}_collectBody(e){if(null!==e)return"string"==typeof e||this._isNativeBodyInit(e)?{body:e,contentType:null}:{body:JSON.stringify(e),contentType:"application/json"};const t=this.querySelector(vl.fetchBody);return t?{body:t.bodyContent||null,contentType:t.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const e=this._connectResolve;this._connectResolve=null;const t=this.url;this.isConnected&&!this.manual&&t&&t!==this._lastFetchedUrl?this.fetch().finally(()=>e?.()):e?.()}))}async fetch(){this._lastFetchedUrl=this.url;const e=this._collectHeaders(),t=this._body;this._body=null;const{body:n,contentType:r}=this._collectBody(t);n instanceof FormData&&Object.keys(e).some(e=>"content-type"===e.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 i=await this._core.fetch(this.url,{method:this.method,headers:e,body:n,contentType:r,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==i){const e=document.getElementById(this.target);e&&function(e,t){try{e.innerHTML=function(e){if("string"!=typeof e)return e;const t=Cl(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(t)}catch(e){if(function(){if(void 0!==xl)return xl;if(!("trustedTypes"in globalThis))return xl=!1,xl;try{document.createElement("div").innerHTML="<i></i>",xl=!1}catch{xl=!0}return xl}())return void function(){if(Tl)return;Tl=!0;const e="function"==typeof Cl()?.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'). ${e}\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 e}}(e,i)}return i}attributeChangedCallback(e,t,n){"url"===e&&this._scheduleAutoFetch()}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!El(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",Sl||(Sl=!0,document.addEventListener("click",Nl)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(e=>{this._connectResolve=e})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Ol extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class Ml extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Ll=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(e){this.setAttribute("target",e)}get root(){return this.getAttribute("root")}set root(e){null===e?this.removeAttribute("root"):this.setAttribute("root",e)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(e){this.setAttribute("root-margin",e)}get threshold(){const e=Number(this.getAttribute("threshold")??"0");return Number.isFinite(e)?e:0}set threshold(e){this.setAttribute("threshold",String(e))}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(e){e?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(e=>{e.some(e=>e.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 e=document.getElementById(this.target);e instanceof Pl&&(e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(e=customElements){e.get(vl.fetch)||e.define(vl.fetch,Pl),e.get(vl.fetchHeader)||e.define(vl.fetchHeader,Ol),e.get(vl.fetchBody)||e.define(vl.fetchBody,Ml),e.get(vl.infiniteScroll)||e.define(vl.infiniteScroll,Ll)}(void 0);const Il="data-storagetarget",jl={storage:"wcs-storage"},Rl="wcs-storage:value-changed",Hl="wcs-storage:loading-changed",Wl="wcs-storage:error",zl="wcs-storage:error-info-changed",Dl="wcs-storage:trigger-changed";let Ul=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Rl,semantics:"state",getter:e=>e.detail},{name:"loading",event:Hl,semantics:"state"},{name:"error",event:Wl,semantics:"state"},{name:"errorInfo",event:zl,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(e){super(),this._target=e??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(e){Object.is(e,this._value)||this._setValue(e)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(e){this._key=String(e)}get type(){return this._type}set type(e){"local"===e||"session"===e?this._type=e:this._setError({operation:"type",message:`Invalid storage type: "${e}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent(Hl,{detail:e,bubbles:!0}))}_setError(e,t){this._error!==e&&(this._error=e,this._commitErrorInfo(null===e?null:function(e,t){return void 0===t?{code:"invalid-argument",phase:"start",recoverable:!1,message:e.message}:"QuotaExceededError"===t?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:e.message}:"SecurityError"===t?{code:"not-allowed",phase:"execute",recoverable:!1,message:e.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:e.message}}(e,t)),this._target.dispatchEvent(new CustomEvent(Wl,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(zl,{detail:e,bubbles:!0}))}_toStorageError(e,t){return{operation:e,message:t instanceof Error?t.message:String(t)}}_errName(e){return e instanceof Error?e.name:""}_setValue(e){this._value=e,this._target.dispatchEvent(new CustomEvent(Rl,{detail:e,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const e=this._getStorage().getItem(this._key);if(null===e)this._setValue(null);else try{this._setValue(JSON.parse(e))}catch{this._setValue(e)}return this._setLoading(!1),this._value}catch(e){return this._setError(this._toStorageError("load",e),this._errName(e)),this._setLoading(!1),null}}save(e){if(this._key){this._setLoading(!0),this._setError(null);try{const t=this._getStorage();null==e?(t.removeItem(this._key),this._setValue(null)):"string"==typeof e?(t.setItem(this._key,e),this._setValue(e)):(t.setItem(this._key,JSON.stringify(e)),this._setValue(e)),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("save",e),this._errName(e)),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(e){this._setError(this._toStorageError("remove",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const e=++this._gen;this._storageListener=t=>{if(e===this._gen&&t.key===this._key&&"session"!==this._type)if(this._setError(null),null===t.newValue)this._setValue(null);else try{this._setValue(JSON.parse(t.newValue))}catch{this._setValue(t.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},Fl=!1;function ql(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Il}]`);if(!n)return;const r=n.getAttribute(Il);if(!r)return;const i=customElements.get(jl.storage),s=document.getElementById(r);i&&s instanceof i&&(e.preventDefault(),s.save())}function Bl(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}let Kl=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Ul.wcBindable,properties:[...Ul.wcBindable.properties,{name:"trigger",event:Dl,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 Ul(this),this._internals=this._initInternals(),this._wireStates({[Hl]:e=>({loading:!0===e}),[Wl]:e=>({error:null!=e})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[n,r]of Object.entries(e))this.addEventListener(n,e=>{const n=this.hasAttribute("debug-states");for(const[i,s]of Object.entries(r(e.detail))){try{s?t.add(i):t.delete(i)}catch{}n&&this.toggleAttribute(`data-wcs-state-${i}`,s)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(e){this.setAttribute("key",e)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(e){this.setAttribute("type",e)}get value(){return this._core.value}set value(e){this.manual?this._core.value=e:(this._syncCore(),this._core.save(e))}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(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(e){if(e){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(Dl,{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(e,t,n){this.isConnected&&("key"===e&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===e&&this._syncCore())}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!Bl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",Fl||(Fl=!0,document.addEventListener("click",ql)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(e=customElements){e.get(jl.storage)||e.define(jl.storage,Kl)}(void 0);const Gl="*",Vl="vanilla",Jl={loaders:{[Vl]:{postfix:".js",loader:async function(e){return(await(import(`${e}`))).default}},[Gl]:Vl},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function Ql(e){if(e.startsWith("@components/")){if(e.endsWith("/")){const t=e.slice(12,e.length-1),[n,r]=t.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:r??null,isNameSpaced:!0}}{const t=e.slice(12),[n,r]=t.split("|",2),[i,s]=(r??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:i||null,extends:s||null,isNameSpaced:!1}}}return null}function Xl(e,t,n){let r;if(null===t||t===Gl||""===t){let t=null;const i=[];for(const[e,t]of Object.entries(n)){if(e===Gl)continue;const r="string"==typeof t?n[t]:t;"string"!=typeof r&&i.push(r)}i.sort((e,t)=>t.postfix.length-e.postfix.length);for(const n of i)if(e.endsWith(n.postfix)){t=n;break}t?r=t:(r=n[Gl],"string"==typeof r&&(r=n[r]))}else if(r=n[t],!r)throw new Error("Loader not found: "+t);if("string"==typeof r)throw new Error("Loader redirection is not supported here");return r}const Yl=new Set,Zl=new Map;let ea=new WeakMap;function ta(e){if(e===globalThis.customElements)return Zl;let t=ea.get(e);return void 0===t&&(t=new Map,ea.set(e,t)),t}const na=new Map;async function ra(e,t,n){try{if(customElements.get(t))return;const r=await n.loader(e.key);if(null!==r){let n=e.extends;if(null===n&&(n=function(e){for(const[t,n]of na)if(e.prototype instanceof t)return n;return null}(r)),customElements.get(t))return;null===n?customElements.define(t,r):customElements.define(t,r,{extends:n})}}catch(e){Yl.has(t)||(console.error(`Failed to eager load component '${t}':`,e),Yl.add(t))}}function ia(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined||"function"!=typeof t.define?null:t}function sa(e){const t=e.tagName.toLowerCase();let n,r;if(t.includes("-"))n=t,r=null;else{const i=e.getAttribute("is");if(null===i)throw new Error("Custom element without a dash or 'is' attribute found: "+t);if(!i.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+t);n=i,r=t}return{name:n,extends:r}}"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(([e,t])=>{void 0!==e&&na.set(e,t)});const oa=new WeakSet,la=new WeakSet;async function aa(e,t,n){e.shadowRoot&&(oa.has(e)||await async function(e,t,n){oa.add(e),await da(e.shadowRoot,t,n)}(e,t,n))}async function ua(e,t,n,r){const i=function(e,t){for(const[n,r]of Object.entries(t))if(e.startsWith(n+"-"))return r;return null}(e.name,n);if(null===i)throw new Error("No matching namespace found for lazy loaded component: "+e.name);const s=ta(r),o=s.get(e.name);if(void 0!==o)return void await o;const l=async function(e,t,n,r){try{let i;try{i=Xl("",n.loaderKey,t.loaders)}catch(t){throw new Error("Loader redirection is not supported for lazy loaded components: "+e.name)}const s=e.name.slice(n.prefix.length+1);if(""===s)throw new Error("Invalid component name for lazy loaded component: "+e.name);const o=n.key+s+i.postfix;if(r.get(e.name))return;const l=await i.loader(o);if(null===l)throw new Error("Loader returned null for component: "+e.name);if(r.get(e.name))return;null===e.extends?r.define(e.name,l):r.define(e.name,l,{extends:e.extends})}catch(t){console.error(`Failed to lazy load component '${e.name}':`,t),Yl.add(e.name)}}(e,t,i,r);s.set(e.name,l);try{await l}finally{s.delete(e.name)}}async function ca(e,t,n,r){const i=[],s=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT,e=>(e=>(e instanceof Element&&(e.tagName.includes("-")||e.getAttribute("is")?.includes("-")))??!1)(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;s.nextNode();)i.push(s.currentNode);const o=[],l=new Set;for(const e of i){const i=sa(e);void 0===r.get(i.name)?(la.has(e)||(la.add(e),r.whenDefined(i.name).then(async()=>{await aa(e,t,n)})),l.has(i.name)||Yl.has(i.name)||(l.add(i.name),o.push(i))):await aa(e,t,n)}let a=0;for(const e of o)await ua(e,t,n,r),a++;return a}async function ha(e,t,n,r){for(;await ca(e,t,n,r)>0;);}async function da(e,t,n){if(0===Object.keys(n).length)return null;const r=function(e=null){if(null!=e){const t=e.customElementRegistry;if(null===t)return null;if(void 0!==t)return ia(t)}return ia(globalThis.customElements)}(e);if(null===r)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await ha(e,t,n,r)}catch(e){throw new Error("Failed to lazy load components: "+e)}if(!t.observable)return null;const i=new MutationObserver(async()=>{try{await ha(e,t,n,r)}catch(e){console.error("Failed to lazy load components: "+e)}});return i.observe(e,{childList:!0,subtree:!0}),i}class fa extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),fa._instance)throw new Error(`${Jl.tagNames.autoloader} can only be instantiated once.`);fa._instance=this;const e=function(){const e={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(t=>{try{const n=JSON.parse(t.innerHTML);n.imports&&(e.imports=Object.assign(e.imports,n.imports))}catch(e){throw new Error("Failed to parse importmap JSON: "+e)}}),Object.keys(e.imports).length>0?e:null}();if(e){const{prefixMap:t,loadMap:n}=function(e){const t={},n={};for(const[r,i]of Object.entries(e.imports)){const e=Ql(r);null!==e&&(e.isNameSpaced?t[e.prefix]=e:n[e.tagName]=e)}return{prefixMap:t,loadMap:n}}(e);this._prefixMap=t,async function(e,t){const n=[];for(const[r,i]of Object.entries(e)){let s;try{s=Xl(i.key,i.loaderKey,t)}catch(e){throw new Error("Loader redirection is not supported for eager loaded components: "+r)}n.push(ra(i,r,s))}await Promise.all(n)}(n,Jl.loaders).catch(e=>{console.error("Failed to eager load components:",e)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(e=>document.addEventListener("DOMContentLoaded",()=>e(),{once:!0})),this._observer=await da(document,Jl,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,fa._instance===this&&(fa._instance=null)}}!function(e=customElements){e.get(Jl.tagNames.autoloader)||e.define(Jl.tagNames.autoloader,fa)}(void 0);
|
|
1
|
+
var e=class{constructor(e,n,r){this.h=[],this.getter=null,this.oe=null,this.de=!1,this.G=[],this.$e=[],this.ct=null,this.F=-1,this.J=t,this.Fe=null,this.Pt=null,this.Tt=null,this.q=null,this.At=new Set,this.t=e,this.d=r,this.s=n;let i=null===r?[null]:r.f.slice(),s="*"===n;s&&i.push(r),this.n=i.length-1,this.U=s?[]:null===r?[n]:[...r.U,n],this.f=i}jn(e){this.At.has(e)||(this.At.add(e),this.G.push(e),e.$e.push(this))}Po(){this.getter=null,this.oe=null,this.F=-1,this.J=t,this.G.length=0,this.At.clear(),this.$e.length=0,this.ct=null,this.Fe=null,this.Pt=null,this.Tt=null,this.q=null}Q(e){let t=this;for(;null!==t;){if(t===e)return!0;t=t.d}return!1}},t=Symbol("unset"),n=Symbol("dirty"),r=Symbol("failed"),i=class{constructor(e=null){this.Ft=new Map,this.Ln=e}Ot(e){return this.Ft.get(e)}get(t){let n=this.Ft.get(t);if(void 0!==n)return n;let r=t.lastIndexOf("."),i=r<0?null:this.get(t.slice(0,r));return n=new e(t,t.slice(r+1),i),this.Ln?.(n),this.Ft.set(t,n),i&&i.h.push(n),n}all(){return this.Ft.values()}},s=new Map;function o(e){let t=s.get(e);if(void 0!==t)return t;let n=!0,r=e.split("."),i=[];for(let e=0;e<r.length;e++){let t=r[e],s=t.charCodeAt(0);e>0&&s>=48&&s<=57?(n=!1,i.push(Number(t)),r[e]="*"):"*"===t&&i.push(-1)}if(!n)return{o:r.join("."),indexes:i};let o={o:e,indexes:null};return s.set(e,o),o}var l=class{constructor(e,t,n){this.ut=null,this.$=null,this.fe=null,this.q=null,this.h=null,this.y=!0,this.l=e,this.b=t,this.T=n}},a=class{constructor(e,t){this.C=null,this.u=[],this.$=null,this.L=null,this.Z=!1,this.Ct=!1,this.dt=!1,this.o=e,this.re=t,this.n=e.n+1}},u=[],c={};function h(e,t){return null==e?t:(...n)=>{e(...n),t(...n)}}function d(e,t,n){return null==t?n:(...r)=>{let i=t(...r);return e(i)?i:n(...r)}}var f=e=>!0===e,p=e=>void 0!==e,m=e=>null!=e,g=new Set;function y(e){let t=e.$features;if(null!=c.jt&&Array.isArray(t)){let e=t.filter(e=>!g.has(e));if(e.length>0)return c.jt(e)}}function b(e,t){if(!g.has(e))throw new Error(`[@wcstack/state] [wcs/feature-not-installed] ${t} needs the add-on @wcstack/state/features/${e}`)}function v(e,t,n){throw new Error(`[@wcstack/state] ${e}${c.Ao?.(e,t,n)??""}`)}var w=["","binding-syntax","template-syntax","binding-path-missing","binding-type-expectation","filter-unknown","filter-arity","getter-cycle","getter-depth-exceeded","index-arity","index-param-range","recursion-unsupported","token-misconfigured","token-undeclared","wildcard-rank","spread-no-bindable","declaration-alias","name-alias"],_=e=>{let t=w[e/100|0];return t?`[wcs/${t}] `:""};function $(e,t=[]){return c.Fo?.(e,t)??`${_(e)}#${e}${t.map(e=>` ${"string"==typeof e?JSON.stringify(e):String(e)}`).join("")}`}function k(e,t,n,r){v($(e,t),n,r)}var S=class{constructor(e){this.ft=new Set,this.name=e}get size(){return this.ft.size}subscribe(e){return this.ft.add(e),()=>{this.ft.delete(e)}}unsubscribe(e){return this.ft.delete(e)}emit(...e){let t=[];for(let n of this.ft)try{t.push(n(...e))}catch(e){t.push(void 0),console.error(`[@wcstack/state] ${$(17,[this.name])}`,e)}return t}};function N(e,t,n){if(void 0===e)return[];Array.isArray(e)||k(18,[t]);let r=new Set;for(let i of e)("string"!=typeof i||""===i)&&k(19,[t]),i===n&&k(20,[t,i,n]),r.has(i)&&k(21,[t,i]),r.add(i);return e}var A=Symbol.for("wcstack.transition-runner");function E(e){let t=globalThis[A];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run||"function"!=typeof t.accepts||!t.accepts(e)?null:t}function C(e,t,n){let r=E(e);if(null!==r)return r.run(t,{source:e,types:n});t()}var x="else",T="eventToken",P=/^\$[1-9]\d{0,2}$/,O=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function M(e){let t=[],n=[],r="",i=null,s=!1,o=-1,l=-1,a=e=>{let i=function(e,t,n){let r=-1===t?e.length:t,i=-1===n?0:n;return e.slice(r-e.slice(0,r).trimStart().length,i+e.slice(i).trimEnd().length)}(r,o,l);(!e||i||s)&&(t.push(i),n.push(function(e,t){return t?e:"true"===e||"false"!==e&&("null"===e?null:O.test(e)?Number(e):e)}(i,s))),r="",s=!1,o=-1,l=-1};for(let t=0;t<e.length;t++){let n=e[t];i?n===i?i=null:(-1===o&&(o=r.length),r+=n,l=r.length):'"'===n||"'"===n?(i=n,s=!0):","===n?a():r+=n}return null!==i&&k(107,[i,e]),a(!0),{args:t,literals:n}}var L=e=>e.trim();function I(e,t){let n=[],r=null;for(let i=0;i<e.length;i++){let s=e[i];null!==r?s===r&&(r=null):"'"===s||'"'===s?r=s:s===t&&n.push(i)}return n}var j=(e,t)=>I(e,t)[0]??-1;function R(e,t){let n=[],r=0;for(let i of I(e,t))n.push(e.slice(r,i)),r=i+1;return n.push(e.slice(r)),n}function H(e,t,n){let r=j(e,"|");if(-1===r)return[e.trim(),[]];let i=e.slice(r+1).trim(),s=n.get(i);return void 0===s&&(s=function(e,t,n){let r=n??e.join("|");return e.map(e=>{let n=j(e,"("),i=(e=>I(e,")").pop()??-1)(e);if(-1===i&&(i=e.lastIndexOf(")")),-1!==n&&-1===i&&k(108,[e]),-1!==i&&-1===n&&k(109,[e]),-1!==i&&i<n&&k(110,[e]),-1!==i&&e.slice(i+1).trim().length>0){let t=e.slice(i+1).trim();k(111,[e,t])}let s=(-1===n?e:e.substring(0,n)).trim();if(0===s.length&&k(112,[r]),s.includes("#")){let[,e]=s.split("#");k("input"===t?113:114,[s,e])}return-1===n?{Bn:s,args:[],literals:[]}:{Bn:s,...M(e.substring(n+1,i))}})}(R(i,"|").map(L),t,e),n.set(i,s)),[e.slice(0,r).trim(),s]}var W=new Map;function z(e){k(1101,[e])}function D(e){let[t,n]=H(e,"output",W);t.includes("@")&&k(32,[t]);let r=t,i=r.startsWith("."),s=i?r.slice(1):r;return(s.length>0&&s.split(".").some(e=>0===e.length)||!i&&0===s.length)&&k(119,[e]),function(e){e.includes("**")&&z(e);let t=e.split(".").length;t>512&&k(117,[e,t])}(r),{Je:r,Qe:n}}var U=[["$streams","$stream"],["$updatedCallback","$renderedCallback"]],F=[["$watch","temporal"],["$stream","temporal"],["$listKeys","list-keys"],["$recursion","recursion"]],q=["enableMustache","sameValueGuard","enableDirectionalInitialSync"];function B(e){return e.includes("**")&&z(e),e}var K=0;function G(e,t,n){let r=e.get(t);return void 0===r&&e.set(t,r=n()),r}var V=()=>new Set,J=()=>[];function Q(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}function X(e,t){return e===t||e!=e&&t!=t}function Y(e,t,n){let r=e.q?.get(t);void 0!==r&&r.delete(n)&&0===r.size&&e.q.delete(t)}function Z(e,t){for(let n=0;n<t.length;n++){if(null==e)return;e=e[t[n]]}return e}function ee(e,t){for(;null!==e&&e.l.n>t;)e=e.l.re;return null!==e&&e.l.n===t?e:null}function te(e,t,n){let r=ee(e,n);return null!==r&&r.l.o===t.f[n]?r:null}var ne=class{constructor(e,t){this.Oe=0,this.c=null,this.Ce=0,this.pt=new Set,this.Ze=new Map,this.Dn=Symbol("wcs.block"),this.element=null,this.mt=[],this.Ie=null,this.Mn=[],this.Mt=0,this.K=null,this.ee=new Map,this.ie=new Map,this.je=[],this.Le=[],this.Be=[],this.ht=!1,this.dn=!1,this.Wt=new WeakMap,this.M=0,this._t=0,this.fn=!1,this.Ht=!1,this.Vt=!1,this.xe=0,this.Wn=()=>{this.M=0,this.fn=!1},this._n=()=>{this.xe--},this.rp=null,this.rr=null,this.Oo=()=>this.Ut(),this.Co=(e,t)=>e(this.proxy,...t),this.Hn=[],this.Io={$untracked:e=>{let t=this.K;if(null===t)return e();t.pe++;try{return e()}finally{t.pe--}},$eqIndex:(e,t=1)=>{let n=ee(this.c,t);null===n&&k(7,[e]);let r=this.o(e);if(null!==r.getter||r.de)return this.watchIndex(t),n.b===this.read(r,null);let i=this.K;if(null!==i){let e=i.getter,n=r.Fe??(r.Fe=[]);if(!n.some(n=>n.getter===e&&n.Vn===t)){n.push({getter:e,Vn:t});let i=e.f[t];(i.Pt??(i.Pt=[])).push({source:r,getter:e})}}return n.b===this.v(r,null)},$eq:(e,t)=>this.eq(e,t),$eqPath:(e,t)=>{let n=this.o(t);return this.eq(e,this.v(n,ee(this.c,n.n)))},$dependOn:e=>{this.resolve(B(e),this.c),null!==this.K&&0===this.K.pe&&this.Un(this.rp,this.rr,this.K)},$getAll:(e,t)=>this.getAll(e,t),$setAll:(e,t,n,r)=>this.pn(e,t,n,r),$resolve:(...e)=>{let t=B(e[0]),n=e[1]??[],r=this.o(t);this.mn("$resolve",t,r,n,!0);let i=this.qn(r,n,null);if(e.length<3)return this.read(r,i);this.P(r,i,e[2])},$postUpdate:e=>{this.resolve(B(e),this.c);let t=this.rp,n=this.rr;"*"===t.s&&null!==n&&(n.T=n.l.C[n.b],this.R.qt(n)),this.hn(t,n),null!==n&&this.Kn(n,t,void 0,n.T,!1),0===t.n&&this.zn(t,void 0,void 0,!0),this.Kt(t,n,void 0,void 0,!1)}},this.R=t,this.B=new i(e=>this.et(e)),this.Xn(e);let n=this,r={getOwnPropertyDescriptor(e,t){let r=Reflect.getOwnPropertyDescriptor(n.target,t);return r&&(r.configurable=!0),r},get(e,t,r){let i=n.target;if("symbol"==typeof t)return Reflect.get(i,t);if(36===t.charCodeAt(0))return n.zt(t);if(t.indexOf(".")<0){let e=n.B.Ot(t);if(void 0===e||null===e.getter){let e=i[t];if("function"==typeof e)return r===n.proxy&&n.W?.(e)||e}if(void 0!==e&&0===e.n)return n.read(e,null)}return n.resolve(t,n.c),n.read(n.rp,n.rr)},set:(e,t,r)=>"symbol"==typeof t?Reflect.set(n.target,t,r):(n.resolve(B(t),n.c),n.P(n.rp,n.rr,r),!0)};for(let e of["has","ownKeys","deleteProperty","defineProperty","getPrototypeOf"])r[e]=(t,...r)=>Reflect[e](n.target,...r);this.proxy=new Proxy({},r)}o(e){return this.B.get(e)}Yn(e){let t=new Set;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n)){if(t.has(e))continue;t.add(e);let r=Object.getOwnPropertyDescriptor(n,e);if(void 0===r.get&&void 0===r.set)continue;let i=this.o(e);i.getter=r.get??null,i.oe=r.set??null,null!==i.getter&&i.n>0&&(i.F=this.Oe++)}for(let e of this.B.all())this.et(e)}et(e){e.t.includes("**")&&z(e.t),("__proto__"===e.s||"prototype"===e.s)&&k(120,[e.t]);let t=e.d;e.de=null!==t&&"*"!==e.s&&t.n===e.n&&(null!==t.getter||t.de),null===e.getter&&this.jo(e)}jo(e){let t=e.t,n=e.s;if(P.test(n))e.getter=function(){return this[n]};else{let r=t.split("."),i=r.findIndex((e,t)=>t>0&&e.charCodeAt(0)>=48&&e.charCodeAt(0)<=57);if(i<0||r.indexOf("*",i)>=0)return;e.getter=()=>(this.resolve(t,this.c),this.rp!==e?this.read(this.rp,this.rr):this.read(e.d,this.c)?.[n]),e.oe=r=>{if(this.resolve(t,this.c),this.rp!==e)return this.P(this.rp,this.rr,r);let i=this.read(e.d,this.c);null==i&&k(4,[t,i]),i[n]=r}}e.n>0&&(e.F=this.Oe++)}De(e,t){let n=null===e?this.ee:e.h??=new Map,r=n.get(t);return void 0===r&&n.set(t,r=new a(t,e)),this.z(r),r}Gn(e){try{this.z(e)}catch(t){this.Xt(t,e.o.t,e.$?.S??null,"for")}}z(e){let t=this.v(e.o,e.re);if(t===e.C)return;this.Jn(e);let n=function(e,t,n){let r=Array.isArray(t)?t:u;if(r===e.C)return null;let i=e.u,s=r.length,o=i.length,a=new Array(s),c=0;for(;c<s&&c<o&&i[c].T===r[c];)a[c]=i[c],c++;let h=o-1,d=s-1;for(;h>=c&&d>=c&&i[h].T===r[d];)a[d]=i[h],h--,d--;if(c>h)for(let t=c;t<=d;t++)a[t]=new l(e,t,r[t]);else if(c>d)for(let e=c;e<=h;e++)n.It(i[e]);else{let t=new Map;for(let e=c;e<=h;e++){let n=i[e],r=t.get(n.T);void 0===r?t.set(n.T,n):Array.isArray(r)?r.push(n):t.set(n.T,[r,n])}for(let n=c;n<=d;n++){let i,s=r[n],o=t.get(s);void 0!==o&&(Array.isArray(o)?(i=o.shift(),0===o.length&&t.delete(s)):(i=o,t.delete(s))),a[n]=i??new l(e,n,s)}for(let e of t.values())if(Array.isArray(e))for(let t of e)n.It(t);else n.It(e)}for(let e=c;e<s;e++){let t=a[e];t.b!==e&&(t.b=e,n.To(t))}return e.u=a,e.C=r,i}(e,t,this);if(null===n)return;if(e.C===t){let n=G(this.Wt,t,J);if(n.push(e),n.length>1)for(let e of n)e.dt=!0}c.Yt?.(this,e,n),(null!==e.$||null!==e.L)&&!e.Z&&(e.Z=!0,this.Le.push(e),this.Re());let r=e.o.Pt;if(null!==r)for(let{source:t,getter:i}of r){let r=this.v(t,null),s=n[r],o=e.u[r];s!==o&&(void 0!==s&&s.y&&this.gn(i,s),void 0!==o&&this.gn(i,o))}}To(e){this.R.Lo(this,e)}It(e){e.y=!1;let t=e.q;if(null!==t){for(let e of t)Y(e.source,e.key,e.sub);e.q=null}if(null!==e.h)for(let t of e.h.values()){this.Jn(t);for(let e of t.u)this.It(e)}}Jn(e){let t=this.Wt.get(e.C);void 0!==t&&(t.splice(t.indexOf(e)>>>0,1),e.dt=!1,1===t.length&&(t[0].dt=!1))}resolve(e,t){let n=o(e),r=this.rp=this.o(n.o),i=n.indexes;this.rr=0===r.n?null:null===i?te(t,r,r.n):this.qn(r,i,t,e)}qn(e,t,n,r){let i=null;for(let s,o=1,l=0;o<=e.n;o++){let a=e.f[o],c=this.De(i,a),h=t[l++];if(h<0)h=te(n,e,o)?.b??-1;else if(r&&c.C===u&&Object(s=this.v(a,i))===s){let t=e.t.split("."),n=a.t.split(".").length;t[n]=r.split(".")[n],e=this.o(t.join(".")),o--;continue}if(i=c.u[h]??null,null===i)break}return this.rp=e,i}yt(e,t){return 0===e.n?Z(this.target,e.U):null===t?void 0:Z(t.T,e.U)}read(e,t){let n=this.K;if(null!==n&&0===n.pe&&this.Un(e,t,n),null!==e.getter)return this.R.Bo(this,e,t);if(e.de){let n=this.read(e.d,t);return n?.[e.s]}return null===e.d&&!(e.s in this.target)&&!this.pt.has(e.s)&&"then"!==e.s&&"toJSON"!==e.s&&k(301,[e.t],e.s,Object.keys(this.target)),this.yt(e,t)}v(e,t){let n=this.K;if(null===n)return this.read(e,t);n.pe++;try{return this.read(e,t)}finally{n.pe--}}Un(e,t,n){let r=n.getter;e.jn(r),e.n>0&&r.n>0&&ee(t,Math.min(e.n,r.n))!==ee(n.r,Math.min(e.n,r.n))&&(r.ct??(r.ct=new Set)).add(e)}Do(e,t){for(let n=0;n<this.Mt;n++){let r=this.Mn[n];r.getter===e&&r.r===t&&k(701,[e.t])}this.Mt>=128&&k(801,[e.t]);let n=this.Mt++;this.Ce++;let r=this.Mn[n]??={getter:e,r:t,pe:0,Me:0};r.getter=e,r.r=t,r.pe=0,r.Me=++K;let i=this.K;this.K=r;let s=this.c;this.c=t;try{return e.getter.call(this.proxy)}finally{this.Ce--,this.Mt--,this.K=i,this.c=s,r.r=null}}watchIndex(e){let t=this.K;if(null!==t&&0===t.pe){let n=t.getter,r=n.f[e];if(r){let e=r.Tt??(r.Tt=[]);e.includes(n)||e.push(n)}}}zt(e){let t=e.charCodeAt(1);if(t>=48&&t<=57){let n=2===e.length?t-48:P.test(e)?+e.slice(1):0;return(n<1||n>128)&&k(1001,[e]),this.watchIndex(n),ee(this.c,n)?.b}let n=this.Io[e];if(void 0!==n)return n;switch(e){case"$trackDependency":return k(1701,[e,"$dependOn"]);case"$untrackDependency":return k(1701,[e,"$untracked"]);case"$stateElement":return this.element;case"$command":return this.commands}return c.zt?.(this,e)}eq(e,t){this.resolve(e,this.c);let n=this.rp,r=this.rr;if(null!==n.getter||n.de||n.n>0)return X(this.read(n,r),t);let i=this.K;return null!==i&&0===i.pe&&this.Mo(n,t,i),X(this.v(n,null),t)}Mo(e,t,n){let r=n.getter,i=n.r,s=null===i?this.Hn:i.q??(i.q=[]);for(let i=0;i<s.length;i++){let o=s[i];if(o.sub.getter===r&&o.source===e){if(X(o.key,t))return void(o.Me=n.Me);o.Me!==n.Me&&(Y(e,o.key,o.sub),s.splice(i--,1))}}let o={getter:r,r:i};G(e.q??=new Map,t,V).add(o),s.push({source:e,key:t,sub:o,Me:n.Me})}zn(e,t,n,r){this.Gt(e,i=>{let s=i.q;if(null===s&&null===i.Fe)return;let o=i===e?[]:i.t.slice(e.t.length+1).split("."),l=Z(t,o),a=Z(n,o);if(null!==i.Fe&&this.Wo(i,l,a,r),null!==s)for(let e of r?s.keys():[l,a]){let t=s.get(e);if(void 0!==t)for(let n of t)null===n.r||n.r.y?this.R.me(this,n.getter,n.r):Y(i,e,n)}})}P(e,t,n,r=!1,i=!1){if(this.Ce>0&&k(8),i||this.xe>0?this.Ht=!0:this.Vt=!0,c.Pe?.(this,e,t,n,i))return;if(null!==e.oe){try{this.yn(e.oe,t,[n])}finally{this.Kt(e,t,void 0,void 0,!1)}return}null!==e.getter&&k(2,[e.t]),e.n>0&&null===t&&k(3,[e.t]);let s=e.de?this.v(e,t):this.yt(e,t);if(r||!this.Bt||!Object.is(s,n)||Object(n)===n){if("*"===e.s){let e=t;e.l.C[e.b]=n,e.T=n,this.R.qt(e)}else{let r=1===e.U.length?0===e.n?this.target:t.T:this.v(e.d,t);null==r&&k(4,[e.t,r]),r[e.s]=n}this.wn(e,t),null!==t&&this.Kn(t,e,s,n),0===e.n&&this.zn(e,s,n),this.Kt(e,t,s,n,!0)}}Qn(e){return(this.Wt.get(e.C)??[]).filter(t=>t.C===e.C&&(null===t.re||t.re.y))}Kn(e,t,r,i,s=!0){let o=e.l;if(!o.dt&&null===o.o.getter&&!o.o.G.length)return;let l=e.T,a=t.t.slice(o.o.t.length+2),u=(t,n)=>{if(void 0===n||n===e)return;let o=this.o(`${t.o.t}.*${a}`);""===a&&(n.T=i,this.R.qt(n)),s?this.wn(o,n):this.hn(o,n),this.Kt(o,n,r,i,s)};for(let t of this.Qn(o))u(t,t.u[e.b]);if(""===a)return;let c=new Set([o.C]),h=e=>Array.isArray(e)&&e.includes(l),d=(e,t)=>{if(!c.has(e)&&c.add(e))for(let t of this.Wt.get(e)??[])for(let e of t.u)e.T===l&&u(t,e);for(let r of t){let t=r.J,i=t===n;i&&(t=this.ee.get(r)?.C),(i||h(t))&&!c.has(r.G)&&c.add(r.G)&&(!i&&t!==e&&this.R.me(this,r,null),d(t,r.G))}},f=e=>{for(let t of e.$e)if(!c.has(t)&&c.add(t))if(null!==t.getter)f(t);else if(!t.de){let e=this.yt(t,null);h(e)&&d(e,t.G)}};null!==o.o.getter?f(o.o):d(o.C,o.o.G)}hn(e,t){this._o(e,t,e=>{this.z(e);for(let t of e.dt?this.Qn(e):[e]){let e=this.o(`${t.o.t}.*`);for(let n of t.u)this.wt(e,n),this.hn(e,n)}})}wn(e,t){let n=null===t?this.ee:t.h;if(null!==n)for(let t of n.values())t.o.Q(e)&&this.z(t)}_o(e,t,n){let r=null===t?this.ee:t.h;if(null!==r)for(let t of r.values())t.o.Q(e)&&n(t)}Wo(e,t,n,r){for(let{getter:i,Vn:s}of e.Fe)this.Zn(i.f[s],e=>{for(let s of r?e.u.keys():[t,n]){let t="number"==typeof s?e.u[s]:void 0;void 0!==t&&this.gn(i,t)}})}gn(e,t){t.l.n===e.n?this.R.me(this,e,t):this.Jt(t,e,t=>this.R.me(this,e,t))}Kt(e,t,n,r,i){c.he?.(this,e,t,n,r,i),this.We(e,t)}We(e,t){this.R.Ho(this,e,t),this.Re()}eo(e){let t=this.Ze.get(e);if(void 0!==t)return t;let n=Symbol(`wcs.on${e}`);this.Ze.set(e,n);let r=this.root,i=this.Dn;return r.addEventListener(e,t=>{for(let s=t.target;null!==s&&s!==r;s=s.parentNode){let r=s[n];if(void 0!==r&&(r(t),t.cancelBubble))return;let o=s[i];if(void 0!==o&&o.y&&o.Vo(e,t))return}}),n}reset(e){let t=this.target,n=this.pt;for(let e of this.B.all())null===e.d&&null!==e.getter&&n.add(e.s);this.Xn(e);for(let e in t)"$"!==e[0]&&n.add(e);for(let t of n)t in e&&n.delete(t);for(let e of this.ie.values())for(let t of e)this.Qt(t);for(let e of this.ee.values())this.to(e);this.Ie=null;try{this.Ut()}finally{this.bn()}c.element?.(this,"reset")}Xn(e){for(let[t,n]of F)void 0!==e[t]&&b(n,t);void 0!==e.$scan&&k(1);for(let[t,n]of U)void 0!==e[t]&&k(1601,[t,n]);let t=e.$features;if(void 0!==t){Array.isArray(t)||k(46);for(let e of t)b(e,"$features")}let n=void 0===e.$behavior?{}:e.$behavior;("object"!=typeof n||!n||Array.isArray(n))&&k(44,["state","$behavior"]);for(let e in n)(!q.includes(e)||"boolean"!=typeof n[e])&&k(44,["$behavior",e]);let[r,i,s]=q.map(e=>n[e]??!0);void 0!==this.target&&(r!==this.Lt||i!==this.Bt||s!==this.Dt)&&k(45);let o=function(e,t){let n={};for(let r of N(e.$commandTokens,"$commandTokens","$command"))n[r]=t?.[r]??new S(r);return Object.freeze(n)}(e,this.commands),l=function(e,t){let n=new Map;for(let t of N(e.$eventTokens,"$eventTokens"))n.set(t,new S(t));let r=e.$on;if(void 0===r)return n;(null===r||"object"!=typeof r)&&k(22);for(let[e,i]of Object.entries(r)){let r=n.get(e);void 0===r&&k(23,[e]),"function"!=typeof i&&k(24,[e]),r.subscribe((...e)=>t(i,e))}return n}(e,this.Co);this.Lt=r,this.Bt=i,this.Dt=s,c.se?.(this,e),this.target=e,this.Oe=0;for(let e of this.B.all())e.Po();this.Hn.length=0,this.Yn(e),this.commands=o,this.Ne=l}to(e){this.Gn(e);let t=this.o(`${e.o.t}.*`);for(let n of e.u)if(n.ut=null,n.q=null,this.wt(t,n),null!==n.h)for(let e of n.h.values())this.to(e)}_(e){let t=[];for(let n=e;null!==n;n=n.l.re)t.unshift(n.b);return t}Uo(e,t,n){let r=this.Ne.get(e);void 0===r&&k(1301,[e],e,this.Ne.keys()),r.emit(t,...this._(n))}command(e){let t=this.commands[e];return void 0===t&&k(1302,[e],e,Object.keys(this.commands)),t}qo(e,t,n){this.command(e).emit(t,...this._(n))}Ko(e,t,n){let r=e.includes(".")?this.v(this.o(e),null):this.target[e];return"function"!=typeof r&&k(5,[e]),this.yn(r,n,[t,...this._(n)])}yn(e,t,n){let r=this.c;this.c=t;try{return e.apply(this.proxy,n)}finally{this.c=r}}wt(e,t){if(null!==e.getter){let n=null===t?this.ee:t.h;if(null!==n)for(let t of n.values())!t.Ct&&t.o.Q(e)&&(t.Ct=!0,this.Be.push(t))}if(null===t)return void this.Gt(e,e=>{let t=this.ie.get(e);if(void 0!==t)for(let e of t)this.Qt(e)});let n=t.fe;if(null!==n)for(let t=0;t<n.length;t++)n[t].o.Q(e)&&this.Qt(n[t]);let r=t.$;null!==r&&null!==r.ae&&r.no(this,e);let i=t.l.L;if(null!==i)for(let n of i){let r=n.map.get(t);void 0!==r&&null!==r.ae&&r.no(this,e)}}vn(e,t,n){this.Gt(e,e=>{let r=e.G;for(let i=0;i<r.length;i++){let s=r[i];if(0===s.n)this.tt(s,null,n);else if(null===t||0===e.n||s.f[1]!==e.f[1]||null!==s.ct&&s.ct.has(e))this.Zt(s.f[s.n],e=>this.tt(s,e,n));else if(s.n<=e.n){let e=ee(t,s.n);null!==e&&this.tt(s,e,n)}else this.Jt(t,s,e=>this.tt(s,e,n))}})}tt(e,t,n){n(e,t)&&(c.ye?.(this,e,t),this.wt(e,t),this.vn(e,t,n))}Gt(e,t){t(e);let n=e.h;for(let e=0;e<n.length;e++)this.Gt(n[e],t)}Zt(e,t){this.Zn(e,e=>{for(let n of e.u)t(n)})}Zn(e,t){if(0===e.n){let n=this.ee.get(e);return void(void 0!==n&&t(n))}this.Zt(e.f[e.n],n=>{let r=n.h?.get(e);void 0!==r&&t(r)})}Jt(e,t,n){if(e.l.n===t.n)return n(e);let r=e.h?.get(t.f[e.l.n+1]);if(void 0!==r)for(let e of r.u)this.Jt(e,t,n)}zo(e){let t=e.r;null===t?G(this.ie,e.o,V).add(e):(t.fe??(t.fe=[])).push(e)}kn(e){let t=e.r;if(null===t)return void this.ie.get(e.o)?.delete(e);let n=t.fe;t.y&&null!==n&&n.splice(n.indexOf(e)>>>0,1)}Qt(e){e.Z||(e.Z=!0,this.je.push(e),this.Re())}Re(){this.ht||(this.ht=!0,queueMicrotask(this.Oo))}Sn(){for(let e of this.je)e.Z=!1;for(let e of this.Le)e.Z=!1;for(let e of this.Be)e.Ct=!1;this.je=[],this.Le=[],this.Be=[],this.R.pt(this)}oo(e,t){let n=[...new Set([...this.je,...this.Le,...this.Be].map(e=>e.o.t))];console.error(`[@wcstack/state] ${$(e)}`,n),c.nt?.(this,{type:"state:render-chain-limit",maxDepth:t,paths:n}),this.Sn()}Ut(){this.ht=!1;let e=this._t;this._t=0;let t=0;if(!this.Ht||this.Vt?this.Wn():e>0?t=e:1===(t=++this.M)&&setTimeout(this.Wn,0),this.Ht=this.Vt=!1,t>100)101===t?this.oo(41,100):this.Sn();else{this.dn=!0;try{for(let e=0;this.je.length>0||this.Le.length>0||this.Be.length>0;e++){if(e>=32){this.fn?this.Sn():this.oo(11,32),this.fn=!0;break}let n=this.Be;if(n.length>0){this.Be=[];for(let e of n)e.Ct=!1,this.Gn(e)}let r=this.Le,i=this.je;this.Le=[],this.je=[];let s=C("state",()=>{for(let e of r){e.Z=!1;for(let t of[e.$,...e.L??[]])if(null!==t&&t.y)try{t.bt()}catch(n){this.Xt(n,e.o.t,t.S,"for")}}for(let e=0;e<i.length;e++){let t=i[e];t.Z&&(t.Z=!1,(null===t.En||t.En.y)&&this._e(t))}this.dn||(this.He(),this.ht&&(this._t=t+1))});void 0!==s&&s.then(void 0,e=>console.error(e))}}finally{this.dn=!1}this.Ht=this.Vt=!1,this.He(),c.Te?.(this),e>0&&this.ht&&(this._t=t+1)}}vt(e,t){this.mt.push([e,t])}Xt(e,t,n,r){this.vt(e,{o:{t:t},a:n,en:()=>r})}_e(e){try{e.apply()}catch(t){return void this.mt.push([t,e])}null!==this.Ie&&this.io(e.o,e.r)}io(e,t){let n=G(this.Ie,e.t,J);null!==t&&n.push(this._(t))}bn(){this.Ie="function"==typeof this.target.$renderedCallback?new Map:null}He(){let e=this.Ie;if(null!==e&&e.size>0){this.Ie=new Map;let t,n=[...e.keys()],r={};for(let[t,n]of e)n.length>0&&(r[t]=n);this.xe++;try{t=this.we("$renderedCallback",[n,r])}catch(e){console.error(e)}Q(t)?t.then(this._n,e=>{this._n(),console.error(e)}):this.xe--}if(0===this.mt.length)return;let t=this.mt;this.mt=[];let n=this.target.$errorCallback;for(let[r,i]of t){c.Ve?.(this,r,i);let t=i.o.t,s=i.en();if("function"==typeof n)try{let e=this.we("$errorCallback",[r,{path:t,bindingType:s,node:i.a}]);Q(e)&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}else console.error(`[@wcstack/state] ${$(12,[s,t])}`,r)}}we(e,t=[]){let n=this.target[e];return"function"==typeof n?this.yn(n,null,t):void 0}so(e,t,n){if(0===e.n)return void n(null,[]);let r=[],i=(s,o)=>{let l=e.f[s];this.read(l,o);let a=this.De(o,l),u=t=>{r.push(t.b),s===e.n?n(t,r):i(s+1,t),r.pop()};for(let e of s-1<t.length?[a.u[t[s-1]]]:a.u)void 0!==e&&u(e)};i(1,null)}getAll(e,t){let n=this.o(e);void 0!==t&&this.mn("$getAll",e,n,t,!1);let r=t;if(void 0===r){r=[];let t=this.c;if(null!==t&&n.n>0){for(let e=1;e<=n.n;e++){let i=te(t,n,e);if(null===i)break;r.push(i.b)}0===r.length&&k(6,[e])}}let i=[];return this.so(n,r,e=>i.push(this.read(n,e))),i}pn(e,t,n,r){Array.isArray(t)||k(9,[e]),this.Ce>0&&k(8);let i=this.o(e);this.mn("$setAll",e,i,t,!1);let s=[];this.so(i,t,(e,t)=>s.push([e,t.slice()]));let o=!0===r?.spread;o&&(!Array.isArray(n)||n.length!==s.length)&&k(10,[e,s.length]);let l=0;for(let e=0;e<s.length;e++){let[t,r]=s[e],a="function"==typeof n?n(this.v(i,t),...r):o?n[e]:n;void 0!==a&&(this.P(i,t,a),l++)}return l}mn(e,t,n,r,i){let s=r.length;(s>n.n||i&&s<n.n)&&k(i?901:902,[e,t,n.n,s])}},re={bindAttributeName:"data-wcs",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:typeof document<"u"&&document.documentElement?.lang||"en"},ie=new Map,se=new Set(["if","elseif","else","for"]),oe=new Set([x,"if","elseif","for","..."]),le=new Set(["class","attr","style","command",T,"state"]);function ae(e){let t=function(e){return R(e,";")}(e).map(L).filter(e=>e.length>0).map(e=>{let t=j(e,":");-1===t&&k(101,[e]);let n=e.slice(0,t).trim(),r=e.slice(t+1).trim(),i=n.split("#")[0].split("|")[0].trim();if(oe.has(i)){let t;return i!==n&&k(102,[e,i]),i===x?(r.length>0&&k(103,[e]),t={Je:"#else",Qe:[]}):"..."===i?(0===r.length&&k(104,[e]),t=D(r),t.Qe.length>0&&k(105,[e])):(t=D(r),"for"===i&&t.Qe.length>0&&k(121,[e])),{be:i,ve:[i],tn:[],I:[],...t,w:"..."===i?"spread":i}}let s=D(r),o=function(e){let[t,n]=H(e,"input",ie),r=t.split("#").map(L);r.length>2&&k(115,[t]);let[i,s]=r,o=i.split(".").map(L);return!(o.length>1&&""===o[0])&&(0===i.length||o.some(e=>0===e.length))&&k(116,[e]),{be:i,ve:o,tn:s?s.split(",").map(L):[],I:n}}(n),[l]=o.ve;if(""===l&&o.ve.length>1){let e=o.ve.slice(1);return(e.includes("")||le.has(e[0]))&&k(106,[n]),{...o,be:e.join("."),ve:e,...s,w:"prop"}}return{...o,...s,w:"radio"===i||"checkbox"===i?i:l===T||l.startsWith("on")?"event":"prop"}});return t.length>1&&t.some(e=>se.has(e.w))&&k(201,[e]),t}var ue=["toFixed","locale","upper","lower","capitalize","trim","slice","padStart","padEnd","repeat","reverse","truncate","join","round","floor","ceil","percent","unit","date","time","datetime","ymd","hms"],ce=new Map,he=new Map;function de(e){for(let t of Object.keys(e))ce.set(t,{...e[t]});he.clear()}function fe(e){return ce.has(e)}function pe(e){k(26,[e])}function me(e){k(27,[e])}function ge(e){k(28,[e])}function ye(e){k(29,[e])}function be(e){return!(!e||isNaN(Number(e)))}function ve(e,t){return be(e)||me(t),Number(e)}function we(e,t,n){return ve(e?.[t]??pe(n),n)}function _e(e,t){return void 0!==t&&t.length>0?t[0]:e}var $e=(e,t)=>({factory:n=>{let r=we(n,0,e);return n=>("number"!=typeof n&&ge(e),t(n,r))},arity:[1,1]}),ke={eq:{factory:(e,t)=>{let n=e?.[0]??pe("eq"),r=_e(n,t);return e=>"number"==typeof e?"string"!=typeof r?e===r:(be(n)||me("eq"),e===Number(n)):"string"==typeof e?e===n:e===r},arity:[1,1]},ne:{factory:(e,t)=>{let n=e?.[0]??pe("ne"),r=_e(n,t);return e=>"number"==typeof e?"string"!=typeof r?e!==r:(be(n)||me("ne"),e!==Number(n)):"string"==typeof e?e!==n:e!==r},arity:[1,1]},not:{factory:()=>e=>!e,arity:[0,0]},lt:$e("lt",(e,t)=>e<t),le:$e("le",(e,t)=>e<=t),gt:$e("gt",(e,t)=>e>t),ge:$e("ge",(e,t)=>e>=t),add:$e("add",(e,t)=>e+t),sub:$e("sub",(e,t)=>e-t),mul:$e("mul",(e,t)=>e*t),div:$e("div",(e,t)=>e/t),mod:$e("mod",(e,t)=>e%t),abs:{factory:()=>e=>("number"!=typeof e&&ge("abs"),Math.abs(e)),arity:[0,0]},clamp:{factory:e=>{let t=we(e,0,"clamp"),n=we(e,1,"clamp");return e=>("number"!=typeof e&&ge("clamp"),Math.min(Math.max(e,t),n))},arity:[2,2]},int:{factory:()=>e=>parseInt(String(e),10),arity:[0,0]},float:{factory:()=>e=>parseFloat(String(e)),arity:[0,0]},falsy:{factory:()=>e=>!e,arity:[0,0]},truthy:{factory:()=>e=>!!e,arity:[0,0]},defaults:{factory:(e,t)=>{let n=_e(e?.[0]??pe("defaults"),t);return e=>e||n},arity:[1,1]},coalesce:{factory:(e,t)=>{let n=_e(e?.[0]??pe("coalesce"),t);return e=>e??n},arity:[1,1]},boolean:{factory:()=>e=>!!e,arity:[0,0]},number:{factory:()=>e=>Number(e),arity:[0,0]},string:{factory:()=>e=>String(e),arity:[0,0]},nullIfEmpty:{factory:()=>e=>""===e?null:e,arity:[0,0]}},Se=!1;function Ne(e,t){if(null!==e)for(let n=0;n<e.length;n++)t=e[n](t);return t}function Ae(e){return 0===e.length?null:(Se||(Se=!0,de(ke)),e.map(e=>function(e,t,n){let r=`${e}${function(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}(t,n)}`,i=he.get(r);if(typeof i<"u")return i;let s=ce.get(e);void 0===s&&function(e,t){ue.includes(e)&&v(`[wcs/filter-unknown] filter not found: ${e}. "${e}" is in the formats add-on — install it with installFeatures([formats]) from "@wcstack/state/features/formats".`,e,t),k(501,[e],e,t)}(e,ce.keys());let[o,l]=s.arity;t.length<o&&k(601,[e,o,t.length]),t.length>l&&k(602,[e,l,t.length]);let a=s.factory(t,n);return he.set(r,a),a}(e.Bn,e.args,e.literals)))}var Ee=Symbol.for("wcstack.trustedTypes.policy");function Ce(){let e=globalThis[Ee];return null!==e&&"object"==typeof e?e:null}function xe(e){return"innerHTML"===e||"outerHTML"===e||"srcdoc"===e}function Te(e){if(globalThis.trustedTypes?.isHTML(e))return e;let t=null==e?"":String(e),n=Ce(),r=n?.createHTML;return"function"==typeof r?r.call(n,t):t}var Pe=Symbol.for("wcstack.state.view-transition-naming"),Oe=new WeakSet;function Me(){let e=E("state");return null!==e&&"auto"===e.naming?e.namingLimit:-1}var Le=new WeakMap,Ie=e=>e.customElementRegistry??customElements;function je(e,t,n,r,i,s=!1){let o=n.localName;if(!o.includes("-"))return i(null);let l=Ie(n);if(!s&&!n.isConnected&&void 0===l.get(o)&&"customElementRegistry"in n)return void queueMicrotask(()=>je(e,t,n,r,i,!0));let a=()=>{let e=l.get(o);l.upgrade(n),i(e?function(e){if(Le.has(e))return Le.get(e);let t=e.wcBindable,n=null;if(null!==t&&"object"==typeof t&&"wc-bindable"===t.protocol&&Number.isInteger(t.version)&&t.version>=1){n={properties:new Map,inputs:new Map,commands:new Set};for(let e of t.properties??[])n.properties.set(e.name,{event:e.event,getter:"function"==typeof e.getter?e.getter:null,lo:"event"===e.semantics});for(let e of t.inputs??[])n.inputs.set(e.name,{attribute:"string"==typeof e.attribute?e.attribute:null});for(let e of t.commands??[])null!==e&&"object"==typeof e&&"string"==typeof e.name&&n.commands.add(e.name)}return Le.set(e,n),n}(e):null)};if(!s&&void 0!==l.get(o))return a();null!==r&&!r.y||function(e,t,n){let r=n;null!==t&&(t.kt??=[]).push(()=>{r=null}),e.then(()=>r?.())}(l.whenDefined(o),r,()=>{try{a()}catch(r){Ue(e,r,t,n)}e.Re()})}function Re(e,t,n,r,i=t.o,s,o,l){let a=l.properties.get(r)??null,u=l.inputs.get(r),h=e.Dt;h&&null===a&&void 0===u&&k(38,[r]);let d=t.H;(null===a?"element"===d||"auto"===d:void 0===u&&("state"===d||"auto"===d))&&k(39,[d,r]),"connect"===t.z&&null===a&&k(40,[r]);let f=h&&null!==a&&void 0===u,p=new Be(e,ze,n,r,i,s,o,t.N,void 0);p.I=t.I,p.attribute=u?.attribute??null,Ze(e,p,!f),null!==a&&!t.ro&&n.addEventListener(a.event,t=>{let i;null!==a.getter?i=a.getter(t):(i=t.detail,a.lo||c.detail?.(n,r,i)),(!p.$n||!Object.is(i,p.value))&&(i=Ne(p.I,i),null===p.N&&(p.value=i),e.P(p.o,p.r,i,a.lo,!0))});let m=d??(f?"element":"state");if("state"===m)f||e._e(p);else if("element"===m||"auto"===m){let i=()=>{if(null!==o&&!o.y)return;if("auto"===m&&void 0!==e.v(p.o,p.r))return void(f||e._e(p));let t=n[r];null===p.N&&(p.value=t),e.P(p.o,p.r,t,!1,!0)};"connect"!==t.z||n.isConnected?i():Promise.resolve().then(i)}return p}function He(e,t,n){k(e,[t.localName,n])}var We=new Set(["click","dblclick","input","change","submit","keydown","keyup","mousedown","mouseup","pointerdown","pointerup"]),ze=11,De=["text","prop","prop","prop","prop","event","for","if","prop","radio","checkbox","prop","prop","event","spread"],Ue=(e,t,n,r)=>e.Xt(t,n.o?.t??n.St,r,De[n.i]),Fe=Symbol();function qe(e,t,n){let r=t.H;return null===r||"state"===r||"auto"===r&&void 0!==e.v(t.o,n)?t.V:Fe}var Be=class{constructor(e,t,n,r,i,s,o,l,a,u=null){this.Z=!1,this.I=null,this.attribute=null,this.$n=!1,this.engine=e,this.i=t,this.a=n,this.name=r,this.o=i,this.r=s,this.En=o,this.N=l,this.value=a,this.M=u}en(){return De[this.i]}apply(){if(null!==this.M)return void this.M.bt();let e=Ne(this.N,this.engine.read(this.o,this.r));if(e===this.value&&("object"!=typeof e||null===e||this.i===ze||8===this.i||xe(this.name)))return;if(this.value===Fe)return void(this.value=e);let t=this.a;if(this.i!==ze)9===this.i?t.checked=void 0!==e&&this.nn()===e:10===this.i?t.checked=Array.isArray(e)&&e.includes(this.nn()):Ge(this.i,t,this.name,e),this.value=e;else{if(void 0===e)return void(this.value=e);this.value=e,this.$n=!0;try{t[this.name]!==e&&(t[this.name]=e)}finally{this.$n=!1}null!==this.attribute&&function(e,t,n){try{if(null==n)e.removeAttribute(t);else{let r=n;if("object"==typeof n)try{r=JSON.stringify(n)}catch{}e.setAttribute(t,String(r))}}catch{}}(t,this.attribute,e)}}nn(){return Ne(this.I,this.a.value)}Xo(){let e,t=this.a,n=this.engine;if(9===this.i){if(!t.checked)return;e=this.nn()}else if(10===this.i){let r=this.nn(),i=n.v(this.o,this.r),s=Array.isArray(i)?i:[],o=s.includes(r);if(t.checked?o:!o)return;e=o?s.filter(e=>e!==r):[...s,r]}else e=Ne(this.I,t[this.name]);n.P(this.o,this.r,e,!1,!0)}},Ke=e=>"textContent"===e||"innerText"===e||"innerHTML"===e;function Ge(e,t,n,r){switch(e){case 0:return void(t.data=null==r?"":String(r));case 1:return void(Ke(n)?t[n]="innerHTML"===n?Te(r):null==r?"":String(r):xe(n)?null==r&&"srcdoc"===n?t.removeAttribute(n):void 0!==r&&(t[n]=Te(r)):void 0!==r&&(t[n]!==r&&!("value"===n&&t.value===String(r))&&(t[n]=r),("value"===n||"selectedIndex"===n)&&"select"===t.localName&&(t[Ve]=[n,r])));case 8:return void(t.innerHTML=Te(r));case 2:return null!=r&&"boolean"!=typeof r&&k(401,[n,typeof r]),void t.classList.toggle(n,!0===r);case 3:return void(null==r?t.removeAttribute(n):t.setAttribute(n,String(r)));case 4:return void(null==r?t.style.removeProperty(n):t.style.setProperty(n,String(r)))}}var Ve=Symbol();function Je(e){let t="optgroup"===e.localName?e.parentNode:e,n=t?.[Ve];void 0!==n&&(t[n[0]]=n[1])}var Qe=class{constructor(e,t,n,r){this.y=!0,this.fe=null,this.h=null,this.kt=null,this.xn=null,this.r=e,this.Ue=t,this.j=n,this.A=r}Vo(e,t){let n=t.target,r=this.A,i=[],s=null;for(let t of r.Ne){if(t.name!==e)continue;let o=r.Rn[t.a],l=at(null===this.j?this.Ue:this.j[o[0]],o,1);l.contains(n)&&(l!==s&&i.unshift([]),i[0].push(t),s=l)}for(let e of i){for(let n of e)n.Nn(t,this.r);if(t.cancelBubble)return!0}return!1}get s(){return null===this.j?this.Ue:this.j[this.j.length-1]}qe(){let e=this.xn;return(null===e?null:e.Pn(this.Ue))??this.Ue}insertBefore(e,t){let n=this.s;for(let r=this.qe();;){let i=r.nextSibling;if(e.insertBefore(r,t),r===n)return;r=i}}uo(){null===this.j?this.Ue.remove():ut(this.qe(),this.s)}Se(e){if(this.y=!1,null!==this.kt)for(let e of this.kt)e();let t=this.fe;if(null!==t)for(let n=0;n<t.length;n++)e.kn(t[n]);if(null!==this.h)for(let e of this.h)e.Se()}},Xe=class extends Qe{constructor(e,t,n,r){super(e,t,n,r),this.fo=0,this.W=null,this.ae=0===r.Ke.length?null:new Array(2*r.Ke.length)}po(e,t){let n=this.W??=new Array(this.A.Ke.length),r=n[t];if(void 0===r){let i=this.A.Ke[t],s=this.ae;r=n[t]=new Be(e,i.i,s[2*t],i.name,i.o,this.r,this,i.N,s[2*t+1])}return r}no(e,t){let n=this.A.Ke;for(let r=0;r<n.length;r++)n[r].o.Q(t)&&e.Qt(this.po(e,r))}Se(e){let t=this.r;t.$===this&&(t.$=null),super.Se(e)}};function Ye(e,t,n,r){let i=ee(n,t.n);try{return e.De(i,t)}catch(n){return e.Xt(n,t.t,r,"for"),null===i?e.ee.get(t):i.h.get(t)}}function Ze(e,t,n){n&&e.zo(t);let r=t.En;null!==r&&(r.fe??=[]).push(t)}var et=null;function tt(){let e=et;return et=null,e}var nt=-1;function rt(e,t,n,r,i=null){let s,o=t.Rn,l=t.build,a=t.mo,u=null,h=c.Ae?.(t,null===r?i:r.S,null!==r),d=!h&&t.Tn,f=h?document.createDocumentFragment():(d?t.root:t.on).cloneNode(!0);if(!h)for(let e=0;e<l.length;e++){let t=l[e];a[t]=at(f,o[t],d?1:0)}d?s=f:(u=h||[...f.childNodes],s=u[0]);let p,m=null;if(null!==r?(p=m=new Xe(n,s,u,t),null===r.map?n.$=m:r.map.set(n,m)):p=new Qe(n,s,u,t),nt>=0&&function(e,t,n,r){let i=null;if(null===t)i=1===e.nodeType?e:null;else for(let e=0;e<t.length&&null===i;e++)1===t[e].nodeType&&(i=t[e]);let s=i?.style;if(null===i||void 0===s||Oe.has(i))return;let o=globalThis[Pe]??={counter:0,assigned:0,warned:!1};o.assigned>=r?o.warned||(o.warned=!0,console.warn(`[@wcstack/state] ${$(25,[r])}`)):(Oe.add(i),o.assigned++,s.setProperty("view-transition-name",`wcs-${n}-${++o.counter}`),s.setProperty("view-transition-class",`wcs-${n}`))}(s,u,null!==r?"row":"branch",nt),t.Ne.length>0){let t=e.Dn;if(null===u)s[t]=p;else for(let e of u)1===e.nodeType&&(e[t]=p)}let g=t.Yo,y=e.Ie,b=t.Go?a.slice(0,o.length):a,v=null===m?null:m.ae;if(null!==v){let e=t.Ke;for(let t=0;t<e.length;t++)v[2*t]=b[e[t].a],v[2*t+1]=e[t].V}for(let r=0;r<g.length;r++){let i=g[r],o=b[i.a],l=i.F;if(l>=0&&null!==v){let r=m.W?.[l];if(void 0!==r){r.Z=!1,e._e(r);continue}try{let t=Ne(i.N,e.read(i.o,n));t!==i.V&&(Ge(i.i,o,i.name,t),v[2*l+1]=t),null!==y&&e.io(i.o,n)}catch(t){e.vt(t,m.po(e,l))}continue}switch(i.i){case 6:{let t=new lt(e,i.A,Ye(e,i.o,n,o),o);(p.h??=[]).push(t),o===s&&(p.xn=t),t.bt();break}case 7:{let t=st(e,i.X.map(e=>({A:e.A,o:e.o,N:e.N,S:b[e.a]})),n,p);(p.h??=[]).push(t),o===s&&(p.xn=t);break}default:try{it(e,i,o,n,p)}catch(t){Ue(e,t,i,o)}}}return et=p,f}function it(e,t,n,r,i){let s=n;switch(t.i){case 5:return void function(e,t,n,r,i){let s=n.Nn,o=e=>s(e,r);if(n.Ze){let r=e.eo(n.name),i=t[r];t[r]=void 0===i?o:e=>{i(e),o(e)},n.ke&&t.addEventListener(n.name,e=>e.bubbles||o(e))}else t.addEventListener(n.name,o),n.co&&null!==i&&(i.kt??=[]).push(()=>t.removeEventListener(n.name,o))}(e,n,t,r,i);case 12:return void je(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name,o=e.command(t.St.slice(9));null===i&&He(1202,n,`command.${s}`),i.commands.has(s)||k(1203,[n.localName,s]);let l=new WeakRef(n),a=o.subscribe((...e)=>{let t=l.deref();if(void 0!==t)return t.isConnected?t[s](...e):void 0;a()});null!==r&&(r.kt??=[]).push(a)}(e,t,s,i,n));case 13:return void je(e,t,s,i,n=>function(e,t,n,r,i){let s=t.name;null===i&&He(1202,n,`eventToken.${s}`);let o=i.properties.get(s);void 0===o&&k(1204,[n.localName,s]);let l=t.St;n.addEventListener(o.event,n=>{t.Et&&n.preventDefault(),t.$t&&n.stopPropagation();try{e.Uo(l,n,r)}catch(e){console.error(e)}})}(e,t,s,r,n))}let o=t.o,l=ee(r,o.n);if(14===t.i)return void je(e,t,s,i,n=>function(e,t,n,r,i,s){null===s&&He(1501,n,`"...: ${t.o.t}"`);let o=new Set([...s.properties.keys(),...s.inputs.keys()]);for(let l of o){if(t.ao?.includes(l))continue;let o=e.o(`${t.o.t}.${l}`),a=0===o.n?null:r;Re(e,{...t,H:null,z:null},n,l,o,a,i,s)}}(e,t,s,l,i,n));if(t.ke&&1===t.i)return void je(e,t,s,i,n=>function(e,t,n,r,i,s){if(null!==s)return void Re(e,t,n,t.name,t.o,r,i,s);let o=new Be(e,1,n,t.name,t.o,r,i,t.N,qe(e,t,r));o.I=t.I,!c.Jo?.(o,t.ro)&&(Ze(e,o,!0),e._e(o))}(e,t,s,l,i,n));let a=new Be(e,t.i,n,t.name,o,l,i,t.N,qe(e,t,l));a.I=t.I,Ze(e,a,!0),e._e(a),null!==t.Nt&&n.addEventListener(t.Nt,()=>a.Xo())}function st(e,t,n,r){let i=new ot(e,t,n),s=null;for(let o of t){if(null===o.o)continue;let t=o.o,l=new Be(e,7,o.S,"if",t,ee(n,t.n),r,null,void 0,i);Ze(e,l,!0),null===r&&i.ie.push(l),s??=l}return e._e(s),i}var ot=class{constructor(e,t,n){this.y=!0,this.O=null,this.b=-1,this.ie=[],this.engine=e,this.X=t,this.r=n}Pn(e){return null!==this.O&&this.X[this.b].S===e?this.O.qe():null}bt(){let e=this.engine,t=-1;for(let n=0;n<this.X.length;n++){let r=this.X[n];if(null===r.o||Ne(r.N,e.read(r.o,ee(this.r,r.o.n)))){t=n;break}}if(t!==this.b&&(nt=Me(),null!==this.O&&(this.O.uo(),this.O.Se(e),this.O=null),this.b=t,t>=0)){let n=this.X[t],r=rt(e,n.A,this.r,null,n.S);this.O=tt();let i=n.S.parentNode;i.insertBefore(r,n.S),Je(i)}}Se(){this.y=!1;for(let e of this.ie)this.engine.kn(e);null!==this.O&&this.O.Se(this.engine)}},lt=class{constructor(e,t,n,r){this.y=!0,this.Ee=[],this.engine=e,this.A=t,this.l=n,this.S=r,null===n.$?(n.$=this,this.map=null):((n.L??=[]).push(this),this.map=new Map)}Pn(e){return 0===this.Ee.length?null:this.Ee[0].qe()}xt(e){return null===this.map?e.$:this.map.get(e)??null}ho(e){let t=this.map;null!==t&&t.get(e.r)===e&&t.delete(e.r),e.Se(this.engine)}bt(){let e=this.engine,t=this.l.u,n=this.Ee;nt=Me();let r=t.length,i=n.length,s=this.S,o=s.parentNode;if(0===r){if(i>0){ut(n[0].qe(),n[i-1].s);for(let e=0;e<i;e++)this.ho(n[e])}return void(this.Ee=[])}let l=new Array(r),a=0;for(;a<r&&a<i&&this.xt(t[a])===n[a];)l[a]=n[a],a++;let u=i-1,c=r-1;for(;u>=a&&c>=a&&this.xt(t[c])===n[u];)l[c]=n[u],u--,c--;for(let e=a;e<=u;e++){let t=n[e],r=t.r;r.y&&this.xt(r)===t?t.fo=e:(t.uo(),this.ho(t))}if(a<=c){let n=c-a+1,u=new Int32Array(n),h=!1;if(i>0)for(let e=0;e<n;e++){let n=this.xt(t[a+e]);null!==n&&n.y?(u[e]=n.fo,h=!0):u[e]=-1}let d=c+1<r?l[c+1].qe():s;if(h){let r=function(e){let t=e.length,n=new Uint8Array(t),r=new Int32Array(t).fill(-1),i=[];for(let n=0;n<t;n++){let t=e[n];if(t<0)continue;let s=0,o=i.length;for(;s<o;){let n=s+o>>1;e[i[n]]<t?s=n+1:o=n}s>0&&(r[n]=i[s-1]),i[s]=n}let s=i.length>0?i[i.length-1]:-1;for(;s>=0;)n[s]=1,s=r[s];return n}(u),i=d;for(let s=n-1;s>=0;s--){let n=t[a+s],u=this.xt(n);null!==u&&u.y?0===r[s]&&u.insertBefore(o,i):(o.insertBefore(rt(e,this.A,n,this),i),u=tt()),l[a+s]=u,i=u.qe()}}else{let n=document.createDocumentFragment();for(let r=a;r<=c;r++)n.appendChild(rt(e,this.A,t[r],this)),l[r]=tt();o.insertBefore(n,d)}}this.Ee=l,Je(o)}Se(){this.y=!1;let e=this.l;if(e.$===this)e.$=null;else if(null!==e.L){let t=e.L.indexOf(this);t>=0&&e.L.splice(t,1),0===e.L.length&&(e.L=null)}for(let e of this.Ee)e.Se(this.engine);this.map?.clear()}};function at(e,t,n){for(;n<t.length;n++){e=e.firstChild;for(let r=t[n];r>0;r--)e=e.nextSibling}return e}function ut(e,t){let n=document.createRange();n.setStartBefore(e),n.setEndAfter(t),n.deleteContents()}var ct=()=>re.bindAttributeName;function ht(){return{a:0,i:1,name:"",o:null,N:null,V:t,Nn:null,A:null,X:null,I:null,Nt:null,ke:!1,H:null,z:null,ro:!1,Et:!1,$t:!1,St:null,ao:null,F:-1,Ze:!1,co:!1}}var dt=["state","element","auto","none"],ft=["call","connect"],pt="$command.";function mt(e,t,n){P.test(t)&&(null===n&&k(1401,[t,Number(t.slice(1))]),t=`${n.t}.*.${t}`);let r=e.o(function(e,t){return 46!==e.charCodeAt(0)?e:(null===t&&k(1402,[e]),"."===e?`${t.t}.*`:`${t.t}.*${e}`)}(t,n)),i=null===n?0:n.n+1;r.n>i&&k(1401,[r.t,r.n,i]);for(let e=1;e<=r.n;e++){let t=e===i?n:n.f[e];r.f[e]!==t&&k(1403,[r.t,r.f[e].t,t.t])}return c.go?.(e,r),r}var gt=e=>1===e.i&&("outerHTML"===e.name||"outerText"===e.name),yt=e=>8===e.i||gt(e)||1===e.i&&Ke(e.name);function bt(e){k(202,[e])}function vt(e,t,n,r,i){let s=ae(t).map(t=>function(e,t,n,r,i){let s=function(e,t){let n=t.find(e=>e.startsWith("on")),r=null,i=null;for(let n of t){let t=n.indexOf("=");if(t<0)continue;e.Dt||k(31);let s=n.slice(0,t).trim(),o=n.slice(t+1).trim(),l="init"===s;!l&&"sync"!==s&&k(33,[s,n]),null!==(l?r:i)&&k(34,[s]),(l?dt:ft).includes(o)||k(35,[s,o]),l?r=o:i=o}return{ro:t.includes("ro"),Et:t.includes("prevent"),$t:t.includes("stop"),event:n?n.slice(2):null,H:r,z:i}}(e,t.tn),o=r.localName.includes("-"),l=t.ve,a=t.Je;if("event"===t.w){if(null!==s.H&&"none"!==s.H&&k(36),"eventToken"===l[0])return{...ht(),a:i,i:13,name:l.slice(1).join("."),St:a,ke:o,Et:s.Et,$t:s.$t};let n=a.startsWith(pt)?a.slice(9):null,{Et:r,$t:u}=s,c=t.be.slice(2),h=t.tn.includes("direct"),d=!h&&We.has(c);return d&&e.eo(c),{...ht(),a:i,i:5,name:c,Ze:d,ke:o,co:h,Nn(t,i){r&&t.preventDefault(),u&&t.stopPropagation();try{if(null!==n)e.qo(n,t,i);else{let n=e.Ko(a,t,i);Q(n)&&n.then(void 0,e=>console.error(e))}}catch(e){console.error(e)}}}}if("spread"===t.w)return{...ht(),a:i,i:14,o:mt(e,a,n),ke:o};if("command"===l[0]&&l.length>1)return a.startsWith(pt)||k(1201,[t.be,a]),{...ht(),a:i,i:12,name:l.slice(1).join("."),St:a,ke:o};let u=mt(e,a,n),c={...ht(),a:i,i:1,name:t.be,o:u,N:Ae(t.Qe),I:Ae(t.I),ro:s.ro,H:s.H,z:s.z};if("radio"===t.w||"checkbox"===t.w)return("element"===s.H||"auto"===s.H)&&k(37,[t.w,s.H]),c.i="radio"===t.w?9:10,s.ro||(c.Nt=s.event??"input"),c;if(l.length>1){let e=l.slice(1).join("."),t=l[0];if("class"===t||"attr"===t||"style"===t)return c.H=null,c.name=e,"class"===t?(c.i=2,c.V=r.classList.contains(e)):c.i="attr"===t?"srcdoc"===e&&"iframe"===r.localName?1:3:4,c}return"html"===t.be?(c.i=8,c):(c.name="text"===t.be?"textContent":t.be,c.ke=o&&!xe(c.name),!o&&!s.ro&&function(e,t){let n=e.localName;if("input"===n){let n=(e.getAttribute("type")||"text").toLowerCase();return"button"!==n&&(("radio"===n||"checkbox"===n)&&"checked"===t||"value"===t||"valueAsNumber"===t||"valueAsDate"===t)}return("select"===n||"textarea"===n)&&"value"===t}(r,c.name)&&(c.Nt=s.event??("select"===r.localName?"change":"input")),c)}(e,t,n,r,i));for(let e=0;e<s.length;e++)14===s[e].i&&(s[e].ao=s.slice(e+1).filter(e=>1===e.i).map(e=>e.name));return s}var wt=/\{\{([\s\S]+?)\}\}/g;function _t(e){let t=e.data,n=[],r=0;wt.lastIndex=0;for(let i=wt.exec(t);null!==i;i=wt.exec(t)){let s=wt.lastIndex-i[0].length;s>r&&e.before(t.slice(r,s));let o=e.ownerDocument.createTextNode("");e.before(o),n.push({a:o,Qo:i[1].trim()}),r=wt.lastIndex}return 0===n.length||(r<t.length&&e.before(t.slice(r)),e.remove()),n}function $t(e,t,n,r){let i=function(e){return{be:"textContent",ve:["textContent"],tn:[],I:[],...D(e),w:"text"}}(t);return{...ht(),a:r,i:0,o:mt(e,i.Je,n),N:Ae(i.Qe),V:""}}function kt(e){let t=e.getAttribute(ct());if(null===t)return null;let n=ae(t)[0];return void 0===n||"for"!==n.w&&"if"!==n.w&&"elseif"!==n.w&&"else"!==n.w?null:n}var St=(e,t)=>0===e?re.commentIfPrefix:null===t.o?re.commentElsePrefix:re.commentElseIfPrefix;function Nt(e,t,n){let r=(t,r)=>({el:t,o:"else"===r.w?null:mt(e,r.Je,n),N:"else"===r.w?null:Ae(r.Qe)}),i=[r(t,kt(t))];for(let e=t.nextSibling;null!==e;e=e.nextSibling){if(3===e.nodeType&&""===e.data.trim()||8===e.nodeType)continue;if(1!==e.nodeType||"template"!==e.localName)break;let t=kt(e);if(null===t||"elseif"!==t.w&&"else"!==t.w||(i.push(r(e,t)),"else"===t.w))break}return i}var At=new WeakSet;function Et(e,t,n,r,i,s,o,l){let a=(t,n)=>{let i=document.createComment(n);return t.replaceWith(i),r&&c.An?.(e,i,t),i},u=t=>{for(let h=0;h<t.length;h++){let d=t[h];if(null!==d.parentNode)if(1===d.nodeType){let t=d,l=t.localName;if(r){if("script"===l||"style"===l||At.has(t))continue;if(At.add(t),l===re.tagNames.state){u([...t.childNodes]);continue}}let h="template"===l?kt(t):null;if(null!==h){if("for"===h.w){let r=mt(e,h.Je,n),s=Tt(e,t,r,!0);i(a(t,re.commentForPrefix),r,s)}else"if"===h.w?s(Nt(e,t,n).map((t,r)=>({A:Tt(e,t.el,n,!1),o:t.o,N:t.N,S:a(t.el,St(r,t))}))):bt(h.w);continue}let f=t.getAttribute(ct()),p=null===f?null:vt(e,f,n,t,0),m="noscript"!==l&&"iframe"!==l&&!p?.some(yt)&&!c.yo?.(t);try{r&&m&&u([...t.childNodes])}finally{null!==p&&o(t,p)}!r&&m&&u([...t.childNodes])}else if(3===d.nodeType&&e.Lt&&d.data.includes("{{")&&!At.has(d))for(let{a:e,Qo:t}of _t(d))l(e,t);else if(8===d.nodeType){let e=Ct.exec(d.data),t=e&&d.parentNode.localName;if(null!==t&&"textarea"!==t&&"title"!==t){let t=document.createTextNode("");d.replaceWith(t),l(t,e[1])}}}};u(t)}var Ct=/^\s*@@\s*(?:wcs-text)?\s*:\s*([\s\S]+?)\s*$/,xt=e=>{let t=document.createRange();return t.selectNodeContents(e),e.content??t.cloneContents()};function Tt(e,t,n,r){let i=document.importNode(xt(t),!0),s=[],o=[],l=e=>s.push(e)-1;Et(e,[...i.childNodes],n,!1,(e,t,n)=>{o.push({...ht(),a:l(e),i:6,o:t,A:n})},e=>{let t=e.map(e=>({a:l(e.S),A:e.A,o:e.o,N:e.N}));o.push({...ht(),a:t[0].a,i:7,X:t})},(e,t)=>{let n=l(e);for(let e of t)gt(e)&&k(203,[e.name]),e.a=n;o.push(...t),e.removeAttribute(ct())},(t,r)=>{o.push($t(e,r,n,l(t)))}),Lt(i,new Set(s),!0);let a=s.map(e=>function(e,t){let n=[];for(let r=t;r!==e;r=r.parentNode){let e=0;for(let t=r.previousSibling;null!==t;t=t.previousSibling)e++;n.unshift(e)}return n}(i,e)),u=1===i.childNodes.length&&8!==i.firstChild.nodeType,c=o.some(e=>6===e.i||7===e.i),h=[],d=new Set,f=[],p=[],m=r?n.n+1:-1;for(let e of o){if(5===e.i&&e.Ze&&!e.ke&&!Pt(s[e.a],i)){f.push(e);continue}p.push(e);let t=e.o;if(null!==t&&t.n===m&&t.f[m]===n&&Ot(e)&&(e.F=h.push(e)-1),7===e.i)for(let t of e.X)d.add(t.a);else d.add(e.a)}let g=[...d].sort((e,t)=>e-t);return{on:i,root:u?i.firstChild:null,Rn:a,build:g,Ne:f,Yo:p,Tn:u,Go:c,mo:[],Ke:h}}function Pt(e,t){for(;e.parentNode!==t;e=e.parentNode){if(e.parentNode.localName.includes("-"))return!0;for(let t=e.previousSibling;t;t=t.previousSibling)if(8===t.nodeType)return!0}return!1}function Ot(e){if(null!==e.H)return!1;switch(e.i){case 0:case 2:case 3:case 4:case 8:return!0;case 1:return!e.ke&&null===e.Nt;default:return!1}}var Mt=new Set(["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","datalist"]);function Lt(e,t,n){for(let r=e.firstChild;null!==r;){let e=r.nextSibling;3===r.nodeType?n&&!t.has(r)&&""===r.data.trim()&&r.remove():1===r.nodeType&&Lt(r,t,Mt.has(r.localName)),r=e}}var It=new WeakMap;function jt(e,t){let n=9===t.nodeType?t.body:t;e.root=t,It.set(t,e),Ht(e,[...n.childNodes]),e.He()}function Rt(e,t,n){try{let r="template"===t.localName?kt(t):null;null!==r&&!n&&k(204,[r.w]),Ht(e,[t])}catch(e){console.error(e)}e.He()}function Ht(e,t){Et(e,t,null,!0,(t,n,r)=>{new lt(e,r,Ye(e,n,null,t),t).bt()},t=>{st(e,t,null,null)},(t,n)=>{c.An?.(e,t,n);for(let r of n)it(e,r,t,null,null)},(t,n)=>{c.An?.(e,t,n),it(e,$t(e,n,null,0),t,null,null)})}var Wt=Symbol.for("wcstack.binder"),zt=Symbol.for("wcstack.binder.pending"),Dt=Symbol.for("wcstack.binder.taken"),Ut=new Map;function Ft(e,t){if(1!==e.nodeType||!e.isConnected)return;let n=It.get(e.getRootNode());void 0===n||!1===n.element?.isConnected?Ut.set(e,t):Rt(n,e,t?.range)}function qt(){let e=[...Ut];Ut.clear();for(let[t,n]of e)Ft(t,n);!function(){let e=function(){let e=globalThis[Wt];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}();if(null===e)return;let t=function(){let e=globalThis,t=e[zt];return void 0===t&&(t=[],e[zt]=t),t}();if(0===t.length)return;let n=t.splice(0,t.length),r=function(){let e=globalThis,t=e[Dt];return void 0===t&&(t=new WeakSet,e[Dt]=t),t}();for(let t of n)r.add(t),e.bind(t)}()}var Bt=class{constructor(){this.name="dirty",this.ot=(e,r)=>{if(0===e.n){let r=e.J;return r!==t&&r!==n&&(e.J=n,!0)}let i=null===r?null:r.ut;if(null===i)return!1;let s=i[e.F];return s!==t&&s!==n&&(i[e.F]=n,!0)}}Ho(e,t,n){null!==t.getter&&this.ot(t,n),e.wt(t,n),e.vn(t,n,this.ot)}Lo(e,t){let n=t.l.o.Tt;if(null!==n)for(let r of n)r.n===t.l.n?e.tt(r,t,this.ot):e.Jt(t,r,t=>e.tt(r,t,this.ot))}me(e,t,n){this.ot(t,n),c.ye?.(e,t,n),e.wt(t,n),e.vn(t,n,this.ot)}Bo(e,i,s){let o=0===i.n;if(!o&&null===s)return;let l=o?null:s.ut??=new Array(e.Oe).fill(t),a=null===l?i.J:l[i.F];if(a!==t&&a!==n&&a!==r&&(null===l||i.F in l))return a;a=r;try{return a=e.Do(i,null===l?null:s)}finally{null===l?i.J=a:l[i.F]=a}}qt(e){e.ut=null}pt(e){for(let t of e.B.all())null!==t.getter&&(0===t.n?t.J===n&&(t.J=r):e.Zt(t.f[t.n],e=>{let i=e.ut;null!==i&&i[t.F]===n&&(i[t.F]=r)}))}},Kt=0,Gt=new WeakMap;function Vt(e,t=e.getRootNode()){Gt.set(t,[...Gt.get(t)??[],e].filter((e,t,n)=>e.isConnected&&n.lastIndexOf(e)===t))}function Jt(e){let t=Gt.get(e)??[],n=t.filter(t=>t.getRootNode()===e);return Promise.any(n.map(e=>e.initializePromise.then(()=>e.W||e.connectedCallbackPromise))).then(()=>{},r=>n.length?Gt.get(e)!==t?Jt(e):Promise.reject(r.errors[0]):void 0)}var Qt=typeof HTMLElement>"u"?class{}:HTMLElement,Xt=class extends Qt{constructor(){super(),this.engine=null,this.Fn=!1,this.Ve=!1,this.V=null,this.ze=null,this.loaded=!1,this.ln=null,this.connectedCallbackPromise=new Promise((e,t)=>{this.sn=e,this.wo=t}),this.connectedCallbackPromise.catch(()=>{}),this.initializePromise=new Promise(e=>{this.rn=e})}static{this.getBindingsReady=Jt}static{this.hasConnectedCallbackPromise=!0}connectedCallback(){if(this.Fn){if(null!==this.ze)return void this.ze.Xe();Vt(this);let e=this.engine;if(null!==e){let t=e.root;t===this.getRootNode()&&!It.has(t)&&It.set(t,e),qt(),c.element?.(e,"back"),this.bo("$connectedCallback",50,()=>{this.isConnected&&c.element?.(e,"connected")})}return}this.Fn=!0;let e=this.getRootNode(),t=c.rt?.(this,e);if(t)return this.ze=t,!t.vo&&this.parentNode instanceof ShadowRoot&&Vt(this),void(void 0===t.jt?this.ko():t.jt()).then(e=>(this.loaded=!0,t.start(e,()=>this.So()))).then(()=>{this.rn(),this.sn()},e=>this.vt(e,t.vo));this.start(e),Vt(this)}disconnectedCallback(){if(null!==this.ze)return void this.ze.On();let e=this.engine;if(null===e)return;let t=e.root;It.get(t)===e&&It.delete(t),Vt(this,t),this.bo("$disconnectedCallback",51),c.element?.(e,"disconnected")}setInitialState(e){if(this.Ve&&k(14),this.loaded)this.ze.reset(e);else if(null===this.engine)if(null!==this.ln){let t=this.ln;this.ln=null,t(e)}else this.V=e;else this.engine.reset(e)}createState(e,t){let n=this.engine;null===n&&k(15),"readonly"===e&&n.Ce++;try{t(n.proxy)}finally{"readonly"===e&&n.Ce--}}async createStateAsync(e,t){let n=this.engine;null===n&&k(15),await t("writable"===e?n.proxy:new Proxy(n.proxy,{get(e,t,n){let r=Reflect.get(e,t,n);return"$setAll"===t||"$resolve"===t?(...e)=>(e.length>2&&k(8),r(...e)):r},set(){k(8)}}))}async ko(){await 0;let e=this.getAttribute("state");if(null!==e){let t=t=>[...t.querySelectorAll('script[type="application/json"]')].find(t=>t.id===e),n=t(this.getRootNode())??t(document);return void 0===n?Promise.reject(new Error(`[@wcstack/state] ${$(16,[e])}`)):Promise.resolve(JSON.parse(n.textContent||"{}"))}let t=this.getAttribute("src");if(null!==t)return async function(e){let t=new URL(e,document.baseURI).href;if(/\.json(?:[?#]|$)/.test(t)){let n=await fetch(t);return n.ok||k(13,[e,n.status]),await n.json()}return(await(import(t))).default??{}}(t);let n=this.getAttribute("json");if(null!==n)return Promise.resolve(JSON.parse(n));let r=this.querySelector('script[type="module"]');return null!==r?async function(e){let t=!1,n=e=>{e.effectiveDirective.startsWith("script-src")&&(t=!0)};document.addEventListener("securitypolicyviolation",n);let r="function"==typeof URL.createObjectURL,i=r?URL.createObjectURL(new Blob([e.text],{type:"application/javascript"})):"data:text/javascript;charset=utf-8,"+encodeURIComponent(`${e.text}\n//${++Kt}`);try{return(await(import(i))).default??{}}catch(e){throw await new Promise(e=>setTimeout(e)),new Error(`[@wcstack/state] ${t?$(42):$(43,[e instanceof Error?e.message:String(e)])}`,{cause:e})}finally{document.removeEventListener("securitypolicyviolation",n),r&&URL.revokeObjectURL(i)}}(r):null!==this.V?Promise.resolve(this.V):new Promise(e=>{this.ln=e})}async start(e){try{let t=e.host;(this.hasAttribute("mount")||this.hasAttribute("bind-component")||t?.hasAttribute("data-wc-definition"))&&b("scopes","<wcs-state>");let n=await this.ko(),r=y(n);if(r&&await r,this.getRootNode()!==e)return this.V=n,this.Fn=!1,void(this.isConnected&&this.connectedCallback());this.hasAttribute("enable-ssr")&&b("ssr","enable-ssr");let i=It.get(e)?.element;i?.isConnected&&(i.W||i.ze)&&k(47);let s=new ne(n,new Bt);s.element=this,this.engine=s,c.element?.(s,"mounting"),jt(s,e),qt(),s.bn(),this.So(),await s.we("$connectedCallback"),this.isConnected&&c.element?.(s,"connected"),this.sn()}catch(e){this.Ve=!this.W,this.vt(e)}}So(){this.W=!0,this.rn()}vt(e,t){this.He(this.W?50:49,e),this.rn(),t?this.sn():this.wo(e)}He(e,t){let n=["mount","bind-component","state","src"].flatMap(e=>this.hasAttribute(e)?[e,this.getAttribute(e)]:[]);console.error(`[@wcstack/state] ${$(e,[this.localName,...n])}`,t)}bo(e,t,n){(async()=>this.engine.we(e))().then(n,e=>this.He(t,e))}},Yt=[];function Zt(){return(Yt=Yt.filter(e=>e.deref())).map(e=>e.deref())}var en,tn=e=>t=>{let n=e(t);return e=>null==e?e:n(e)},nn="en";function rn(){if(re.locale!==en){en=re.locale;try{nn=Intl.getCanonicalLocales(en)[0]}catch{console.warn(`[@wcstack/state] ${$(48,[en])}`),nn="en"}}return nn}var sn={toFixed:{factory:e=>{let t=ve(e?.[0]??"0","toFixed");return e=>("number"!=typeof e&&ge("toFixed"),e.toFixed(t))},arity:[0,1]},locale:{factory:e=>{let t=e?.[0];return e=>("number"!=typeof e&&ge("locale"),e.toLocaleString(t??rn()))},arity:[0,1]},upper:{factory:tn(()=>e=>String(e).toUpperCase()),arity:[0,0]},lower:{factory:tn(()=>e=>String(e).toLowerCase()),arity:[0,0]},capitalize:{factory:tn(()=>e=>{let t=String(e);return 0===t.length?t:1===t.length?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)}),arity:[0,0]},trim:{factory:tn(()=>e=>String(e).trim()),arity:[0,0]},slice:{factory:tn(e=>{let t=[we(e,0,"slice")],n=e?.[1];return typeof n<"u"&&t.push(ve(n,"slice")),e=>String(e).slice(...t)}),arity:[1,2]},padStart:{factory:tn(e=>{let t=we(e,0,"padStart"),n=e?.[1]??"0";return e=>String(e).padStart(t,n)}),arity:[1,2]},padEnd:{factory:tn(e=>{let t=we(e,0,"padEnd"),n=e?.[1]??" ";return e=>String(e).padEnd(t,n)}),arity:[1,2]},repeat:{factory:tn(e=>{let t=we(e,0,"repeat");return e=>String(e).repeat(t)}),arity:[1,1]},reverse:{factory:tn(()=>e=>String(e).split("").reverse().join("")),arity:[0,0]},truncate:{factory:tn(e=>{let t=we(e,0,"truncate"),n=e?.[1]??"…";return e=>{let r=String(e);return r.length<=t?r:r.slice(0,t)+n}}),arity:[1,2]},join:{factory:e=>{let t=e?.[0]??", ";return e=>(Array.isArray(e)||k(30,["join"]),e.join(t))},arity:[0,1]},round:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","round"));return e=>("number"!=typeof e&&ge("round"),Math.round(e*t)/t)},arity:[0,1]},floor:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","floor"));return e=>("number"!=typeof e&&ge("floor"),Math.floor(e*t)/t)},arity:[0,1]},ceil:{factory:e=>{let t=Math.pow(10,ve(e?.[0]??"0","ceil"));return e=>("number"!=typeof e&&ge("ceil"),Math.ceil(e*t)/t)},arity:[0,1]},percent:{factory:e=>{let t=ve(e?.[0]??"0","percent");return e=>("number"!=typeof e&&ge("percent"),`${(100*e).toFixed(t)}%`)},arity:[0,1]},unit:{factory:tn(e=>{let t=e?.[0]??pe("unit");return e=>String(e)+t}),arity:[1,1]},date:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("date"),e.toLocaleDateString(t??rn()))},arity:[0,1]},time:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("time"),e.toLocaleTimeString(t??rn()))},arity:[0,1]},datetime:{factory:e=>{let t=e?.[0];return e=>(e instanceof Date||ye("datetime"),e.toLocaleString(t??rn()))},arity:[0,1]},ymd:{factory:e=>{let t=e?.[0]??"-";return e=>{e instanceof Date||ye("ymd");let n=e.getFullYear().toString(),r=(e.getMonth()+1).toString().padStart(2,"0"),i=e.getDate().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]},hms:{factory:e=>{let t=e?.[0]??":";return e=>{e instanceof Date||ye("hms");let n=e.getHours().toString().padStart(2,"0"),r=e.getMinutes().toString().padStart(2,"0"),i=e.getSeconds().toString().padStart(2,"0");return`${n}${t}${r}${t}${i}`}},arity:[0,1]}},on=!1,ln={name:"formats",install:function(){on||(on=!0,de(sn))}};function an(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;let r=new Array(t.length+1),i=new Array(t.length+1);for(let e=0;e<=t.length;e++)r[e]=e;for(let n=1;n<=e.length;n++){i[0]=n;for(let s=1;s<=t.length;s++){let o=e[n-1]===t[s-1]?0:1;i[s]=Math.min(r[s]+1,i[s-1]+1,r[s-1]+o)}for(let e=0;e<=t.length;e++)r[e]=i[e]}return r[t.length]}function un(e,t){if(0===e.length)return"";let n=e.toLowerCase(),r=null,i=3;for(let e of t){let t=an(n,e.toLowerCase(),2);t<i&&(r=e,i=t)}return null!==r?` Did you mean "${r}"?`:""}var cn=" Validate statically: npx @wcstack/lint <file>.",hn=["enableMustache","sameValueGuard","enableDirectionalInitialSync"],dn=(e,t)=>`<${e}${t.map((e,t)=>t%2?`="${e}"`:` ${e}`).join("")}>`,fn="https://github.com/wcstack/wcstack/blob/main/docs/csp.md",pn={1:()=>"$scan was removed (use $watch or $on)",2:e=>`"${e}" is a getter without a setter`,3:e=>`no row for "${e}"`,4:(e,t)=>`cannot write "${e}": its parent is ${t}`,5:e=>`"${e}" is not a method`,6:e=>`$getAll("${e}"): no loop level in common with the context`,7:e=>`$eqIndex("${e}") needs a list row scope.`,8:()=>"This state is readonly.",9:e=>`$setAll("${e}") needs indexes ([] for every match)`,10:(e,t)=>`$setAll("${e}", …, { spread: true }) needs an array of ${t} values`,11:()=>"updates did not settle after 32 passes",41:()=>"render chain depth limit exceeded (100 drains that rendering itself started); bindings for this batch were not applied.",12:(e,t)=>`binding "${e}: ${t}" failed to apply.`,13:(e,t)=>`failed to load "${e}": ${t}`,14:()=>"this <wcs-state> failed to initialize; create a new one",15:()=>"state is not initialized",16:e=>`no <script> with id "${e}"`,42:()=>`The inline <script> of <wcs-state> was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/state, or allow blob: in script-src. Moving the state into an external file (src="./state.js") needs neither. See ${fn}`,43:e=>`Failed to evaluate the inline <script> of <wcs-state>: ${e}. If this page sets a Content-Security-Policy, see ${fn}`,17:e=>`a subscriber of token "${e}" threw.`,18:e=>`${e} must be an array of strings.`,19:e=>`${e} entries must be non-empty strings.`,20:(e,t,n)=>`${e} entry "${t}" conflicts with the reserved namespace name "${n}".`,21:(e,t)=>`${e} entry "${t}" is duplicated.`,22:()=>"$on must be an object of handlers.",23:e=>`$on entry "${e}" is not declared in $eventTokens.`,24:e=>`$on entry "${e}" must be a function.`,25:e=>`view-transition naming-limit (${e}) reached.`,26:e=>`filter ${e} requires at least one option`,27:e=>`filter ${e} requires a number as option`,28:e=>`filter ${e} requires a number value`,29:e=>`filter ${e} requires a date value`,30:e=>`filter ${e} requires an array value`,31:()=>"init=/sync= modifiers require enableDirectionalInitialSync.",33:(e,t)=>`Unknown binding modifier "${e}" in "${t}".`,34:e=>`Binding modifier "${e}" may only be specified once.`,35:(e,t)=>`Invalid ${e} modifier value "${t}".`,36:()=>"Event bindings only allow init=none.",37:(e,t)=>`Binding type "${e}" does not support init=${t}.`,38:e=>`Property "${e}" is not declared by wcBindable.`,39:(e,t)=>`init=${e} is incompatible with wcBindable member "${t}".`,40:e=>`sync=connect requires observable property "${e}".`,44:(e,t)=>`${e}: "${t}" is not one of its options, or not of the option's type.${"bootstrapState"===e&&hn.includes(t)?" 4.0 moved it to the state's $behavior.":""}`,45:()=>"a re-set state may not change $behavior: create the element again.",47:()=>'a second <wcs-state> on the same root: there is one state tree per root — graft a subtree with <wcs-state mount="path"> (v1\'s name="…" is gone: read the mounted state by its path).',48:e=>`the locale "${e}" (<html lang> or bootstrapState's locale) is not a language tag Intl takes (en-US, not en_US): the locale filters use "en".`,46:()=>'$features must be an array of add-on names (["temporal", "formats"]).',49:(e,...t)=>`${dn(e,t)} failed to initialize.`,50:(e,...t)=>`${dn(e,t)} $connectedCallback failed.`,51:(e,...t)=>`${dn(e,t)} $disconnectedCallback failed.`,101:e=>`Invalid bindText: "${e}". Missing ':' separator between propPart and statePart.`,102:(e,t)=>`"${e}": "${t}" takes no modifiers or filters on its left side — write "${t}:".`,103:e=>`"${e}": "else" takes no value — write "else:".`,104:e=>`Invalid spread binding "${e}": spread target path is required.`,105:e=>`Invalid spread binding "${e}": filters are not allowed on spread targets.`,106:e=>`"${e}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (class, attr, style, command, eventToken, state).`,107:(e,t)=>`unterminated ${e} quote in the filter arguments "(${t})". Close the quote.`,108:e=>`Invalid filter format: missing closing parenthesis in "${e}".`,109:e=>`Invalid filter format: missing opening parenthesis in "${e}".`,110:e=>`Invalid filter format: ")" comes before "(" in "${e}".`,111:(e,t)=>`"${e}": unexpected "${t}" after the filter's closing ")" — separate filters with "|" (write "${e.slice(0,e.lastIndexOf(")")+1)}|${t}").`,112:e=>`an empty filter in "${e}" — remove the extra "|" or name the filter.`,113:(e,t)=>`"${e}" is not a filter name: a modifier list "#${t}" comes before the input filters, not inside one`,114:e=>`"${e}" is not a filter name: "#" cannot appear in one.`,115:e=>`"${e}": a binding takes one modifier list after a single "#"`,116:e=>`"${e}": the left side of a binding must name a property — write "<property>: <path>" (modifiers and input filters come after the name).`,117:(e,t)=>`"${e}" has ${t} path segments — the limit is 512.`,32:e=>`"${e}": 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.`,120:e=>`"${e}": a state path cannot go through "__proto__" or "prototype" (it would reach every object's prototype).`,121:e=>`"${e}": "for:" takes no filters — a row is "<path>.<index>", so the rows of a filtered list would name other elements. Declare a getter that returns the filtered list and loop over it ("for: <getter>").`,119:e=>`"${e}": the right side of a binding must name a state path — write "<property>: <path>" (a path segment cannot be empty; "." alone and a leading "." are the loop-relative shorthand).`,201:e=>`Invalid bindText: "${e}". 'if', 'elseif', 'else', and 'for' bindings must be single binding.`,202:e=>`"${e}:" must follow an "if:" template`,204:e=>`a "${e}:" template at the top of inserted content was not rendered, as it would render beside itself out of the inserter's reach: wrap it in an element.`,203:e=>`"${e}:" replaces its element, so it cannot be used inside a "for" / "if" template (a row or branch keeps its nodes by position): bind innerHTML: on a wrapper element instead.`,301:e=>`Path "${e}" does not exist on the state tree.`,401:(e,t)=>`class.${e} needs a boolean, got ${t}.`,501:e=>`filter not found: ${e}.`,601:(e,t,n)=>`filter "${e}" requires at least ${t} argument(s) (${n} given).`,602:(e,t,n)=>`filter "${e}" accepts at most ${t} argument(s) (${n} given).`,701:e=>`"${e}" depends on itself`,801:e=>`"${e}"`,901:(e,t,n,r)=>`${e}("${t}") takes ${n} index(es), got ${r}.`,902:(e,t,n,r)=>`${e}("${t}") takes at most ${n} index(es), got ${r}.`,1001:e=>`"${e}": list index parameters run from $1 to $128.`,1101:e=>`"${e}" uses "**", which is not accepted here.`,1201:(e,t)=>`"${e}: ${t}": the right-hand side must be $command.<name>`,1202:(e,t)=>`<${e}> declares no static wcBindable (${t}).`,1203:(e,t)=>`<${e}> declares no command "${t}".`,1204:(e,t)=>`<${e}> declares no property "${t}".`,1301:e=>`eventToken "${e}" is not declared in $eventTokens.`,1302:e=>`"$command.${e}" is not declared in $commandTokens.`,1401:(e,t,n=0)=>`"${e}" needs ${t} enclosing loop level(s); the scope provides ${n}.`,1402:e=>`"${e}" is relative: it needs an enclosing "for" template`,1403:(e,t,n)=>`"${e}" ranges over the rows of "${t}", but the enclosing "for" template at that level renders "${n}".`,1501:(e,t)=>`<${e}> declares no static wcBindable (${t}).`,1601:(e,t)=>`${e} was removed: write ${t}.`,1701:(e,t)=>`${e} was removed: write ${t}.`};function mn(e,t){let n=pn[e];return void 0===n?`${_(e)}#${e} ${t.join(" ")}`:_(e)+n(...t)}var gn=new Set(["binding-syntax","template-syntax","filter-unknown","filter-arity","index-arity","wildcard-rank","token-undeclared","binding-path-missing","index-param-range"]),yn=[[/no loop level in common with the context/,"; pass indexes ([] for all)."],[/"([^"#]+)#([^"]*)" is not a filter name: a modifier list .* comes before the input filters/,' — write "<property>#$2|$1".'],[/\[wcs\/recursion-unsupported\]/," 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."],[/must be single binding/,' Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).'],[/\[wcs\/wildcard-rank\] .* needs \d+ enclosing/,' Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.'],[/\[wcs\/wildcard-rank\] .* ranges over the rows of/,' A "*" in a binding is the row of the loop around it: read a row of another list in a getter, with $resolve(path, indexes).'],[/\[wcs\/binding-type-expectation\] class\.([^ ]+)/,' Write "class.$1: path|truthy" to toggle on truthiness.'],[/path segments — the limit/," Every prefix of a path is interned, so the cost grows with the square of the depth."],[/\[wcs\/index-arity\] \$resolve/,' $resolve takes one index per "*"; $getAll / $setAll take at most that many (fewer expands the rest).'],[/"([^"#]+)#[^"]*" is not a filter name: "#" cannot appear in one/,' Modifiers belong on the left side of the binding, before the ":" — write "$1" here.']],bn={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function vn(e,t,n){let r=(void 0!==t&&e.includes("[wcs/filter-unknown]")?function(e){if("substr"===e)return' "substr" was removed in 4.0 — write slice(start, start + length): slice takes the end index, not a length.';let t=Object.hasOwn(bn,e)?bn[e]:null;return null===t?null:` "${e}" was renamed "${t}" in 3.2 and removed in 4.0 — write "${t}".`}(t):null)??(void 0!==t&&void 0!==n?un(t,n):"");for(let[t,n]of yn){let i=t.exec(e);null!==i&&(r+=n.replace(/\$(\d)/g,(e,t)=>i[Number(t)]))}let i=/"([^"#]+)#([^"]+)": a binding takes one modifier list/.exec(e);null!==i&&(r+=` — write "${i[1]}#${i[2].split("#").join(",")}".`),e.includes("[wcs/filter-unknown]")&&(e.includes("formats add-on")?r+=' On a split auto page: features="formats" on the root, or "$features": ["formats"].':ue.some(fe)||(r+=' No formatting filters are installed — add the formats add-on: installFeatures([formats]) from "@wcstack/state/features/formats" (a split auto page: features="formats", or "$features").'));let s=/\[wcs\/([\w-]+)\]/.exec(e);return null!==s&&gn.has(s[1])&&!/ path segments — the limit is |inserted content was not rendered|formats add-on/.test(e)&&(r+=cn),r}var wn=new WeakMap,_n=new WeakMap,$n=new WeakSet,kn=new WeakSet;function Sn(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function Nn(e){let t=new Set;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"$"!==e[0]&&"constructor"!==e&&t.add(e);return[...t]}function An(e,t){let n=[];for(let e=t;null!==e;e=e.d)n.unshift(e);let r=e.target,i=t=>null===t?null:function(e,t){let n=t.t.split("."),r=n.findIndex((e,t)=>t>0&&/^\d/.test(e));return r<0||n.indexOf("*",r)>=0||void 0!==Sn(e.target,t.t)?.get?t:e.B.Ot(o(t.t).o)}(e,t);for(let t of n){if(null!=i(t)?.getter||null===r||"object"!=typeof r)return null;if("*"===t.s){if(!Array.isArray(r)||0===r.length)return null;r=r[0];continue}if(Array.isArray(r)&&/^\d+$/.test(t.s)){if(Number(t.s)>=r.length)return null;r=r[Number(t.s)];continue}let n=Sn(r,t.s);if(void 0===n&&null===t.d&&e.pt.has(t.s))return null;if(void 0===n){let n=Nn(r),s=i(t.d);for(let t of e.B.all())t.d===s&&null!==t.getter&&n.push(t.s);return{seg:t.s,names:n}}if(void 0!==n.get||void 0!==n.set)return null;r=n.value}return null}function En(e){$n.has(e)||($n.add(e),setTimeout(()=>function(e){$n.delete(e);let t=wn.get(e);if(void 0===t)return;let n=_n.get(e);void 0===n&&_n.set(e,n=new Set);for(let[r,i]of t){if(n.has(r))continue;n.add(r);let t=An(e,r);if(null===t)continue;let s=[...e.root?.querySelectorAll(`${re.tagNames.state}[mount]`)??[]].find(e=>!kn.has(e)&&(r.t+".").startsWith(e.getAttribute("mount")+"."));if(void 0!==s){n.delete(r),s.initializePromise.then(()=>{kn.add(s),En(e)});continue}let[l,a]=i?["watch-path-missing","$watch path"]:["binding-path-missing","Bound path"];c.nt?.(e,{type:"state:path-unresolved",source:i?"watch":"binding",path:r.t,missingSegment:t.seg});let u=e.B.Ot(o(r.t).o),h="";if(void 0!==u&&u!==r&&null!==u.getter){let e=u.f.slice(1).map((e,t)=>`for: ${0===t?e.t:e.t.slice(u.f[t].t.length+2)}`);h=` The getter "${u.t}" is declared for the rows of ${e.join(" → ")}; a list named by an index has rows of its own.`}console.warn(`[@wcstack/state] [wcs/${l}] ${a} "${r.t}" does not resolve on the state tree: "${t.seg}" is not declared.${un(t.seg,t.names)}${h} Updates to this path will be silently dropped.${cn}`)}}(e),0))}function Cn(e,t,n=!1){if("$"===t.t[0]||t.t.includes("#")||!n&&null===t.d)return;let r=wn.get(e);void 0===r&&wn.set(e,r=new Map),r.has(t)||r.set(t,n),En(e)}var xn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Tn=!1;function Pn(e,t,n){let r="html"===n.name?"innerHTML":n.name;if(Tn||!(t instanceof TypeError)||!xe(r)||!("trustedTypes"in globalThis))return;Tn=!0;let i="function"==typeof Ce()?.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 "${r}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${i}\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:n.a,property:r})}var On=new WeakMap;function Mn(e,t,n){let r=e[t],i=void 0===n?void 0===r?null:`the event carried no detail (undefined) while element.${t} is ${typeof r}`:null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,t)||null!==r&&"object"==typeof r?null:`the event's detail is an object with a "${t}" key while element.${t} is ${typeof r}`;if(null===i)return;let s=On.get(e);void 0===s&&On.set(e,s=new Set),!s.has(t)&&(s.add(t),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${e.localName}> "${t}": ${i}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${t}, or (e) => e.target.${t}) on that wcBindable property.`))}var Ln={name:"diagnostics",install(){c.Ao=vn,c.Fo=mn,c.go=Cn,c.detail=Mn,c.Ve=h(c.Ve,Pn),c.se=h(c.se,(e,t)=>{(function(e){let t=e.$recursion;if(null===t||"object"!=typeof t)return;let n=Object.entries(t);if(1!==n.length||"string"!=typeof n[0][1])return;let[r,i]=n[0];if(!r.endsWith(".*")||!i.endsWith(".*"))return;let s=r.slice(0,-2),o=i.slice(0,-2),l=`.${i}`,a=`${s}.**`,u=Nn(e),c=u.filter(e=>e.startsWith(a)).map(e=>e.slice(a.length)),h=e=>v(`[wcs/recursion-declaration-invalid] ${e}`);for(let e of c){(e===`.${o}`||e.startsWith(`.${o}.`))&&h(`"${a}${e}" names the recursion structure itself (the "${o}" lists): recursive getters compute values over the nodes.`);for(let t of c)t.length>e.length&&t.endsWith(e)&&new RegExp(`^(?:${xn(l)})+$`).test(t.slice(0,t.length-e.length))&&h(`"${a}${e}" and "${a}${t}" expand to the same concrete path at different depths (they differ by whole repetitions of "${i}"). Rename one of them.`);let t=new RegExp(`^${xn(r)}(?:${xn(l)})*${xn(e)}$`);for(let n of u)!n.includes("**")&&t.test(n)&&h(`"${n}" is already defined on the state, so the recursive getter "${a}${e}" cannot expand to it.`)}})(t),function(e){_n.delete(e),wn.has(e)&&En(e)}(e)})}},In={},jn=/\.\d/,Rn=new Set(Object.getOwnPropertyNames(Object.prototype)),Hn=0,Wn=!1,zn=null,Dn=()=>{Wn=!1,Hn++};function Un(){if(null===zn)if("function"==typeof MessageChannel){let e=new MessageChannel;e.port1.onmessage=Dn,e.port1.unref?.(),zn=()=>e.port2.postMessage(0)}else zn=()=>setTimeout(Dn,0);return Wn||(Wn=!0,zn()),Hn}function Fn(e,t){let n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(!n.has(e)){n.add(e);for(let n of e.$e){for(let r of t)if(n.Q(r)&&(n.n===r.n||!(r.n<e.n&&e.f[r.n+1].Q(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var qn=class{constructor(e,t){this.active=!1,this.Ye=new Map,this.n=0,this.$o=-1,this.Cn=new Set,this.We=null,this.engine=e,this.it=t}Zo(){let e=this.engine;this.Ye.clear();for(let t of this.it)t.getter=null!==t.p.getter||t.p.de,t.s=new WeakMap,this.prime(t,()=>{0===t.p.n?t.getter&&t.s.set(In,e.v(t.p,null)):this.In(t.p,1,null,n=>{t.getter&&this.prime(t,()=>t.s.set(n,e.v(t.p,n)))})});this.active=!0}prime(e,t){try{t()}catch(t){console.error(`[@wcstack/state] $watch initial evaluation of "${e.t}" threw.`,t),c.nt?.(this.engine,{type:"state:watch-error",phase:"prime",path:e.t,error:t})}}No(){this.active=!1,this.Ye.clear()}In(e,t,n,r){let i=this.engine.De(n,e.f[t]);for(let n of i.u)t===e.n?r(n):this.In(e,t+1,n,r)}an(e,t,n,r){let i=this.Ye.get(e);void 0===i&&this.Ye.set(e,i=new Map);let s=i.get(t);void 0===s?i.set(t,[n,this.n,r]):(s[1]<this.n&&(s[1]=this.n),s[2]||=r)}he(e,t,n,r,i){if(this.active){(this.We??=new Set).add(e);for(let s of this.it){let o=s.p;o.n!==e.n||!o.Q(e)||this.an(s,t,s.getter?s.s.get(t??In):o===e&&i&&this.engine.Bt&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}}ye(e,t){if(this.active)for(let n of this.it)(n.getter||=null!==n.p.getter||n.p.de)&&n.p.n===e.n&&n.p.Q(e)&&this.an(n,t,n.s.get(t??In),!1)}Yt(e,t){if(!this.active)return;let n=null;for(let r of this.it){let i=r.p;if(!(i.n<e.n||i.f[e.n]!==e.o)){n??=new Set(t);for(let t of e.u)n.has(t)||(i.n===e.n?this.an(r,t,void 0,!0):this.In(i,e.n+1,t,e=>this.an(r,e,void 0,!0)))}}}Te(){let e=this.We;if(this.We=null,!this.active||0===this.Ye.size)return;let t=this.Ye;this.Ye=new Map;let n=this.engine,r=[];for(let i of this.it){let s=t.get(i);if(void 0===s)continue;let o,l=[...s].filter(([e])=>null===e||e.y);l.length>1&&l.sort((e,t)=>Kn(e[0],t[0]));for(let[t,[s,a,u]]of l){let l,h="evaluate",d=n.c;this.n=a+1,n.xe++;try{if(l=n.v(i.p,t),i.getter&&(i.s.set(t??In,l),Object.is(l,s)&&(jn.test(i.t)||null!==t&&!u&&!(o??=null!==e&&Fn(Bn(i.p),e)))))continue;if(a>32){r.includes(i.t)||r.push(i.t);continue}n.c=t,c.nt?.(n,{type:"state:watch-fired",path:i.t}),h="handler",i.handler.call(n.proxy,l,s,...n._(t))}catch(e){console.error(`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`,e),c.nt?.(n,{type:"state:watch-error",phase:h,path:i.t,error:e})}finally{n.c=d,this.n=0,n.xe--}}}r.length>0&&this.xo(r)}xo(e){let t=Un();t!==this.$o&&(this.$o=t,this.Cn.clear());let n=e.filter(e=>!this.Cn.has(e));if(0!==n.length){for(let e of n)this.Cn.add(e);console.error("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),c.nt?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:n})}}};function Bn(e){for(;null===e.getter&&null!==e.d;)e=e.d;return e}function Kn(e,t){let n=[],r=[];for(let t=e;null!==t;t=t.l.re)n.unshift(t.b);for(let e=t;null!==e;e=e.l.re)r.unshift(e.b);for(let e=0;e<n.length&&e<r.length;e++)if(n[e]!==r[e])return n[e]-r[e];return n.length-r.length}var Gn="$streamStatus",Vn="$streamError",Jn=new Set(Object.getOwnPropertyNames(Object.prototype)),Qn=!1;function Xn(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return void 0!==e.get||void 0!==e.set||"function"==typeof e.value}return!1}var Yn=class{constructor(e,t,n){this.engine=e,this.entries=t,this.D=n}set(e,t,n){Qn=!0;try{this.engine.P(this.engine.o(`${e}.${t}`),null,n)}finally{Qn=!1}}er(){for(let e of this.entries)this.start(e,!0)}tr(){for(let e of this.entries)e.st=!1,e.Y?.abort(),e.Y=null}nr(){for(let e of this.entries)e.st=!1,null!==e.Y&&(e.Y.abort(),e.Y=null),this.set(Gn,e.name,"idle")}ye(e){let t=this.D.n;for(let n of this.entries)n.g===e&&(n.n=n.st?Math.max(n.n,t):t,n.st=!0)}Te(){let e=this.engine,t=this.D,n=[];for(let i of this.entries){if(!i.st)continue;let s=i.n;if(i.st=!1,s>32)n.push(i.name),i.g.J=r;else{t.n=s+1,e.xe++;try{this.start(i,!1)}finally{e.xe--,t.n=0}}}n.length>0&&t.xo(n)}start(e,t){let n,i=this.engine;if(null!==e.Y&&e.Y.abort(),e.Y=null,null!==e.g){let s=e.g;s.getter=e.args;let o=s.$e.slice();Zn(s);try{n=i.read(s,null),function(e,t,n){null!==n&&"function"==typeof n?.then&&v(`$stream "${e}": args must be synchronous (it returned a Promise).`);for(let n of t.$e)n.n>0&&v(`$stream "${e}": args must not read a wildcard path ("${n.t}").`),(n.t===e||n.t===`${Gn}.${e}`||n.t===`${Vn}.${e}`)&&v(`$stream "${e}": args must not read the stream itself ("${n.t}").`)}(e.name,s,n)}catch(n){Zn(s);for(let e of o)e.jn(s);if(s.J=r,t)throw n;return this.set(Vn,e.name,n),void this.set(Gn,e.name,"error")}}let s=new AbortController;e.Y=s,i.P(i.o(e.name),null,e.V),this.set(Vn,e.name,null),this.set(Gn,e.name,"active"),this.or(e,s,n)}async or(e,t,n){let r=this.engine,i=t.signal,s=()=>!i.aborted&&e.Y===t,o=r.o(e.name),l=this.D.n,a=Un(),u=e=>{Un()===a&&(this.D.n=l);try{e()}finally{this.D.n=0}},c=e.V;try{let t=await e.source(n,i);if(!s())return;let l=t=>{c=void 0!==e.Ro?e.Ro(c,t):t,u(()=>r.P(o,null,c))};if(null!==t&&"function"==typeof t?.getReader){let e=t.getReader();for(i.addEventListener("abort",()=>{e.cancel().catch(()=>{})});;){let t=await e.read();if(!s())return;if(t.done)break;l(t.value)}}else{if(null===t||"function"!=typeof t?.[Symbol.asyncIterator])throw new TypeError(`$stream "${e.name}": source must return an async iterable or a ReadableStream`);{let e=t[Symbol.asyncIterator]();for(i.addEventListener("abort",()=>{e.return?.()});;){let t=await e.next();if(!s())return;if(t.done)break;l(t.value)}}}if(!s())return;e.Y=null,u(()=>this.set(Gn,e.name,"done"))}catch(n){if(!s())return;e.Y=null,t.abort(),u(()=>{this.set(Vn,e.name,n),this.set(Gn,e.name,"error")})}}};function Zn(e){for(let t of e.$e){let n=t.G.indexOf(e);n>=0&&t.G.splice(n,1),t.At.delete(e)}e.$e.length=0,e.J=t}var er=new WeakMap;function tr(e){let t=er.get(e);return t?.target===e.target?t:void 0}function nr(e,t){let n=new qn(e,function(e,t){if(void 0===t)return[];(null===t||"object"!=typeof t)&&v("$watch must be an object mapping paths to handler functions.");let n=[];for(let r of Object.keys(t)){let i=t[r];(""===r||"$"===r[0]||r.includes("@")||Rn.has(r))&&v(`$watch path "${r}" is not a path of the state tree.`),"function"!=typeof i&&v(`$watch entry "${r}" must be a function.`);let s=e.o(r);c.go?.(e,s,!0),n.push({t:r,p:s,handler:i,getter:!1,s:new WeakMap})}return n}(e,t.$watch)),r=new Yn(e,function(e,t){let n=t.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&v("$stream must be an object mapping stream names to definitions.");let r=[],i={},s={};for(let o of Object.keys(n)){let l=n[o];(""===o||"$"===o[0]||/[.*]/.test(o)||Jn.has(o))&&v(`$stream entry "${o}" must be a flat property name.`),(null===l||"object"!=typeof l)&&v(`$stream entry "${o}" must be an object.`);let a=l.source,u=l.fold,c=l.args,h=l.initial;"function"!=typeof a&&v(`$stream entry "${o}" needs a source function.`),void 0!==u&&"function"!=typeof u&&v(`$stream entry "${o}": fold must be a function.`),void 0!==u&&!("initial"in l)&&v(`$stream entry "${o}": fold needs an initial value.`),void 0!==c&&"function"!=typeof c&&v(`$stream entry "${o}": args must be a function.`),Xn(t,o)&&v(`$stream entry "${o}" collides with a getter, setter or method of the state.`),void 0===t[o]&&(t[o]=h),i[o]="idle",s[o]=null,r.push({name:o,source:a,Ro:u,V:h,Y:null,st:!1,n:0,g:void 0===c?null:e.o(`$streamArgs.${o}`),args:void 0===c?null:function(){return c(this)}})}return t[Gn]=i,t[Vn]=s,r}(e,t),n),i=er.get(e);void 0!==i&&(i.D.No(),i.Rt.tr()),er.set(e,{D:n,Rt:r,Xe:i?.Xe??!1,target:t})}function rr(e,t){let n=er.get(e);if(void 0!==n&&"mounting"!==t&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==t&&(n.Xe="connected"===t),n.target===e.target)){if("disconnected"===t)return n.D.No(),void n.Rt.nr();n.Xe&&(n.D.Zo(),n.Rt.er())}}var ir=["$streamStatus","$streamError"],sr={name:"temporal",install(){c.se=h(c.se,nr),c.element=h(c.element,rr),c.he=h(c.he,(e,t,n,r,i,s)=>tr(e)?.D.he(t,n,r,i,s)),c.ye=h(c.ye,(e,t,n)=>{let r=tr(e);void 0!==r&&(r.D.ye(t,n),r.Rt.ye(t))}),c.Yt=h(c.Yt,(e,t,n)=>tr(e)?.D.Yt(t,n)),c.Te=h(c.Te,e=>{let t=tr(e);void 0!==t&&(t.D.Te(),t.Rt.Te())}),c.zt=d(p,c.zt,(e,t)=>{let n=t.split(".",1)[0];if(ir.includes(n))return n===t?e.target[t]:e.read(e.o(t),null)}),c.Pe=d(f,c.Pe,(e,t)=>(!Qn&&36===t.t.charCodeAt(0)&&ir.includes(t.t.split(".",1)[0])&&v(`"${t.t}" is read-only (the stream runtime owns it).`),!1))}},or=new WeakMap,lr=!1,ar=/^(?!prototype$)[^\d.*$][^.*]*$/;function ur(e,t){let n=t.$listKeys,r=new Map;if(void 0!==n){(null===n||"object"!=typeof n)&&v("$listKeys must be an object mapping list paths to a key field or function.");for(let t of Object.keys(n)){let i=n[t];"string"==typeof i?r.set(e.o(t),e=>e[i]):"function"==typeof i?r.set(e.o(t),i):v(`$listKeys "${t}" must be a field name or a function.`)}}or.set(t,r)}function cr(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function hr(e,t,n){let r=new Map;for(let i of t){cr(i)||v(`$listKeys "${e}": rows must be plain objects.`);let t=n(i);null==t&&v(`$listKeys "${e}": a row has no key.`),r.has(t)&&v(`$listKeys "${e}": duplicate key ${JSON.stringify(t)}.`),r.set(t,i)}return r}function dr(e,t,n,r){if(lr||!Array.isArray(r))return!1;let i=or.get(e.target)?.get(t);if(void 0===i)return!1;let s=e.yt(t,n);if(!Array.isArray(s)||s===r)return!1;let o=hr(t.t,s,i);hr(t.t,r,i);let l=[],a=[],u=s.length===r.length;for(let e=0;e<r.length;e++){let t=r[e],n=o.get(i(t));l.push(n??t),void 0!==n&&a.push([e,n,t]),l[e]!==s[e]&&(u=!1)}let c=[];for(let[e,t,n]of a){for(let r of Object.keys(n))Object.is(t[r],n[r])||c.push([e,r,n[r]]);for(let r of Object.keys(t))!(r in n)&&null!==t[r]&&c.push([e,r,null])}if(u&&0===c.length)return!0;if(!u){lr=!0;try{e.P(t,n,l)}finally{lr=!1}}if(c.length>0){let r=e.De(0===t.n?null:n,t);for(let[n,i,s]of c){if("__proto__"===i)continue;let o=r.u[n],l=ar.test(i)?e.o(`${t.t}.*.${i}`):null;null===l?.getter?e.P(l,o,s):(o.T[i]=s,e.P(e.o(`${t.t}.*`),o,o.T,!0))}}return!0}var fr={name:"list-keys",install(){c.se=h(c.se,ur),c.Pe=d(f,c.Pe,dr)}},pr=new WeakMap,mr=new WeakMap,gr="will not graft: the root state failed to initialize.",yr=new WeakSet,br=new WeakMap,vr=["$stream","$streams","$scan","$recursion","$watch","$listKeys","$renderedCallback","$updatedCallback","$behavior","$features"],wr=["$commandTokens","$eventTokens","$on","$errorCallback"],_r=e=>`[@wcstack/state] <${re.tagNames.state} mount="${e}">`,$r=new Set(["$getAll","$setAll","$resolve","$postUpdate","$dependOn","$eq","$eqIndex"]),kr=e=>e?.element?.isConnected?e:void 0;function Sr(e){let t=mr.get(e);return void 0!==t&&!Array.isArray(t)&&t.isConnected}function Nr(e,t){let n=mr.get(t);if(mr.delete(t),Array.isArray(n))for(let t of n)xr(t,e)}function Ar(e){let t=pr.get(e.root);t?.get(e.t)===e&&t.delete(e.t)}function Er(e,t){console.error(`${_r(e.t)} ${t}`),Ar(e),e.Ge?.(),e.Ge=null}function Cr(e,t){let n=e.state?.[t];if("function"==typeof n)try{let t=n.call(e.chroot);null!==t&&"object"==typeof t&&"function"==typeof t.then&&t.then(void 0,e=>console.error(e))}catch(e){console.error(e)}}function xr(e,t){if(yr.has(t))return Er(e,"will not graft: its component is wired to its host.");let n=e.state,r=t.target,i=e.t.split("."),s=r;for(let e of i)s=s?.[e];if(void 0!==s&&!0!==t.hydrated)return Er(e,`will not graft: the root state already has "${e.t}".`);let o=function(e,t){let n=e=>`${t}.${e}`;return new Proxy({},{get(t,r){if("symbol"==typeof r)return;if(36!==r.charCodeAt(0))return e.proxy[n(r)];let i=e.proxy[r];return"$eqPath"===r?(e,t)=>i(n(e),n(t)):$r.has(r)&&"function"==typeof i?(e,...t)=>i(n(e),...t):i},set:(t,r,i)=>"symbol"!=typeof r&&(e.proxy[n(r)]=i,!0)})}(t,e.t);e.chroot=o;let l={},a={},u=new Set;for(let t=n;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let n of Object.getOwnPropertyNames(t)){if(u.has(n)||"constructor"===n)continue;u.add(n);let{get:r,set:i,value:s}=Object.getOwnPropertyDescriptor(t,n);if(void 0!==r||void 0!==i)a[`${e.t}.${n}`]={get:r&&function(){return r.call(o)},set:i&&function(e){i.call(o,e)}};else{if("$"===n[0])continue;if("function"==typeof s){let t=s.bind(o);a[`${e.t}.${n}`]={get:()=>t}}else l[n]=s}}if(void 0===s){for(let e=1;e<i.length;e++){let n=t.o(i.slice(0,e).join("."));null==t.yt(n,null)&&t.P(n,null,{})}t.P(t.o(e.t),null,l)}t.Yn(Object.defineProperties({},a));for(let e in a)t.We(t.o(e),null);e.engine=t;let c=br.get(t);void 0===c&&br.set(t,c=[]),c.push(e),e.el.isConnected&&Cr(e,"$connectedCallback"),e.Ge?.(),e.Ge=null}function Tr(e,t){let n=mr.get(e);if(Array.isArray(n))for(let e of n)Er(e,gr);mr.set(e,t)}var Pr=new WeakMap;function Or(e,t){let n=e.getAttribute("mount");if(null===n)return null;let r={el:e,root:t,t:n,state:null,engine:null,chroot:null,Ge:null},i=null;if(function(e){return""!==e&&e.split(".").every(e=>""!==e&&!/[*$#@\s]/.test(e))}(n))if(e.hasAttribute(re.bindAttributeName))i='injections (data-wcs="state.<key>: …") are not supported — read the root path in a root getter.';else{let e=pr.get(t);void 0===e&&pr.set(t,e=new Map);let s=e.get(n);if(void 0!==s&&s!==r&&(null===s.engine?s.el.isConnected:kr(s.engine)))i=`will not graft: another volume already holds "${n}".`;else{if(null===s?.engine){let e=mr.get(t);Array.isArray(e)&&mr.set(t,e.filter(e=>e!==s)),s.Ge?.(),s.Ge=null}e.set(n,r)}}else i='has an invalid mount path: it must be a static path (no "*", "$", "#", "@").';return{vo:!0,start(e){if(null!==i)return Er(r,i);if(pr.get(t).get(n)===r){for(let t of vr)if(void 0!==e[t])return Er(r,`${t} is not run in a volume — declare it on the root state.`);for(let t of wr)void 0!==e[t]&&console.warn(`${_r(n)} ${t} is not run in a volume (it belongs to the root).`);return r.state=e,new Promise(e=>{r.Ge=e;let n=kr(It.get(t)),i=mr.get(t);void 0!==n?xr(r,n):Sr(t)?Er(r,gr):mr.set(t,[...Array.isArray(i)?i:[],r])})}},Xe(){null!==r.engine&&Cr(r,"$connectedCallback")},On(){null!==r.engine&&Cr(r,"$disconnectedCallback")},reset(){v(`re-setting a volume is not supported: its data was copied into the root tree at "${n}" — write the paths under it on the root instead.`)}}}var Mr=new WeakMap,Lr=new WeakMap;function Ir(e,t){let n=e[t];if(void 0===n)return[];Array.isArray(n)||v(`${t} must be an array of state member names.`);let r=new Set;for(let e of n)("string"!=typeof e||""===e)&&v(`${t} entries must be non-empty strings.`),"$"===e[0]&&v(`${t} entry "${e}": internal ($) members are never exposed.`),r.has(e)&&v(`${t} entry "${e}" is duplicated.`),r.add(e);return n}function jr(e,t){let n=t.host;if(void 0===n||!n.hasAttribute("data-wc-definition"))return null;let r=document.createDocumentFragment();for(let e of[...t.childNodes])r.appendChild(e.cloneNode(!0));let i=t.mode;return{start(t){e.hasAttribute("bind-component")&&v("DCC: a <wcs-state bind-component> cannot define a component (use one mechanism)."),function(e,t,n,r){e.includes("-")||v(`DCC: <${e} data-wc-definition> is not a valid custom element name.`),void 0!==customElements.get(e)&&v(`DCC: <${e}> is already defined.`);let i=function(e){let t=new Map;for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n))for(let e of Object.getOwnPropertyNames(n))"constructor"===e||"$"===e[0]||t.has(e)||t.set(e,Object.getOwnPropertyDescriptor(n,e));let n=e.$stream;if(null!==n&&"object"==typeof n)for(let e of Object.keys(n))t.has(e)||t.set(e,{value:void 0});return t}(r),s=Ir(r,"$bindables"),o=Ir(r,"$commands");for(let e of s){let t=i.get(e);void 0===t&&v(`$bindables entry "${e}" does not exist on the state.`),"function"==typeof t.value&&v(`$bindables entry "${e}" is a method: list it in $commands.`)}for(let e of o){let t=i.get(e);void 0===t&&v(`$commands entry "${e}" does not exist on the state.`),"function"!=typeof t.value&&v(`$commands entry "${e}" is not a method: list it in $bindables.`)}let l={tag:e,bindables:s},a=new WeakMap,u=new WeakMap,c=r=>{if(a.has(r))return a.get(r);if(r.hasAttribute("data-wc-definition"))return null;let i=r.attachShadow({mode:n});i.appendChild(t.cloneNode(!0));let o=i.querySelector(re.tagNames.state);return a.set(r,o),Mr.set(r,l),null===o&&s.length>0&&console.warn(`[@wcstack/state] DCC: <${e}> declares $bindables but its content has no <${re.tagNames.state}>: no change events.`),o},h=e=>c(e)?.engine??null,d=e=>Promise.resolve(c(e)?.initializePromise).then(()=>{let t=u.get(e);u.delete(e);let n=h(e);if(void 0!==t&&null!==n)for(let[e,r]of t)n.proxy[e]=r});class f extends HTMLElement{static{this.wcBindable=0===s.length&&0===o.length?null:{protocol:"wc-bindable",version:1,properties:s.map(t=>({name:t,event:`${e}:${t}-changed`,getter:e=>e.target[t]})),inputs:s.map(e=>({name:e})),...0===o.length?{}:{commands:o.map(e=>({name:e,async:!0}))}}}connectedCallback(){null!==c(this)&&d(this)}get stateElement(){return c(this)}}for(let[e,t]of i)"function"==typeof t.value?Object.defineProperty(f.prototype,e,{configurable:!0,value(...t){return d(this).then(()=>{let n=h(this);return null===n?void 0:n.proxy[e].apply(n.proxy,t)})}}):Object.defineProperty(f.prototype,e,{configurable:!0,get(){return h(this)?.proxy[e]},set(t){let n=h(this);if(null!==n)n.proxy[e]=t;else{let n=u.get(this);void 0===n&&u.set(this,n=[]),n.push([e,t])}}});customElements.define(e,f)}(n.localName,r,i,t)},Xe(){},On(){},reset(){v("re-setting a DCC definition is not supported: each instance loads its own state.")}}}var Rr=new WeakMap,Hr=new WeakSet,Wr=new WeakMap,zr=new WeakMap,Dr="data-wcs-wired",Ur=new WeakMap,Fr=new WeakMap,qr=new WeakMap,Br=0,Kr=new Set,Gr={},Vr=["$watch","$stream","$renderedCallback"],Jr=e=>e.split(".",1)[0];function Qr(e,t){let n=0;return e.split(".").map(e=>"*"===e?String(t[n++]):e).join(".")}function Xr(e,t){let n=e.a,r=Jr(e.name);if(!0!==document.documentElement?.hasAttribute("data-wcs-server"))n.removeAttribute(Dr);else if(!Zr(n,r)){let e=n.getAttribute(Dr)?.split(" ")??[];e.includes(r)||n.setAttribute(Dr,[...e,r].join(" "))}Ur.get(n)?.ce===r&&v(`<${n.localName}>.${r} has loaded its state: the wiring "${e.name}" added afterwards cannot reach it — bind the host's wiring before the component loads.`);let i=Rr.get(n);void 0===i&&Rr.set(n,i=[]),i.push(e),t&&Hr.add(e);let s=Wr.get(n);return void 0===s&&Wr.set(n,s=new Map),s.has(r)||s.set(r,n[r]),zr.get(n)?.(),!1}function Yr(e){return e.localName.includes("-")&&null!==e.querySelector(`:scope > ${re.tagNames.state}[bind-component]`)}function Zr(e,t){let n=e.getAttribute(re.bindAttributeName);return null!==n&&new RegExp(`(^|;)\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[.#:]`).test(n)}function ei(e){let t=e.parentElement;for(;null!==t&&!Yr(t);)t=t.parentElement;let n=It.get(t??e.getRootNode()),r=n?.element;(r?.isConnected?r.W:null===t)&&(null===t?Ft(e):Rt(n,e))}var ti=new Set;function ni(e,t){ti.has(e)||(ti.add(e),console.warn(`[@wcstack/state] ${t}`))}var ri=(e,t)=>t in e.state;function ii(e,t){let n=si(e.state,t);return void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)}function si(e,t){for(let n=e;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return e}}function oi(e,t,n){if(null!==n.getter)return;let r,i=e.host,s=i.engine,o=Jr(n.t),l=i.entries.find(e=>e.E===n.t);if(void 0===l&&null!==n.d)return function(e,t){let n,r=t.d;for(;null!==r&&void 0===(n=e.at.get(r));)r=r.d;if(null===r||void 0===n)return;let i=e.x,s=e.host.engine,o=s.o(n.p.t+t.t.slice(r.t.length));if(null===o.getter)return;let l=n,a=()=>{let n=li(e,l.r);return 0===t.n?n:(s.resolve(Qr(o.t,[...s._(n),...i._(ee(i.c,t.n))]),null),s.rr)};t.getter=()=>{let e=a();return o.n>0&&null===e?void 0:s.v(o,e)},null!==o.oe&&(t.oe=n=>{let r=a();ai(e,l.e,()=>s.P(o,r,n)),e.cn=t}),t.n>0&&(t.F=i.Oe++),e.at.set(t,{e:l.e,p:o,r:l.r})}(e,n);if(0!==n.n)return;if(void 0!==l){if(l.E!==o?ri(i,o):ii(i,o))return;r=l.ue}else{if(null===t||null!==n.d||"$"===o[0]||ri(i,o))return;l=t,r=s.o(`${t.ue.t}.${o}`)}let a=l.r,u=l;n.getter=()=>s.v(r,li(e,a)),n.oe=t=>{ai(e,u,()=>s.P(r,a,t)),e.cn=n},e.at.set(n,{e:l,p:r,r:a})}function li(e,t){return null!==t&&!t.y&&v(`The host row of <${e.host.el.localName}> was removed.`),t}function ai(e,t,n){let r=Kr.has(e.x);Kr.add(e.x),e.from=t;try{n()}finally{r||Kr.delete(e.x),e.from=null}}var ui=(e,t)=>t||!Kr.has(e.m.x)||null!==e.m.from&&e.m.from!==e.e;function ci(e,t){if(e.un===t||null===e.host.engine)return;e.un=t,Br+=t?1:-1;let n=e.host.engine,r=qr.get(n);void 0===r&&qr.set(n,r=new Map);for(let n of e.ae){let e=r.get(n.e.ue);void 0===e&&r.set(n.e.ue,e=new Map);let i=e.get(n.e.r);void 0===i&&e.set(n.e.r,i=new Set),t?i.add(n):(i.delete(n),0===i.size&&e.delete(n.e.r))}let i=e.host.entries.find(e=>""===e.E);if(void 0!==i){null===e.te&&function(e,t){let n=e.host,r=n.engine;e.te=new Map;let i=new Set;for(let s=n.state;null!==s&&s!==Object.prototype;s=Object.getPrototypeOf(s))for(let o of Object.getOwnPropertyNames(s)){if(i.has(o))continue;i.add(o);let l=Object.getOwnPropertyDescriptor(s,o);if(void 0===l.get&&void 0===l.set||"$"===o[0]||o.includes("*"))continue;let a=Jr(o);if(o!==a&&!ri(n,a))continue;let u=r.o(`${t.ue.t}.${o}`);if(null===u.getter)fi(r,u,t.ue);else if(!hi.has(u.getter))continue;e.te.set(u,e.x.o(o))}}(e,i);for(let r of e.te.keys())t&&null===r.getter&&fi(n,r,i.ue),n.R.me(n,r,i.r);e.te.size>0&&n.Re(),t&&function(e,t){let n=e.host.engine;for(let[r,i]of e.te){let s=n.v(r.d,t.r);if(null===s||"object"!=typeof s||!(r.s in s))continue;let o=e.host.el.localName;ni(`${o}|${r.t}`,`[wcs/mount-export-shadowed] <${o}>.${e.host.ce}.${i.t} is exported at "${r.t}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`)}}(e,i)}}var hi=new WeakSet;function di(e,t,n,r){let i=qr.get(e)?.get(t)?.get(n);if(void 0===i)return null;let s=null;for(let e of i)""!==e.e.E||!0!==e.m.te?.has(r)||e.m===s||(null!==s&&v(`[wcs/mount-export-ambiguous] "${r.t}" is exported by two mounted components on the same instance: <${s.host.el.localName}> and <${e.m.host.el.localName}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),s=e.m);return s}function fi(e,t,n){let r=t.d,i=t.s,s=()=>{let t=e.read(r,e.c);return null!==t&&"object"==typeof t&&i in t?t:null};t.getter=()=>{let r=s();if(null!==r)return r[i];let o=di(e,n,e.c,t);return null===o?void 0:o.x.read(o.te.get(t),null)},hi.add(t.getter),t.oe=o=>{let l=null===s()?di(e,n,e.c,t):null;if(null===l){let t=e.read(r,e.c);return void(null!==t&&"object"==typeof t&&(t[i]=o))}let a=l.te.get(t);void 0===si(l.host.state,a.t)?.set&&v(`Cannot write to "${a.t}" on mounted <${l.host.el.localName}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),l.x.P(a,null,o)},t.n>0&&(t.F=e.Oe++)}function pi(e,t,n,r,i,s){if(null!==t.getter)return e.R.me(e,t,n),void e.Re();if("*"===t.s){if(null===n)return;if(n.T=n.l.C[n.b],e.R.qt(n),null!==n.h)for(let t of n.h.values())e.z(t)}else e.wn(t,n);c.he?.(e,t,n,r,i,s),e.We(t,n)}function mi(e){let t=e.m.x;for(let[n,r]of e.m.at)r.e===e.e&&(0===n.n?t.R.me(t,n,null):t.Zt(n.f[n.n],e=>t.R.me(t,n,e)));t.Re()}function gi(e,t,n,r,i,s,o){let l=n.t.slice(t.t.length);if(""===l)return mi(e);let a,u=e.m,c=u.x;if(""===e.e.E){a=l.slice(1);let e=Jr(a);if("$"===e[0]||ri(u.host,e)||u.host.entries.some(e=>""!==e.E&&(a===e.E||a.startsWith(`${e.E}.`))))return}else a=e.e.E+l;let h=[];for(let e=t.n+1;e<=n.n;e++)h.push(ee(r,e).b);c.resolve(Qr(a,h),null);let d=c.rp,f=c.rr;d.n>0&&null===f||pi(c,d,f,i,s,o)}function yi(e,t,n,r,i,s,o){if(0===Br)return;let l=Kr.has(e);Kr.add(e);try{let l=Fr.get(e);!o&&void 0!==l&&l.un&&!Kr.has(l.host.engine)&&function(e,t,n,r,i,s){let o,l=t;for(;null!==l&&void 0===(o=e.at.get(l));)l=l.d;if(null===l||void 0===o)return;let a=e.host.engine;if(l===t&&e.cn===t)return void(e.cn=null);if(null!==o.r&&!o.r.y)return;let u=[...a._(o.r),...e.x._(n)];a.resolve(Qr(o.p.t+t.t.slice(l.t.length),u),null);let c=a.rp,h=a.rr;c.n>0&&null===h||ai(e,o.e,()=>pi(a,c,h,r,i,s))}(l,t,n,r,i,s),o&&void 0!==l&&l.un&&null!==l.te&&function(e,t){let n=e.host.entries.find(e=>""===e.E),r=e.host.engine;for(let[i,s]of e.te)s===t&&(r.R.me(r,i,n.r),r.Re())}(l,t);let a=qr.get(e);if(void 0===a)return;for(let[e,l]of a)if(t.Q(e)){let a=l.get(0===e.n?null:ee(n,e.n));if(void 0!==a)for(let l of[...a])ui(l,o)&&gi(l,e,t,n,r,i,s)}else if(e.Q(t))for(let[e,r]of[...l])if(0===t.n||ee(e,t.n)===n)for(let e of[...r])ui(e,o)&&mi(e)}finally{l||Kr.delete(e)}}async function bi(e,t,n,r,i){if(r===Gr)return;let s=y(r);s&&await s;let o=Ur.get(t);o.engine&&r.$recursion&&v(`[wcs/mount-dollar-declaration] <${t.localName}>: $recursion is not run in a mounted component — declare it on the root state.`);let l=o.O;if(null!==l&&l.el!==e&&l.el.isConnected&&v(`<${t.localName}> already has a connected <${re.tagNames.state} bind-component="${o.ce}">.`),null!==l&&ci(l,!1),null!==l&&function(e,t,n){let r=e.x,i=`[${re.bindAttributeName}]`,s=e=>1===e.nodeType&&(e.matches(i)||null!==e.querySelector(i)),o=new Set,l=e=>{for(;null!==e&&e.parentNode!==n;)e=e.parentNode;null!==e&&o.add(e)},a=(e,t)=>{for(let n=e.Pn(t);null!==n&&n!==t;n=n.nextSibling)l(n);l(t)};for(let e of r.ie.values())for(let t of e)if(null===t.M)l(t.a);else for(let e of t.M.X)a(t.M,e.S);for(let e of r.ee.values())for(let t of[e.$,...e.L??[]])null!==t&&a(t,t.S);for(let t of e.j)t.parentNode===n&&s(t)&&o.add(t);if(0===o.size)return!1;let u=[...n.childNodes].filter(n=>n!==t&&!o.has(n)&&!e.j.includes(n)&&(s(n)||r.Lt&&n.textContent.includes("{{")));return u.length>0&&console.warn(`[@wcstack/state] <${e.host.el.localName}>: ${u.length} node(s) added beside the content taken over are not bound.`),!0}(l,e,n))return async function(e,t,n,r){e.el.engine=null,e.el=t,e.x.element=t,t.engine=e.x,e.j=e.j.filter(e=>e.parentNode===n),t.isConnected?await vi(e,r):r()}(l,e,n,i);let a=new ne(r,new Bt);a.element=e,e.engine=a,function(e,t){let n=new Map;for(let e=t;null!==e&&e!==Object.prototype;e=Object.getPrototypeOf(e))for(let t of Object.getOwnPropertyNames(e)){let r=Object.getOwnPropertyDescriptor(e,t).value;"function"==typeof r&&"constructor"!==t&&n.set(r,null)}let r=(t,n,r)=>Reflect.apply(t,e.proxy,r);e.W=e=>{let t=n.get(e);return null===t&&n.set(e,t=new Proxy(e,{apply:r})),t}}(a,r);let u={el:e,j:[],x:a,host:o,ae:[],at:new Map,un:!1,cn:null,from:null,te:null};for(let e of o.entries)u.ae.push({m:u,e:e});o.O=u,Fr.set(a,u);let h=null===o.engine;h?c.element?.(a,"mounting"):(function(e){let t=e.x,n=e.host,r=n.engine,i=n.el.localName,s=n.entries.find(e=>""===e.E)??null;for(let e of n.entries){if(""===e.E)continue;let t=Jr(e.E);ri(n,t)&&(e.E!==t||ii(n,t))&&ni(`${i}.${e.E}`,`[wcs/mount-own-key-shadow] <${i}>: "${n.ce}.${e.E}" is hidden by the component's own "${t}"; rename one side.`)}if(null!==s){let e=r.v(s.ue,s.r);if(null!==e&&"object"==typeof e)for(let t of Object.keys(n.state))"$"!==t[0]&&t in e&&!n.entries.some(e=>e.E===t)&&ni(`${i}.${t}`,`[wcs/mount-own-key-shadow] <${i}>: its own "${t}" hides "${s.ue.t}.${t}" — remove the default to read the tree, or rename it to keep it private.`)}let o=Vr.filter(e=>void 0!==n.state[e]);o.length>0&&ni(`${i}.${n.ce}$`,`[wcs/mount-dollar-declaration] <${i}>: ${o.join(", ")} ${1===o.length?"is":"are"} not run in a mounted component — declare it on the root state.`);let l=t.et;t.et=n=>{oi(e,s,n),l.call(t,n)};let a=[...t.B.all()];for(let t of a)oi(e,s,t);for(let e of a)l.call(t,e);let u=n.entries.filter(e=>null!==e.r);if(u.length>0){let e=t.Ut;t.Ut=()=>{u.every(e=>e.r.y)&&e.call(t)}}}(u),ci(u,!0),yr.add(a),Nr(a,n));let d=c.ir?.(n);jt(a,n),d?.(),u.j=[...n.childNodes],qt(),h&&a.bn(),Object.defineProperty(t,o.ce,{configurable:!0,enumerable:!0,get:()=>a.proxy});let f=t.$stateReadyCallback;if("function"==typeof f)try{let e=f.call(t,o.ce);null!==e&&"object"==typeof e&&"function"==typeof e.then&&e.then(void 0,e=>console.error(e))}catch(e){console.error(e)}i(),e.isConnected?(await a.we("$connectedCallback"),h&&e.isConnected&&c.element?.(a,"connected")):ci(u,!1)}async function vi(e,t){ci(e,!0);for(let t of e.ae)mi(t);t?.(),!e.broken&&(await e.x.we("$connectedCallback"),null===e.host.engine&&e.el.isConnected&&c.element?.(e.x,"connected"))}function wi(e,t){let n=e.getAttribute("bind-component");if(null===n)return function(e,t){return e.connectedCallbackPromise.catch(()=>{let n=It.get(t)?.element;if(!(e.W||void 0!==n&&n!==e&&n.isConnected)){Tr(t,e);for(let e of Pr.get(t)??[])e()}}),null}(e,t);let r=e.parentNode,i=r instanceof ShadowRoot,s=i?r.host:r instanceof Element?r:null,o=()=>{let t=null===s?void 0:Ur.get(s)?.O;return t?.el===e?t:null},l=t=>{throw i&&Tr(r,e),t},a=!1;return{jt:()=>(null!==s&&s.localName.includes("-")?async function(e,t,n,r){let i=n.localName;(["state","src","json"].some(t=>e.hasAttribute(t))||null!==e.querySelector('script[type="module"]'))&&v(`<${re.tagNames.state} bind-component> takes its state from <${i}>.${t}: it cannot also load one (state / src / json / an inline script).`),await Ie(n).whenDefined(i);let s=Ur.get(n);if(void 0!==s)return s.ce!==t&&v(`<${i}> already has a <${re.tagNames.state} bind-component="${s.ce}">.`),s.state;let o=()=>(Rr.get(n)??[]).filter(e=>Jr(e.name)===t),l=Zr(n,t);if(l&&0===o().length&&ei(n),0===o().length&&(l||((e,t)=>!0===e.getAttribute(Dr)?.split(" ").includes(t))(n,t))){let e;await new Promise((r,s)=>{zr.set(n,r),e=function(e,t){Sr(e)&&t();let n=Pr.get(e)??new Set;return Pr.set(e,n.add(t)),()=>n.delete(t)}(n.getRootNode(),()=>s(new Error(`[@wcstack/state] <${i}>.${t} will not mount: the root state failed to initialize.`)))}).finally(()=>e())}zr.delete(n);let a=o(),u=Wr.get(n),c=void 0!==u&&u.has(t)?u.get(t):n[t];if((null===c||"object"!=typeof c)&&v(`"bind-component": <${i}>.${t} must be an object (the component's state), got ${null===c?"null":typeof c}.`),0===a.length&&r){let e=new Error(`[@wcstack/state] A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${i}>, or mount it from the host (${re.bindAttributeName}="${t}: path").`);return queueMicrotask(()=>{throw e}),Gr}let h=[];for(let e of a){let r=e.name===t?"":e.name.slice(t.length+1);h.some(e=>e.E===r)&&v(`<${i}> maps "${e.name}" twice.`);let s=r.split(".").indexOf("*");if(s>=0){let n=r.split(".").slice(0,s).join(".");v(`<${i}> maps "${e.name}": the component-side path of a mount cannot contain "*"${""===n?"":` — map the list itself ("${t}.${n}: <the host's list>")`}.`)}h.push({E:r,ue:e.o,r:e.r,ro:Hr.has(e)}),e.engine.kn(e),""!==r&&delete n[e.name]}let d=0===a.length?function(e){let t=Object.getOwnPropertyDescriptors(e),n=Object.isFrozen(e);for(let e of Object.values(t))"value"in e&&!1===e.writable&&(e.writable=!0,n=!0);return n?Object.create(Object.getPrototypeOf(e),t):e}(c):c;return Ur.set(n,s={el:n,ce:t,state:d,engine:0===a.length?null:a[0].engine,entries:h,O:null}),d}(e,n,s,!i):Promise.reject(new Error(`[@wcstack/state] "bind-component" requires <${re.tagNames.state}> to be a direct child of a custom element.`))).catch(l),async start(t,n){await bi(e,s,i?r:s,t,()=>{a=!0,n()}).catch(e=>{let t=o();return!a&&null!==t&&(t.broken=!0),l(e)})},Xe(){let t=o();null!==t?vi(t).catch(e=>console.error(e)):a?Promise.resolve().then(()=>{if(e.parentNode===r)return bi(e,s,i?r:s,Ur.get(s).state,()=>{})}).catch(e=>console.error(e)):zr.has(s)&&ei(s)},On(){let e=o();null!==e&&(ci(e,!1),!e.broken&&(e.x.we("$disconnectedCallback"),null===e.host.engine&&c.element?.(e.x,"disconnected")))},reset(){v(`re-setting a component's state is not supported: write <${s?.localName}>.${n} instead.`)}}}var _i={name:"scopes",install(){c.rt=d(m,c.rt,Or),c.rt=d(m,c.rt,jr),c.rt=d(m,c.rt,wi),c.Jo=Xr,c.yo=Yr,c.element=h(c.element,(e,t)=>{if("mounting"!==t)return function(e,t){let n=br.get(e)??[];if("disconnected"===t)for(let e of n)Ar(e);else if("reset"!==t&&kr(It.get(e.root))===e){Nr(e,e.root);for(let e of n)pr.get(e.root).has(e.t)||pr.get(e.root).set(e.t,e)}}(e,t);let n=e.element.getRootNode();Nr(e,n),function(e,t){let n=t.host,r=void 0===n?void 0:Mr.get(n);void 0!==r&&Lr.set(e,{host:n,def:r})}(e,n)}),c.he=h(c.he,(e,t,n,r,i,s)=>{(function(e,t,n,r){let i=Lr.get(e);if(void 0===i)return;let s=t.t.split(".",1)[0];if(!i.def.bindables.includes(s))return;let o=r&&t.t===s;i.host.dispatchEvent(new CustomEvent(`${i.def.tag}:${s}-changed`,{detail:o?n:void 0,bubbles:!0}))})(e,t,i,s),yi(e,t,n,r,i,s,!1)}),c.ye=h(c.ye,(e,t,n)=>yi(e,t,n,void 0,void 0,!1,!0)),c.Pe=d(f,c.Pe,(e,t,n,r,i)=>(function(e,t){let n=br.get(e);if(void 0!==n&&0===t.n)for(let{t:e}of n)e.startsWith(`${t.t}.`)&&v(`writing "${t.t}" would replace the volume grafted at "${e}"; write the paths under it instead.`)}(e,t),function(e,t,n){let r,i=Fr.get(e);if(void 0===i)return!1;for(let e=t;null!==e&&void 0===r;e=e.d)r=i.at.get(e);if(void 0===r)return!1;let s=r.e;return!((null===s.r||s.r.y)&&!s.ro)&&(!!n||(li(i,s.r),void v(`[wcs/mount-readonly] <${i.host.el.localName}> cannot write "${t.t}": it is mounted read-only ("${i.host.ce}${""===s.E?"":`.${s.E}`}#ro: ${s.ue.t}"). Write it on the host, or drop #ro from the mount.`)))}(e,t,i)));let e=c.se;c.se=(t,n)=>{let r=br.get(t);void 0!==r&&r.length>0&&v(`re-setting a root state with grafted volumes (${r.map(e=>e.t).join(", ")}) is not supported: their data is part of the tree.`),function(e){let t=qr.get(e);if(void 0===t)return!1;for(let e of t.values())if(e.size>0)return!0;return!1}(t)&&v("re-setting a root state with mounted components is not supported: they read its data."),e?.(t,n)}}},$i="$recursion",ki=new WeakMap,Si=new WeakSet,Ni=new WeakSet,Ai=0,Ei=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ci=e=>`[wcs/recursion-${e}]`;function xi(e,t){let n=n=>v(`${Ci("declaration-invalid")} ${$i} ${e} "${String(t)}" ${n}`);("string"!=typeof t||""===t)&&v(`${Ci("declaration-invalid")} ${$i} ${e} must be a non-empty string.`);let r=t.split(".");(r.length<2||"*"!==r[r.length-1])&&n('must end with ".*" (a list element).');for(let e=0;e<r.length-1;e++){let t=r[e];""===t&&n("must not contain empty path segments."),("*"===t||"**"===t||/^\d/.test(t))&&n('must have exactly one "*", at the end.'),t.includes("#")&&n('must not contain "#".')}return"$"===t[0]&&n('must not start with "$".'),t}var Ti=(e,t)=>`${e.l}.*${e.step.repeat(t)}`;function Pi(e,t){let n=`${e.l}.**`,r=t.slice(n.length);return(!t.startsWith(n)||""!==r&&"."!==r[0]||r.includes("**"))&&v(`[wcs/recursion-anchor] "${t}" does not start at the recursion anchor "${e.l}.*".`),r}function Oi(e,t,n){let r=Pi(e,t),i=function(e,t){for(let n=t;null!==n;n=n.l.re){let t=e.nodeList.exec(n.l.o.t);if(null!==t)return{k:t[1].length/(e.key.length+3),r:n}}return null}(e,n);return null===i&&v(`[wcs/recursion-context] "${t}" uses "**", which is bound to the depth of the row it is evaluated in; there is none here — use $getAll("${t}", []) for every depth.`),Ti(e,i.k)+r}function Mi(e,t,n){let r=new Set,i=new Set,s=(e,n,s)=>!(!Array.isArray(e)||0===e.length||(r.has(e)&&v(`${Ci("cycle")} "${n}" is reachable from itself: the data under "${t.l}" must be a tree.`),i.has(e)&&v(`${Ci("shared-list")} "${n}" is the same array instance as a list reached before: the data under "${t.l}" must be a tree.`),s+1>128&&v(`${Ci("depth-exceeded")} Recursion on "${t.l}.*" reached depth ${s+1} (the limit is 128).`),i.add(e),0)),o=(i,l)=>{for(let a of i){n(l,a);let i=e.o(`${Ti(t,l)}.${t.key}`),u=e.read(i,a);s(u,i.t,l+1)&&(r.add(u),o(e.De(a,i).u,l+1),r.delete(u))}},l=e.o(t.l),a=e.read(l,null);s(a,t.l,0)&&(r.add(a),o(e.De(null,l).u,0))}function Li(e,t){let n=function(e){let t=e[$i],n=[],r=new Set;for(let t=e;null!==t&&t!==Object.prototype;t=Object.getPrototypeOf(t))for(let e of Object.getOwnPropertyNames(t))!r.has(e)&&e.includes("**")&&n.push([e,Object.getOwnPropertyDescriptor(t,e)]),r.add(e);if(void 0===t)return n.length>0&&z(n[0][0]),null;(null===t||"object"!=typeof t||Array.isArray(t))&&v(`${Ci("declaration-invalid")} ${$i} must be an object mapping one anchor path to its repeating sub-path.`);let i=Object.entries(t);1!==i.length&&v(`${Ci("declaration-invalid")} ${$i} must declare exactly one anchor (it declares ${i.length}).`);let s=xi("anchor",i[0][0]),o=xi("repeat",i[0][1]),l=s.slice(0,-2),a=o.slice(0,-2),u=`.${o}`,c=new Map,h=[],d=`${l}.**`;for(let[e,t]of n){let n=e.slice(d.length);(!e.startsWith(d)||""!==n&&"."!==n[0]||n.includes("**"))&&v(`[wcs/recursion-anchor] "${e}": a recursive key is "${d}" followed by a path (the anchor is "${s}").`),(""===n||n.split(".").slice(1).some(e=>""===e))&&v(`[wcs/recursion-anchor] "${e}" needs a path after "**".`),(void 0===t.get||void 0!==t.set)&&v(`${Ci("declaration-invalid")} "${e}": a recursive key is a getter without a setter.`),c.set(n,t.get),h.push([new RegExp(`^${Ei(s)}((?:${Ei(u)})*)${Ei(n)}$`),n])}return{l:l,step:u,key:a,families:c,matchers:h,owners:new Map,nodeList:new RegExp(`^${Ei(l)}((?:${Ei(`.*.${a}`)})*)$`)}}(t),r=ki.has(e);null!==n?(r||Ai++,ki.set(e,n),Ni.add(e),Si.has(e)||function(e){Si.add(e);let t=e,n=t.et;t.et=r=>{let i=ki.get(e);if(r.t.includes("**")){let t=e.B.Ot(r.t)===r;return void(Ni.has(e)||void 0===i&&t?r.getter=()=>z(r.t):t||n.call(e,r))}if(void 0!==i&&null===r.getter)for(let[e,n]of i.matchers)if(e.test(r.t)){r.getter=i.families.get(n),r.n>0&&(r.F=t.Oe++),i.owners.set(r,i.l+".**"+n);break}n.call(e,r)};let r=t.resolve;t.resolve=(t,n)=>{let i=ki.get(e);return r.call(e,void 0!==i&&t.includes("**")?Oi(i,t,n):t,n)};let i=t.getAll;t.getAll=(n,r)=>{let s=ki.get(e);if(void 0===s||!n.includes("**"))return i.call(e,n,r);if(void 0===r)return i.call(e,Oi(s,n,t.c));(!Array.isArray(r)||r.length>0)&&v(`${Ci("getall-form")} $getAll("${n}", indexes) with "**" takes either no indexes (this depth) or [] (every depth).`);let o=Pi(s,n),l=[];return Mi(e,s,(t,n)=>{for(let r of i.call(e,Ti(s,t)+o,e._(n)))l.push(r)}),l};let s=t.pn;t.pn=(n,r,i,o)=>{let l=ki.get(e);if(void 0===l||!n.includes("**"))return s.call(e,n,r,i,o);Array.isArray(r)||k(9,[n]),r.length>0&&v(`${Ci("setall-form")} $setAll("${n}", indexes, …) with "**" takes no partial prefix: pass [] to write every node.`),("function"==typeof i||!0===o?.spread)&&v(`${Ci("setall-form")} $setAll("${n}", [], value) with "**" takes a plain value (no mapper, no spread).`),t.Ce>0&&k(8);let a=Pi(l,n),u=a.replace(/\.\d+(?=\.|$)/g,".*");for(;u.startsWith(l.step);)u=u.slice(l.step.length);let c=l.key.split(".");(""===u||u===`.${l.key}.length`||c.some((e,t)=>u===`.${c.slice(0,t+1).join(".")}`))&&v(`${Ci("structural-write")} "${n}" writes the recursion structure itself (a node, its "${l.key}" list or that list's length, or an object on the way to it).`);for(let e of l.families.keys()){let t=e;for(;t.startsWith(l.step);)t=t.slice(l.step.length);(u===t||u.startsWith(`${t}.`))&&v(`${Ci("readonly")} "${n}" writes into the recursive getter "${l.l}.**${e}".`)}let h=[];Mi(e,l,(e,t)=>h.push([e,t]));let d=0;for(let[t,n]of h)d+=s.call(e,Ti(l,t)+a,e._(n),i);return d}}(e)):r&&(ki.delete(e),Ai--)}function Ii(e,t){if(0===Ai)return!1;let n=ki.get(e);if(void 0===n)return!1;for(let e=t;null!==e;e=e.d){let r=n.owners.get(e);void 0!==r&&v(`${Ci("readonly")} "${t.t}" writes into the recursive getter "${r}".`)}return!1}var ji={name:"recursion",install(){c.se=h(c.se,Li),c.element=h(c.element,(e,t)=>{("mounting"===t||"reset"===t)&&function(e){Ni.delete(e)}(e)}),c.Pe=d(f,c.Pe,Ii)}},Ri="4.0.0-rc.3",Hi=e=>e.split(".").slice(0,2).join("."),Wi=class extends Qt{static find(e){return e.querySelector?.(re.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return Hi(this.version)===Hi(Ri)}};function zi(e){let t=re.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends Wi{})}var Di=()=>re.tagNames.ssr,Ui=Symbol.for("wcstack.ssr.snapshotBuilder"),Fi=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),qi=e=>document.createComment(e),Bi=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,Ki=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),Gi=new WeakMap,Vi=new WeakMap,Ji=new WeakMap,Qi=new WeakSet,Xi=new WeakMap;function Yi(e,t){let n=[];for(let r=e;null!==r&&(n.push(r),r!==t);r=r.nextSibling);return n}function Zi(e,t,...n){for(let n of Array.from(e.attributes))t.setAttribute(n.name,n.value);return(t.content??t).append(...n),t}var es=e=>null===e.j?e.Ue:e.j[e.j.length-1];function ts(e,t,n){let r=[qi(null===n?"wcs-[":`wcs-[:${n}`)];for(let e of t)null===n&&r.push(qi("wcs-|")),r.push(...Yi(e.Ue,es(e)));r.push(qi("wcs-]")),e.after(...r);for(let e of r)Qi.add(e)}function ns(e){if(e instanceof lt){ts(e.S,e.Ee,null);for(let t of e.Ee)rs(t);return}let t=e.O;null!==t&&(ts(e.X[e.X.length-1].S,[t],e.b),rs(t))}function rs(e){if(null!==e.h)for(let t of e.h)ns(t)}var is=new Set(["script","style","template","textarea","title"]),ss="data-wcs-raw",os=e=>is.has(e.localName)||e.localName===Di();function ls(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(qi("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(qi("wcs-s")):1===t.nodeType&&!os(t)&&ls(t)}var as=0;function us(e,t){let n=e.getRootNode(),r=[t];for(let e of Vi.get(n)??[])e!==t&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let i=new Map;for(let e of r){let t=Gi.get(e);if(void 0===t)continue;let n=new Map;for(let t of e.ee.values())if(null!==t.$&&n.set(t.$.S,t.$),null!==t.L)for(let e of t.L)n.set(e.S,e);for(let t of e.ie.values())for(let e of t)if(null!==e.M)for(let t of e.M.X)n.set(t.S,e.M);let r=new Set;for(let[e,s]of t){i.set(e,s);let t=n.get(e);void 0!==t&&!r.has(t)&&e.isConnected&&(r.add(t),ns(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=Ji.get(e);if(void 0!==t){let n=document.createTreeWalker(e,133,{acceptNode:e=>Qi.has(e)||1===e.nodeType&&t.has(e)&&ps(e)?2:1}),r=[];for(let e=n.nextNode();null!==e;e=n.nextNode()){let n=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(os(e.parentNode)?Xi.has(e):t.has(n)&&Ki(n,"wcs-t:"))&&(Xi.has(e)||t.get(e)!==e.data):!t.has(e))&&r.push(e)}for(let e of r)e.remove()}let n=Array.from(e.childNodes);os(e)&&n.some(e=>Xi.has(e))&&e.setAttribute(ss,n.map(e=>Xi.has(e)?`{{ ${Xi.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}ls(9===n.nodeType?n.body:n);let s=document.createElement(Di());s.setAttribute("version",Ri);let o=document.createElement("script");o.type="application/json",o.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let n of Object.keys(e)){if("$"===n[0])continue;let r=Object.getOwnPropertyDescriptor(e,n);void 0!==r.get||void 0!==r.set||"function"==typeof r.value||(t[n]=r.value)}return t}(t.target)),s.append(o);for(let[e,t]of i){if(!e.isConnected)continue;let n=e.parentNode;for(;null!==n&&"svg"!==n.localName&&"foreignObject"!==n.localName;)n=n.parentElement;let r="svg"===n?.localName,i=`wcs-${r?"s":"t"}${as++}`;e.replaceWith(qi(`wcs-p:${i}`));let o=document.importNode(xt(t),!0);for(let e of Array.from(o.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(Zi(e,document.createElement("template"),...e.childNodes));if(r){let e=document.createElementNS(n.namespaceURI,"svg");e.append(o),o=e}let l=document.createElement("template");l.id=i,s.append(Zi(t,l,o))}e.before(s)}function cs(e){!function(e){if(null!==e.querySelector(re.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>Xi.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${re.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===Di())continue;let e=t.engine;null!=e&&us(t,e)}}var hs=Symbol.for("wcstack.state.ssr.impl"),ds=new Map,fs=new WeakMap,ps=e=>!0===c.yo?.(e),ms=e=>1===e.nodeType&&!os(e)&&!ps(e),gs=e=>e.u.flat().concat(e.U??[]),ys=e=>{for(let t of gs(e))t.remove()};function bs(e,t,n){let r=/^wcs-\[(?::(\d+))?/.exec(e.data),i=e.previousSibling,s=e.parentNode,o=[],l=e.nextSibling;for(e.remove();null!==l&&!Bi(l,"wcs-]");){let e=l.nextSibling;if(Bi(l,"wcs-|"))o.push([]),l.remove();else{0===o.length&&o.push([]);let n=o[o.length-1];Ki(l,"wcs-[")?e=bs(l,t,n):(n.push(l),ms(l)&&vs(l,t))}l=e}let a={branch:void 0===r[1]?null:Number(r[1]),u:o,U:l??s.appendChild(qi("wcs-]"))},u=gs(a);l=a.U.nextSibling;for(let e of u)n?.push(e),t&&At.add(e);return t&&null!==i?ds.set(i,a):ys(a),l}function vs(e,t){for(let n=e.firstChild;null!==n;)Ki(n,"wcs-[")?n=bs(n,t):(ms(n)&&vs(n,t),n=n.nextSibling)}function ws(e,t,n){let r=e=>{for(let i of Array.from(e.childNodes))if(i.parentNode===e)if(8===i.nodeType){let e=i.data;try{if("wcs-s"===e)i.remove();else if("wcs-e"===e)i.replaceWith("");else if(e.startsWith("wcs-t:")){let t=qi(`@@:${decodeURIComponent(e.slice(6))}`),n=i.nextSibling;for(;null!==n&&!Bi(n,"wcs-/t");){let e=n.nextSibling;n.remove(),n=e}n?.remove(),i.replaceWith(t)}else if(e.startsWith("wcs-p:")){let n=t.querySelector(`template[id="${e.slice(6)}"]`);if(null!==n){let t=i.parentNode,r="s"===e[10]?Zi(n,document.createElementNS(t.namespaceURI,"template"),...document.importNode(n.content.firstChild,!0).childNodes):document.importNode(n,!0);r.removeAttribute("id"),t.replaceChild(r,i)}}}catch{}}else 1===i.nodeType&&!os(i)&&(ps(i)?fs.set(i,{ssr:t,Ae:n}):r(i))};r(e),function(e){for(let t of Array.from(e.querySelectorAll("table > tbody"))){let e=[];for(let n=t.previousSibling;null!==n&&(8===n.nodeType||Es(n)||"template"===n.localName);n=n.previousSibling)e.unshift(n);let n=0,r=0;if(e.forEach((e,t)=>{Ki(e,"wcs-[")?r++:Bi(e,"wcs-]")&&--r<0&&(r=0,n=t+1)}),0===r)continue;let i=0;for(let r=t.firstChild;null!==r;r=r.nextSibling)if(Ki(r,"wcs-["))i++;else if(Bi(r,"wcs-]")&&0===i--){t.prepend(...e.slice(n));break}}}(e),vs(e,n)}function _s(e){let t=fs.get(e);if(void 0===t||(fs.delete(e),ws(e,t.ssr,t.Ae),!t.Ae))return null;let n=c.Ae;return c.Ae=Ts,()=>{c.Ae=n,$s()}}function $s(){for(let e of ds.values())ys(e);ds.clear()}function ks(e){let t=[];for(let n=document.createTreeWalker(e,128);n.nextNode();)t.push(n.currentNode);return t}function Ss(e,t,n,r){let i=null;for(let r of e){let e=r[n];null!==e&&(""===e||t===e||t.startsWith(`${e}.`))&&(null===i||e.length>i[n].length)&&(i=r)}let s=i?.[r];if(null==s)return null;let o=i[n],l=""===o?t:t.slice(o.length+1);return""===s?l:""===l?s:`${s}.${l}`}function Ns(e,t,n){if(Fi()){if(n instanceof Array){for(let e=n.length;e-- >0;)gt(n[e])&&n.splice(e,1);let e=t;if(n.some(yt))Qi.add(e);else if(e.localName.includes("-")&&!ps(e)){let t=new Map;for(let n=document.createTreeWalker(e,133);n.nextNode();)t.set(n.currentNode,n.currentNode.data);Ji.set(e,t)}return}if("string"==typeof n){if(Xi.set(t,n),os(t.parentNode))return;let e=qi(`wcs-t:${encodeURIComponent(n)}`),r=qi("wcs-/t");return t.before(e),void t.after(r)}let r=Gi.get(e);void 0===r&&Gi.set(e,r=new Map),r.set(t,n);let i=t.getRootNode(),s=Vi.get(i);return void 0===s&&Vi.set(i,s=new Set),void s.add(e)}if("string"!=typeof n&&ds.size>0){let e=ds.get(n);void 0!==e&&(ds.delete(n),ds.set(t,e))}}var As=e=>null!==e&&8===e.nodeType&&[re.commentIfPrefix,re.commentElseIfPrefix,re.commentElsePrefix].includes(e.data),Es=e=>3===e.nodeType&&""===e.data.trim(),Cs=e=>(ds.get(e)?.U??e).nextSibling;function xs(e,t){if(t.length!==e.on.childNodes.length)return!1;let n=e.Rn;for(let r=0;r<n.length;r++){let i=n[r],s=e.on,o=t[i[0]];for(let e=0;;){if(s=s.childNodes[i[e]],o?.nodeName!==s.nodeName)return!1;if(++e===i.length)break;o=o.firstChild;for(let t=i[e];t>0&&null!==o;t--)o=Cs(o)}e.mo[r]=o}return!0}function Ts(e,t,n){if(0===ds.size)return null;let r=t,i=0;if(!n){let e=re.commentIfPrefix;if(!Bi(t,e))for(let n=t.previousSibling;null!==n&&1!==n.nodeType&&(As(n)&&i++,!Bi(n,e));n=n.previousSibling);for(let n=t.nextSibling;!ds.has(r)&&null!==n&&!Bi(n,e)&&1!==n.nodeType;n=n.nextSibling)As(n)&&(r=n)}let s=ds.get(r);if(void 0===s)return null;if(!n&&s.branch!==i)return ds.delete(r),ys(s),null;let o=s.u.shift();if(0===s.u.length&&ds.delete(r),s.U?.replaceWith(...Yi(t,r)),s.U=null,void 0===o)return null;let l=[];for(let e=0;e<o.length;e++){let t=ds.get(o[e]);if(l.push(o[e]),void 0!==t)for(;e<o.length&&o[e]!==t.U;)e++}if(!xs(e,l)){let n=(e.Tn?e.root:e.on).cloneNode(!0);l=e.Tn?[n]:[...n.childNodes],xs(e,l),(o[0]??s.u.find(e=>e.length>0)?.[0]??t).before(n);for(let e of o)e.remove()}return l}var Ps={name:"ssr",install(){c.An=Ns,c.ir=_s;let e=c.element;c.element=(t,n)=>{"mounting"===n&&function(e){let t=e.element;if(!t.hasAttribute("enable-ssr")||Fi())return;let n=t.previousElementSibling,r=n?.localName===Di(),i=r?n.getAttribute("version"):null,s=null===i||Hi(i)===Hi(Ri);if(s){let t=e,n=t.we;t.we=(t,r)=>"$connectedCallback"===t?void 0:n.call(e,t,r)}if(!r)return;let o=!s&&parseInt(i)<4,l=/^3\.(\d+)\.(\d+)$/.exec(i),a=null!==l&&(+l[1]-5||+l[2]-3)>=0;s||console.warn(`[@wcstack/state] <${Di()} version="${i}"> does not match ${Ri}: its snapshot is discarded, and the page renders on the client from its own state.${o&&!a?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let u=s?n.querySelector('script[type="application/json"]'):null;if(null!==u){let t=JSON.parse(u.textContent||"{}"),n=e.target;for(let e of Object.keys(t)){let r=Object.getOwnPropertyDescriptor(n,e);void 0!==r&&(void 0!==r.get||void 0!==r.set||"function"==typeof r.value)||(n[e]=t[e])}e.hydrated=!0}let h=t.getRootNode();for(let e of Array.from(h.querySelectorAll(`[${ss}]`)))e.textContent=e.getAttribute(ss),e.removeAttribute(ss);let d=9===h.nodeType?h.body:h;o?function(e,t,n){let r=new Map,i=e=>{let t=e.parentElement;for(;null!==t&&!ps(t);)t=t.parentElement;if(null===t)return null;let n=r.get(t);if(void 0===n){let e=i(t),s=t.querySelector(`:scope > ${re.tagNames.state}[bind-component]`).getAttribute("bind-component");r.set(t,n=[]);for(let r of ae(t.getAttribute(re.bindAttributeName)??"")){let t=r.Je;r.ve[0]===s&&n.push([e?Ss(e,t,1,0):t,r.ve.slice(1).join("."),e&&t])}}return n},s=(e,t,n)=>{let r=i(e);if(null===r)return t;let s=/^([^|]*)#m\d+\.([^|]*)$/.exec(t);if(null===s)return n?t:Ss(r,t,0,1)??t;let o=s[1].replace(/#m\d+\./g,"").slice(0,-1);return r.some(e=>""===e[1]&&(e[0]===o||e[2]===o))?s[2]:Ss(r,s[2],2,1)??s[2]};for(let t of ks(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let r=t.nextSibling;for(;null!==r&&!Bi(r,`@@wcs-${e[1]}-end:${e[2]}`);)r=r.nextSibling;if(null!==r){for(;t.nextSibling!==r;)t.nextSibling.remove();r.remove(),t.replaceWith(..."text"===e[1]?[qi(`@@:${s(t,e[2],n)}`)]:[])}}let o=(e,n)=>{for(let r of ks(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(r.data)?.[1],i=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===i)continue;let l=document.importNode(i,!0),a=re.bindAttributeName;l.removeAttribute("id"),l.setAttribute(a,l.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,i)=>t+s(n??r,i))),o(l.content,n??r);let u=l.content.firstChild;r.replaceWith(.../^\s*elseif\s*:/.test(u?.getAttribute?.(a)??"")?l.content.childNodes:[l])}};o(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(d,n,a):ws(d,n,s),n.remove(),s&&(c.Ae=Ts,queueMicrotask(()=>{$s(),c.Ae=null}))}(t),e?.(t,n)},function(){let e=globalThis;e[hs]={build:cs,reset(){as=0}},void 0===e[Ui]&&(e[Ui]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[hs].build(t),reset:()=>e[hs].reset()})}(),c.Eo=h(c.Eo,zi);for(let e of Zt())zi(e)}},Os="__WCSTACK_DEVTOOLS_HOOK__",Ms=null,Ls=new Set,Is=(e,t,n)=>({absolutePathInfo:{pathInfo:{path:t.t},stateElement:e.element},listIndex:null===n?null:{indexes:e._(n)}}),js=new WeakMap,Rs=0,Hs=new WeakMap;function Ws(e){if(null===Ms)return;let t=Hs.get(e),n=Ls.has(e)?function(e,t){let n=new Map,r=new Set,i=(r,i,s,o,l,a)=>{if(5===r)return;let u=function(e,t){return 0===e?"textContent":2===e?`class.${t}`:3===e?`attr.${t}`:4===e?`style.${t}`:t}(r,i),c=0===o.n?null:l,h=`${(e=>{let t=js.get(e);return void 0===t&&js.set(e,t=++Rs),t})(s)}|${u}|${o.t}|${null===c?"":e._(c).join(",")}`;if(n.has(h))return;let d=t?.get(h);n.set(h,d??{binding:{propName:u,statePathName:o.t,bindingType:a,node:s,replaceNode:s},absoluteAddress:Is(e,o,c)})},s=e=>i(e.i,e.name,e.a,e.o,e.r,e.en()),o=e=>{if(!r.has(e)){if(r.add(e),null!==e.fe)for(let t of e.fe)s(t);if(e instanceof Xe&&null!==e.ae){let t=e.A.Ke;for(let n=0;n<t.length;n++){let r=e.W?.[n];void 0!==r?s(r):i(t[n].i,t[n].name,e.ae[2*n],t[n].o,e.r,0===t[n].i?"text":"prop")}}if(null!==e.h)for(let t of e.h)l(t)}},l=e=>{if(!r.has(e))if(r.add(e),e instanceof lt){i(-1,"for",e.S,e.l.o,e.l.re,"for");for(let t of e.Ee)o(t)}else null!==e.O&&o(e.O)};for(let t of e.ie.values())for(let e of t)s(e),null!==e.M&&l(e.M);for(let t of e.ee.values())if(null!==t.$&&l(t.$),null!==t.L)for(let e of t.L)l(e);return n}(e,t):new Map;if(void 0!==t)for(let[e,r]of t)n.has(e)||Ms({type:"state:binding-removed",...r});for(let[e,r]of n)(void 0===t||!t.has(e))&&Ms({type:"state:binding-added",...r});Hs.set(e,n)}function zs(e){let t=It.get(e);if(void 0===t)throw new Error("[@wcstack/state] devtools: no state tree on this root");return t}function Ds(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let s of e.B.all()){for(let e=1;e<=s.n;e++)t.add(s.f[e].t);"*"===s.s&&n.add(s.t),null!==s.getter&&r.add(s.t),null!==s.oe&&i.add(s.t)}let s=e.target;return{rootNode:e.root,element:e.element,paths:{list:t,element:n,getter:r,setter:i},commandTokenNames:new Set(Object.keys(e.commands)),eventTokenNames:new Set(e.Ne.keys()),staticDependency:new Map,dynamicDependency:new Map,watchPaths:null!==s.$watch&&"object"==typeof s.$watch?new Set(Object.keys(s.$watch)):null,keyedListPaths:null!==s.$listKeys&&"object"==typeof s.$listKeys?new Set(Object.keys(s.$listKeys)):null}}var Us=new WeakSet,Fs=new WeakMap;function qs(e,t){if(("mounting"===t||"reset"===t)&&function(e){let t=(t,n)=>{if(Us.has(t))return;Us.add(t);let r=t.emit;t.emit=(...i)=>(null!==Ms&&Ms({type:"state:token-emit",kind:n,tokenName:t.name,args:i,subscriberCount:t.size,stateElement:e.element}),r.apply(t,i))};for(let n of Object.values(e.commands))t(n,"command");for(let n of e.Ne.values())t(n,"event")}(e),"connected"===t){if(Ls.has(e))return;Ls.add(e),Ms?.({type:"state:element-registered",rootNode:e.root,element:e.element}),Ws(e)}else"disconnected"===t&&(Ls.delete(e),Ws(e),Ms?.({type:"state:element-unregistered",rootNode:e.root,element:e.element}))}function Bs(e,t,n,r,i,s){if(null===Ms)return;let o=Is(e,t,0===t.n?null:n),l=Fs.get(e);void 0===l&&Fs.set(e,l=new Set),l.add(o),s&&Ms({type:"state:write",absoluteAddress:o,value:i,oldValue:r,hasOldValue:!0})}function Ks(e){if(null===Ms)return;let t=Fs.get(e);Fs.delete(e),void 0!==t&&Ms({type:"state:update-batch",addresses:t}),Ws(e)}function Gs(e,t,n){Ms?.({type:"state:binding-apply-error",path:n.o.t,bindingType:n.en(),error:t})}!function(e){for(let t of e)g.has(t.name)||(g.add(t.name),t.install())}([ln,Ln,sr,fr,_i,ji,Ps,{name:"devtools",install(){c.element=h(c.element,qs),c.he=h(c.he,Bs),c.Te=h(c.Te,Ks),c.Ve=h(c.Ve,Gs),function(){if(typeof document>"u"||document.documentElement?.hasAttribute("data-wcs-server"))return;let e=globalThis,t=e[Os]??(e[Os]=function(){let e=new Map,t=new Set,n=e=>{0===t.size?e._setSink(null):e._setSink(n=>{for(let r of t)r.onEvent?.(e.id,n)})};return{version:2,sources:e,register(r){if(!e.has(r.id)){e.set(r.id,r),n(r);for(let e of t)e.onSourceRegistered?.(r)}},unregister(n){let r=e.get(n);if(void 0!==r){r._setSink(null),e.delete(n);for(let e of t)e.onSourceUnregistered?.(n)}},addListener(r){t.add(r);for(let t of e.values())n(t),r.onSourceRegistered?.(t);return()=>{if(t.delete(r))for(let t of e.values())n(t)}}}}());2!==t.version&&console.warn(`[@wcstack/state] devtools hook registry version ${t.version}, expected 2: keeping the existing one.`),t.register({id:`state:${Math.random().toString(36).slice(2,10)}`,kind:"state",packageVersion:Ri,getStateElements:()=>[...Ls].map(Ds),overlays:()=>[],keyedSubscriptions:e=>function(e){let t=[];for(let n of e.B.all()){let r=n.q,i=n.Fe?.length??0;if((null===r||0===r.size)&&0===i)continue;let s,o=0;if(null!==r)for(let e of r.values())o+=e.size;try{s=0===n.n?e.v(n,null):void 0}catch{s=void 0}t.push({path:n.t,tracked:!1,rows:o,keys:null===r?0:r.size,lists:i,lastValue:s})}return t}(zs(e)),keys(e){let t=zs(e).target;return Object.keys(t).filter(e=>{if(e.includes("*")||"$"===e[0])return!1;let n=Object.getOwnPropertyDescriptor(t,e);return void 0!==n.get||"function"!=typeof n.value})},read(e,t,n){let r;return zs(e).element.createState("readonly",e=>{r=e.$resolve(t,n??[])}),r},write(e,t,n,r){zs(e).element.createState("writable",e=>{e.$resolve(t,r??[],n)})},_setSink(e){let t=null===Ms&&null!==e;Ms=e,null===e&&(Hs=new WeakMap),c.nt=e&&((e,t)=>Ms?.({...t,stateElement:e.element})),t&&queueMicrotask(()=>{for(let e of Ls)Ws(e)})}})}()}}]),function(e=customElements){(function(){let e=globalThis;void 0===e[Wt]&&(e[Wt]={protocol:"wcs-binder",version:1,bind:Ft})})(),Zt().includes(e)||Yt.push(new WeakRef(e));let t=re.tagNames.state;void 0===e.get(t)&&e.define(t,class extends Xt{}),c.Eo?.(e)}();const Vs={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"},Js=!1,Qs=[".html"];function Xs(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function Ys(e,t){if(t&&"cause"in t)throw new Error(`[@wcstack/router] ${e}`,{cause:t.cause});throw new Error(`[@wcstack/router] ${e}`)}let Zs=class extends Error{fallbackPath;constructor(e,t){super(e),this.fallbackPath=t}};const eo={int:{typeName:"int",pattern:/^-?\d+$/,parse(e){if(this.pattern.test(e))return parseInt(e,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(e){if(this.pattern.test(e))return parseFloat(e)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(e){if(this.pattern.test(e))return"true"===e||"1"===e}},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(e){if(this.pattern.test(e))return e}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(e){if(this.pattern.test(e))return e}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(e){if(!this.pattern.test(e))return;const[t,n,r]=e.split("-").map(Number),i=new Date(t,n-1,r);return i.getFullYear()===t&&i.getMonth()===n-1&&i.getDate()===r?i:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(e){if(this.pattern.test(e))return e}}};function to(e){const t={};for(const[n,r]of new URLSearchParams(e))t[n]=r;return Object.freeze(t)}function no(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const r of n){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(e[r]!==t[r])return!1}return!0}const ro={static:2,param:1,"catch-all":0};let io=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(e){super(),this._target=e??this}get parentCore(){return this._parentCore}set parentCore(e){this._parentCore=e}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(e,t){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&Ys(`${Vs.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&Ys(`${Vs.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):t()}get absolutePath(){return this._checkParentCore(e=>{const t=e.absolutePath;return t.endsWith("/")?t+this._path:t+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(e=>[...e.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 e=[];for(const t of this._segmentInfos)t.paramName&&e.push(t.paramName);this._paramNames=e}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(e=>[...e.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let e=0;for(const t of this._segmentInfos)e+=ro[t.type];this._weight=e}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(e=>e.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let e=0;for(const t of this._segmentInfos)"catch-all"!==t.type&&e++;this._segmentCount=""===this._path?0:e}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(e=>e.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(e,t={}){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=e,this._name=t.name||"",this._isFallbackRoute=t.isFallback||!1,t.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=e.split("/");for(let e=0;e<n.length;e++){const r=n[e];if(!(""===r&&e===n.length-1&&e>0)){if("*"===r){this._segmentInfos.push({type:"catch-all",segmentText:r,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(r.startsWith(":")){const e=r.match(/^:([^()]+)(\(([^)]+)\))?$/);let t,n="any";e?(t=e[1],e[3]&&Object.keys(eo).includes(e[3])&&(n=e[3])):t=r.substring(1),this._segmentInfos.push({type:"param",segmentText:r,paramName:t,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===r&&t.isIndex||this._segmentInfos.push({type:"static",segmentText:r,paramName:null,pattern:new RegExp(`^${r}$`)})}}this._hasGuard=t.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=t.guardFallback||"/",this._waitForSetGuardHandler=new Promise(e=>{this._resolveSetGuardHandler=e}))}setParams(e,t){const n=this._active;this._params=e,this._typedParams=t,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:e,typedParams:t},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const e=this._active;this._params={},this._typedParams={},this._active=!1,e&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(e){for(const t of this.paramNames)if(this._params[t]!==e[t])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||Ys(`${Vs.route} has no guardHandler.`),this._guardHandler}set guardHandler(e){this._guardHandler=e,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(e){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const t=e.path,n=e.lastPath,r=await this._guardHandler(t,n,function(e){return Object.freeze({params:Object.freeze({...e.params}),typedParams:Object.freeze({...e.typedParams}),searchParams:to(e.search??""),routeName:e.routes[e.routes.length-1]?.name??""})}(e));if("string"==typeof r&&""!==r)throw new Zs("Navigation cancelled by guard.",r);if(!r)throw new Zs("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof r?r:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new Zs("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}};const so="data-wcs-ssr",oo="data-wcs-ssr-link",lo="@@wcs-route-ph:",ao="@@wcs-route-start:",uo="@@wcs-route-end:";let co=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=Xs();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new io(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||Ys(`${Vs.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${uo}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(e,t){for(this._childNodeArray=[...e],t&&(this._endMarker=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(e){this._core.guardHandler=e}setParams(e,t){this._core.setParams(e,t)}clearParams(){this._core.clearParams()}shouldChange(e){return this._core.shouldChange(e)}async guardCheck(e){return this._core.guardCheck(e)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(e){let t=this._routeParentNode;for(;t;){if(t===e)return!0;t=t.routeParentNode}return!1}initialize(e,t){if(this._initialized)return;let n;this._initialized=!0;let r=!1,i=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",r=!0):this.hasAttribute("fallback")?(n="",i=!0):Ys(`${Vs.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=t;const s=t||e;s.routeChildNodes.push(this),this._childIndex=s.routeChildNodes.length-1,i&&(t&&Ys(`${Vs.route} with fallback attribute must be a direct child of ${Vs.router}.`),e.fallbackRoute&&Ys(`${Vs.router} can have only one fallback route.`),e.fallbackRoute=this),t&&(this._core.parentCore=t._core),this._core.parsePath(n,{isIndex:r,isFallback:i,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const ho=Symbol.for("wcstack.trustedTypes.policy"),fo=Symbol.for("wcstack.trustedTypes.internal"),po="wcstack";function mo(){const e=globalThis[ho];return null===e||"object"!=typeof e?null:e}let go=!1;function yo(e){const t=function(){const e=globalThis,t=e[fo];if(void 0!==t)return t;const n=globalThis.trustedTypes;let r=null;if(n&&"function"==typeof n.createPolicy)try{r=n.createPolicy(po,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){"function"!=typeof mo()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${po}". Allow it in the CSP (\`trusted-types ${po};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,e)}return e[fo]=r,r}(),n=t?.createHTML;if("function"==typeof n)return n.call(t,e);if(!("trustedTypes"in globalThis))return e;const r=mo(),i=r?.createHTML;return"function"==typeof i?(go||(go=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${po}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${po};\` in the CSP to avoid this. See docs/csp.md section 7.`)),i.call(r,e)):e}const bo=new Map;let vo=class extends HTMLElement{_uuid=Xs();constructor(){super()}async _loadTemplateFromSource(e){try{const t=await fetch(e);t.ok||Ys(`${Vs.layout} failed to fetch layout from source: ${e}, status: ${t.status}`);const n=await t.text();return bo.set(e,n),n}catch(t){Ys(`${Vs.layout} failed to load layout from source: ${e}, error: ${t}`,{cause:t})}}_loadTemplateFromDocument(e){const t=document.getElementById(`${e}`);return t&&t instanceof HTMLTemplateElement?t.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),t=this.getAttribute("layout");e&&t&&console.warn(`${Vs.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)bo.has(e)?n.innerHTML=yo(bo.get(e)||""):n.innerHTML=yo(await this._loadTemplateFromSource(e)||"");else if(t){const e=this._loadTemplateFromDocument(t);e?n.innerHTML=yo(e):console.warn(`${Vs.layout} could not find template with id "${t}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Js}get name(){return this.getAttribute("name")||""}};class wo extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||Ys(`${Vs.outlet} has no routesNode.`),this._routesNode}set routesNode(e){this._routesNode=e}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(e){this._lastRoutes=[...e]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Js}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const _o=new Set(["props","states","attr",""]);function $o(e,t,n){for(const[r,i]of Object.entries(t))switch(n){case"props":e.props={...e.props,[r]:i};break;case"states":e.states={...e.states,[r]:i};break;case"attr":null==i?e.removeAttribute(r):e.setAttribute(r,String(i));break;case"":e[r]=i}}function ko(e,t){e.hasAttribute("data-bind")||Ys(`${e.tagName} has no 'data-bind' attribute.`);const n=e.getAttribute("data-bind")||"";_o.has(n)||Ys(`${e.tagName} has invalid 'data-bind' attribute: ${n}`);const r=n,i=function(e){const t=e.tagName.toLowerCase();if(t.includes("-"))return t;const n=e.getAttribute("is");return n&&n.includes("-")?n:null}(e);i&&void 0===customElements.get(i)?customElements.whenDefined(i).then(()=>{e.isConnected&&$o(e,t,r)}).catch(()=>{Ys(`Failed to define custom element: ${i}`)}):$o(e,t,r)}const So=Symbol.for("wcstack.binder");function No(){const e=globalThis[So];return null==e||"wcs-binder"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.bind?null:e}const Ao=Symbol.for("wcstack.binder.pending"),Eo=Symbol.for("wcstack.binder.taken");function Co(){const e=globalThis;let t=e[Eo];return void 0===t&&(t=new WeakSet,e[Eo]=t),t}function xo(e,t){const n=No();return null===n?(function(){const e=globalThis;let t=e[Ao];return void 0===t&&(t=[],e[Ao]=t),t}().push(e),!1):(Co().add(e),n.bind(e,t),!0)}const To={range:!0};function Po(e,t){for(const n of e.routeChildNodes)t.add(n.placeHolder).add(n.endMarker),Po(n,t);return t}function Oo(e){const t=e.placeHolder,n=e.endMarker,r=null!==n.parentNode&&n.parentNode===t.parentNode&&!!(4&t.compareDocumentPosition(n)),i=r?null:Po(e,new Set),s=[];let o=0;for(let l=t.nextSibling;null!==l&&l!==n&&(null===i||8!==l.nodeType||!/^@@(route:|wcs-route-)/.test(l.data)||i.has(l));l=l.nextSibling)s.push(l),(r||e.childNodeArray.includes(l))&&(o=s.length);return s.length=o,s}let Mo=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||Ys(`${Vs.layoutOutlet} has no layout.`),this._layout}set layout(e){this._layout=e,this.setAttribute("name",e.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 e=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(e.content.cloneNode(!0));for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),this.appendChild(e)}else{const t=e.content.cloneNode(!0),n=new Map;t.querySelectorAll("slot").forEach(e=>{const t=e.getAttribute("name")||"";n.has(t)?console.warn(`${Vs.layoutOutlet} duplicate slot name "${t}" in layout template.`):n.set(t,e)});const r=new Map,i=document.createDocumentFragment();for(const e of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(e),e instanceof Element){const t=e.getAttribute("slot")||"";if(t.length>0&&n.has(t)){r.has(t)||r.set(t,document.createDocumentFragment()),r.get(t)?.appendChild(e);continue}}i.appendChild(e)}for(const[e,t]of n){const n=r.get(e);n&&t.replaceWith(n)}const s=n.get("");s&&s.replaceWith(i),this.appendChild(t)}!function(e){if(null!==No())for(const t of e)1===t.nodeType&&xo(t,To)}(Array.from(this.childNodes))}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(e){for(const t of this._layoutChildNodes)t instanceof Element&&(t.querySelectorAll("[data-bind]").forEach(t=>{ko(t,e)}),t.hasAttribute("data-bind")&&ko(t,e))}};function Lo(){return document.createElement(Vs.layoutOutlet)}const Io="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function jo(e,t){(async function(e,t){let n=null,r=null;const i=t.uuid||"",s=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=e.text+s;let l=!1;const a=e=>{e.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",a);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),i=URL.createObjectURL(t);try{n=await(import(i))}catch(e){r=e}finally{URL.revokeObjectURL(i)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await(import(`data:application/javascript;base64,${t}`))}catch(e){await new Promise(e=>setTimeout(e)),Ys(function(e,t,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${Io}`:`loadGuardHandler: failed to import guard script. data: URL error: ${e?.message??String(e)}`+(t?`. Blob URL error: ${t?.message??String(t)}`:"")+`. If this page sets a Content-Security-Policy, see ${Io}`}(e,r,l),{cause:r??e})}}}finally{document.removeEventListener("securitypolicyviolation",a)}return n&&"function"==typeof n.default?n.default:null})(e,t).then(e=>{e?t.guardHandler=e:t.notifyGuardHandlerLoadFailed()}).catch(e=>{console.error("loadGuardHandler failed:",e),t.notifyGuardHandlerLoadFailed()})}function Ro(e,t){let n=e.get(t.absolutePath);n||(n=[]);for(const e of n)if(!t.testAncestorNode(e)){console.warn(`Duplicate route path detected: '${t.absolutePath}' (defined as '${t.path}')`);break}n.push(t),1===n.length&&e.set(t.absolutePath,n)}async function Ho(e,t,n,r){const i=n.length>0?n[n.length-1]:null,s=document.createDocumentFragment(),o=Array.from(t.childNodes);for(const t of o)if(t.nodeType===Node.ELEMENT_NODE){let o=t,l=t;const a=l.tagName.toLowerCase();if(a===Vs.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const s=document.importNode(l,!0);customElements.upgrade(s),s.appendChild(t);const a=s;a.initialize(e,i),Ro(r,a),n.push(a),o=a.placeHolder,l=a}else{if(a===Vs.guardHandler){if(n.length>0){const e=n[n.length-1],t=l.querySelector('script[type="module"]');t&&jo(t,e)}continue}if("template"===a){s.appendChild(l);continue}if(a===Vs.layout){const e=document.createDocumentFragment();for(const t of Array.from(l.childNodes))e.appendChild(t);const t=document.importNode(l,!0);customElements.upgrade(t),t.appendChild(e);const n=t,r=Lo();r.layout=n,o=r,l=t}}const u=await Ho(e,l,n,r);l.replaceChildren(),l.appendChild(u),s.appendChild(o)}else s.appendChild(t);return s}async function Wo(e){const t=new Map;return await Ho(e,e.template.content,[],t)}function zo(e){return!1!==e.checkVisibility?.()}function Do(e,t,n,r){const i=function(e,t,n){const r={},i={};let s=!0,o=!1,l=0,a=0;for(;l<e.absoluteSegmentInfos.length;){const t=e.absoluteSegmentInfos[l];if(t.isIndex){l++;continue}if(0===l&&""===t.segmentText&&"static"===t.type){l++;continue}const u=n[a];if(void 0===u){s=!1;break}let c=!1;if("param"===t.type){const e=t.paramType||"any",n=eo[e].parse(u);void 0!==n&&(t.paramName&&(r[t.paramName]=u,i[t.paramName]=n),c=!0)}else c=null!==t.pattern.exec(u);if(!c){s=!1;break}if("catch-all"===t.type){const e=n.slice(a).join("/");r["*"]=e,i["*"]=e,o=!0;break}l++,a++}let u=!1;return s&&(o||l===e.absoluteSegmentInfos.length&&a===n.length)&&(u=!0),u?{path:t,routes:e.routes,params:r,typedParams:i,lastPath:""}:null}(e,t,n);i&&r.push(i);for(const i of e.routeChildNodes)Do(i,t,n,r)}function Uo(e,t){const n=e.routeChildNodes,r=[],i=t.split("/"),s=i.filter((e,t)=>!(0===t&&""===e||t===i.length-1&&""===e&&i.length>1));for(const e of n)Do(e,t,s,r);return r.sort((e,t)=>{const n=e.routes.at(-1),r=t.routes.at(-1),i=n.absoluteSegmentCount-r.absoluteSegmentCount;if(0!==i)return-i;const s=n.absoluteWeight-r.absoluteWeight;return 0!==s?-s:n.childIndex-r.childIndex}),r.length>0?r[0]:null}let Fo=null,qo=null;function Bo(){const e=Qs;return 0===e.length?null:(Fo===e&&qo||(Fo=e,qo=new RegExp(`\\/[^/]+(?:${e.map(e=>e.replace(/\./g,"\\.")).join("|")})$`,"i")),qo)}function Ko(e){let t=e||"/";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=Bo();return n&&(t=t.replace(n,"")),""===t&&(t="/"),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Go(e,t){let n=e;return""!==t&&(e===t?n="":e.startsWith(t+"/")&&(n=e.slice(t.length))),""===n?"/":n}function Vo(e){let t=e||"";if(!t)return"";t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/");const n=Bo();return n&&(t=t.replace(n,"")),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),"/"===t?"":t}function Jo(e){if(null!==e.held)return;const t=Oo(e),n=new Set(t),r=[...t,...e.childNodeArray];let i=null;for(const s of e.childNodeArray)n.has(s)?i=s:null===s.parentNode||r.some(e=>e!==s&&e.contains(s))||(t.splice(null===i?0:t.indexOf(i)+1,0,s),n.add(s),i=s);const s=document.createDocumentFragment();!function(e,t){const n=t.map(e=>e.parentNode);for(let r=0;r<t.length;r++)t[r].parentNode===n[r]&&e.appendChild(t[r])}(s,t),s.appendChild(e.endMarker),e.held=s}function Qo(e){e.clearParams(),Jo(e)}function Xo(e,t){const n={},r={};for(const i of e.paramNames)n[i]=t.params[i],r[i]=t.typedParams[i];e.setParams(n,r);for(const t of e.childNodeArray)if(t.nodeType===Node.ELEMENT_NODE){const n=t;n.querySelectorAll("[data-bind]").forEach(t=>{ko(t,e.typedParams)}),n.hasAttribute("data-bind")&&ko(n,e.typedParams),n.querySelectorAll(Vs.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===Vs.layoutOutlet&&n.assignParams(e.typedParams)}}const Yo=new WeakSet;function Zo(e){const t=e.placeHolder;null!==t.parentNode&&(Yo.has(e)||null!==e.endMarker.parentNode?(Jo(e),t.after(e.held),e.held=null):t.after(...e.childNodeArray,e.endMarker),Yo.add(e))}const el=Symbol.for("wcstack.transition-runner");const tl=new WeakSet,nl="data-wcs";function rl(e,t,n){!tl.has(e)&&function(e){return e.hasAttribute(nl)||null!==e.querySelector(`[${nl}]`)}(e)&&(tl.add(e),function(e){"complete"===document.readyState?e():window.addEventListener("load",e,{once:!0})}(()=>{var r;null!==No()||(r=e,Co().has(r))||console.warn(`[@wcstack/router] ${t} contains ${nl} 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 il(e){for(const t of e.childNodeArray)if(1===t.nodeType){if(t.isConnected){if(xo(t,To))continue}else if(null!==No())continue;rl(t,`<${t.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 sl(e,t){try{let e=null;for(const n of t.routes){const r=await n.guardCheck(t);r&&(e=null===e?r:Object.assign({},e,r))}t.data=e}catch(t){if(t instanceof Zs)return console.warn(`Navigation cancelled: ${t.message}. Redirecting to ${t.fallbackPath}`),queueMicrotask(()=>{e.navigate(t.fallbackPath).catch(e=>{console.error("Fallback navigation failed:",e)})}),!1;throw t}return!0}async function ol(e,t,n,r,i=""){const s=Go(n,e.basename);if(e.isSameMatch(s))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:i,path:s}),!0;let o=Uo(e,s);o||(e.fallbackRoute?o={routes:[e.fallbackRoute],params:{},typedParams:{},path:s,lastPath:r}:Ys(`${Vs.router} No route matched for path: ${s}`)),o.lastPath=r,o.search=i;const l=t.lastRoutes,a=await async function(e,t,n){if(!await sl(e,t))return!1;const r=new Set(t.routes),i=new Set(n),s=()=>{for(const e of n)r.has(e)||Qo(e);const e=[];for(const n of t.routes)(e.length>0||!i.has(n)||n.shouldChange(t.params))&&(e.push(n),Xo(n,t));let s=!1;for(const t of e){const e=i.has(t);e&&s||Zo(t),s||=e,n.length>0&&!e&&il(t)}};let o;return 0===n.length?s():o=function(e,t,n){const r=function(e){const t=globalThis[el];return null==t||"wcs-transition-runner"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.run?null:"function"==typeof t.accepts&&t.accepts(e)?t:null}(e);if(null!==r)return r.run(t,{source:e,types:n});t()}("router",s),void 0!==o&&await o,!0}(e,o,l);return!!a&&(e.commitNavigation({params:o.params,typedParams:o.typedParams,routeName:o.routes[o.routes.length-1]?.name??"",data:o.data??null,search:i,path:s}),t.lastRoutes=o.routes,l.length>0&&function(e,t){if("title"===e.announcePolicy){const t=e.a11yRegion;null!==t&&(t.textContent=document.title)}if("heading"===e.focusPolicy){const e=function(e){for(const t of e){if(t.nodeType!==Node.ELEMENT_NODE)continue;const e=t;if(/^H[1-6]$/.test(e.tagName)){if(zo(e))return e}else for(const t of e.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(zo(t))return t}return null}(t.routes[t.routes.length-1].childNodeArray);if(null!==e)e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus();else{const e=document.querySelector("[autofocus]");null!==e?e.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(e,o),!0)}function ll(){const e=window.navigation;return e?"function"!=typeof e.addEventListener||"function"!=typeof e.removeEventListener?null:e:null}function al(e){let t=e,n="";const r=t.indexOf("#");r>=0&&(n=t.slice(r),t=t.slice(0,r));let i="";const s=t.indexOf("?");return s>=0&&(i=t.slice(s),t=t.slice(0,s)),{pathname:t,search:i,hash:n}}function ul(e){return"?"===e?"":e}function cl(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}function hl(){const e=document.documentElement;return!!e&&e.hasAttribute("data-wcs-server")}const dl=Object.freeze({});class fl 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:e=>e.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:e=>e.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=dl;_typedParams=dl;_searchParams=dl;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((e,t)=>{this._resolveConnectedCallback=e,this._rejectConnectedCallback=t}),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 e=document.createElement("div");e.setAttribute("role","status"),e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",e.style.clipPath="inset(50%)",e.style.whiteSpace="nowrap",this.appendChild(e),this._a11yRegion=e}_normalizePathname(e){return Ko(e)}_normalizeBasename(e){return Vo(e)}_joinInternalPath(e,t){const n=this._normalizeBasename(e);let r=t.startsWith("/")?t:"/"+t;return r=this._normalizePathname(r),n?"/"===r?n+"/":n+r:r}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let e=new URL(document.baseURI).pathname||"/";return"/"===e?"":this._normalizeBasename(e)}get basename(){return this._basename}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(Vs.outlet))return e;const t=document.createElement(Vs.outlet);return this.parentNode?this.parentNode.insertBefore(t,this.nextSibling):document.body.appendChild(t),t}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||Ys(`${Vs.router} has no outlet.`),this._outlet}get template(){return this._template||Ys(`${Vs.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(e){const t=this._path!==e;this._path=e,t&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:e,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(e){return!!this._hasCommitted&&this._path===e}commitNavigation(e){const t=Object.freeze({...e.params}),n=Object.freeze({...e.typedParams}),r=to(e.search),i=e.data??null,s=this._data!==i,o=!no(this._params,t),l=this._routeName!==e.routeName,a=!no(this._searchParams,r),u=this._path!==e.path;s&&(this._data=i),o&&(this._params=t,this._typedParams=n),l&&(this._routeName=e.routeName),a&&(this._searchParams=r),this._path=e.path,this._hasCommitted=!0,s&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),o&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:e.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(e){this._fallbackRoute=e}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{console.error(`${Vs.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{console.error(`${Vs.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(e){await this._performNavigation(e,!1)}async replace(e){await this._performNavigation(e,!0)}async _performNavigation(e,t){const n=al(e),r=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,i=r+ul(n.search)+n.hash,s=ll();if(s?.navigate){const e=t?s.navigate(i,{history:"replace"}):s.navigate(i);await(e?.finished)}else{t?history.replaceState(null,"",i):history.pushState(null,"",i);const e=this._normalizePathname(r),s=this.isSameMatch(Go(e,this._basename));await ol(this,this.outlet,e,this._path,ul(n.search))&&!s&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(e){return""===this._basename||e===this._basename||e.startsWith(this._basename+"/")}_onNavigateFunc(e){if(!e.canIntercept||e.hashChange||null!==e.downloadRequest)return;const t=new URL(e.destination.url),n=this._normalizePathname(t.pathname);if(!this._isOwnPath(n))return;const r=this.isSameMatch(Go(n,this._basename)),i=r&&("push"===e.navigationType||"replace"===e.navigationType),s=t.search,o=this;e.intercept({handler:async()=>{try{await ol(o,o.outlet,n,o.path,s)}catch(e){throw console.error(`${Vs.router} applyRoute failed:`,e),e}},scroll:i?"manual":"after-transition",focusReset:r||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const e=this._normalizePathname(window.location.pathname);this._isOwnPath(e)&&(await ol(this,this.outlet,e,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=hl();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const t=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||t||"/"===n.pathname||Ys(`${Vs.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||Ys(`${Vs.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await Wo(this),s=!e&&this._outlet.hasAttribute(so);if(s||this._outlet.rootNode.appendChild(i),null!==r){const e=this._template.content;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(r)}0===this.routeChildNodes.length&&Ys(`${Vs.router} has no route definitions.`),e||this._ensureA11yRegion();const o=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(o),void(this._initialized=!0);if(s){if(await this._hydrateFromSsr(o))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(so);const e=this._outlet.rootNode;for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(i)}await ol(this,this.outlet,o,this._path,window.location.search||""),(s||null!==No())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const t=this.outlet.rootNode,n=new Map;let r=!1;if(this._forEachRoute(e=>{n.has(e.absolutePath)?r=!0:n.set(e.absolutePath,e)}),r)return!1;if(null!==t.querySelector(Vs.layoutOutlet))return!1;const i=new Map,s=new Map,o=new Map,l=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);let a=0;for(;l.nextNode();){const e=l.currentNode,t=e.data;if(a++,t.startsWith(lo)){const r=t.slice(15);if(i.has(r)||!n.has(r))return!1;i.set(r,e)}else if(t.startsWith(ao)){const r=t.slice(18);if(s.has(r)||!n.has(r))return!1;s.set(r,{comment:e,index:a})}else if(t.startsWith(uo)){const r=t.slice(16);if(o.has(r)||!n.has(r))return!1;o.set(r,{comment:e,index:a})}}if(s.size!==o.size)return!1;const u=[];for(const[e,t]of s){const n=o.get(e);if(!n)return!1;if(n.comment.parentNode!==t.comment.parentNode)return!1;if(n.index<=t.index)return!1;u.push({start:t.index,end:n.index})}for(const e of u)for(const t of u)if(e.start<t.start&&t.start<e.end&&e.end<t.end)return!1;const c=Go(e,this._basename);let h=Uo(this,c);if(!h){if(null===this._fallbackRoute)return!1;h={routes:[this._fallbackRoute],params:{},typedParams:{},path:c,lastPath:this._path}}if(h.lastPath=this._path,h.routes.length!==s.size)return!1;for(const e of h.routes)if(!s.has(e.absolutePath))return!1;const d=new Set;for(const e of this.routeChildNodes)d.add(e.absolutePath);for(const e of h.routes)for(const t of e.routeChildNodes)d.add(t.absolutePath);if(i.size!==d.size)return!1;for(const e of d)if(!i.has(e))return!1;for(const[e,t]of i){const r=n.get(e);t.parentNode.replaceChild(r.placeHolder,t)}for(const e of h.routes){const t=s.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,r=[],i=new Set;let l=t.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const e=l.data;if(e.startsWith(ao)){const t=e.slice(18);l=o.get(t).comment.nextSibling;continue}}if(i.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===Vs.link){const e=l.anchorElement;null!==e&&i.add(e)}r.push(l),l=l.nextSibling}}e.adoptChildNodes(r,n)}for(const{comment:e}of s.values())e.remove();this.outlet.removeAttribute(so);for(const e of h.routes)Xo(e,h);return this.outlet.lastRoutes=h.routes,!await sl(this,h)||(this.commitNavigation({params:h.params,typedParams:h.typedParams,routeName:h.routes[h.routes.length-1].name,data:h.data??null,search:window.location.search||"",path:c}),!0)}async _renderForSsr(e){const t=Go(e,this._basename),n=Uo(this,t),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&Ys(`${Vs.router} No route matched for path: ${t}`),!r.some(e=>e.hasGuard)){await ol(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(e=>{e.placeHolder.data=`${lo}${e.absolutePath}`}),this.outlet.setAttribute(so,"");for(const e of this.outlet.lastRoutes)e.placeHolder.after(document.createComment(`${ao}${e.absolutePath}`))}}_offerInitialContentToBinder(){for(const e of this.outlet.lastRoutes)for(const t of e.childNodeArray)t.nodeType===Node.ELEMENT_NODE&&t.isConnected&&xo(t,To)}_forEachRoute(e,t=this){for(const n of t.routeChildNodes)e(n),this._forEachRoute(e,n)}async connectedCallback(){if(function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!cl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),hl()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(e){throw this._rejectConnectedCallback?.(e),e}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const e=ll();e&&!this._listeningNavigate&&(e.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),e||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(ll()?.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 pl=["title","rel","target","download","hreflang","lang","dir"];class ml extends HTMLElement{static get observedAttributes(){return["to",...pl]}_childNodeArray=[];_uuid=Xs();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const e=this.closest(Vs.router);if(e)return this._router=e;const t=this.getRootNode(),n=t.querySelector?.(Vs.router);if(n)return this._router=n;Ys(`${Vs.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(e){return Ko(e)}_joinInternalPath(e,t){const n=Vo(e),r=t.startsWith("/")?t:"/"+t,i=this._normalizePathname(r);return n?"/"===i?n+"/":n+i:i}_isInternalTarget(e){return e.startsWith("/")||e.startsWith("?")}_setAnchorHref(e,t){if(this._isInternalTarget(t)){const{pathname:n,search:r,hash:i}=al(t),s=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);e.href=s+ul(r)+i}else try{e.href=new URL(t).toString()}catch{Ys(`[${Vs.link}] Invalid URL in 'to' attribute: ${t}`)}}connectedCallback(){hl()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const e=this.nextElementSibling;return null!==e&&"A"===e.tagName&&e.hasAttribute(oo)?e:null}_connect(){this._initialized||this._initialize();const e=this.parentNode;if(!e)return;const t=this._findSsrAnchor();let n;if(null!==t)n=t,n.removeAttribute(oo),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const t=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const e of Array.from(this.attributes))(e.name.startsWith("aria-")||pl.includes(e.name))&&n.setAttribute(e.name,e.value);for(const e of this._childNodeArray)n.appendChild(e);t?e.insertBefore(n,t):e.appendChild(n)}if(this._anchorElement=n,hl())return this._updateActiveState(),void n.setAttribute(oo,"");ll()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!ll()?.navigate&&(this._onClick=async e=>{e.defaultPrevented||0===e.button&&(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||this._isInternalTarget(this._path)&&(e.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){ll()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const e=this._anchorElement;e&&(this._onClick&&(e.removeEventListener("click",this._onClick),this._onClick=void 0),e.remove(),this._anchorElement=null);for(const t of this._childNodeArray)e&&t.parentNode===e&&e.removeChild(t);this._router=null}attributeChangedCallback(e,t,n){if("to"===e&&t!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(pl.includes(e)){const t=this._anchorElement;t&&(null===n?t.removeAttribute(e):t.setAttribute(e,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const e=this._normalizePathname(new URL(window.location.href).pathname),{pathname:t}=al(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t):t);this._anchorElement&&(e===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 gl=[],yl=new Map;let bl=!1;const vl=new WeakMap;class wl 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 e of this._childElementArray)this.removeChild(e)}}connectedCallback(){this._initialize(),bl||(this._captureInitialHead(),bl=!0),gl.push(this),this._reapplyHead()}disconnectedCallback(){const e=gl.indexOf(this);-1!==e&&gl.splice(e,1),this._reapplyHead()}get childElementArray(){return this._initialized||Ys("Head component is not initialized yet."),this._childElementArray}_getKey(e){const t=vl.get(e);if(void 0!==t)return t;const n=this._computeKey(e);return vl.set(e,n),n}_computeKey(e){const t=e.tagName.toLowerCase();if("title"===t)return"title";if("meta"===t)return`meta:${e.getAttribute("name")||""}:${e.getAttribute("property")||""}:${e.getAttribute("http-equiv")||""}:${e.hasAttribute("charset")?"charset":""}:${e.getAttribute("media")||""}`;if("link"===t)return`link:${e.getAttribute("rel")||""}:${e.getAttribute("href")||""}:${e.getAttribute("media")||""}:${e.getAttribute("hreflang")||""}`;if("base"===t)return"base";if("script"===t){const t=e.getAttribute("src")||"",n=e.getAttribute("id")||"",r=e.getAttribute("type")||"";return t||n?`script:${t}:${n}:${r}`:`script::${r}:${e.outerHTML.slice(0,100)}`}if("style"===t){const t=e.getAttribute("id")||"",n=e.getAttribute("media")||"";return t?`style:${t}:${n}`:`style::${n}:${e.outerHTML.slice(0,100)}`}return`${t}:${e.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const e=new Map;for(const t of Array.from(document.head.children)){const n=this._getKey(t);e.has(n)||e.set(n,t)}return e}_captureInitialHead(){const e=document.head;for(const t of Array.from(e.children)){const e=this._getKey(t);yl.has(e)||yl.set(e,t.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of gl)for(const n of t._childElementArray)e.add(this._getKey(n));for(const t of yl.keys())e.add(t);const t=this._buildHeadElementMap();for(const n of t.keys())e.add(n);for(const n of e){let e=null;for(let t=gl.length-1;t>=0;t--){const r=gl[t];for(const t of r._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}!e&&yl.has(n)&&(e=yl.get(n).cloneNode(!0));const r=t.get(n)??null;e?(r?r.replaceWith(e):document.head.appendChild(e),t.set(n,e),xo(e)||rl(e,`<${e.tagName.toLowerCase()}> inside <${Vs.head}>`,`<${Vs.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.`)):(r?.remove(),t.delete(n))}}}await void function(e=customElements){e.get(Vs.layout)||e.define(Vs.layout,vo),e.get(Vs.layoutOutlet)||e.define(Vs.layoutOutlet,Mo),e.get(Vs.outlet)||e.define(Vs.outlet,wo),e.get(Vs.route)||e.define(Vs.route,co),e.get(Vs.router)||e.define(Vs.router,fl),e.get(Vs.link)||e.define(Vs.link,ml),e.get(Vs.head)||e.define(Vs.head,wl)}(void 0);const _l="data-fetchtarget",$l={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let kl=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(e,t,n={}){this.laneKey=e,this.policy=t,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 e;switch(this.policy){case"latest":e=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const t=this._nextOperationId++,n={operationId:t,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:e};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=t;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=t);break;case"overlap":this._activeOperationIds.add(t)}this._inFlightCount+=1,this._attempts.set(t,1);const r=this._makeAttempt(t,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:t,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:r}}retry(e){if(e.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(e.operationId))return null;const t=this._attempts.get(e.operationId);if(void 0===t)return null;const n=t+1;this._attempts.set(e.operationId,n),this._releaseController(e.operationId);const r=this._makeAttempt(e.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:e.operationId,laneKey:this.laneKey,attempt:n}),r}canCommit(e){if(e.ownerGeneration!==this._ownerGeneration)return!1;const t=this._terminal.get(e.operationId);return(void 0===t||"committing"===t)&&this._isEligible(e)}claimTerminal(e,t){return e.ownerGeneration===this._ownerGeneration&&!this._terminal.has(e.operationId)&&!!this._isEligible(e)&&(this._terminal.set(e.operationId,"committing"),this._claimedOutcome.set(e.operationId,t),!0)}claimedOutcome(e){return this._claimedOutcome.get(e.operationId)}finalize(e){const t=e.operationId,n=this._terminal.get(t);if(void 0!==n&&"committing"!==n)return;let r;r="committing"===n?this._claimedOutcome.get(t)??"stale":"stale",this._terminal.set(t,r),this._claimedOutcome.delete(t),this._releaseController(t),this._attempts.delete(t),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(t),void 0!==this._trace&&("stale"===r?this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:t,laneKey:this.laneKey,outcome:r}))}signalOf(e){return this._controllers.get(e.operationId)?.signal}abort(e){this._abortController(e.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const e of this._activeOperationIds)this._abortController(e)}disposeOwner(){this._ownerGeneration+=1;for(const e of Array.from(this._controllers.keys()))this._abortController(e),this._releaseController(e);for(const e of Array.from(this._attempts.keys()))this._terminal.has(e)||this._terminal.set(e,"stale"),this._claimedOutcome.delete(e),this._attempts.delete(e),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(e,t){let n;if(this._withSignal&&"function"==typeof AbortController){const t=new AbortController;this._controllers.set(e,t),n=t.signal}return{operationId:e,attempt:t,signal:n}}_isEligible(e){switch(this.policy){case"latest":return e.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===e.operationId;case"overlap":return this._activeOperationIds.has(e.operationId)}}_advanceBookkeeping(e){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===e&&(this._activeOperationId=void 0);break;case"queue":{const t=this._queue.filter(t=>t.operationId!==e);this._queue.length=0,this._queue.push(...t),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(e)}}_abortController(e){const t=this._controllers.get(e);void 0===t||t.signal.aborted||t.abort()}_releaseController(e){this._controllers.delete(e)}};function Sl(e,t){return t.every(t=>"available"===e.availability.get(t))}const Nl=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Al=class e extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:e=>e.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:e=>e.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:e=>e.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 kl("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(e){super(),this._target=e??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 Sl(this.platformAssessment,e.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(e,t){const n=new Map,r=t=>{const n=e.get(t);return void 0===n?"unknown":n.probe()?"available":"missing"};let i=!0;for(const e of t.required){const t=r(e);n.set(e,t),"available"!==t&&(i=!1)}let s=!0;for(const e of t.optional??[]){const t=r(e);n.set(e,t),"available"!==t&&(s=!1)}const o=i?s?"ready":"degraded":"idle",l=[...t.required,...t.optional??[]],a=l.some(t=>!0===e.get(t)?.requiresSecureContext),u=l.some(t=>!0===e.get(t)?.requiresUserActivation),c=a?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",h=u?"required":"not-applicable";return{availability:n,permission:t.permission??"not-applicable",readiness:o,activity:t.activity??"inactive",preconditions:{secureContext:c,userActivation:h},epoch:t.epoch??0,lastError:t.lastError}}(Nl,{required:e.REQUIRED_CAPABILITIES,optional:e.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(e,t,n,r,i){this._commitErrorInfo({code:e,phase:t,recoverable:n,message:r,...void 0===i?{}:{capabilityId:i}})}_commitErrorInfo(e){this._errorInfo!==e&&(this._errorInfo=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:e,bubbles:!0})))}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:e,bubbles:!0}))}_setError(e){this._error!==e&&(this._error=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:e,bubbles:!0})))}_setResponse(e,t,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=e,this._status=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:e,status:t,objectURL:n},bubbles:!0}))}_createObjectURL(e){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(e):null}_revokeObjectURL(e){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(e)}abort(){this._lane.abortActive()}_commitStep(e,t){this._lane.canCommit(e)&&t()}async fetch(t,n={}){if(!t)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const r=this.platformAssessment;if(!Sl(r,e.REQUIRED_CAPABILITIES)){const t=e.REQUIRED_CAPABILITIES.find(e=>"available"!==r.availability.get(e));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const i=this._doFetch(t,n);return this._promise=i,i}async _doFetch(e,t){const n=this._lane.begin(),{ticket:r,attempt:i}=n,s=i.signal;this._commitStep(r,()=>this._setLoading(!0)),this._commitStep(r,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:o="GET",body:l=null,contentType:a=null,forceText:u=!1,responseType:c="auto",timeout:h=0}=t;let d=null;h>0&&(d=setTimeout(()=>{if(!this._lane.claimTerminal(r,"timeout"))return;const e=`Request timed out after ${h}ms.`;this._commitStep(r,()=>{this._setErrorInfo("timeout","execute",!0,e),this._setError({name:"TimeoutError",message:e})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),this._lane.abort(r),this._lane.finalize(r)},h));const f={...t.headers??{}};try{a&&!f["Content-Type"]&&(f["Content-Type"]=a);const t={method:o,headers:f,signal:s};"GET"!==o&&"HEAD"!==o&&null!==l&&(t.body=l);const n=await globalThis.fetch(e,t);let i=null;if("HEAD"===o);else if(n.ok)if(u)i=await n.text();else if("blob"===c)i=await n.blob();else if("arrayBuffer"===c)i=await n.arrayBuffer();else if("text"===c)i=await n.text();else if("json"===c)i=await n.json();else{const e=n.headers.get("Content-Type")||"";i=e.includes("application/json")?await n.json():await n.text()}if(!n.ok){const e=await n.text().catch(()=>""),t={status:n.status,statusText:n.statusText,body:e};return this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(t)}),this._commitStep(r,()=>this._setResponse(null,n.status)),this._commitStep(r,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(r,"success"))return null;const h=i instanceof Blob?this._createObjectURL(i):null;return this._commitStep(r,()=>this._setResponse(i,n.status,h)),this._commitStep(r,()=>this._setLoading(!1)),this._value}catch(e){return e&&"AbortError"===e.name?(this._lane.claimTerminal(r,"aborted")&&this._commitStep(r,()=>this._setLoading(!1)),null):this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{const t=String(e?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,t),this._setError(e??{message:t})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),null):null}finally{null!==d&&clearTimeout(d),this._lane.finalize(r)}}},El=!1;function Cl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${_l}]`);if(!n)return;const r=n.getAttribute(_l);if(!r)return;const i=customElements.get($l.fetch),s=document.getElementById(r);if(!(i&&s instanceof i))return;const o=s;o.url&&(e.preventDefault(),o.fetch())}function xl(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}const Tl=Symbol.for("wcstack.trustedTypes.policy");function Pl(){const e=globalThis[Tl];return null===e||"object"!=typeof e?null:e}let Ol,Ml=!1;let Ll=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Al.wcBindable,properties:[...Al.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":e=>({loading:!0===e}),"wcs-fetch:error":e=>({error:null!=e})}),this._core=new Al(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[n,r]of Object.entries(e))this.addEventListener(n,e=>{const n=this.hasAttribute("debug-states");for(const[i,s]of Object.entries(r(e.detail))){try{s?t.add(i):t.delete(i)}catch{}n&&this.toggleAttribute(`data-wcs-state-${i}`,s)}})}get url(){return this.getAttribute("url")||""}set url(e){null==e?this.removeAttribute("url"):this.setAttribute("url",e)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(e){null==e?this.removeAttribute("method"):this.setAttribute("method",e)}get target(){return this.getAttribute("target")}set target(e){null==e?this.removeAttribute("target"):this.setAttribute("target",e)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(e){null==e?this.removeAttribute("response-type"):this.setAttribute("response-type",e)}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(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(e){this._body=e??null}get trigger(){return this._trigger}set trigger(e){if(e){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 e={},t=this.querySelectorAll($l.fetchHeader);for(const n of t){const t=n.headerName,r=n.headerValue;t&&(e[t]=r)}return e}_isNativeBodyInit(e){return e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||e instanceof ArrayBuffer||ArrayBuffer.isView(e)}_collectBody(e){if(null!==e)return"string"==typeof e||this._isNativeBodyInit(e)?{body:e,contentType:null}:{body:JSON.stringify(e),contentType:"application/json"};const t=this.querySelector($l.fetchBody);return t?{body:t.bodyContent||null,contentType:t.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const e=this._connectResolve;this._connectResolve=null;const t=this.url;this.isConnected&&!this.manual&&t&&t!==this._lastFetchedUrl?this.fetch().finally(()=>e?.()):e?.()}))}async fetch(){this._lastFetchedUrl=this.url;const e=this._collectHeaders(),t=this._body;this._body=null;const{body:n,contentType:r}=this._collectBody(t);n instanceof FormData&&Object.keys(e).some(e=>"content-type"===e.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 i=await this._core.fetch(this.url,{method:this.method,headers:e,body:n,contentType:r,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==i){const e=document.getElementById(this.target);e&&function(e,t){try{e.innerHTML=function(e){if("string"!=typeof e)return e;const t=Pl(),n=t?.createHTML;return"function"!=typeof n?e:n.call(t,e)}(t)}catch(e){if(function(){if(void 0!==Ol)return Ol;if(!("trustedTypes"in globalThis))return Ol=!1,Ol;try{document.createElement("div").innerHTML="<i></i>",Ol=!1}catch{Ol=!0}return Ol}())return void function(){if(Ml)return;Ml=!0;const e="function"==typeof Pl()?.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'). ${e}\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 e}}(e,i)}return i}attributeChangedCallback(e,t,n){"url"===e&&this._scheduleAutoFetch()}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!xl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",El||(El=!0,document.addEventListener("click",Cl)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(e=>{this._connectResolve=e})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Il extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class jl extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Rl=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(e){this.setAttribute("target",e)}get root(){return this.getAttribute("root")}set root(e){null===e?this.removeAttribute("root"):this.setAttribute("root",e)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(e){this.setAttribute("root-margin",e)}get threshold(){const e=Number(this.getAttribute("threshold")??"0");return Number.isFinite(e)?e:0}set threshold(e){this.setAttribute("threshold",String(e))}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(e){e?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(e=>{e.some(e=>e.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 e=document.getElementById(this.target);e instanceof Ll&&(e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(e=customElements){e.get($l.fetch)||e.define($l.fetch,Ll),e.get($l.fetchHeader)||e.define($l.fetchHeader,Il),e.get($l.fetchBody)||e.define($l.fetchBody,jl),e.get($l.infiniteScroll)||e.define($l.infiniteScroll,Rl)}(void 0);const Hl="data-storagetarget",Wl={storage:"wcs-storage"},zl="wcs-storage:value-changed",Dl="wcs-storage:loading-changed",Ul="wcs-storage:error",Fl="wcs-storage:error-info-changed",ql="wcs-storage:trigger-changed";let Bl=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:zl,semantics:"state",getter:e=>e.detail},{name:"loading",event:Dl,semantics:"state"},{name:"error",event:Ul,semantics:"state"},{name:"errorInfo",event:Fl,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(e){super(),this._target=e??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(e){Object.is(e,this._value)||this._setValue(e)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(e){this._key=String(e)}get type(){return this._type}set type(e){"local"===e||"session"===e?this._type=e:this._setError({operation:"type",message:`Invalid storage type: "${e}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent(Dl,{detail:e,bubbles:!0}))}_setError(e,t){this._error!==e&&(this._error=e,this._commitErrorInfo(null===e?null:function(e,t){return void 0===t?{code:"invalid-argument",phase:"start",recoverable:!1,message:e.message}:"QuotaExceededError"===t?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:e.message}:"SecurityError"===t?{code:"not-allowed",phase:"execute",recoverable:!1,message:e.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:e.message}}(e,t)),this._target.dispatchEvent(new CustomEvent(Ul,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(Fl,{detail:e,bubbles:!0}))}_toStorageError(e,t){return{operation:e,message:t instanceof Error?t.message:String(t)}}_errName(e){return e instanceof Error?e.name:""}_setValue(e){this._value=e,this._target.dispatchEvent(new CustomEvent(zl,{detail:e,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const e=this._getStorage().getItem(this._key);if(null===e)this._setValue(null);else try{this._setValue(JSON.parse(e))}catch{this._setValue(e)}return this._setLoading(!1),this._value}catch(e){return this._setError(this._toStorageError("load",e),this._errName(e)),this._setLoading(!1),null}}save(e){if(this._key){this._setLoading(!0),this._setError(null);try{const t=this._getStorage();null==e?(t.removeItem(this._key),this._setValue(null)):"string"==typeof e?(t.setItem(this._key,e),this._setValue(e)):(t.setItem(this._key,JSON.stringify(e)),this._setValue(e)),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("save",e),this._errName(e)),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(e){this._setError(this._toStorageError("remove",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const e=++this._gen;this._storageListener=t=>{if(e===this._gen&&t.key===this._key&&"session"!==this._type)if(this._setError(null),null===t.newValue)this._setValue(null);else try{this._setValue(JSON.parse(t.newValue))}catch{this._setValue(t.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},Kl=!1;function Gl(e){const t=e.target;if(!(t instanceof Element))return;const n=t.closest(`[${Hl}]`);if(!n)return;const r=n.getAttribute(Hl);if(!r)return;const i=customElements.get(Wl.storage),s=document.getElementById(r);i&&s instanceof i&&(e.preventDefault(),s.save())}function Vl(e,t){let n=Object.getPrototypeOf(e);for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;n=Object.getPrototypeOf(n)}return!1}let Jl=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Bl.wcBindable,properties:[...Bl.wcBindable.properties,{name:"trigger",event:ql,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 Bl(this),this._internals=this._initInternals(),this._wireStates({[Dl]:e=>({loading:!0===e}),[Ul]:e=>({error:null!=e})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[n,r]of Object.entries(e))this.addEventListener(n,e=>{const n=this.hasAttribute("debug-states");for(const[i,s]of Object.entries(r(e.detail))){try{s?t.add(i):t.delete(i)}catch{}n&&this.toggleAttribute(`data-wcs-state-${i}`,s)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(e){this.setAttribute("key",e)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(e){this.setAttribute("type",e)}get value(){return this._core.value}set value(e){this.manual?this._core.value=e:(this._syncCore(),this._core.save(e))}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(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(e){if(e){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(ql,{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(e,t,n){this.isConnected&&("key"===e&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===e&&this._syncCore())}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,n=t?.inputs;if(void 0!==n)for(const t of n){const n=t.name;if(!Object.prototype.hasOwnProperty.call(e,n))continue;if(!Vl(e,n))continue;const r=e,i=r[n];delete r[n],r[n]=i}}(this),this.style.display="none",Kl||(Kl=!0,document.addEventListener("click",Gl)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(e=customElements){e.get(Wl.storage)||e.define(Wl.storage,Jl)}(void 0);const Ql="*",Xl="vanilla",Yl={loaders:{[Xl]:{postfix:".js",loader:async function(e){return(await(import(`${e}`))).default}},[Ql]:Xl},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function Zl(e){if(e.startsWith("@components/")){if(e.endsWith("/")){const t=e.slice(12,e.length-1),[n,r]=t.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:r??null,isNameSpaced:!0}}{const t=e.slice(12),[n,r]=t.split("|",2),[i,s]=(r??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+e);return{key:e,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:i||null,extends:s||null,isNameSpaced:!1}}}return null}function ea(e,t,n){let r;if(null===t||t===Ql||""===t){let t=null;const i=[];for(const[e,t]of Object.entries(n)){if(e===Ql)continue;const r="string"==typeof t?n[t]:t;"string"!=typeof r&&i.push(r)}i.sort((e,t)=>t.postfix.length-e.postfix.length);for(const n of i)if(e.endsWith(n.postfix)){t=n;break}t?r=t:(r=n[Ql],"string"==typeof r&&(r=n[r]))}else if(r=n[t],!r)throw new Error("Loader not found: "+t);if("string"==typeof r)throw new Error("Loader redirection is not supported here");return r}const ta=new Set,na=new Map;let ra=new WeakMap;function ia(e){if(e===globalThis.customElements)return na;let t=ra.get(e);return void 0===t&&(t=new Map,ra.set(e,t)),t}const sa=new Map;async function oa(e,t,n){try{if(customElements.get(t))return;const r=await n.loader(e.key);if(null!==r){let n=e.extends;if(null===n&&(n=function(e){for(const[t,n]of sa)if(e.prototype instanceof t)return n;return null}(r)),customElements.get(t))return;null===n?customElements.define(t,r):customElements.define(t,r,{extends:n})}}catch(e){ta.has(t)||(console.error(`Failed to eager load component '${t}':`,e),ta.add(t))}}function la(e){if("object"!=typeof e||null===e)return null;const t=e;return"function"!=typeof t.get||"function"!=typeof t.whenDefined||"function"!=typeof t.define?null:t}function aa(e){const t=e.tagName.toLowerCase();let n,r;if(t.includes("-"))n=t,r=null;else{const i=e.getAttribute("is");if(null===i)throw new Error("Custom element without a dash or 'is' attribute found: "+t);if(!i.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+t);n=i,r=t}return{name:n,extends:r}}"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(([e,t])=>{void 0!==e&&sa.set(e,t)});const ua=new WeakSet,ca=new WeakSet;async function ha(e,t,n){e.shadowRoot&&(ua.has(e)||await async function(e,t,n){ua.add(e),await ma(e.shadowRoot,t,n)}(e,t,n))}async function da(e,t,n,r){const i=function(e,t){for(const[n,r]of Object.entries(t))if(e.startsWith(n+"-"))return r;return null}(e.name,n);if(null===i)throw new Error("No matching namespace found for lazy loaded component: "+e.name);const s=ia(r),o=s.get(e.name);if(void 0!==o)return void await o;const l=async function(e,t,n,r){try{let i;try{i=ea("",n.loaderKey,t.loaders)}catch(t){throw new Error("Loader redirection is not supported for lazy loaded components: "+e.name)}const s=e.name.slice(n.prefix.length+1);if(""===s)throw new Error("Invalid component name for lazy loaded component: "+e.name);const o=n.key+s+i.postfix;if(r.get(e.name))return;const l=await i.loader(o);if(null===l)throw new Error("Loader returned null for component: "+e.name);if(r.get(e.name))return;null===e.extends?r.define(e.name,l):r.define(e.name,l,{extends:e.extends})}catch(t){console.error(`Failed to lazy load component '${e.name}':`,t),ta.add(e.name)}}(e,t,i,r);s.set(e.name,l);try{await l}finally{s.delete(e.name)}}async function fa(e,t,n,r){const i=[],s=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_ELEMENT,e=>(e=>(e instanceof Element&&(e.tagName.includes("-")||e.getAttribute("is")?.includes("-")))??!1)(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;s.nextNode();)i.push(s.currentNode);const o=[],l=new Set;for(const e of i){const i=aa(e);void 0===r.get(i.name)?(ca.has(e)||(ca.add(e),r.whenDefined(i.name).then(async()=>{await ha(e,t,n)})),l.has(i.name)||ta.has(i.name)||(l.add(i.name),o.push(i))):await ha(e,t,n)}let a=0;for(const e of o)await da(e,t,n,r),a++;return a}async function pa(e,t,n,r){for(;await fa(e,t,n,r)>0;);}async function ma(e,t,n){if(0===Object.keys(n).length)return null;const r=function(e=null){if(null!=e){const t=e.customElementRegistry;if(null===t)return null;if(void 0!==t)return la(t)}return la(globalThis.customElements)}(e);if(null===r)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await pa(e,t,n,r)}catch(e){throw new Error("Failed to lazy load components: "+e)}if(!t.observable)return null;const i=new MutationObserver(async()=>{try{await pa(e,t,n,r)}catch(e){console.error("Failed to lazy load components: "+e)}});return i.observe(e,{childList:!0,subtree:!0}),i}class ga extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),ga._instance)throw new Error(`${Yl.tagNames.autoloader} can only be instantiated once.`);ga._instance=this;const e=function(){const e={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(t=>{try{const n=JSON.parse(t.innerHTML);n.imports&&(e.imports=Object.assign(e.imports,n.imports))}catch(e){throw new Error("Failed to parse importmap JSON: "+e)}}),Object.keys(e.imports).length>0?e:null}();if(e){const{prefixMap:t,loadMap:n}=function(e){const t={},n={};for(const[r,i]of Object.entries(e.imports)){const e=Zl(r);null!==e&&(e.isNameSpaced?t[e.prefix]=e:n[e.tagName]=e)}return{prefixMap:t,loadMap:n}}(e);this._prefixMap=t,async function(e,t){const n=[];for(const[r,i]of Object.entries(e)){let s;try{s=ea(i.key,i.loaderKey,t)}catch(e){throw new Error("Loader redirection is not supported for eager loaded components: "+r)}n.push(oa(i,r,s))}await Promise.all(n)}(n,Yl.loaders).catch(e=>{console.error("Failed to eager load components:",e)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(e=>document.addEventListener("DOMContentLoaded",()=>e(),{once:!0})),this._observer=await ma(document,Yl,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,ga._instance===this&&(ga._instance=null)}}!function(e=customElements){e.get(Yl.tagNames.autoloader)||e.define(Yl.tagNames.autoloader,ga)}(void 0);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|