@wcstack/state 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.ja.md +47 -17
  2. package/README.md +47 -17
  3. package/dist/auto.min.js +1 -1
  4. package/dist/auto.min.js.map +1 -1
  5. package/dist/define.d.ts +11 -7
  6. package/dist/index.d.ts +15 -7
  7. package/dist/index.esm.js +1 -1
  8. package/dist/index.esm.js.map +1 -1
  9. package/dist/manifest.d.ts +14 -1
  10. package/dist/manifest.esm.js +91 -35
  11. package/dist/parser.esm.js +25 -0
  12. package/dist/split/chunks/binder.js +1 -1
  13. package/dist/split/chunks/binder.js.map +1 -1
  14. package/dist/split/chunks/checkDependency.js +1 -1
  15. package/dist/split/chunks/declarationAliases.js +2 -0
  16. package/dist/split/chunks/declarationAliases.js.map +1 -0
  17. package/dist/split/chunks/filterRegistry.js +1 -1
  18. package/dist/split/chunks/filterRegistry.js.map +1 -1
  19. package/dist/split/chunks/mount.js +1 -1
  20. package/dist/split/chunks/mount.js.map +1 -1
  21. package/dist/split/chunks/pathDiagnostics.js +1 -1
  22. package/dist/split/chunks/pathDiagnostics.js.map +1 -1
  23. package/dist/split/chunks/registerComponents.js +1 -1
  24. package/dist/split/chunks/registerComponents.js.map +1 -1
  25. package/dist/split/chunks/setAll.js +1 -1
  26. package/dist/split/chunks/version.js +1 -1
  27. package/dist/split/chunks/watchRuntime.js +1 -1
  28. package/dist/split/core.d.ts +11 -7
  29. package/dist/split/core.js +1 -1
  30. package/dist/split/core.js.map +1 -1
  31. package/dist/split/features/devtools.js +1 -1
  32. package/dist/split/features/devtools.js.map +1 -1
  33. package/dist/split/features/diagnostics.js +1 -1
  34. package/dist/split/features/formats.js +1 -1
  35. package/dist/split/features/formats.js.map +1 -1
  36. package/dist/split/features/recursion.js +1 -1
  37. package/dist/split/features/scopes.js +1 -1
  38. package/dist/split/features/scopes.js.map +1 -1
  39. package/dist/split/features/ssr.js +1 -1
  40. package/dist/split/features/ssr.js.map +1 -1
  41. package/dist/split/features/temporal.js +1 -1
  42. package/dist/split/features/temporal.js.map +1 -1
  43. package/dist/wcs-manifest.json +65 -25
  44. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- import{a as e,N as t,g as n,r}from"../chunks/getAllPropertyDescriptors.js";import{R as s,D as i,W as o,M as a,r as c,g as l,s as h,m as u}from"../chunks/pathDiagnostics.js";import{g as f,a as d,s as p,b as g,c as m,d as v,e as w}from"../chunks/setAll.js";import{K as $,k as y,l as x,L as P,M as _,N as A,J as b,G as k}from"../chunks/binder.js";import{r as I}from"../chunks/errorGuidance.js";import"../chunks/checkDependency.js";import"../chunks/filterRegistry.js";function L(e){return-1!==e.indexOf(s)}function R(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+i;if(!t.startsWith(n))return null;const r=t.slice(e.recursiveAnchor.length);if(L(r))return null;const s=r.slice(i.length).split(i);return s[0]===o||s.some(e=>0===e.length)?null:r}function j(e){return 0===e.length?e:i+S(e.slice(i.length))}function O(e,t,n){const r=i+e.repeat,s=t.length<=n.length?t:n,o=t.length<=n.length?n:t;if(!o.endsWith(s))return!1;const a=o.slice(0,o.length-s.length);if(0===a.length)return!0;if(a.length%r.length!==0)return!1;for(let e=0;e<a.length;e+=r.length)if(!a.startsWith(r,e))return!1;return!0}function W(e,t,n){for(let r=n.length;r>0;r=n.lastIndexOf(i,r-1))if(O(e,t,n.slice(0,r)))return!0;return!1}function S(e){const t=e.split(i);for(let e=0;e<t.length;e++)t[e]===o||Number.isNaN(Number(t[e]))||(t[e]=o);return t.join(i)}function N(e,t){const n=e.repeat.split(i),r=i+e.repeat;let s=t;for(;s.startsWith(r);)s=s.slice(r.length);if(0===s.length||s===i+e.repeatList+i+"length")return!0;for(let e=1;e<n.length;e++)if(s===i+n.slice(0,e).join(i))return!0;return!1}function B(e,t,n){n<0&&I(`Recursion depth must not be negative (got ${n}).`);let r=e.anchor;for(let t=0;t<n;t++)r+=i+e.repeat;const s=r+t;let c=0;for(const e of s.split(i))e===o&&c++;return c>a&&I(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${s}"), which needs ${c} wildcard levels — the limit is ${a}. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function E(e,t){return B(e,"",t)}function C(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const r=n.slice(e.anchor.length,n.length-t.length);if(0===r.length)return 0;const s=i+e.repeat;let o=0,a=0;for(;a<r.length;){if(!r.startsWith(s,a))return null;a+=s.length,o++}return o}function G(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const r=t.accessorFor(n.pathInfo.path);return null!==r?r.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const r=i+n.repeat;let s=0,o=n.anchor.length;for(;t.startsWith(r,o);)o+=r.length,s++;return o!==t.length&&46!==t.charCodeAt(o)?null:s}(t,n.pathInfo.path)}function D(e,t,n){const r=e.recursionRegistry,s=R(r.spec,n);null===s&&I(c(n,r.spec.recursiveAnchor));const i=G(t,r);return null===i&&I(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${r.spec.anchor}", or name a concrete depth (for example "${r.spec.anchor}${n.slice(r.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),r.concretePathAt(s,i)}function M(e,t,n,r,s){const o=r.spec,a=[],c=new Map,h=[],u=o.repeatList,d=o.anchorList,p=new Set,g=new Set,m=(e,t,n)=>{const r=e.wildcardParentPathInfos;if(t>=r.length)return void a.push(y(e,n));const s=v(r[t],n,null).rows;for(let n=0;n<s.length;n++)m(e,t+1,s[n])};function v(r,s,i){const a=y(r,s),l=x(n.stateElement,a),h=f(e,a,t,n),d=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const r=t;return p.has(r)&&I(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${o.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(r)&&I(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${o.anchor}" needs a tree: give each node its own "${u}" array.`),r})(r.path,h,i),g=P(s,_(l),h);return c.set(l,Array.isArray(h)?h:[]),null!==d&&null!==i&&i.add(d),{rows:g.newIndexes,tracked:d}}const w=(e,t,n)=>{const{rows:o,tracked:c}=v(t,n,g);if(0===o.length)return;const f=(e=>{const t=h[e];if(void 0!==t)return t;const n=r.concretePathAt(s,e),o=0===s.length?n:r.concretePathAt("",e),a={nodePath:o,concretePathInfo:l(n),childListPathInfo:l(o+i+u)};return h[e]=a,a})(e),d=c;p.add(d);const $=f.concretePathInfo.wildcardCount===e+1;for(let t=0;t<o.length;t++){const n=o[t];$?a.push(y(f.concretePathInfo,n)):m(f.concretePathInfo,e+1,n),w(e+1,f.childListPathInfo,n)}p.delete(d)};w(0,l(d),null);for(const[e,t]of c)$(e,t);return a}function z(e,t,n,r,s,i,o){d(n);const a=n.stateElement.recursionRegistry,l=R(a.spec,r);null===l&&I(c(r,a.spec.recursiveAnchor));const u=j(l);Array.isArray(s)||I(h(r,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&I(`[wcs/recursion-setall-form] $setAll("${r}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof i&&I(h(r,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===o?.spread&&I(h(r,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(e,t,n){N(e,n)&&I(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,r,u);const f=a.conflictingRecursiveGetter(u);null!==f&&I(`[wcs/recursion-readonly] "${r}" writes into the recursive getter "${f}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const g=M(e,t,n,a,l);let m=0;for(let r=0;r<g.length;r++)void 0!==i&&(p(e,g[r],i,t,n),m++);return m}const T={write(e,n){if(!0!==e.hasRecursion)return t;const r=e.recursionRegistry.recursiveGetterOwningPath(n.pathInfo);return null!==r&&I(`[wcs/recursion-readonly] "${n.pathInfo.path}" writes into the recursive getter "${r}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),t},get(e,n,r,s){if(!0!==e.stateElement.hasRecursion)return t;if("$getAll"===n)return(t,i)=>{if(L(t)){if(void 0!==i)return function(e,t,n,r,s){const i=n.stateElement.recursionRegistry,o=R(i.spec,r);null===o&&I(c(r,i.spec.recursiveAnchor)),Array.isArray(s)||I(`[wcs/recursion-getall-form] $getAll("${r}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&I(`[wcs/recursion-getall-form] $getAll("${r}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=M(e,t,n,i,o),l=[];for(let r=0;r<a.length;r++)l.push(f(e,a[r],t,n));return l}(s,r,e,t,i);t=D(e.stateElement,e,t)}return g(s,n,r,e)(t,i)};if("$setAll"===n)return(t,i,o,a)=>L(t)?z(s,r,e,t,i,o,a):m(s,n,r,e)(t,i,o,a);if(36!==n.charCodeAt(0)&&L(n)){const t=v(D(e.stateElement,e,n)),i=w(s,t,r,e);return f(s,y(t.pathInfo,i),r,e)}return t}};let F=!1;function q(e,t){"string"==typeof t&&0!==t.length||I(`[wcs/recursion-declaration-invalid] ${u} ${e} must be a non-empty string.`);const n=t.split(i);n.some(e=>0===e.length)&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not contain empty path segments.`),n.length<2&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must name a list element: a property path ending with "${i}${o}" (for example "nodes${i}${o}").`),n[n.length-1]!==o&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must end with "${i}${o}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let r=0;r<n.length-1;r++)n[r]===o&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must have exactly one "${o}", at the end. Wildcards in the middle are not supported in this version.`),n[r]===s&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not contain "${s}" — the declaration is what gives "${s}" its meaning.`),isNaN(Number(n[r]))||I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not contain an index segment ("${n[r]}") — the recursion is declared over the shape of the tree, not over one row.`)}const H=new WeakSet;function J(e){return"function"==typeof e.get&&H.has(e.get)}function K(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&J(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,r]of t){let s=null;for(let e=0;e<r.length;e++)n.has(r[e])?s??=r.slice(0,e):s?.push(r[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}!function(e,t,n){for(const r of n){const n=l(r),s=n.wildcardParentPathInfos,i=(t,r,o)=>{if(o===s.length)return void A(b(e,n,r),null);const a=0===o?0:s[o-1].segments.length+1;let c=t;for(const e of s[o].segments.slice(a))c=c?.[e];if(!Array.isArray(c))return;const l=k(c);if(null===l)return;const h=Math.min(l.length,c.length);for(let e=0;e<h;e++)i(c[e],l[e],o+1)};i(t,null,0)}}(e,t,n)}}const Q="[wcs/recursion-declaration-invalid]";class U{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(e,t){this.spec=e;const r=n(t);for(const[t,n]of Object.entries(r)){if(!L(t))continue;"function"==typeof n.set&&I(`${Q} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof n.get&&I(`${Q} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const r=R(e,t);null===r&&I(c(t,e.recursiveAnchor)),0===r.length&&I(`${Q} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${i}total"), not the node.`),N(e,j(r))&&I(`${Q} "${t}" names the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${e.recursiveAnchor}${i}total").`),this._definitions.set(t,{recursivePath:t,suffix:r,get:n.get})}this._assertNoColliding(),this._assertNoConcreteCollision(r)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(L(t)||J(n))continue;const e=this._matchExpansion(t);null!==e&&I(`${Q} "${t}" is already defined on the state, so the recursive getter "${e}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const e=Array.from(this._definitions.values());for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)O(this.spec,e[t].suffix,e[n].suffix)&&I(`${Q} "${e[t].recursivePath}" and "${e[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(e){for(const t of this._definitions.values())if(W(this.spec,t.suffix,e))return t.recursivePath;return null}recursiveGetterOwningPath(e){const t=this._ownerByPathInfo.get(e);if(void 0!==t)return t;const n=this.recursiveGetterOwning(e.path);return this._ownerByPathInfo.set(e,n),n}recursiveGetterOwning(e){const t=this._accessors.get(e);if(void 0!==t)return t.recursivePath;const n=S(e),r=this._ownerByPath.get(n);if(void 0!==r)return r;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let e=n.lastIndexOf(i);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(i,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==C(this.spec,t.suffix,e))return t.recursivePath;return null}materializeForPathInfo(e,t){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(t);if(void 0!==n)return n;const r=this.materializeFor(e,t.path);return this._accessorByPathInfo.set(t,r),r}materializeFor(e,t){const n=this._accessors.get(t);if(void 0!==n)return n;if(!t.startsWith(this.spec.anchor))return null;let r=null,s=0;for(const e of this._definitions.values()){const n=C(this.spec,e.suffix,t);null!==n&&(null!==r&&I(`"${t}" matches both "${r.recursivePath}" and "${e.recursivePath}".`),r=e,s=n)}return null===r?null:this._define(e,r,s,t)}_define(e,t,n,r){const s=e.findStateDescriptor(r);void 0===s||J(s)||I(`"${r}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const i=Object.freeze({recursivePath:t.recursivePath,depth:n}),o=t.get,a=function(){return o.call(this)};var c;return c=a,H.add(c),e.defineTreeAccessor(r,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(e,n),this._accessors.set(r,i),i}_registerListPaths(e,t){for(const n of function(e,t){const n=[];n.push(e.anchorList);for(let r=0;r<t;r++)n.push(E(e,r)+i+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return K(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let r=n[t];return void 0===r&&(r=B(this.spec,e,t),n[t]=r),r}accessorFor(e){return this._accessors.get(e)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const V="recursionSpec",X="recursionRegistry",Y={order:5,validateEarly(e,t,n){const r=function(e){const t=e[u];if(void 0===t)return null;"object"==typeof t&&null!==t||I(`[wcs/recursion-declaration-invalid] ${u} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&I(`[wcs/recursion-declaration-invalid] ${u} must declare exactly one anchor; it is empty.`),n.length>1&&I(`[wcs/recursion-declaration-invalid] ${u} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[r,a]=n[0];q("anchor",r),"string"!=typeof a&&I(`[wcs/recursion-declaration-invalid] ${u} entry "${r}" must map to the repeating sub-path as a string (for example "children${i}${o}").`),q("repeating sub-path",a);const c=r.slice(0,r.lastIndexOf(i)),l=a.slice(0,a.lastIndexOf(i)),h=c+i+s;return Object.freeze({anchor:r,repeat:a,recursiveAnchor:h,anchorList:c,repeatList:l})}(t);n.set(V,r),n.set(X,null===r?null:new U(r,t))},preCommit(e,t,n){const r=e.recursionRegistry;if(null!==r)for(const t of r.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(X)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",u)},apply(e,t,n){const r=n.get(V)??null;null!==r&&e.addListPath(r.anchorList)}};let Z=!1;function ee(){Z||(Z=!0,F||(F=!0,e("recursion",T)),r("recursion",Y))}const te={name:"recursion",install(){ee()}};export{te as default,te as recursion};
1
+ import{a as e,N as t,g as n,r}from"../chunks/getAllPropertyDescriptors.js";import{R as s,D as i,W as o,M as a,s as c,g as l,t as h,n as u}from"../chunks/pathDiagnostics.js";import{g as f,a as d,s as p,b as g,c as m,d as v,e as w}from"../chunks/setAll.js";import{L as $,k as y,l as x,M as P,N as _,O as A,K as b,H as k}from"../chunks/binder.js";import{r as I}from"../chunks/errorGuidance.js";import"../chunks/checkDependency.js";import"../chunks/filterRegistry.js";function L(e){return-1!==e.indexOf(s)}function R(e,t){if(t===e.recursiveAnchor)return"";const n=e.recursiveAnchor+i;if(!t.startsWith(n))return null;const r=t.slice(e.recursiveAnchor.length);if(L(r))return null;const s=r.slice(i.length).split(i);return s[0]===o||s.some(e=>0===e.length)?null:r}function j(e){return 0===e.length?e:i+S(e.slice(i.length))}function O(e,t,n){const r=i+e.repeat,s=t.length<=n.length?t:n,o=t.length<=n.length?n:t;if(!o.endsWith(s))return!1;const a=o.slice(0,o.length-s.length);if(0===a.length)return!0;if(a.length%r.length!==0)return!1;for(let e=0;e<a.length;e+=r.length)if(!a.startsWith(r,e))return!1;return!0}function W(e,t,n){for(let r=n.length;r>0;r=n.lastIndexOf(i,r-1))if(O(e,t,n.slice(0,r)))return!0;return!1}function S(e){const t=e.split(i);for(let e=0;e<t.length;e++)t[e]===o||Number.isNaN(Number(t[e]))||(t[e]=o);return t.join(i)}function N(e,t){const n=e.repeat.split(i),r=i+e.repeat;let s=t;for(;s.startsWith(r);)s=s.slice(r.length);if(0===s.length||s===i+e.repeatList+i+"length")return!0;for(let e=1;e<n.length;e++)if(s===i+n.slice(0,e).join(i))return!0;return!1}function B(e,t,n){n<0&&I(`Recursion depth must not be negative (got ${n}).`);let r=e.anchor;for(let t=0;t<n;t++)r+=i+e.repeat;const s=r+t;let c=0;for(const e of s.split(i))e===o&&c++;return c>a&&I(`[wcs/recursion-depth-exceeded] Recursion on "${e.anchor}" reached depth ${n} ("${s}"), which needs ${c} wildcard levels — the limit is ${a}. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function E(e,t){return B(e,"",t)}function C(e,t,n){if(!n.startsWith(e.anchor))return null;if(t.length>0&&!n.endsWith(t))return null;if(n.length<e.anchor.length+t.length)return null;const r=n.slice(e.anchor.length,n.length-t.length);if(0===r.length)return 0;const s=i+e.repeat;let o=0,a=0;for(;a<r.length;){if(!r.startsWith(s,a))return null;a+=s.length,o++}return o}function D(e,t){if(0===e.addressStackLength)return null;const n=e.lastAddressStack;if(null===n)return null;const r=t.accessorFor(n.pathInfo.path);return null!==r?r.depth:function(e,t){const n=e.spec;if(!t.startsWith(n.anchor))return null;const r=i+n.repeat;let s=0,o=n.anchor.length;for(;t.startsWith(r,o);)o+=r.length,s++;return o!==t.length&&46!==t.charCodeAt(o)?null:s}(t,n.pathInfo.path)}function G(e,t,n){const r=e.recursionRegistry,s=R(r.spec,n);null===s&&I(c(n,r.spec.recursiveAnchor));const i=D(t,r);return null===i&&I(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${r.spec.anchor}", or name a concrete depth (for example "${r.spec.anchor}${n.slice(r.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),r.concretePathAt(s,i)}function M(e,t,n,r,s){const o=r.spec,a=[],c=new Map,h=[],u=o.repeatList,d=o.anchorList,p=new Set,g=new Set,m=(e,t,n)=>{const r=e.wildcardParentPathInfos;if(t>=r.length)return void a.push(y(e,n));const s=v(r[t],n,null).rows;for(let n=0;n<s.length;n++)m(e,t+1,s[n])};function v(r,s,i){const a=y(r,s),l=x(n.stateElement,a),h=f(e,a,t,n),d=null===i?null:((e,t,n)=>{if(!Array.isArray(t)||0===t.length)return null;const r=t;return p.has(r)&&I(`[wcs/recursion-cycle] "${e}" is reachable from itself: the recursion on "${o.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(r)&&I(`[wcs/recursion-shared-list] "${e}" is the same array instance as a list reached from another node. The recursion on "${o.anchor}" needs a tree: give each node its own "${u}" array.`),r})(r.path,h,i),g=P(s,_(l),h);return c.set(l,Array.isArray(h)?h:[]),null!==d&&null!==i&&i.add(d),{rows:g.newIndexes,tracked:d}}const w=(e,t,n)=>{const{rows:o,tracked:c}=v(t,n,g);if(0===o.length)return;const f=(e=>{const t=h[e];if(void 0!==t)return t;const n=r.concretePathAt(s,e),o=0===s.length?n:r.concretePathAt("",e),a={nodePath:o,concretePathInfo:l(n),childListPathInfo:l(o+i+u)};return h[e]=a,a})(e),d=c;p.add(d);const $=f.concretePathInfo.wildcardCount===e+1;for(let t=0;t<o.length;t++){const n=o[t];$?a.push(y(f.concretePathInfo,n)):m(f.concretePathInfo,e+1,n),w(e+1,f.childListPathInfo,n)}p.delete(d)};w(0,l(d),null);for(const[e,t]of c)$(e,t);return a}function z(e,t,n,r,s,i,o){d(n);const a=n.stateElement.recursionRegistry,l=R(a.spec,r);null===l&&I(c(r,a.spec.recursiveAnchor));const u=j(l);Array.isArray(s)||I(h(r,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&I(`[wcs/recursion-setall-form] $setAll("${r}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof i&&I(h(r,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===o?.spread&&I(h(r,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(e,t,n){N(e,n)&&I(`[wcs/recursion-structural-write] "${t}" writes the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,r,u);const f=a.conflictingRecursiveGetter(u);null!==f&&I(`[wcs/recursion-readonly] "${r}" writes into the recursive getter "${f}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const g=M(e,t,n,a,l);let m=0;for(let r=0;r<g.length;r++)void 0!==i&&(p(e,g[r],i,t,n),m++);return m}const T={write(e,n){if(!0!==e.hasRecursion)return t;const r=e.recursionRegistry.recursiveGetterOwningPath(n.pathInfo);return null!==r&&I(`[wcs/recursion-readonly] "${n.pathInfo.path}" writes into the recursive getter "${r}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),t},get(e,n,r,s){if(!0!==e.stateElement.hasRecursion)return t;if("$getAll"===n)return(t,i)=>{if(L(t)){if(void 0!==i)return function(e,t,n,r,s){const i=n.stateElement.recursionRegistry,o=R(i.spec,r);null===o&&I(c(r,i.spec.recursiveAnchor)),Array.isArray(s)||I(`[wcs/recursion-getall-form] $getAll("${r}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&I(`[wcs/recursion-getall-form] $getAll("${r}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=M(e,t,n,i,o),l=[];for(let r=0;r<a.length;r++)l.push(f(e,a[r],t,n));return l}(s,r,e,t,i);t=G(e.stateElement,e,t)}return g(s,n,r,e)(t,i)};if("$setAll"===n)return(t,i,o,a)=>L(t)?z(s,r,e,t,i,o,a):m(s,n,r,e)(t,i,o,a);if(36!==n.charCodeAt(0)&&L(n)){const t=v(G(e.stateElement,e,n)),i=w(s,t,r,e);return f(s,y(t.pathInfo,i),r,e)}return t}};let F=!1;function H(e,t){"string"==typeof t&&0!==t.length||I(`[wcs/recursion-declaration-invalid] ${u} ${e} must be a non-empty string.`);const n=t.split(i);n.some(e=>0===e.length)&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not contain empty path segments.`),n.length<2&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must name a list element: a property path ending with "${i}${o}" (for example "nodes${i}${o}").`),n[n.length-1]!==o&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must end with "${i}${o}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not start with "$" — that namespace is reserved.`),-1!==t.indexOf("#")&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not contain "#" — that segment is reserved for mounts.`);for(let r=0;r<n.length-1;r++)n[r]===o&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must have exactly one "${o}", at the end. Wildcards in the middle are not supported in this version.`),n[r]===s&&I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not contain "${s}" — the declaration is what gives "${s}" its meaning.`),isNaN(Number(n[r]))||I(`[wcs/recursion-declaration-invalid] ${u} ${e} "${t}" must not contain an index segment ("${n[r]}") — the recursion is declared over the shape of the tree, not over one row.`)}const q=new WeakSet;function K(e){return"function"==typeof e.get&&q.has(e.get)}function J(e,t,n){if(0!==n.size){for(const e of n){const n=Object.getOwnPropertyDescriptor(t,e);void 0!==n&&K(n)&&delete t[e]}for(const t of[e.staticDependency,e.dynamicDependency]){for(const e of n)t.delete(e);for(const[e,r]of t){let s=null;for(let e=0;e<r.length;e++)n.has(r[e])?s??=r.slice(0,e):s?.push(r[e]);null!==s&&(0===s.length?t.delete(e):t.set(e,s))}}!function(e,t,n){for(const r of n){const n=l(r),s=n.wildcardParentPathInfos,i=(t,r,o)=>{if(o===s.length)return void A(b(e,n,r),null);const a=0===o?0:s[o-1].segments.length+1;let c=t;for(const e of s[o].segments.slice(a))c=c?.[e];if(!Array.isArray(c))return;const l=k(c);if(null===l)return;const h=Math.min(l.length,c.length);for(let e=0;e<h;e++)i(c[e],l[e],o+1)};i(t,null,0)}}(e,t,n)}}const Q="[wcs/recursion-declaration-invalid]";class U{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(e,t){this.spec=e;const r=n(t);for(const[t,n]of Object.entries(r)){if(!L(t))continue;"function"==typeof n.set&&I(`${Q} Recursive setters are not supported in this version: "${t}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof n.get&&I(`${Q} "${t}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const r=R(e,t);null===r&&I(c(t,e.recursiveAnchor)),0===r.length&&I(`${Q} "${t}" names the recursive node itself. "**" names a computed path under a node (for example "${e.recursiveAnchor}${i}total"), not the node.`),N(e,j(r))&&I(`${Q} "${t}" names the recursion structure itself (a node, its "${e.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${e.recursiveAnchor}${i}total").`),this._definitions.set(t,{recursivePath:t,suffix:r,get:n.get})}this._assertNoColliding(),this._assertNoConcreteCollision(r)}_assertNoConcreteCollision(e){for(const[t,n]of Object.entries(e)){if(L(t)||K(n))continue;const e=this._matchExpansion(t);null!==e&&I(`${Q} "${t}" is already defined on the state, so the recursive getter "${e}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const e=Array.from(this._definitions.values());for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++)O(this.spec,e[t].suffix,e[n].suffix)&&I(`${Q} "${e[t].recursivePath}" and "${e[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(e){for(const t of this._definitions.values())if(W(this.spec,t.suffix,e))return t.recursivePath;return null}recursiveGetterOwningPath(e){const t=this._ownerByPathInfo.get(e);if(void 0!==t)return t;const n=this.recursiveGetterOwning(e.path);return this._ownerByPathInfo.set(e,n),n}recursiveGetterOwning(e){const t=this._accessors.get(e);if(void 0!==t)return t.recursivePath;const n=S(e),r=this._ownerByPath.get(n);if(void 0!==r)return r;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let e=n.lastIndexOf(i);null===s&&e>this.spec.anchor.length;e=n.lastIndexOf(i,e-1))s=this._matchExpansion(n.slice(0,e))}return this._ownerByPath.set(n,s),s}_matchExpansion(e){for(const t of this._definitions.values())if(null!==C(this.spec,t.suffix,e))return t.recursivePath;return null}materializeForPathInfo(e,t){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(t);if(void 0!==n)return n;const r=this.materializeFor(e,t.path);return this._accessorByPathInfo.set(t,r),r}materializeFor(e,t){const n=this._accessors.get(t);if(void 0!==n)return n;if(!t.startsWith(this.spec.anchor))return null;let r=null,s=0;for(const e of this._definitions.values()){const n=C(this.spec,e.suffix,t);null!==n&&(null!==r&&I(`"${t}" matches both "${r.recursivePath}" and "${e.recursivePath}".`),r=e,s=n)}return null===r?null:this._define(e,r,s,t)}_define(e,t,n,r){const s=e.findStateDescriptor(r);void 0===s||K(s)||I(`"${r}" is already defined on the state, so the recursive getter "${t.recursivePath}" cannot expand to it. Rename one of them.`);const i=Object.freeze({recursivePath:t.recursivePath,depth:n}),o=t.get,a=function(){return o.call(this)};var c;return c=a,q.add(c),e.defineTreeAccessor(r,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(e,n),this._accessors.set(r,i),i}_registerListPaths(e,t){for(const n of function(e,t){const n=[];n.push(e.anchorList);for(let r=0;r<t;r++)n.push(E(e,r)+i+e.repeatList);return n}(this.spec,t))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),e.addListPath(n))}forgetGenerated(e,t){const n=new Set(this._accessors.keys());return J(e,t,n),n}concretePathAt(e,t){let n=this._concreteBySuffix.get(e);void 0===n&&(n=[],this._concreteBySuffix.set(e,n));let r=n[t];return void 0===r&&(r=B(this.spec,e,t),n[t]=r),r}accessorFor(e){return this._accessors.get(e)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const V="recursionSpec",X="recursionRegistry",Y={order:5,validateEarly(e,t,n){const r=function(e){const t=e[u];if(void 0===t)return null;"object"==typeof t&&null!==t||I(`[wcs/recursion-declaration-invalid] ${u} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(t);0===n.length&&I(`[wcs/recursion-declaration-invalid] ${u} must declare exactly one anchor; it is empty.`),n.length>1&&I(`[wcs/recursion-declaration-invalid] ${u} declares ${n.length} anchors (${n.map(([e])=>`"${e}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[r,a]=n[0];H("anchor",r),"string"!=typeof a&&I(`[wcs/recursion-declaration-invalid] ${u} entry "${r}" must map to the repeating sub-path as a string (for example "children${i}${o}").`),H("repeating sub-path",a);const c=r.slice(0,r.lastIndexOf(i)),l=a.slice(0,a.lastIndexOf(i)),h=c+i+s;return Object.freeze({anchor:r,repeat:a,recursiveAnchor:h,anchorList:c,repeatList:l})}(t);n.set(V,r),n.set(X,null===r?null:new U(r,t))},preCommit(e,t,n){const r=e.recursionRegistry;if(null!==r)for(const t of r.forgetGenerated(e,n.get("previousState")))e.addGeneratedPath?.(t);const s=n.get(X)??null;e.setRecursionRegistry?.(s),null!==s&&e.attachAddressHooks?.("recursion",u)},apply(e,t,n){const r=n.get(V)??null;null!==r&&e.addListPath(r.anchorList)}};let Z=!1;function ee(){Z||(Z=!0,F||(F=!0,e("recursion",T)),r("recursion",Y))}const te={name:"recursion",install(){ee()}};export{te as default,te as recursion};
2
2
  //# sourceMappingURL=recursion.js.map
@@ -1,2 +1,2 @@
1
- import{r as t,l as e,a as n,C as o}from"../chunks/lifecycleHooks.js";import{f as r,h as s,a,i,D as c,g as l,j as u,W as d,k as f,l as h,m,R as p,n as g}from"../chunks/pathDiagnostics.js";import{r as y,d as b}from"../chunks/errorGuidance.js";import{a as w,g as $,N as v}from"../chunks/getAllPropertyDescriptors.js";import{c as k}from"../chunks/filterRegistry.js";import{h as S,u as P,i as C,j as x,k as A,m as I,n as N,o as R,p as j,q as M,t as O,v as E,w as D,x as z,y as W,z as L,A as B,B as V,C as _,D as F}from"../chunks/binder.js";import{p as q}from"../chunks/diagnosticsHooks.js";import{t as U,a as T,c as H,s as K,g as G,b as X,d as J,r as Q,e as Y,f as Z,h as tt,i as et,j as nt,k as ot,l as rt,w as st}from"../chunks/mount.js";import{c as at}from"../chunks/checkDependency.js";import{y as it,z as ct,A as lt}from"../chunks/watchRuntime.js";const ut={written:function(t,e,n){const o=t.bindableEventMap,r=o[e.path],s="string"==typeof r,a=s?r:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof a)return;const i=t.rootNode;i instanceof ShadowRoot&&i.host.dispatchEvent(new CustomEvent(a,{detail:s&&void 0!==n?n.value:void 0,bubbles:!0}))}};let dt=!1;function ft(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function ht(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function mt(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function pt(t){return t.startsWith("$")}function gt(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function yt(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||y(`${e} must be an array of strings.`);const o=[],r=new Set;for(const t of n)"string"==typeof t&&0!==t.length||y(`${e} entries must be non-empty strings.`),t.startsWith("$")&&y(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),r.has(t)&&y(`${e} entry "${t}" is duplicated.`),r.add(t),o.push(t);return o}function bt(t){const e=yt(t,r)??[],n=yt(t,s)??[],o=$(t),i=function(t){const e=t[a];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];for(const t of e){const e=o[t];if(void 0===e){if(i.has(t)){c.push(t);continue}y(`${r} entry "${t}" is not declared on the state.${b(t,gt(o,"value"))}`)}"function"==typeof e.value&&y(`${r} entry "${t}" is a method. Declare it in ${s} instead.`)}for(const t of n){const e=o[t];void 0===e&&y(`${s} entry "${t}" is not declared on the state.${b(t,gt(o,"method"))}`),"function"!=typeof e.value&&y(`${s} entry "${t}" is not a method. Declare it in ${r} instead.`)}return{bindables:e,commands:n,streamBackedBindables:c}}function wt(t,e,n){const o=t.tagName.toLowerCase();o.includes("-")||y(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const s=S(t);null!==s&&"function"==typeof s.define||y(`DCC: CustomElementRegistry is unavailable for "${o}".`),s.get(o)&&y(`DCC: "${o}" is already registered. A custom element name can only be defined once.`);const a=document.createElement("template"),c=a.content.ownerDocument;for(const t of Array.from(e.childNodes))a.content.appendChild(c.importNode(t,!0));const l=e.mode,{bindables:u,commands:d,streamBackedBindables:f}=bt(n),h=u.length>0||d.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const r=n.map(t=>({name:t,async:!0}));return{...o,commands:r}}(o,u,d):null,m=u.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(o,u):{},p=k.tagNames.state,g=class extends HTMLElement{static template=a;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=m;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(i))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const t=S(this._shadow);return null!==t&&P(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(g.bindableEventMap).length>0){const e=t.querySelector(p);e?(dt||(dt=!0,w("dcc",ut)),e.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${r} but its template has no <${k.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},b=$(n);for(const[t,e]of Object.entries(b)){if(pt(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=mt(t,o)}else n.get=ft(t),n.set=ht(t);Object.defineProperty(g.prototype,t,n)}for(const t of f)Object.defineProperty(g.prototype,t,{configurable:!0,enumerable:!0,get:ft(t),set:ht(t)});s.define(o,g)}async function $t(t,o,r){const s=t;try{s.hasAttribute("bind-component")&&y(`"bind-component" cannot be used inside a [${i}] host. DCC state comes from the template, not from a component property.`);const a=await async function(t,o){try{if(t.hasAttribute("src")){const n=t.getAttribute("src");if(n.endsWith(".js"))return await e(n);y(`DCC: Unsupported src type: ${n}`)}const r=t.querySelector('script[type="module"]');if(r)return await n(r,o.tagName.toLowerCase());y(`DCC: No state source found for "${o.tagName.toLowerCase()}".`)}catch(t){y(`DCC: Failed to load state: ${t}`)}}(s,o);wt(o,r,a),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}const vt={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(i)?$t(t,e.host,e):null}};let kt=!1;const St=new WeakMap;function Pt(t,e,n){let o=St.get(t);void 0===o&&(o=new Map,St.set(t,o));const r=o.get(e);null!=r&&y(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function Ct(t,e){if(null===t)return!1;const n=St.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+c)||t.startsWith(e+c))return!0;return!1}const xt=new WeakMap;function At(t,e){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{e.$postUpdate(t+c+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...r)=>e[n](t+c+o,...r)}return e[o]}return e[t+c+o]}},set:(n,o,r)=>("string"!=typeof o||(e[t+c+o]=r),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const It=new WeakMap,Nt=[];const Rt=new WeakMap,jt=new WeakSet;function Mt(t){console.error(`[@wcstack/state] volume "${t.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),t.onGrafted(null)}let Ot=null;const Et=new WeakMap,Dt=new Set;function zt(t,e,n,o){let r=Et.get(t);if(void 0===r){if(!o)return null;r=new Map,Et.set(t,r)}let s=r.get(e);if(void 0===s){if(!o)return null;s=new Map,r.set(e,s)}let a=s.get(n);if(void 0===a){if(!o)return null;a={holders:new Set,byListIndex:new WeakMap,noIndex:null},s.set(n,a)}return a}function Wt(t,e){if(!t.component.isConnected)return!1;const n=C(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function Lt(t,e,n,o){const r=zt(t,e,n,!1);if(null===r)return null;const s=null===o?r.noIndex:r.byListIndex.get(o)??null;if(null!==s){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&Wt(n,e)?n:null}(s,o);if(null!==t)return{record:t,entry:s.entry}}let a=null,i=null;for(const t of r.holders){const s=t.ref.deref();void 0!==s?Wt(s,o)&&(null!==i&&y(`[wcs/mount-export-ambiguous] "${e}${c}${n}" is exported by two mounted components on the same instance: <${i.component.tagName.toLowerCase()}> and <${s.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),a=t,i=s):r.holders.delete(t)}return null===a||null===i?null:(null===o?r.noIndex=a:r.byListIndex.set(o,a),{record:i,entry:a.entry})}function Bt(t){const e=t.parentStateElement,n=C(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[x](n,()=>{t.$postUpdate(o.exportedPath)})})}const Vt=new WeakMap;class _t{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,r,s){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=r,this.handler=s}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return A(l(this.markerParentPath+c+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(U(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,r,...s)=>{const a=s.length>0?T(t,e):U(t,e),i=H(t,e,a,r??[],n);return o.$resolve(a,i,...s)};const r=e;return(e,s,...a)=>{const i="$setAll"===r?T(t,e):U(t,e),c=H(t,e,i,s,n);return o[r](i,c,...a)}}return this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return at(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[U(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const r=this.accessorNameFor(e);if(void 0!==r){this.record.setterKeys.has(r)||y(`Cannot write to "${r}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,r,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(t,e)?(t[e]=n,!0):(this.receiver[T(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return U(this.record,e),!0}catch{return!1}}}function Ft(t,e,n,o){const r=e.pathInfo.path,s=r===t.markerBasePath,a=s?function(t,e){let n=Vt.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Vt.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(a,new _t(t,r,e.listIndex,s,n,o))}function qt(t){const e=t.parentStateElement,n=(e,n)=>{const o=C(t.component);let r;return e[x](o,()=>{r=n()}),r};return new Proxy({},{get(o,r){if("string"!=typeof r||"then"===r)return;if("$getAll"===r||"$setAll"===r||"$resolve"===r||"$postUpdate"===r)return function(t,e,n){const o=t.parentStateElement,r=(t,e)=>{let r;return o.createState(t,t=>{r=n(t,()=>e(t))}),r};return"$postUpdate"===e?e=>r("readonly",n=>n.$postUpdate(U(t,e))):(n,o,...s)=>{const a="$setAll"===e||"$resolve"===e&&s.length>0,i=a?T(t,n):U(t,n),c=C(t.component)?.listIndex.indexes??[],l=H(t,n,i,"$resolve"===e?o??[]:o,c);return r(a?"writable":"readonly",t=>t[e](i,l,...s))}}(t,r,n);let s;return e.createState("readonly",e=>{s=n(e,()=>e["$"===r[0]?r:U(t,r)])}),s},set:(o,r,s)=>("string"!=typeof r||e.createState("writable",e=>{n(e,()=>{e["$"===r[0]?r:T(t,r)]=s})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return U(t,n),!0}catch{return!1}}})}function Ut(t,e){const n=J(e);null!==n&&n.stateProp!==t.stateProp&&y(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&I(e).dispose(),Q(e,t),e instanceof ShadowRoot&&j(e,t.parentStateElement),function(t,e){const n=(e,n)=>Y(t,e,n);O(e);const o=C(t.component),r=e instanceof ShadowRoot?e:e.getRootNode();E(r,e,void 0,n),D(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=U(t,n)}catch{continue}const o=e.indexOf(c+t.marker);if(-1===o)continue;const r=e.slice(0,o+1+t.marker.length),s=e.slice(r.length+1),a=e.slice(0,o)+c+s,i=l(a);if(i.wildcardCount!==t.delta)continue;const u={markerTerminalPath:r,suffix:s,markerPath:e,exportedPath:a};t.exports.set(a,u),zt(t.parentStateElement,i.parentPath,i.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:u}),t.parentStateElement.addDynamicDependency(e,a),q?.markExported(t.parentStateElement,a)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=C(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const r=`${n}|${o.exportedPath}`;if(Dt.has(r))continue;const s=l(o.exportedPath);let a;t.parentStateElement.createState("readonly",t=>{t[x](e,()=>{a=t[s.parentPath]})}),null!=a&&s.lastSegment in Object(a)&&(Dt.add(r),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(t),Bt(t),M(e,Promise.resolve())}function Tt(t,e){const n=I(e),o=C(t.component);n.forEachActiveBindingNode(t=>N(t,o));const r=n.rebindAddresses();R(r),Bt(t)}function Ht(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const Kt={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const r=tt(t,e.pathInfo.path);if(null!==r)return Ft(r,e,n,o)}return v},readMissing(t,e,n,o,r){if(null===n){if(Ct(t.rootNode??null,e.pathInfo.path))return;return v}if(!0===t.hasMounts){const n=Lt(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,r){const s=Ft(t,A(l(e.markerTerminalPath),n),o,r);return Reflect.get(s,e.suffix)}(n.record,n.entry,e.listIndex,o,r)}return v},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=xt.get(t);if(void 0===n||0===n.size)return null;const o=e+c;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&y(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return v},writeMissing(t,e,n,o,r,s,a){if(!0===t.hasMounts){const n=Lt(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,r,s){const a=Ft(t,A(l(e.markerTerminalPath),n),r,s);return Reflect.set(a,e.suffix,o)}(n.record,n.entry,e.listIndex,r,s,a)}return v},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=tt(n,o);if(null!==t)return et(t,o)}return 0},handlerScope(t,e,n,o,r){if(!0!==t.hasMounts)return r;const s=Z(e,n);if(null===s)return r;const a=s.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==a?r-a:0},updated(t,e,n){const o=function(t){return It.get(t)??Nt}(t);for(const r of o){const o=r.mountPath+c,s=new Set,a={};for(const n of e){if(n.absolutePathInfo.stateElement!==t)continue;const e=n.absolutePathInfo.pathInfo.path;if(e!==r.mountPath&&!e.startsWith(o))continue;if(-1!==e.indexOf("#"))continue;const i=e===r.mountPath?"":e.slice(o.length);if(""===i)continue;s.add(i);const c=n.absolutePathInfo.pathInfo.wildcardCount;if(c>0&&null!==n.listIndex){const t=z(n.listIndex,c);(a[i]??=[]).push(t)}}if(s.size>0)try{r.callback.call(At(r.mountPath,n),Array.from(s),a)}catch(t){console.error(`[@wcstack/state] volume "${r.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>Ct(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(K(e))for(const n of G(e)){if(!Ht(n.component,t))continue;const e=X(n);null!==e&&Tt(n,e)}}(e,t)}};let Gt=!1;const Xt=new WeakMap;function Jt(t){let e=Xt.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},Xt.set(t,e)),e}function Qt(t,e){null!==e.slotRootNode&&(!function(t,e,n){const o=St.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function Yt(t,e,n){if(e.slotRootNode===n)return!0;const o=e.mountPath;try{Pt(n,o,t)}catch{return console.error(`[@wcstack/state] <${k.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return W(n)?.markHasVolume?.(),e.slotRootNode=n,!0}async function Zt(t,e){const n=t,o=t.connectedRootNode,r=n.getAttribute("mount");try{!function(t){0===t.length&&y('"mount" requires a non-empty tree path.');const e=l(t);for(const n of e.segments)0===n.length&&y(`"mount" path "${t}" has an empty segment.`),n===d&&y(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&y(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),n.hasAttribute("bind-component")&&y('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${k.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),Pt(o,r,t),W(o)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=o}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===W(o)&&function(t,e){const n=()=>{if(null!==W(t))return;const n=t.querySelectorAll(k.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${k.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${k.tagNames.state}> to this root node (an empty <${k.tagNames.state}></${k.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=t.ownerDocument??t;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const s=n=>{e.graftInfo=n,t.markInitialized(),null===n&&Qt(t,e),t.settleInitialization()};let a;try{a=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void s(null)}const i=t.connectedRootNode??null;null!==i&&Yt(t,e,i)?function(t,e,n,o,r,s){const a={mountPath:n,volumeState:o,onGrafted:r,acquireSlot:s};if(null!==e)return void xe(e,a);Ie(),function(t,e){if(jt.has(t))return void Mt(e);let n=Rt.get(t);void 0===n&&(n=[],Rt.set(t,n)),n.push(e)}(t,a)}(i,W(i),r,a,s,()=>Yt(t,e,i)):s(null)}const te={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=Jt(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{Pt(n,e.mountPath,t),W(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,o}return Zt(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=Jt(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&W(n)===e.graftInfo.rootStateElement&&Se(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==Xt.get(t)?.initializing)return;const e=t.getAttribute("mount");y(`Cannot replace the state of <${k.tagNames.state} mount="${e}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){jt.add(t);const e=Rt.get(t);if(void 0!==e){Rt.delete(t);for(const t of e)Mt(t)}}(e)},initializeFailureCleared(t,e){!function(t){jt.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=Jt(t);return null!==e.graftInfo&&Se(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,Qt(t,e)),t.clearConnectedRootNode(),!0}};let ee=!1;const ne=new WeakMap;function oe(t,e){let n=ne.get(t);n||(n=new Set,ne.set(t,n)),n.add(e)}const re=new WeakMap;const se=new WeakMap,ae=new WeakMap;const ie=new WeakMap;const ce={isComplete:function(t,e){return!0===ne.get(t)?.has(e)},isDeclared:function(t,e){return!0===re.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=se.get(t);o||(o=new Map,se.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=ae.get(t);o||(o=new Map,ae.set(t,o));let r=o.get(e);r||(r=new Set,o.set(e,r)),r.add(n)},rememberOverwrittenValue:function(t,e,n,o){let r=ie.get(t);r||(r=new Map,ie.set(t,r));let s=r.get(e);s||(s=new Map,r.set(e,s)),s.has(n)||s.set(n,o)}};function le(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}const ue=new WeakMap;class de{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=ue.get(t);return n?n.get(e)??null:null}(t,e)??y("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const fe=t=>()=>t;function he(t,e,n,o){!function(t,e,n){let o=ue.get(t);o||(o=new Map,ue.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(le(o));const r=function(t,e){const n=new de(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:fe(r),enumerable:!0,configurable:!0}),oe(e,n),me(e,n)}function me(t,e){if(u in t){const n=t[u];"function"==typeof n?n.call(t,e).catch(t=>{y(`Error in ${u}: ${t instanceof Error?t.message:String(t)}`)}):y(`${u} is not a function.`)}}const pe=new Set;function ge(t,e){pe.has(t)||(pe.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function ye(t){const e=t.rootEntry,n=C(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[x](n,()=>{o=t[e.outerPathInfo.path]})}),o}const be=new WeakMap;function we(t,e){t.landInitialization(),y(e)}async function $e(t,e){const n=t;if(n.hasAttribute("bind-component")){const o=n.parentNode,r=o instanceof ShadowRoot?o.host:o instanceof Element?o:null,s=r?V(r):null;null!==r&&null!==s||y(`"bind-component" requires <${k.tagNames.state}> to be a direct child of a custom element.`),o instanceof ShadowRoot||r.hasAttribute(k.bindAttributeName)||we(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${s}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const a=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&a.push('<script type="module">'),a.length>0&&y(`"bind-component" cannot be combined with ${a.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const i=n.getAttribute("bind-component");!function(t,e){let n=re.get(t);n||(n=new Set,re.set(t,n)),n.add(e)}(r,i);const c=S(r);null===c&&y(`CustomElementRegistry is unavailable for <${s}>.`),await c.whenDefined(s.toLowerCase()),r.hasAttribute(k.bindAttributeName)&&await _(r),i in r||y(`Component does not have property "${i}" for state binding.`);let l=r[i];"object"==typeof l&&null!==l||y(`Component property "${i}" is not an object for state binding.`);const u=function(t,e){const n=se.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(r,i);if(void 0!==u&&function(t,e){if(!t.hasAttribute(k.bindAttributeName))return!1;const n=L(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(r,i)&&(r[i]=u,l=u),e.boundComponent=r,e.boundComponentStateProp=i,t.setBoundComponent(r,i),o instanceof ShadowRoot||(L(r)??[]).some(t=>t.propSegments[0]===i)||we(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${s}>, or mount it from the host (data-wcs="${i}: path").`),r.hasAttribute(k.bindAttributeName)){const a=(L(r)??[]).filter(t=>t.propSegments[0]===i);if(a.length>0){const c=W(r.getRootNode())??we(t,`No state tree found on this root for mount host <${s}>.`);let u=ot(r,i);const d=null!==u;if(null===u&&(function(t,e,n){const o=ie.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;ie.get(t).delete(e)}}(r,i,l),u=rt(r,i,a,c,l,function(t,e){return ae.get(t)?.get(e)}(r,i)),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp;let r,s=!1;for(const a of e){if(null===t.rootEntry)continue;if(s||(r=ye(t),s=!0),"object"!=typeof r||null===r||!(a in r))continue;const e=t.rootEntry.outerPathInfo.path;ge(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted tree key "${e}.${a}" (${o}: ${e}). Remove the default to read the tree, or rename it to keep it private.`)}}(u)),e.mountRecord=u,n.parentNode!==o)return;try{Ut(u,o instanceof ShadowRoot?o:r)}catch(e){throw t.landInitialization(),e}if(!d){const t=qt(u);Object.defineProperty(r,i,{get:()=>t,enumerable:!0,configurable:!0}),oe(r,i)}return me(r,i),st(u),void nt(u,"$connectedCallback")}}he(t,e.boundComponent,e.boundComponentStateProp,l)}}const ve={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=be.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},be.set(t,e)),e}(t);return $e(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=be.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&Tt(n,o)}),nt(n,"$connectedCallback"),!0},disconnecting(t){const e=be.get(t);return void 0!==e&&null!==e.mountRecord&&(nt(e.mountRecord,"$disconnectedCallback"),Bt(e.mountRecord),t.clearConnectedRootNode(),!0)}};let ke=!1;function Se(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const r=n.call(At(t.mountPath,o));r instanceof Promise&&r.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function Pe(t,e,n){const o=n[f];if(void 0!==o){const n=[],r=new Set;let s=0;for(const[a,i]of Object.entries(o)){const o=e+c+a,u=function(t,n,...o){i.call(At(e,this),t,n,...o)};n.push({path:o,pathInfo:l(o),handler:u,order:1e6+s++}),r.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(ct(t,n),t.addVolumeWatchPaths?.(r),lt(t))}const r=n[h];if(void 0!==r){const n=new Map;for(const[t,o]of Object.entries(r))n.set(e+c+t,o);t.mergeVolumeListKeys?.(n)}const s=n[g];"function"==typeof s&&(!function(t,e){let n=It.get(t);void 0===n&&(n=[],It.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,callback:s}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}function Ce(t,e,n){!function(t,e,n){const o=n[f];if(void 0!==o){"object"==typeof o&&null!==o||y(`${f} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&y(`${f} entry "${t}" must be a function.`),it(t)}const r=n[h];if(void 0!==r){"object"==typeof r&&null!==r||y(`${h} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(r))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&y(`${h} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+c+n)&&y(`${h} entry "${e+c+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&y(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&y(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[m]&&y(`Volume "${e}" declares ${m}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys($(n)))-1!==t.indexOf(p)&&y(`Volume "${e}" declares "${t}", which uses "${p}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n);const{data:o,accessors:r}=function(t){const e={},n=new Map;for(const[o,r]of Object.entries(Object.getOwnPropertyDescriptors(t)))o.startsWith("$")||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(e[o]=r.value):n.set(o,r));return{data:e,accessors:n}}(n),s=l(e),a=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===s.segments.length&&e in t){if(a)return;y(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<s.segments.length-1;e++){const o=s.segments[e],r=""===n?o in t:void 0!==t[n+c+o];n=""===n?o:n+c+o,r||(t[n]={})}if(s.segments.length>1&&void 0!==t[e]){if(a)return;y(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=o}),function(t,e){let n=xt.get(t);void 0===n&&(n=new Set,xt.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,o]of r){const r=e+c+n,s=o.get,a=o.set,i={enumerable:!1,configurable:!0};"function"==typeof s&&(i.get=function(){return s.call(At(e,this))}),"function"==typeof a&&(i.set=function(t){a.call(At(e,this),t)}),t.defineTreeAccessor(r,i)}Pe(t,e,n);const i=n.$connectedCallback;return"function"==typeof i&&t.createState("writable",t=>{let n;try{n=i.call(At(e,t))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function xe(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=Ce(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}let Ae=!1;function Ie(){Ae||(Ae=!0,Gt||(Gt=!0,w("scopes",Kt)),ee||(ee=!0,t("scopes",te)),ke||(ke=!0,t("bindComponent",ve),B(ce)),Ot=xe,F(Ne))}function Ne(t,e){(function(t){const e=St.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){jt.delete(t);const n=Rt.get(t);if(void 0===n||0===n.length||null===Ot)return;Rt.delete(t);const o=Ot;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const Re={name:"scopes",install(){Ie(),kt||(kt=!0,t("dcc",vt))}};export{Re as default,Re as scopes};
1
+ import{r as t,l as e,a as n,C as o}from"../chunks/lifecycleHooks.js";import{f as r,h as s,a,i,D as c,V as l,j as u,g as d,k as f,W as h,l as m,m as p,n as g,R as y,o as b}from"../chunks/pathDiagnostics.js";import{r as w,d as $}from"../chunks/errorGuidance.js";import{a as v,g as k,N as S}from"../chunks/getAllPropertyDescriptors.js";import{c as P}from"../chunks/filterRegistry.js";import{n as j}from"../chunks/declarationAliases.js";import{h as C,u as I,i as A,j as x,k as N,m as R,n as M,o as O,p as E,q as D,t as W,v as z,w as L,x as V,y as B,z as F,A as _,B as q,C as T,D as U,E as H}from"../chunks/binder.js";import{f as K,t as G,a as X,b as J,c as Q,s as Y,g as Z,d as tt,e as et,r as nt,h as ot,i as rt,j as st,k as at,l as it,m as ct,n as lt,w as ut}from"../chunks/mount.js";import{p as dt}from"../chunks/diagnosticsHooks.js";import{c as ft}from"../chunks/checkDependency.js";import{y as ht,z as mt,A as pt}from"../chunks/watchRuntime.js";const gt={written:function(t,e,n){const o=t.bindableEventMap,r=o[e.path],s="string"==typeof r,a=s?r:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof a)return;const i=t.rootNode;i instanceof ShadowRoot&&i.host.dispatchEvent(new CustomEvent(a,{detail:s&&void 0!==n?n.value:void 0,bubbles:!0}))}};let yt=!1;function bt(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function wt(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function $t(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function vt(t){return t.startsWith("$")}function kt(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function St(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||w(`${e} must be an array of strings.`);const o=[],r=new Set;for(const t of n)"string"==typeof t&&0!==t.length||w(`${e} entries must be non-empty strings.`),t.startsWith("$")&&w(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),r.has(t)&&w(`${e} entry "${t}" is duplicated.`),r.add(t),o.push(t);return o}function Pt(t){j(t);const e=St(t,r)??[],n=St(t,s)??[],o=k(t),i=function(t){const e=t[a];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];for(const t of e){const e=o[t];if(void 0===e){if(i.has(t)){c.push(t);continue}w(`${r} entry "${t}" is not declared on the state.${$(t,kt(o,"value"))}`)}"function"==typeof e.value&&w(`${r} entry "${t}" is a method. Declare it in ${s} instead.`)}for(const t of n){const e=o[t];void 0===e&&w(`${s} entry "${t}" is not declared on the state.${$(t,kt(o,"method"))}`),"function"!=typeof e.value&&w(`${s} entry "${t}" is not a method. Declare it in ${r} instead.`)}return{bindables:e,commands:n,streamBackedBindables:c}}function jt(t,e,n){const o=t.tagName.toLowerCase();o.includes("-")||w(`DCC: "${o}" is not a valid custom element name (must contain a hyphen).`);const s=C(t);null!==s&&"function"==typeof s.define||w(`DCC: CustomElementRegistry is unavailable for "${o}".`),s.get(o)&&w(`DCC: "${o}" is already registered. A custom element name can only be defined once.`);const a=document.createElement("template"),c=a.content.ownerDocument;for(const t of Array.from(e.childNodes))a.content.appendChild(c.importNode(t,!0));const l=e.mode,{bindables:u,commands:d,streamBackedBindables:f}=Pt(n),h=u.length>0||d.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const r=n.map(t=>({name:t,async:!0}));return{...o,commands:r}}(o,u,d):null,m=u.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(o,u):{},p=P.tagNames.state,g=class extends HTMLElement{static template=a;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=m;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(i))return null;this._shadow=this.attachShadow({mode:g.shadowRootMode}),this._shadow.appendChild(g.template.content.cloneNode(!0));const t=C(this._shadow);return null!==t&&I(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(g.bindableEventMap).length>0){const e=t.querySelector(p);e?(yt||(yt=!0,v("dcc",gt)),e.setBindableEventMap(g.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${o}" declares ${r} but its template has no <${P.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},y=k(n);for(const[t,e]of Object.entries(y)){if(vt(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=$t(t,o)}else n.get=bt(t),n.set=wt(t);Object.defineProperty(g.prototype,t,n)}for(const t of f)Object.defineProperty(g.prototype,t,{configurable:!0,enumerable:!0,get:bt(t),set:wt(t)});s.define(o,g)}async function Ct(t,o,r){const s=t;try{s.hasAttribute("bind-component")&&w(`"bind-component" cannot be used inside a [${i}] host. DCC state comes from the template, not from a component property.`);const a=await async function(t,o){try{if(t.hasAttribute("src")){const n=t.getAttribute("src");if(n.endsWith(".js"))return await e(n);w(`DCC: Unsupported src type: ${n}`)}const r=t.querySelector('script[type="module"]');if(r)return await n(r,o.tagName.toLowerCase());w(`DCC: No state source found for "${o.tagName.toLowerCase()}".`)}catch(t){w(`DCC: Failed to load state: ${t}`)}}(s,o);jt(o,r,a),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}const It={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(i)?Ct(t,e.host,e):null}};let At=!1;const xt=new WeakMap;function Nt(t,e,n){let o=xt.get(t);void 0===o&&(o=new Map,xt.set(t,o));const r=o.get(e);null!=r&&w(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function Rt(t,e){if(null===t)return!1;const n=xt.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+c)||t.startsWith(e+c))return!0;return!1}const Mt=new WeakMap;const Ot=[];function Et(t,e,n,o){if(e.length>0){const r=n.split(c),s=K(e,r);if(null!==s)return o&&s.readonly&&w(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${l}.${s.innerSegments.join(c)}#${u}: ${s.outerPathInfo.path}"). Write "${s.outerPathInfo.path}" on the root, or drop #${u} from the injection.`),G(s,r)}return t+c+n}function Dt(t,e,n){for(const t of e){const e=t.outerPathInfo.path;if(n===e)return t.innerSegments.join(c);if(n.startsWith(e+c))return t.innerSegments.join(c)+n.slice(e.length)}return n===t?"":n.startsWith(t+c)?n.slice(t.length+1):null}function Wt(t,e,n=Ot){return new Proxy({},{get(o,r){if("string"==typeof r&&"then"!==r){if("$"===r[0]){if("$postUpdate"===r||"$getAll"===r){const o=r;return(r,...s)=>e[o](Et(t,n,r,!1),...s)}return"$setAll"===r?(o,...r)=>e.$setAll(Et(t,n,o,!0),...r):"$resolve"===r?(o,...r)=>e.$resolve(Et(t,n,o,r.length>1),...r):e[r]}return e[Et(t,n,r,!1)]}},set:(o,r,s)=>("string"!=typeof r||(e[Et(t,n,r,!0)]=s),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const zt=new WeakMap,Lt=[];const Vt=new WeakMap,Bt=new WeakSet;function Ft(t){console.error(`[@wcstack/state] volume "${t.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),t.onGrafted(null)}let _t=null;const qt=new WeakMap,Tt=new Set;function Ut(t,e,n,o){let r=qt.get(t);if(void 0===r){if(!o)return null;r=new Map,qt.set(t,r)}let s=r.get(e);if(void 0===s){if(!o)return null;s=new Map,r.set(e,s)}let a=s.get(n);if(void 0===a){if(!o)return null;a={holders:new Set,byListIndex:new WeakMap,noIndex:null},s.set(n,a)}return a}function Ht(t,e){if(!t.component.isConnected)return!1;const n=A(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function Kt(t,e,n,o){const r=Ut(t,e,n,!1);if(null===r)return null;const s=null===o?r.noIndex:r.byListIndex.get(o)??null;if(null!==s){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&Ht(n,e)?n:null}(s,o);if(null!==t)return{record:t,entry:s.entry}}let a=null,i=null;for(const t of r.holders){const s=t.ref.deref();void 0!==s?Ht(s,o)&&(null!==i&&w(`[wcs/mount-export-ambiguous] "${e}${c}${n}" is exported by two mounted components on the same instance: <${i.component.tagName.toLowerCase()}> and <${s.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),a=t,i=s):r.holders.delete(t)}return null===a||null===i?null:(null===o?r.noIndex=a:r.byListIndex.set(o,a),{record:i,entry:a.entry})}function Gt(t){const e=t.parentStateElement,n=A(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[x](n,()=>{t.$postUpdate(o.exportedPath)})})}const Xt=new WeakMap;class Jt{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,r,s){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=r,this.handler=s}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return N(d(this.markerParentPath+c+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(X(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,r,...s)=>{const a=s.length>0?J(t,e):X(t,e),i=Q(t,e,a,r??[],n);return o.$resolve(a,i,...s)};const r=e;return(e,s,...a)=>{const i="$setAll"===r?J(t,e):X(t,e),c=Q(t,e,i,s,n);return o[r](i,c,...a)}}return this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return ft(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[X(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const r=this.accessorNameFor(e);if(void 0!==r){this.record.setterKeys.has(r)||w(`Cannot write to "${r}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,r,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(t,e)?(t[e]=n,!0):(this.receiver[J(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return X(this.record,e),!0}catch{return!1}}}function Qt(t,e,n,o){const r=e.pathInfo.path,s=r===t.markerBasePath,a=s?function(t,e){let n=Xt.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Xt.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(a,new Jt(t,r,e.listIndex,s,n,o))}function Yt(t){const e=t.parentStateElement,n=(e,n)=>{const o=A(t.component);let r;return e[x](o,()=>{r=n()}),r};return new Proxy({},{get(o,r){if("string"!=typeof r||"then"===r)return;if("$getAll"===r||"$setAll"===r||"$resolve"===r||"$postUpdate"===r)return function(t,e,n){const o=t.parentStateElement,r=(t,e)=>{let r;return o.createState(t,t=>{r=n(t,()=>e(t))}),r};return"$postUpdate"===e?e=>r("readonly",n=>n.$postUpdate(X(t,e))):(n,o,...s)=>{const a="$setAll"===e||"$resolve"===e&&s.length>0,i=a?J(t,n):X(t,n),c=A(t.component)?.listIndex.indexes??[],l=Q(t,n,i,"$resolve"===e?o??[]:o,c);return r(a?"writable":"readonly",t=>t[e](i,l,...s))}}(t,r,n);let s;return e.createState("readonly",e=>{s=n(e,()=>e["$"===r[0]?r:X(t,r)])}),s},set:(o,r,s)=>("string"!=typeof r||e.createState("writable",e=>{n(e,()=>{e["$"===r[0]?r:J(t,r)]=s})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return X(t,n),!0}catch{return!1}}})}function Zt(t,e){const n=et(e);null!==n&&n.stateProp!==t.stateProp&&w(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&R(e).dispose(),nt(e,t),e instanceof ShadowRoot&&E(e,t.parentStateElement),function(t,e){const n=(e,n)=>ot(t,e,n);W(e);const o=A(t.component),r=e instanceof ShadowRoot?e:e.getRootNode();z(r,e,void 0,n),L(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=X(t,n)}catch{continue}const o=e.indexOf(c+t.marker);if(-1===o)continue;const r=e.slice(0,o+1+t.marker.length),s=e.slice(r.length+1),a=e.slice(0,o)+c+s,i=d(a);if(i.wildcardCount!==t.delta)continue;const l={markerTerminalPath:r,suffix:s,markerPath:e,exportedPath:a};t.exports.set(a,l),Ut(t.parentStateElement,i.parentPath,i.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:l}),t.parentStateElement.addDynamicDependency(e,a),dt?.markExported(t.parentStateElement,a)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=A(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const r=`${n}|${o.exportedPath}`;if(Tt.has(r))continue;const s=d(o.exportedPath);let a;t.parentStateElement.createState("readonly",t=>{t[x](e,()=>{a=t[s.parentPath]})}),null!=a&&s.lastSegment in Object(a)&&(Tt.add(r),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(t),Gt(t),D(e,Promise.resolve())}function te(t,e){const n=R(e),o=A(t.component);n.forEachActiveBindingNode(t=>M(t,o));const r=n.rebindAddresses();O(r),Gt(t)}function ee(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const ne={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const r=st(t,e.pathInfo.path);if(null!==r)return Qt(r,e,n,o)}return S},readMissing(t,e,n,o,r){if(null===n){if(Rt(t.rootNode??null,e.pathInfo.path))return;return S}if(!0===t.hasMounts){const n=Kt(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,r){const s=Qt(t,N(d(e.markerTerminalPath),n),o,r);return Reflect.get(s,e.suffix)}(n.record,n.entry,e.listIndex,o,r)}return S},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=Mt.get(t);if(void 0===n||0===n.size)return null;const o=e+c;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&w(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return S},writeMissing(t,e,n,o,r,s,a){if(!0===t.hasMounts){const n=Kt(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,r,s){const a=Qt(t,N(d(e.markerTerminalPath),n),r,s);return Reflect.set(a,e.suffix,o)}(n.record,n.entry,e.listIndex,r,s,a)}return S},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=st(n,o);if(null!==t)return at(t,o)}return 0},handlerScope(t,e,n,o,r){if(!0!==t.hasMounts)return r;const s=rt(e,n);if(null===s)return r;const a=s.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==a?r-a:0},updated(t,e,n){const o=function(t){return zt.get(t)??Lt}(t);for(const r of o){const o=new Set,s={};for(const n of e){if(n.absolutePathInfo.stateElement!==t)continue;const e=n.absolutePathInfo.pathInfo.path;if(-1!==e.indexOf("#"))continue;const a=Dt(r.mountPath,r.injections,e);if(null===a||""===a)continue;o.add(a);const i=n.absolutePathInfo.pathInfo.wildcardCount;if(i>0&&null!==n.listIndex){const t=V(n.listIndex,i);(s[a]??=[]).push(t)}}if(o.size>0)try{r.callback.call(Wt(r.mountPath,n,r.injections),Array.from(o),s)}catch(t){console.error(`[@wcstack/state] volume "${r.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>Rt(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(Y(e))for(const n of Z(e)){if(!ee(n.component,t))continue;const e=tt(n);null!==e&&te(n,e)}}(e,t)}};let oe=!1;const re=new WeakMap;function se(t){let e=re.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},re.set(t,e)),e}function ae(t,e){null!==e.slotRootNode&&(!function(t,e,n){const o=xt.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function ie(t,e,n){if(e.slotRootNode===n)return!0;const o=e.mountPath;try{Nt(n,o,t)}catch{return console.error(`[@wcstack/state] <${P.tagNames.state} mount="${o}"> will not graft: another volume already holds the "${o}" slot on this root. Keep one volume per mount path.`),!1}return B(n)?.markHasVolume?.(),e.slotRootNode=n,!0}async function ce(t,e){const n=t,o=t.connectedRootNode,r=n.getAttribute("mount");let s;try{!function(t){0===t.length&&w('"mount" requires a non-empty tree path.');const e=d(t);for(const n of e.segments)0===n.length&&w(`"mount" path "${t}" has an empty segment.`),n===h&&w(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&w(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),s=function(t,e){const n=[],o=new Set;for(const r of U(t)){if(r.propSegments[0]!==l)continue;const t=r.propSegments.slice(1),s=r.statePathInfo,a=t=>w(`[wcs/mount-path-invalid] <${P.tagNames.state} mount="${e}"> "${r.propName}: ${r.statePathName}": ${t}`);1===t.length&&t[0]&&t[0]!==h&&"$"!==t[0][0]&&"#"!==t[0][0]||a(`inject one key at a time ("${l}.<key>: path"); change "mount" to move the whole volume.`),(s.wildcardCount>0||"$"===s.path[0]||"#"===s.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(r.inFilters.length>0||r.outFilters.length>0)&&a("an injection takes no filters."),r.propModifiers.some(t=>t!==u)&&a(`an injection accepts only #${u}.`),o.has(t[0])&&a(`"${t[0]}" is injected twice.`),o.add(t[0]),n.push({innerSegments:t,outerPathInfo:s,readonly:r.propModifiers.includes(u)})}return n}(n.getAttribute(P.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&w('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${P.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),Nt(o,r,t),B(o)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=o}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===B(o)&&function(t,e){const n=()=>{if(null!==B(t))return;const n=t.querySelectorAll(P.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${P.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${P.tagNames.state}> to this root node (an empty <${P.tagNames.state}></${P.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},o=t.ownerDocument??t;"loading"===o.readyState?o.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(o,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&ae(t,e),t.settleInitialization()};let i;try{i=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void a(null)}const c=t.connectedRootNode??null;null!==c&&ie(t,e,c)?function(t,e,n,o,r,s,a=[]){const i={mountPath:n,volumeState:o,injections:a,onGrafted:r,acquireSlot:s};if(null!==e)return void De(e,i);ze(),function(t,e){if(Bt.has(t))return void Ft(e);let n=Vt.get(t);void 0===n&&(n=[],Vt.set(t,n)),n.push(e)}(t,i)}(c,B(c),r,i,a,()=>ie(t,e,c),s):a(null)}const le={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=se(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{Nt(n,e.mountPath,t),B(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,o}return ce(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=se(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&B(n)===e.graftInfo.rootStateElement&&Me(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==re.get(t)?.initializing)return;const e=t.getAttribute("mount");w(`Cannot replace the state of <${P.tagNames.state} mount="${e}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){Bt.add(t);const e=Vt.get(t);if(void 0!==e){Vt.delete(t);for(const t of e)Ft(t)}}(e)},initializeFailureCleared(t,e){!function(t){Bt.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=se(t);return null!==e.graftInfo&&Me(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,ae(t,e)),t.clearConnectedRootNode(),!0}};let ue=!1;const de=new WeakMap;function fe(t,e){let n=de.get(t);n||(n=new Set,de.set(t,n)),n.add(e)}const he=new WeakMap;const me=new WeakMap,pe=new WeakMap;const ge=new WeakMap;const ye={isComplete:function(t,e){return!0===de.get(t)?.has(e)},isDeclared:function(t,e){return!0===he.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=me.get(t);o||(o=new Map,me.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=pe.get(t);o||(o=new Map,pe.set(t,o));let r=o.get(e);r||(r=new Set,o.set(e,r)),r.add(n)},rememberOverwrittenValue:function(t,e,n,o){let r=ge.get(t);r||(r=new Map,ge.set(t,r));let s=r.get(e);s||(s=new Map,r.set(e,s)),s.has(n)||s.set(n,o)}};function be(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}const we=new WeakMap;class $e{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=we.get(t);return n?n.get(e)??null:null}(t,e)??w("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const ve=t=>()=>t;function ke(t,e,n,o){!function(t,e,n){let o=we.get(t);o||(o=new Map,we.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(be(o));const r=function(t,e){const n=new $e(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:ve(r),enumerable:!0,configurable:!0}),fe(e,n),Se(e,n)}function Se(t,e){if(f in t){const n=t[f];"function"==typeof n?n.call(t,e).catch(t=>{w(`Error in ${f}: ${t instanceof Error?t.message:String(t)}`)}):w(`${f} is not a function.`)}}const Pe=new Set;function je(t,e){Pe.has(t)||(Pe.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Ce(t){const e=t.rootEntry,n=A(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[x](n,()=>{o=t[e.outerPathInfo.path]})}),o}const Ie=new WeakMap;function Ae(t,e){t.landInitialization(),w(e)}async function xe(t,e){const n=t;if(n.hasAttribute("bind-component")){const o=n.parentNode,r=o instanceof ShadowRoot?o.host:o instanceof Element?o:null,s=r?q(r):null;null!==r&&null!==s||w(`"bind-component" requires <${P.tagNames.state}> to be a direct child of a custom element.`),o instanceof ShadowRoot||r.hasAttribute(P.bindAttributeName)||Ae(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${s}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const a=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&a.push('<script type="module">'),a.length>0&&w(`"bind-component" cannot be combined with ${a.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const i=n.getAttribute("bind-component");!function(t,e){let n=he.get(t);n||(n=new Set,he.set(t,n)),n.add(e)}(r,i);const c=C(r);null===c&&w(`CustomElementRegistry is unavailable for <${s}>.`),await c.whenDefined(s.toLowerCase()),r.hasAttribute(P.bindAttributeName)&&await T(r),i in r||w(`Component does not have property "${i}" for state binding.`);let l=r[i];"object"==typeof l&&null!==l||w(`Component property "${i}" is not an object for state binding.`);const u=function(t,e){const n=me.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(r,i);if(void 0!==u&&function(t,e){if(!t.hasAttribute(P.bindAttributeName))return!1;const n=F(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(r,i)&&(r[i]=u,l=u),e.boundComponent=r,e.boundComponentStateProp=i,t.setBoundComponent(r,i),o instanceof ShadowRoot||(F(r)??[]).some(t=>t.propSegments[0]===i)||Ae(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${s}>, or mount it from the host (data-wcs="${i}: path").`),r.hasAttribute(P.bindAttributeName)){const a=(F(r)??[]).filter(t=>t.propSegments[0]===i);if(a.length>0){const c=B(r.getRootNode())??Ae(t,`No state tree found on this root for mount host <${s}>.`);let u=ct(r,i);const d=null!==u;if(null===u&&(function(t,e,n){const o=ge.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;ge.get(t).delete(e)}}(r,i,l),u=lt(r,i,a,c,l,function(t,e){return pe.get(t)?.get(e)}(r,i)),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp;let r,s=!1;for(const a of e){if(null===t.rootEntry)continue;if(s||(r=Ce(t),s=!0),"object"!=typeof r||null===r||!(a in r))continue;const e=t.rootEntry.outerPathInfo.path;je(`${n}|${o}|${a}|root`,`<${n}>.${o}.${a} is private and hides the mounted tree key "${e}.${a}" (${o}: ${e}). Remove the default to read the tree, or rename it to keep it private.`)}}(u)),e.mountRecord=u,n.parentNode!==o)return;try{Zt(u,o instanceof ShadowRoot?o:r)}catch(e){throw t.landInitialization(),e}if(!d){const t=Yt(u);Object.defineProperty(r,i,{get:()=>t,enumerable:!0,configurable:!0}),fe(r,i)}return Se(r,i),ut(u),void it(u,"$connectedCallback")}}ke(t,e.boundComponent,e.boundComponentStateProp,l)}}const Ne={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=Ie.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Ie.set(t,e)),e}(t);return xe(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=Ie.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&te(n,o)}),it(n,"$connectedCallback"),!0},disconnecting(t){const e=Ie.get(t);return void 0!==e&&null!==e.mountRecord&&(it(e.mountRecord,"$disconnectedCallback"),Gt(e.mountRecord),t.clearConnectedRootNode(),!0)}};let Re=!1;function Me(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const r=n.call(Wt(t.mountPath,o,t.injections));r instanceof Promise&&r.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function Oe(t,e,n,o){const r=n[m];if(void 0!==r){const n=[],s=new Set;let a=0;for(const[i,c]of Object.entries(r)){const r=Et(e,o,i,!1),l=function(t,n,...r){c.call(Wt(e,this,o),t,n,...r)};n.push({path:r,pathInfo:d(r),handler:l,order:1e6+a++}),s.add(r),t.setPathInfo(r,"prop","watch")}n.length>0&&(mt(t,n),t.addVolumeWatchPaths?.(s),pt(t))}const s=n[p];if(void 0!==s){const n=new Map;for(const[t,r]of Object.entries(s))n.set(Et(e,o,t,!1),r);t.mergeVolumeListKeys?.(n)}const a=n[b];"function"==typeof a&&(!function(t,e){let n=zt.get(t);void 0===n&&(n=[],zt.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,injections:o,callback:a}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}function Ee(t,e,n,o=[]){j(n),function(t,e,n,o){for(const t of o){const o=t.innerSegments[0],r=Object.getOwnPropertyDescriptor(n,o);void 0===r||"function"!=typeof r.get&&"function"!=typeof r.set&&"function"!=typeof r.value||w(`Volume "${e}" declares "${o}" as an accessor or a method and also injects it ("${l}.${o}: ${t.outerPathInfo.path}"). Rename one of them.`)}const r=n[m];if(void 0!==r){"object"==typeof r&&null!==r||w(`${m} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(r))"function"!=typeof e&&w(`${m} entry "${t}" must be a function.`),ht(t)}const s=n[p];if(void 0!==s){"object"==typeof s&&null!==s||w(`${p} must be an object mapping list paths to key specs.`);for(const[n,r]of Object.entries(s)){(0===n.length||"string"!=typeof r&&"function"!=typeof r)&&w(`${p} entry "${n}" must map a list path to a field name or a key function.`);const s=Et(e,o,n,!1);t.listKeys?.has(s)&&w(`${p} entry "${s}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[a]&&w(`Volume "${e}" declares ${a}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&w(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[g]&&w(`Volume "${e}" declares ${g}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys(k(n)))-1!==t.indexOf(y)&&w(`Volume "${e}" declares "${t}", which uses "${y}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n,o);const{data:r,accessors:s}=function(t,e){const n={},o=new Map;for(const[r,s]of Object.entries(Object.getOwnPropertyDescriptors(t)))r.startsWith("$")||e.has(r)||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(n[r]=s.value):o.set(r,s));return{data:n,accessors:o}}(n,new Set(o.map(t=>t.innerSegments[0]))),i=d(e),u=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(u)return;w(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],r=""===n?o in t:void 0!==t[n+c+o];n=""===n?o:n+c+o,r||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(u)return;w(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=r}),function(t,e){let n=Mt.get(t);void 0===n&&(n=new Set,Mt.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,r]of s){const s=e+c+n,a=r.get,i=r.set,l={enumerable:!1,configurable:!0};"function"==typeof a&&(l.get=function(){return a.call(Wt(e,this,o))}),"function"==typeof i&&(l.set=function(t){i.call(Wt(e,this,o),t)}),t.defineTreeAccessor(s,l)}Oe(t,e,n,o);const f=n.$connectedCallback;return"function"==typeof f&&t.createState("writable",t=>{let n;try{n=f.call(Wt(e,t,o))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n,injections:o}}function De(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=Ee(t,e.mountPath,e.volumeState,e.injections)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}let We=!1;function ze(){We||(We=!0,oe||(oe=!0,v("scopes",ne)),ue||(ue=!0,t("scopes",le)),Re||(Re=!0,t("bindComponent",Ne),_(ye)),_t=De,H(Le))}function Le(t,e){(function(t){const e=xt.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){Bt.delete(t);const n=Vt.get(t);if(void 0===n||0===n.length||null===_t)return;Vt.delete(t);const o=_t;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const Ve={name:"scopes",install(){ze(),At||(At=!0,t("dcc",It))}};export{Ve as default,Ve as scopes};
2
2
  //# sourceMappingURL=scopes.js.map