@wcstack/state 4.10.1 → 4.11.1

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 (54) hide show
  1. package/README.ja.md +27 -7
  2. package/README.md +28 -7
  3. package/dist/auto.min.js +1 -1
  4. package/dist/auto.min.js.map +1 -1
  5. package/dist/index.d.ts +5 -1
  6. package/dist/index.esm.js +1 -1
  7. package/dist/index.esm.js.map +1 -1
  8. package/dist/split/auto.js +1 -1
  9. package/dist/split/chunks/{chunk-JCQTA35B.js → chunk-AKTGQ6TC.js} +2 -2
  10. package/dist/split/chunks/chunk-CYMUD7KV.js +2 -0
  11. package/dist/split/chunks/chunk-CYMUD7KV.js.map +1 -0
  12. package/dist/split/chunks/chunk-E3XSBW55.js +2 -0
  13. package/dist/split/chunks/chunk-IYPAK7PO.js +2 -0
  14. package/dist/split/chunks/chunk-IYPAK7PO.js.map +1 -0
  15. package/dist/split/chunks/{chunk-FFXJVUTT.js → chunk-JJYM4JVZ.js} +2 -2
  16. package/dist/split/chunks/chunk-KBQKAD3I.js +2 -0
  17. package/dist/split/chunks/{chunk-PTFWXISY.js.map → chunk-KBQKAD3I.js.map} +1 -1
  18. package/dist/split/chunks/{chunk-SJRJALR4.js → chunk-LPJFTEVT.js} +2 -2
  19. package/dist/split/chunks/chunk-NAV7FBTI.js +2 -0
  20. package/dist/split/chunks/{chunk-MZVF2WEY.js.map → chunk-NAV7FBTI.js.map} +1 -1
  21. package/dist/split/chunks/{chunk-FT7OW7CG.js → chunk-R6RHIIR4.js} +2 -2
  22. package/dist/split/chunks/chunk-REB4RMZ3.js +2 -0
  23. package/dist/split/chunks/{chunk-65B2K2XD.js.map → chunk-REB4RMZ3.js.map} +1 -1
  24. package/dist/split/chunks/chunk-T66VJGI5.js +2 -0
  25. package/dist/split/chunks/{chunk-SANIIUS2.js.map → chunk-T66VJGI5.js.map} +1 -1
  26. package/dist/split/core.js +1 -1
  27. package/dist/split/features/devtools.js +1 -1
  28. package/dist/split/features/devtools.js.map +1 -1
  29. package/dist/split/features/diagnostics.js +1 -1
  30. package/dist/split/features/diagnostics.js.map +1 -1
  31. package/dist/split/features/formats.js +1 -1
  32. package/dist/split/features/list-keys.js +1 -1
  33. package/dist/split/features/native-commands.js +1 -1
  34. package/dist/split/features/recursion.js +1 -1
  35. package/dist/split/features/scopes.js +1 -1
  36. package/dist/split/features/scopes.js.map +1 -1
  37. package/dist/split/features/ssr.js +1 -1
  38. package/dist/split/features/ssr.js.map +1 -1
  39. package/dist/split/features/temporal.js +1 -1
  40. package/package.json +1 -1
  41. package/dist/split/chunks/chunk-65B2K2XD.js +0 -2
  42. package/dist/split/chunks/chunk-GU7IAIWW.js +0 -2
  43. package/dist/split/chunks/chunk-GU7IAIWW.js.map +0 -1
  44. package/dist/split/chunks/chunk-IWY3I2DG.js +0 -2
  45. package/dist/split/chunks/chunk-IWY3I2DG.js.map +0 -1
  46. package/dist/split/chunks/chunk-MZVF2WEY.js +0 -2
  47. package/dist/split/chunks/chunk-PTFWXISY.js +0 -2
  48. package/dist/split/chunks/chunk-SANIIUS2.js +0 -2
  49. package/dist/split/chunks/chunk-UE6JK2ZA.js +0 -2
  50. /package/dist/split/chunks/{chunk-JCQTA35B.js.map → chunk-AKTGQ6TC.js.map} +0 -0
  51. /package/dist/split/chunks/{chunk-UE6JK2ZA.js.map → chunk-E3XSBW55.js.map} +0 -0
  52. /package/dist/split/chunks/{chunk-FFXJVUTT.js.map → chunk-JJYM4JVZ.js.map} +0 -0
  53. /package/dist/split/chunks/{chunk-SJRJALR4.js.map → chunk-LPJFTEVT.js.map} +0 -0
  54. /package/dist/split/chunks/{chunk-FT7OW7CG.js.map → chunk-R6RHIIR4.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{a as e}from"../chunks/chunk-SANIIUS2.js";import{b as t,c as l}from"../chunks/chunk-FT7OW7CG.js";import"../chunks/chunk-65B2K2XD.js";import{a as n,i as o,j as r,k as i,l as s,m as a,n as c,o as u}from"../chunks/chunk-IWY3I2DG.js";import"../chunks/chunk-FFXJVUTT.js";import"../chunks/chunk-GU7IAIWW.js";import{a as f}from"../chunks/chunk-JCQTA35B.js";import"../chunks/chunk-MZVF2WEY.js";import"../chunks/chunk-PTFWXISY.js";import"../chunks/chunk-UE6JK2ZA.js";import{a as d,b as p}from"../chunks/chunk-SJRJALR4.js";var m=e=>e.split(".").slice(0,2).join("."),h=class extends t{static find(e){return e.querySelector?.(f.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return m(this.version)===m(e)}};function g(e){let t=f.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends h{})}var b=()=>f.tagNames.ssr,v=Symbol.for("wcstack.ssr.snapshotBuilder"),y=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),w=e=>document.createComment(e),N=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,S=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),A=new WeakMap,x=new WeakMap,k=new WeakMap,T=new WeakSet,$=new WeakMap;function W(e,t){let l=[];for(let n=e;null!==n&&(l.push(n),n!==t);n=n.nextSibling);return l}function C(e,t,...l){for(let l of Array.from(e.attributes))t.setAttribute(l.name,l.value);return(t.content??t).append(...l),t}var E=e=>{let t=e.nextSibling;return 1!==e.nodeType||"a"!==t?.localName||!t.hasAttribute("data-wcs-ssr-link")&&e.anchorElement!==t?null:t};function j(e,t,l,n){let o=w(null===n?"wcs-[":`wcs-[:${n}`),r=w("wcs-]");l.length>0&&l[0].Pe().before(...W(e,t)),t.after(o);for(let e of l)null===n&&e.Pe().before(w("wcs-|"));let i=l.length>0?(e=>null===e.L?e.ut:e.L[e.L.length-1])(l[l.length-1]):o;(E(i)??i).after(r);for(let e of W(o,r))T.add(e)}function q(e){if(e instanceof o){j(e.S,e.S,e.Ae,null);for(let t of e.Ae)I(t);return}let t=e.I;null!==t&&(j(e.q[e.y].S,e.q[e.q.length-1].S,[t],e.y),I(t))}function I(e){if(null!==e.u)for(let t of e.u)q(t)}var M=new Set(["script","style","template","textarea","title"]),O="data-wcs-raw",P=e=>M.has(e.localName)||e.localName===b();function D(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(w("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(w("wcs-s")):1===t.nodeType&&!P(t)&&D(t)}var R=0;function z(t,l){let n=t.getRootNode(),o=[l];for(let e of x.get(n)??[])e!==l&&!0===e.element?.hasAttribute("bind-component")&&o.push(e);let r=new Map;for(let e of o){let t=A.get(e);if(void 0===t)continue;let l=new Map;for(let t of e.oe.values())if(null!==t.N&&l.set(t.N.S,t.N),null!==t.W)for(let e of t.W)l.set(e.S,e);for(let t of e.ue.values())for(let e of t)if(null!==e.D)for(let t of e.D.q)l.set(t.S,e.D);let n=new Set;for(let[e,o]of t){r.set(e,o);let t=l.get(e);void 0!==t&&!n.has(t)&&e.isConnected&&(n.add(t),q(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=k.get(e);if(void 0!==t){let l=document.createTreeWalker(e,133,{acceptNode:e=>T.has(e)||1===e.nodeType&&t.has(e)&&F(e)?2:1}),n=[];for(let e=l.nextNode();null!==e;e=l.nextNode()){let l=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(P(e.parentNode)?$.has(e):t.has(l)&&S(l,"wcs-t:"))&&($.has(e)||t.get(e)!==e.data):!t.has(e))&&n.push(e)}for(let e of n)e.remove()}let l=Array.from(e.childNodes);P(e)&&l.some(e=>$.has(e))&&e.setAttribute(O,l.map(e=>$.has(e)?`{{ ${$.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}D(9===n.nodeType?n.body:n);let i=document.createElement(b());i.setAttribute("version",e);let s=document.createElement("script");s.type="application/json",s.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let l of Object.keys(e)){if("$"===l[0])continue;let n=Object.getOwnPropertyDescriptor(e,l);void 0!==n.get||void 0!==n.set||"function"==typeof n.value||(t[l]=n.value)}return t}(l.target)),i.append(s);for(let[e,t]of r){if(!e.isConnected)continue;let l=e.parentNode;for(;null!==l&&"svg"!==l.localName&&"foreignObject"!==l.localName;)l=l.parentElement;let n="svg"===l?.localName,o=`wcs-${n?"s":"t"}${R++}`;e.replaceWith(w(`wcs-p:${o}`));let r=document.importNode(u(t),!0);for(let e of Array.from(r.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(C(e,document.createElement("template"),...e.childNodes));if(n){let e=document.createElementNS(l.namespaceURI,"svg");e.append(r),r=e}let s=document.createElement("template");s.id=o,i.append(C(t,s,r))}t.before(i)}function U(e){!function(e){if(null!==e.querySelector(f.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>$.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${f.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===b())continue;let e=t.engine;null!=e&&z(t,e)}}var J=Symbol.for("wcstack.state.ssr.impl"),L=new Map,V=new WeakMap,F=e=>!0===d.Po?.(e),B=e=>1===e.nodeType&&!P(e)&&!F(e),G=e=>e.f.flat().concat(e.z??[]),X=e=>{for(let t of G(e))t.remove()};function Y(e,t,l){let n=/^wcs-\[(?::(\d+))?/.exec(e.data),o=e.previousSibling,r=e.parentNode,i=[],s=e.nextSibling;for(e.remove();null!==s&&!N(s,"wcs-]");){let e=s.nextSibling;if(N(s,"wcs-|"))i.push([]),s.remove();else{0===i.length&&i.push([]);let l=i[i.length-1];S(s,"wcs-[")?e=Y(s,t,l):(l.push(s),B(s)&&K(s,t))}s=e}let c={branch:void 0===n[1]?null:Number(n[1]),f:i,z:s??r.appendChild(w("wcs-]"))},u=G(c);s=c.z.nextSibling;for(let e of u)l?.push(e),t&&a.add(e);return t&&null!==o?L.set(o,c):X(c),s}function K(e,t){for(let l=e.firstChild;null!==l;)S(l,"wcs-[")?l=Y(l,t):(B(l)&&K(l,t),l=l.nextSibling)}function Z(e,t,l){let n=e=>{for(let o of Array.from(e.childNodes))if(o.parentNode===e)if(8===o.nodeType){let e=o.data;try{if("wcs-s"===e)o.remove();else if("wcs-e"===e)o.replaceWith("");else if(e.startsWith("wcs-t:")){let t=w(`@@:${decodeURIComponent(e.slice(6))}`),l=o.nextSibling;for(;null!==l&&!N(l,"wcs-/t");){let e=l.nextSibling;l.remove(),l=e}l?.remove(),o.replaceWith(t)}else if(e.startsWith("wcs-p:")){let l=t.querySelector(`template[id="${e.slice(6)}"]`);if(null!==l){let t=o.parentNode,n="s"===e[10]?C(l,document.createElementNS(t.namespaceURI,"template"),...document.importNode(l.content.firstChild,!0).childNodes):document.importNode(l,!0);n.removeAttribute("id"),t.replaceChild(n,o)}}}catch{}}else 1===o.nodeType&&!P(o)&&(F(o)?V.set(o,{ssr:t,Te:l}):n(o))};n(e),function(e){for(let t of Array.from(e.querySelectorAll("table > tbody"))){let e=[];for(let l=t.previousSibling;null!==l&&(8===l.nodeType||oe(l)||"template"===l.localName);l=l.previousSibling)e.unshift(l);let l=0,n=0;if(e.forEach((e,t)=>{S(e,"wcs-[")?n++:N(e,"wcs-]")&&--n<0&&(n=0,l=t+1)}),0===n)continue;let o=0;for(let n=t.firstChild;null!==n;n=n.nextSibling)if(S(n,"wcs-["))o++;else if(N(n,"wcs-]")&&0===o--){t.prepend(...e.slice(l));break}}}(e),K(e,l)}function Q(e,t){let l=V.get(e);if(void 0===l)return null;V.delete(e);let n=e=>Z(e,l.ssr,l.Te);if(l.Te||te(t,e,e,n),n(e),!l.Te)return null;let o=d.Te;return d.Te=se,()=>{d.Te=o,H()}}function H(){for(let e of L.values())X(e);L.clear()}function _(e){let t=[];for(let l=document.createTreeWalker(e,128);l.nextNode();)t.push(l.currentNode);return t}function ee(e,t,l,n){let o=null;for(let n of e){let e=n[l];null!==e&&(""===e||t===e||t.startsWith(`${e}.`))&&(null===o||e.length>o[l].length)&&(o=n)}let r=o?.[n];if(null==r)return null;let i=o[l],s=""===i?t:t.slice(i.length+1);return""===r?s:""===s?r:`${r}.${s}`}function te(e,t,l,n){let o=document.createElement("template").content;for(let e of l.childNodes)o.appendChild(o.ownerDocument.importNode(e,!0));n(o),e.root=t;let r=()=>{};c(e,[...o.childNodes],null,!0,r,r,r,(t,l)=>s(e,l,null,0))}function le(e,t,l){if(y()){if(l instanceof Array){for(let e=l.length;e-- >0;)r(l[e])&&l.splice(e,1);let e=t;if(l.some(i))T.add(e);else if(e.localName.includes("-")&&!F(e)){let t=new Map;for(let l=document.createTreeWalker(e,133);l.nextNode();)t.set(l.currentNode,l.currentNode.data);k.set(e,t)}return}if("string"==typeof l){if($.set(t,l),P(t.parentNode))return;let e=w(`wcs-t:${encodeURIComponent(l)}`),n=w("wcs-/t");return t.before(e),void t.after(n)}let n=A.get(e);void 0===n&&A.set(e,n=new Map),n.set(t,l);let o=t.getRootNode(),s=x.get(o);return void 0===s&&x.set(o,s=new Set),void s.add(e)}if("string"!=typeof l&&L.size>0){let e=L.get(l);void 0!==e&&(L.delete(l),L.set(t,e))}}var ne=e=>null!==e&&8===e.nodeType&&[f.commentIfPrefix,f.commentElseIfPrefix,f.commentElsePrefix].includes(e.data),oe=e=>3===e.nodeType&&""===e.data.trim(),re=e=>{let t=L.get(e)?.z??e;return(E(t)??t).nextSibling};function ie(e,t){if(t.length!==e.ln.childNodes.length)return!1;let l=e.Dn;for(let n=0;n<l.length;n++){let o=l[n],r=e.ln,i=t[o[0]];for(let e=0;;){if(r=r.childNodes[o[e]],i?.nodeName!==r.nodeName)return!1;if(++e===o.length)break;i=(E(i)??i).firstChild;for(let t=o[e];t>0&&null!==i;t--)i=re(i)}e.No[n]=i}return!0}function se(e,t,l){if(0===L.size)return null;let n=t,o=0;if(!l){let e=f.commentIfPrefix;if(!N(t,e))for(let l=t.previousSibling;null!==l&&1!==l.nodeType&&(ne(l)&&o++,!N(l,e));l=l.previousSibling);for(let l=t.nextSibling;!L.has(n)&&null!==l&&!N(l,e)&&1!==l.nodeType;l=l.nextSibling)ne(l)&&(n=l)}let r=L.get(n);if(void 0===r)return null;if(!l&&r.branch!==o)return L.delete(n),X(r),null;let i=r.f.shift();if(0===r.f.length&&L.delete(n),r.z?.replaceWith(...W(t,n)),r.z=null,void 0===i)return null;let s=[];for(let e=0;e<i.length;e++){let t=L.get(i[e]);if(s.push(i[e]),void 0!==t)for(;e<i.length&&i[e]!==t.z;)e++;else E(i[e])===i[e+1]&&e++}if(!ie(e,s)){let l=(e.Ln?e.root:e.ln).cloneNode(!0);s=e.Ln?[l]:[...l.childNodes],ie(e,s),(i[0]??r.f.find(e=>e.length>0)?.[0]??t).before(l);for(let e of i)e.remove()}return s}var ae={name:"ssr",hooks:d,install(){d.Bn=le,d.wr=Q;let t=d.element;d.element=(l,o)=>{"mounting"===o&&function(t){let l=t.element;if(!l.hasAttribute("enable-ssr")||y())return;let o=l.previousElementSibling,r=o?.localName===b(),i=r?o.getAttribute("version"):null,s=null===i||m(i)===m(e);if(s){let e=t,l=e.$e;e.$e=(e,n)=>"$connectedCallback"===e?void 0:l.call(t,e,n)}if(!r)return;let a=!s&&parseInt(i)<4,c=/^3\.(\d+)\.(\d+)$/.exec(i),u=null!==c&&(+c[1]-5||+c[2]-3)>=0;s||console.warn(`[@wcstack/state] <${b()} version="${i}"> does not match ${e}: its snapshot is discarded, and the page renders on the client from its own state.${a&&!u?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let p=s?o.querySelector('script[type="application/json"]'):null;if(null!==p){let e=JSON.parse(p.textContent||"{}"),l=t.target;for(let t of Object.keys(e)){let n=Object.getOwnPropertyDescriptor(l,t);void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)||(l[t]=e[t])}t.hydrated=!0}let h=l.getRootNode();for(let e of Array.from(h.querySelectorAll(`[${O}]`)))e.textContent=e.getAttribute(O),e.removeAttribute(O);let g=9===h.nodeType?h.body:h;o.remove();let v=e=>a?function(e,t,l){let o=new Map,r=e=>{let t=e.parentElement;for(;null!==t&&!F(t);)t=t.parentElement;if(null===t)return null;let l=o.get(t);if(void 0===l){let e=r(t),i=t.querySelector(`:scope > ${f.tagNames.state}[bind-component]`).getAttribute("bind-component");o.set(t,l=[]);for(let o of n(t.getAttribute(f.bindAttributeName)??"")){let t=o.et;o.Ne[0]===i&&l.push([e?ee(e,t,1,0):t,o.Ne.slice(1).join("."),e&&t])}}return l},i=(e,t,l)=>{let n=r(e);if(null===n)return t;let o=/^([^|]*)#m\d+\.([^|]*)$/.exec(t);if(null===o)return l?t:ee(n,t,0,1)??t;let i=o[1].replace(/#m\d+\./g,"").slice(0,-1);return n.some(e=>""===e[1]&&(e[0]===i||e[2]===i))?o[2]:ee(n,o[2],2,1)??o[2]};for(let t of _(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let n=t.nextSibling;for(;null!==n&&!N(n,`@@wcs-${e[1]}-end:${e[2]}`);)n=n.nextSibling;if(null!==n){for(;t.nextSibling!==n;)t.nextSibling.remove();n.remove(),t.replaceWith(..."text"===e[1]?[w(`@@:${i(t,e[2],l)}`)]:[])}}let s=(e,l)=>{for(let n of _(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(n.data)?.[1],o=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===o)continue;let r=document.importNode(o,!0),a=f.bindAttributeName;r.removeAttribute("id"),r.setAttribute(a,r.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,o)=>t+i(l??n,o))),s(r.content,l??n);let c=r.content.firstChild;n.replaceWith(.../^\s*elseif\s*:/.test(c?.getAttribute?.(a)??"")?r.content.childNodes:[r])}};s(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(e,o,u):Z(e,o,s);s||te(t,h,g,v),queueMicrotask(function(e){let t=[];for(let l of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===l.localName){let e=Array.from(l.options),n=e.map(e=>e.selected),o=e.map(e=>e.hasAttribute("selected")),r=o.lastIndexOf(!0);r<0&&(r=e.findIndex(e=>!e.disabled)),(l.multiple?e.some((e,t)=>n[t]!==o[t]):l.selectedIndex!==r)&&t.push([l,()=>e.forEach((e,t)=>e.selected=n[t])])}else if("checkbox"===l.type||"radio"===l.type){let e=l.checked;e!==l.defaultChecked&&(e||"checkbox"===l.type)&&t.push([l,()=>l.checked=e])}else if("file"!==l.type&&l.value!==l.defaultValue){let e=l.value;t.push([l,()=>l.value=e])}return()=>{for(let[e,l]of t)e.isConnected&&(l(),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})))}}(g)),v(g),s&&(d.Te=se,queueMicrotask(()=>{H(),d.Te=null}))}(l),t?.(l,o)},function(){let e=globalThis;e[J]={build:U,reset(){R=0}},void 0===e[v]&&(e[v]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[J].build(t),reset:()=>e[J].reset()})}(),d.Co=p(d.Co,g);for(let e of l())g(e)}},ce=ae;export{ce as default,ae as ssr};
1
+ import{a as e}from"../chunks/chunk-T66VJGI5.js";import{b as t,c as l}from"../chunks/chunk-R6RHIIR4.js";import"../chunks/chunk-REB4RMZ3.js";import{h as n,i as r,j as o,k as i,l as s,m as a,n as c}from"../chunks/chunk-CYMUD7KV.js";import"../chunks/chunk-JJYM4JVZ.js";import{g as u}from"../chunks/chunk-IYPAK7PO.js";import{a as f}from"../chunks/chunk-AKTGQ6TC.js";import"../chunks/chunk-NAV7FBTI.js";import"../chunks/chunk-KBQKAD3I.js";import"../chunks/chunk-E3XSBW55.js";import{a as d,b as p}from"../chunks/chunk-LPJFTEVT.js";var m=e=>e.split(".").slice(0,2).join("."),h=class extends t{static find(e){return e.querySelector?.(f.tagNames.ssr)??null}get version(){return this.getAttribute("version")??""}get stateData(){let e=this.querySelector('script[type="application/json"]');return null===e?{}:JSON.parse(e.textContent||"{}")}get templates(){let e=new Map;for(let t of Array.from(this.children))"template"===t.localName&&e.set(t.id,t);return e}get hydrateProps(){return{}}getTemplate(e){return this.templates.get(e)??null}verifyVersion(){return m(this.version)===m(e)}};function g(e){let t=f.tagNames.ssr;void 0===e.get(t)&&e.define(t,class extends h{})}var b=()=>f.tagNames.ssr,v=Symbol.for("wcstack.ssr.snapshotBuilder"),y=()=>!0===document.documentElement?.hasAttribute("data-wcs-server"),w=e=>document.createComment(e),N=(e,t)=>null!==e&&8===e.nodeType&&e.data===t,A=(e,t)=>null!==e&&8===e.nodeType&&e.data.startsWith(t),S=new WeakMap,x=new WeakMap,k=new WeakMap,T=new WeakSet,$=new WeakMap;function I(e,t){let l=[];for(let n=e;null!==n&&(l.push(n),n!==t);n=n.nextSibling);return l}function W(e,t,...l){for(let l of Array.from(e.attributes))t.setAttribute(l.name,l.value);return(t.content??t).append(...l),t}var j=e=>{let t=e.nextSibling;return 1!==e.nodeType||"a"!==t?.localName||!t.hasAttribute("data-wcs-ssr-link")&&e.anchorElement!==t?null:t};function C(e,t,l,n){let r=w(null===n?"wcs-[":`wcs-[:${n}`),o=w("wcs-]");l.length>0&&l[0].Re().before(...I(e,t)),t.after(r);for(let e of l)null===n&&e.Re().before(w("wcs-|"));let i=l.length>0?(e=>null===e.B?e.dt:e.B[e.B.length-1])(l[l.length-1]):r;(j(i)??i).after(o);for(let e of I(r,o))T.add(e)}function E(e){if(e instanceof n){C(e.$,e.$,e.Ae,null);for(let t of e.Ae)q(t);return}let t=e.D;null!==t&&(C(e.W[e.y].$,e.W[e.W.length-1].$,[t],e.y),q(t))}function q(e){if(null!==e.u)for(let t of e.u)E(t)}var M=new Set(["script","style","template","textarea","title"]),R="data-wcs-raw",O=e=>M.has(e.localName)||e.localName===b();function P(e){for(let t of Array.from(e.childNodes))3===t.nodeType?""===t.data?t.replaceWith(w("wcs-e")):null!==t.nextSibling&&3===t.nextSibling.nodeType&&t.after(w("wcs-s")):1===t.nodeType&&!O(t)&&P(t)}var Y=0;function B(t,l){let n=t.getRootNode(),r=[l];for(let e of x.get(n)??[])e!==l&&!0===e.element?.hasAttribute("bind-component")&&r.push(e);let o=new Map;for(let e of r){let t=S.get(e);if(void 0===t)continue;let l=new Map;for(let t of e.H.values())if(null!==t.S&&l.set(t.S.$,t.S),null!==t.j)for(let e of t.j)l.set(e.$,e);for(let t of e.ie.values())for(let e of t)if(null!==e.I)for(let t of e.I.W)l.set(t.$,e.I);let n=new Set;for(let[e,r]of t){o.set(e,r);let t=l.get(e);void 0!==t&&!n.has(t)&&e.isConnected&&(n.add(t),E(t))}}for(let e of Array.from(n.querySelectorAll("*"))){let t=k.get(e);if(void 0!==t){let l=document.createTreeWalker(e,133,{acceptNode:e=>T.has(e)||1===e.nodeType&&t.has(e)&&K(e)?2:1}),n=[];for(let e=l.nextNode();null!==e;e=l.nextNode()){let l=e.previousSibling;(3===e.nodeType?e.data.includes("{{")&&!(O(e.parentNode)?$.has(e):t.has(l)&&A(l,"wcs-t:"))&&($.has(e)||t.get(e)!==e.data):!t.has(e))&&n.push(e)}for(let e of n)e.remove()}let l=Array.from(e.childNodes);O(e)&&l.some(e=>$.has(e))&&e.setAttribute(R,l.map(e=>$.has(e)?`{{ ${$.get(e)} }}`:8===e.nodeType?`\x3c!--${e.data}--\x3e`:e.textContent).join(""))}P(9===n.nodeType?n.body:n);let i=document.createElement(b());i.setAttribute("version",e);let s=document.createElement("script");s.type="application/json",s.textContent=function(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}(function(e){let t={};for(let l of Object.keys(e)){if("$"===l[0])continue;let n=Object.getOwnPropertyDescriptor(e,l);void 0!==n.get||void 0!==n.set||"function"==typeof n.value||(t[l]=n.value)}return t}(l.target)),i.append(s);for(let[e,t]of o){if(!e.isConnected)continue;let l=e.parentNode;for(;null!==l&&"svg"!==l.localName&&"foreignObject"!==l.localName;)l=l.parentElement;let n="svg"===l?.localName,r=`wcs-${n?"s":"t"}${Y++}`;e.replaceWith(w(`wcs-p:${r}`));let o=document.importNode(c(t),!0);for(let e of Array.from(o.querySelectorAll("template")))"http://www.w3.org/2000/svg"===e.namespaceURI&&e.replaceWith(W(e,document.createElement("template"),...e.childNodes));if(n){let e=document.createElementNS(l.namespaceURI,"svg");e.append(o),o=e}let s=document.createElement("template");s.id=r,i.append(W(t,s,o))}t.before(i)}function V(e){!function(e){if(null!==e.querySelector(f.tagNames.state))for(let t of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===t.localName){let e=Array.from(t.options);if(t.multiple||e.some(e=>e.hasAttribute("selected"))||e[t.selectedIndex]!==e.find(e=>!e.disabled))for(let t of e)t.toggleAttribute("selected",t.selected)}else"textarea"===t.localName?t.value!==t.defaultValue&&!t.value.includes("{{")&&!Array.from(t.childNodes).some(e=>$.has(e))&&(t.textContent=t.value):"checkbox"===t.type||"radio"===t.type?t.toggleAttribute("checked",t.checked):"password"!==t.type&&t.value!==t.defaultValue&&t.setAttribute("value",t.value)}(e);for(let t of Array.from(e.querySelectorAll(`${f.tagNames.state}[enable-ssr]`))){if(t.hasAttribute("mount")||t.hasAttribute("bind-component")||t.previousElementSibling?.localName===b())continue;let e=t.engine;null!=e&&B(t,e)}}var J=Symbol.for("wcstack.state.ssr.impl"),D=new Map,U=new WeakMap,K=e=>!0===d.Po?.(e),L=e=>1===e.nodeType&&!O(e)&&!K(e),z=e=>e.d.flat().concat(e.Y??[]),F=e=>{for(let t of z(e))t.remove()};function G(e,t,l){let n=/^wcs-\[(?::(\d+))?/.exec(e.data),r=e.previousSibling,o=e.parentNode,i=[],a=e.nextSibling;for(e.remove();null!==a&&!N(a,"wcs-]");){let e=a.nextSibling;if(N(a,"wcs-|"))i.push([]),a.remove();else{0===i.length&&i.push([]);let l=i[i.length-1];A(a,"wcs-[")?e=G(a,t,l):(l.push(a),L(a)&&H(a,t))}a=e}let c={branch:void 0===n[1]?null:Number(n[1]),d:i,Y:a??o.appendChild(w("wcs-]"))},u=z(c);a=c.Y.nextSibling;for(let e of u)l?.push(e),t&&s.add(e);return t&&null!==r?D.set(r,c):F(c),a}function H(e,t){for(let l=e.firstChild;null!==l;)A(l,"wcs-[")?l=G(l,t):(L(l)&&H(l,t),l=l.nextSibling)}function Q(e,t,l){let n=e=>{for(let r of Array.from(e.childNodes))if(r.parentNode===e)if(8===r.nodeType){let e=r.data;try{if("wcs-s"===e)r.remove();else if("wcs-e"===e)r.replaceWith("");else if(e.startsWith("wcs-t:")){let t=w(`@@:${decodeURIComponent(e.slice(6))}`),l=r.nextSibling;for(;null!==l&&!N(l,"wcs-/t");){let e=l.nextSibling;l.remove(),l=e}l?.remove(),r.replaceWith(t)}else if(e.startsWith("wcs-p:")){let l=t.querySelector(`template[id="${e.slice(6)}"]`);if(null!==l){let t=r.parentNode,n="s"===e[10]?W(l,document.createElementNS(t.namespaceURI,"template"),...document.importNode(l.content.firstChild,!0).childNodes):document.importNode(l,!0);n.removeAttribute("id"),t.replaceChild(n,r)}}}catch{}}else 1===r.nodeType&&!O(r)&&(K(r)?U.set(r,{ssr:t,Te:l}):n(r))};n(e),function(e){for(let t of Array.from(e.querySelectorAll("table > tbody"))){let e=[];for(let l=t.previousSibling;null!==l&&(8===l.nodeType||re(l)||"template"===l.localName);l=l.previousSibling)e.unshift(l);let l=0,n=0;if(e.forEach((e,t)=>{A(e,"wcs-[")?n++:N(e,"wcs-]")&&--n<0&&(n=0,l=t+1)}),0===n)continue;let r=0;for(let n=t.firstChild;null!==n;n=n.nextSibling)if(A(n,"wcs-["))r++;else if(N(n,"wcs-]")&&0===r--){t.prepend(...e.slice(l));break}}}(e),H(e,l)}function Z(e,t){let l=U.get(e);if(void 0===l)return null;U.delete(e);let n=e=>Q(e,l.ssr,l.Te);if(l.Te||te(t,e,e,n),n(e),!l.Te)return null;let r=d.Te;return d.Te=se,()=>{d.Te=r,X()}}function X(){for(let e of D.values())F(e);D.clear()}function _(e){let t=[];for(let l=document.createTreeWalker(e,128);l.nextNode();)t.push(l.currentNode);return t}function ee(e,t,l,n){let r=null;for(let n of e){let e=n[l];null!==e&&(""===e||t===e||t.startsWith(`${e}.`))&&(null===r||e.length>r[l].length)&&(r=n)}let o=r?.[n];if(null==o)return null;let i=r[l],s=""===i?t:t.slice(i.length+1);return""===o?s:""===s?o:`${o}.${s}`}function te(e,t,l,n){let r=document.createElement("template").content;for(let e of l.childNodes)r.appendChild(r.ownerDocument.importNode(e,!0));n(r),e.root=t;let o=()=>{};a(e,[...r.childNodes],null,!0,o,o,o,(t,l)=>i(e,l,null,0))}function le(e,t,l){if(y()){if(l instanceof Array){for(let e=l.length;e-- >0;)r(l[e])&&l.splice(e,1);let e=t;if(l.some(o))T.add(e);else if(e.localName.includes("-")&&!K(e)){let t=new Map;for(let l=document.createTreeWalker(e,133);l.nextNode();)t.set(l.currentNode,l.currentNode.data);k.set(e,t)}return}if("string"==typeof l){if($.set(t,l),O(t.parentNode))return;let e=w(`wcs-t:${encodeURIComponent(l)}`),n=w("wcs-/t");return t.before(e),void t.after(n)}let n=S.get(e);void 0===n&&S.set(e,n=new Map),n.set(t,l);let i=t.getRootNode(),s=x.get(i);return void 0===s&&x.set(i,s=new Set),void s.add(e)}if("string"!=typeof l&&D.size>0){let e=D.get(l);void 0!==e&&(D.delete(l),D.set(t,e))}}var ne=e=>null!==e&&8===e.nodeType&&[f.commentIfPrefix,f.commentElseIfPrefix,f.commentElsePrefix].includes(e.data),re=e=>3===e.nodeType&&""===e.data.trim(),oe=e=>{let t=D.get(e)?.Y??e;return(j(t)??t).nextSibling};function ie(e,t){if(t.length!==e.It.childNodes.length)return!1;let l=e.an;for(let n=0;n<l.length;n++){let r=l[n],o=e.It,i=t[r[0]];for(let e=0;;){if(o=o.childNodes[r[e]],i?.nodeName!==o.nodeName)return!1;if(++e===r.length)break;i=(j(i)??i).firstChild;for(let t=r[e];t>0&&null!==i;t--)i=oe(i)}e.No[n]=i}return!0}function se(e,t,l){if(0===D.size)return null;let n=t,r=0;if(!l){let e=f.commentIfPrefix;if(!N(t,e))for(let l=t.previousSibling;null!==l&&1!==l.nodeType&&(ne(l)&&r++,!N(l,e));l=l.previousSibling);for(let l=t.nextSibling;!D.has(n)&&null!==l&&!N(l,e)&&1!==l.nodeType;l=l.nextSibling)ne(l)&&(n=l)}let o=D.get(n);if(void 0===o)return null;if(!l&&o.branch!==r)return D.delete(n),F(o),null;let i=o.d.shift();if(0===o.d.length&&D.delete(n),o.Y?.replaceWith(...I(t,n)),o.Y=null,void 0===i)return null;let s=[];for(let e=0;e<i.length;e++){let t=D.get(i[e]);if(s.push(i[e]),void 0!==t)for(;e<i.length&&i[e]!==t.Y;)e++;else j(i[e])===i[e+1]&&e++}if(!ie(e,s)){let l=(e.Ln?e.root:e.It).cloneNode(!0);s=e.Ln?[l]:[...l.childNodes],ie(e,s),(i[0]??o.d.find(e=>e.length>0)?.[0]??t).before(l);for(let e of i)e.remove()}return s}var ae={name:"ssr",hooks:d,install(){d.Bn=le,d.wr=Z;let t=d.element;d.element=(l,n)=>{"mounting"===n&&function(t){let l=t.element;if(!l.hasAttribute("enable-ssr")||y())return;let n=l.previousElementSibling,r=n?.localName===b(),o=r?n.getAttribute("version"):null,i=null===o||m(o)===m(e);if(i){let e=t,l=e.xe;e.xe=(e,n)=>"$connectedCallback"===e?void 0:l.call(t,e,n)}if(!r)return;let s=!i&&parseInt(o)<4,a=/^3\.(\d+)\.(\d+)$/.exec(o),c=null!==a&&(+a[1]-5||+a[2]-3)>=0;i||console.warn(`[@wcstack/state] <${b()} version="${o}"> does not match ${e}: its snapshot is discarded, and the page renders on the client from its own state.${s&&!c?" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.":""}`);let p=i?n.querySelector('script[type="application/json"]'):null;if(null!==p){let e=JSON.parse(p.textContent||"{}"),l=t.target;for(let t of Object.keys(e)){let n=Object.getOwnPropertyDescriptor(l,t);void 0!==n&&(void 0!==n.get||void 0!==n.set||"function"==typeof n.value)||(l[t]=e[t])}t.hydrated=!0}let h=l.getRootNode();for(let e of Array.from(h.querySelectorAll(`[${R}]`)))e.textContent=e.getAttribute(R),e.removeAttribute(R);let g=9===h.nodeType?h.body:h;n.remove();let v=e=>s?function(e,t,l){let n=new Map,r=e=>{let t=e.parentElement;for(;null!==t&&!K(t);)t=t.parentElement;if(null===t)return null;let l=n.get(t);if(void 0===l){let e=r(t),o=t.querySelector(`:scope > ${f.tagNames.state}[bind-component]`).getAttribute("bind-component");n.set(t,l=[]);for(let n of u(t.getAttribute(f.bindAttributeName)??"")){let t=n.et;n.ye[0]===o&&l.push([e?ee(e,t,1,0):t,n.ye.slice(1).join("."),e&&t])}}return l},o=(e,t,l)=>{let n=r(e);if(null===n)return t;let o=/^([^|]*)#m\d+\.([^|]*)$/.exec(t);if(null===o)return l?t:ee(n,t,0,1)??t;let i=o[1].replace(/#m\d+\./g,"").slice(0,-1);return n.some(e=>""===e[1]&&(e[0]===i||e[2]===i))?o[2]:ee(n,o[2],2,1)??o[2]};for(let t of _(e).reverse()){let e=/^@@wcs-(\w+)-start:([\s\S]*)/.exec(t.data);if(null===e)continue;let n=t.nextSibling;for(;null!==n&&!N(n,`@@wcs-${e[1]}-end:${e[2]}`);)n=n.nextSibling;if(null!==n){for(;t.nextSibling!==n;)t.nextSibling.remove();n.remove(),t.replaceWith(..."text"===e[1]?[w(`@@:${o(t,e[2],l)}`)]:[])}}let i=(e,l)=>{for(let n of _(e)){let e=/^@@wcs-(?:for|if|elseif|else):(\S+)$/.exec(n.data)?.[1],r=Array.from(t.querySelectorAll("template")).find(t=>t.id===e);if(void 0===r)continue;let s=document.importNode(r,!0),a=f.bindAttributeName;s.removeAttribute("id"),s.setAttribute(a,s.getAttribute(a).replace(/^(\s*\w+\s*:\s*)([^\s|]+)/,(e,t,r)=>t+o(l??n,r))),i(s.content,l??n);let c=s.content.firstChild;n.replaceWith(.../^\s*elseif\s*:/.test(c?.getAttribute?.(a)??"")?s.content.childNodes:[s])}};i(e);for(let t of Array.from(e.querySelectorAll("[data-wcs-ssr-id]")))t.removeAttribute("data-wcs-ssr-id")}(e,n,c):Q(e,n,i);i||te(t,h,g,v),queueMicrotask(function(e){let t=[];for(let l of Array.from(e.querySelectorAll("input,textarea,select")))if("select"===l.localName){let e=Array.from(l.options),n=e.map(e=>e.selected),r=e.map(e=>e.hasAttribute("selected")),o=r.lastIndexOf(!0);o<0&&(o=e.findIndex(e=>!e.disabled)),(l.multiple?e.some((e,t)=>n[t]!==r[t]):l.selectedIndex!==o)&&t.push([l,()=>e.forEach((e,t)=>e.selected=n[t])])}else if("checkbox"===l.type||"radio"===l.type){let e=l.checked;e!==l.defaultChecked&&(e||"checkbox"===l.type)&&t.push([l,()=>l.checked=e])}else if("file"!==l.type&&l.value!==l.defaultValue){let e=l.value;t.push([l,()=>l.value=e])}return()=>{for(let[e,l]of t)e.isConnected&&(l(),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})))}}(g)),v(g),i&&(d.Te=se,queueMicrotask(()=>{X(),d.Te=null}))}(l),t?.(l,n)},function(){let e=globalThis;e[J]={build:V,reset(){Y=0}},void 0===e[v]&&(e[v]={protocol:"wcs-ssr-snapshot",version:1,build:t=>e[J].build(t),reset:()=>e[J].reset()})}(),d.Io=p(d.Io,g);for(let e of l())g(e)}},ce=ae;export{ce as default,ae as ssr};
2
2
  //# sourceMappingURL=ssr.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["majorMinor","v","split","slice","join","Ssr","HTMLElementBase","find","root","querySelector","config","tagNames","ssr","version","this","getAttribute","stateData","script","JSON","parse","textContent","templates","map","Map","t","Array","from","children","localName","set","id","hydrateProps","getTemplate","get","verifyVersion","VERSION","defineSsr","registry","tag","define","BUILDER","Symbol","for","isServer","document","documentElement","hasAttribute","mark","data","createComment","isMark","n","nodeType","startsMark","prefix","startsWith","anchors","WeakMap","enginesByRoot","kept","skip","WeakSet","rawTexts","range","to","out","push","nextSibling","attrs","content","a","attributes","setAttribute","name","value","append","beside","anchorElement","region","blocks","branch","open","close","length","head","before","after","b","last","nodes","first","lastOf","add","visitView","ForView","anchor","rowViews","visitBlock","cur","current","branches","index","c","RAW","Set","RAW_ATTR","raw","el","has","protectTexts","parent","childNodes","replaceWith","ids","snapshot","engine","getRootNode","engines","E","element","own","byAnchor","l","rootLists","values","view","extra","bs","rootBindings","chain","br","done","template","isConnected","h","querySelectorAll","w","createTreeWalker","acceptNode","scoped","nextNode","p","previousSibling","includes","parentNode","remove","cs","some","body","createElement","type","stringify","replace","charCodeAt","toString","padStart","json","target","key","Object","keys","d","getOwnPropertyDescriptor","e","parentElement","svg","importNode","templateContent","x","namespaceURI","createElementNS","build","doc","state","o","options","multiple","selectedIndex","disabled","toggleAttribute","selected","defaultValue","checked","forms","previousElementSibling","IMPL","held","deferred","hooks","componentScope","enters","nodesOf","r","rows","flat","concat","tail","drop","read","start","keep","row","m","exec","next","strip","Number","appendChild","walked","firstChild","prepare","container","adopt","walk","text","decodeURIComponent","copy","removeAttribute","replaceChild","run","isBlank","unshift","forEach","i","depth","prepend","mend","adoptScope","host","delete","undo","plan","prev","release","clear","comments","scope","currentNode","across","wiring","path","best","k","rest","ownerDocument","none","walkBindings","_","expr","textSpec","ssrMark","node","source","isOuter","splice","setsContent","encodeURIComponent","es","size","isIfAnchor","commentIfPrefix","commentElseIfPrefix","commentElsePrefix","trim","fits","fragment","paths","nodePaths","j","nodeName","scratch","isFor","shift","inner","fresh","single","cloneNode","install","phase","found","same","callHook","args","call","old","parseInt","console","warn","snap","hydrated","wirings","wiringOf","up","prop","parseBindTextsForElement","bindAttributeName","at","statePathName","propSegments","asIs","reverse","restore","f","test","legacy","queueMicrotask","edits","sel","marked","lastIndexOf","findIndex","defaultChecked","put","dispatchEvent","Event","bubbles","typed","hydrate","g","globalThis","reset","protocol","installBuilder","tags","registries","ssr_default"],"sources":["../../../src/ssr/element.ts","../../../src/ssr/ssr.ts","../../../src/features/ssr.ts"],"sourcesContent":["/**\n * `<wcs-ssr>` (`config.tagNames.ssr`): the server's snapshot before a `<wcs-state enable-ssr>` —\n * `version`, the state's data (a JSON `<script>`) and the page-level templates. The SSR add-on\n * defines the tag; this class only reads the snapshot (the add-on hydrates from it and removes it).\n */\nimport { config } from \"../config\";\nimport { VERSION } from \"../version\";\nimport { HTMLElementBase } from \"../element\";\n\nexport interface ISsrElement {\n /** The @wcstack/state version that rendered the page. */\n readonly version: string;\n /** The state's data the server rendered with. */\n readonly stateData: Record<string, any>;\n /** The page-level templates, by id. */\n readonly templates: Map<string, HTMLTemplateElement>;\n /** Always empty: every binding is applied when the client adopts the server's DOM (3.x kept a value table here). */\n readonly hydrateProps: Record<string, Record<string, unknown>>;\n getTemplate(id: string): HTMLTemplateElement | null;\n /** The snapshot is adoptable: the same major.minor as this build. */\n verifyVersion(): boolean;\n}\n\n/** `4.0.1` → `4.0`: a snapshot is adoptable by the same major.minor. */\nexport const majorMinor = (v: string): string => v.split(\".\").slice(0, 2).join(\".\");\n\nexport class Ssr extends HTMLElementBase implements ISsrElement {\n /** The first snapshot element under `root`, or null. */\n static find(root: Node): ISsrElement | null {\n return ((root as ParentNode).querySelector?.(config.tagNames.ssr) as Ssr | null) ?? null;\n }\n\n get version(): string {\n return this.getAttribute(\"version\") ?? \"\";\n }\n\n get stateData(): Record<string, any> {\n const script = this.querySelector('script[type=\"application/json\"]');\n return script === null ? {} : JSON.parse(script.textContent || \"{}\");\n }\n\n get templates(): Map<string, HTMLTemplateElement> {\n const map = new Map<string, HTMLTemplateElement>();\n // quoted: `children` is an internal name the bundles shorten (mangle.mjs)\n for (const t of Array.from(this[\"children\"])) if (t.localName === \"template\") map.set(t.id, t as HTMLTemplateElement);\n return map;\n }\n\n get hydrateProps(): Record<string, Record<string, unknown>> {\n return {};\n }\n\n getTemplate(id: string): HTMLTemplateElement | null {\n return this.templates.get(id) ?? null;\n }\n\n verifyVersion(): boolean {\n return majorMinor(this.version) === majorMinor(VERSION);\n }\n}\n\n/** Defines `<wcs-ssr>` in `registry` (once per registry). */\nexport function defineSsr(registry: CustomElementRegistry): void {\n const tag = config.tagNames.ssr;\n if (registry.get(tag) === undefined) registry.define(tag, class extends Ssr {});\n}\n","/**\n * Server-side rendering with @wcstack/server (README \"Server-Side Rendering\"), for\n * `<wcs-state enable-ssr>` roots.\n *\n * Server (`<html data-wcs-server>`): the page renders as usual; the snapshot builder\n * (`Symbol.for(\"wcstack.ssr.snapshotBuilder\")`, called by the server before it serializes)\n * then makes the DOM adoptable:\n * - every view's rows / branch move right after its anchor, between `<!--wcs-[-->` and\n * `<!--wcs-]-->`, each row opened by `<!--wcs-|-->` (a branch region carries its index,\n * `<!--wcs-[:i-->`, and follows the chain's last anchor so the chain's templates stay adjacent);\n * - a page-level anchor becomes `<!--wcs-p:ID-->`, its template kept in `<wcs-ssr>` as\n * `<template id=ID>`; a page-level text binding (a mustache, a comment binding) is wrapped in\n * `<!--wcs-t:EXPR-->…<!--wcs-/t-->` (the client puts a comment binding back);\n * - adjacent text nodes are separated (`<!--wcs-s-->`) and empty ones kept (`<!--wcs-e-->`), so\n * parsing the HTML gives back the rows' exact structure;\n * - `<wcs-ssr version>` before the element holds the state's data (JSON) and the templates.\n *\n * Client: before the page is bound, the texts and templates are restored and the regions read where\n * they are (their marks go; the page's walk passes their nodes by); each block the engine builds\n * takes its region's next row instead of a clone (a row's nested regions wait for its nested views\n * in turn). The server's nodes never leave the page — no custom element in a row or a branch is\n * disconnected — and get their bindings; a view's anchors move after its rows instead. A row that\n * does not fit its plan is built anew in its place, and the rows no view took go once the page is\n * bound. `$connectedCallback` does not run (the server ran it).\n *\n * A snapshot of another major.minor is discarded, and the page renders on the client as it would\n * without a server: the state comes from its own source, `$connectedCallback` runs, and the server's\n * rows and marks give way to the templates they came from — those of @wcstack/server 3.x's output\n * too (`legacy`). They give way only once the page was planned on a copy: markup this client cannot\n * plan fails its initialization with the server's HTML left as it was.\n *\n * Not carried over from @wcstack/state 3.3 (approved): the inline snapshot for servers without\n * the builder protocol, and the property value table (every binding is applied on adoption).\n */\nimport type { Engine } from \"../engine\";\nimport { ForView, type Block, type IfView, type RowPlan, type Spec } from \"../dom/view\";\nimport { config } from \"../config\";\nimport { hooks } from \"../hooks\";\n\nimport { VERSION } from \"../version\";\nimport { isOuter, setsContent, templateContent, textSpec, walkBindings, walked } from \"../dom/plan\";\nimport { majorMinor } from \"./element\";\nimport { parseBindTextsForElement } from \"../parser/parseBindTextsForElement\";\n/** The snapshot element's tag (`config.tagNames.ssr`, `wcs-ssr` by default). */\nconst tag = (): string => config.tagNames.ssr;\nconst BUILDER = Symbol.for(\"wcstack.ssr.snapshotBuilder\");\n\nexport const isServer = (): boolean => document.documentElement?.hasAttribute(\"data-wcs-server\") === true;\n\nconst mark = (data: string): Comment => document.createComment(data);\nconst isMark = (n: Node | null, data: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data === data;\nconst startsMark = (n: Node | null, prefix: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data.startsWith(prefix);\n\n// ---------------------------------------------------------------- server\n\n/** Page-level anchors (the walker's) and the template each replaced, by engine. */\nconst anchors = new WeakMap<Engine, Map<Node, Element>>();\n/** The engines that recorded anchors in a page (its root node): the page's, and its Light DOM components'. */\nconst enginesByRoot = new WeakMap<Node, Set<Engine>>();\n/**\n * The custom elements the page's walker bound, with the nodes in them then (and a text's data): the\n * walk is post-order, so its anchors, text marks and rows are there, and the element's own bindings\n * have not written yet. What an element renders from a value comes later: in the server's HTML the\n * client would walk it as the page's markup (a user's `{{ … }}`, a `data-wcs` in sanitized HTML),\n * so the snapshot leaves it — and a text with `{{` that it was not then (a value's, in a node of\n * its own or one the page wrote) — to the client.\n */\nconst kept = new WeakMap<Node, Map<Node, string>>();\n/** What the client does not walk: a region (rows it adopts), an element whose content a binding sets. */\nconst skip = new WeakSet<Node>();\n/**\n * Mustache texts: their expressions. In an element whose content is text (`<textarea>`, `<title>`),\n * a mark would be text to the browser, and the value the client's markup: the element takes its\n * template along instead (`data-wcs-raw`), and the client puts it back before binding the page.\n */\nconst rawTexts = new WeakMap<Node, string>();\n\n/** Nodes from `from` to `to`, siblings, inclusive. */\nfunction range(from: Node, to: Node): Node[] {\n const out: Node[] = [];\n for (let n: Node | null = from; n !== null; n = n.nextSibling) {\n out.push(n);\n if (n === to) break;\n }\n return out;\n}\n\n/** `to` with `from`'s attributes, and `content` (into a template's content when it has one). */\nfunction attrs<T extends Element>(from: Element, to: T, ...content: Node[]): T {\n for (const a of Array.from(from.attributes)) to.setAttribute(a.name, a.value);\n ((to as unknown as HTMLTemplateElement).content ?? to).append(...content);\n return to;\n}\n\nconst lastOf = (b: Block): Node => (b.nodes === null ? b.first : b.nodes[b.nodes.length - 1]);\n\n/**\n * The anchor `<wcs-link>` (@wcstack/router) renders right after itself, its children moved into it:\n * the server's is marked `data-wcs-ssr-link`, and is the link's `anchorElement` once the router took\n * it (dropping the mark). In a row it is the link's: the link's children are there.\n */\nconst beside = (n: Node): Node | null => {\n const a = n.nextSibling as Element | null;\n return n.nodeType === 1 && a?.localName === \"a\" && (a.hasAttribute(\"data-wcs-ssr-link\") || (n as any).anchorElement === a) ? a : null;\n};\n\n/**\n * Makes the blocks one region right after the anchors `from` … `to` (a view renders its blocks before\n * its anchor; a branch before its own, the chain's later anchors after it). The anchors move, not the\n * blocks: a custom element in a row is not disconnected, so what it rendered as it connected stays\n * (`<wcs-link>` renders its anchor a microtask later, and would not again before the server serializes).\n */\nfunction region(from: Node, to: Node, blocks: Block[], branch: number | null): void {\n const open = mark(branch === null ? \"wcs-[\" : `wcs-[:${branch}`);\n const close = mark(\"wcs-]\");\n if (blocks.length > 0) (blocks[0].head() as ChildNode).before(...range(from, to));\n (to as ChildNode).after(open);\n for (const b of blocks) if (branch === null) b.head().before(mark(\"wcs-|\"));\n const last = blocks.length > 0 ? lastOf(blocks[blocks.length - 1]) : open;\n ((beside(last) ?? last) as ChildNode).after(close);\n for (const n of range(open, close)) skip.add(n);\n}\n\nfunction visitView(v: ForView | IfView): void {\n if (v instanceof ForView) {\n region(v.anchor, v.anchor, v.rowViews, null);\n for (const b of v.rowViews) visitBlock(b);\n return;\n }\n const cur = v.current;\n if (cur === null) return;\n region(v.branches[v.index].anchor, v.branches[v.branches.length - 1].anchor, [cur], v.index);\n visitBlock(cur);\n}\n\nfunction visitBlock(b: Block): void {\n if (b.children !== null) for (const c of b.children) visitView(c);\n}\n\nconst RAW = new Set([\"script\", \"style\", \"template\", \"textarea\", \"title\"]);\nconst RAW_ATTR = \"data-wcs-raw\";\nconst raw = (el: Element): boolean => RAW.has(el.localName) || el.localName === tag();\n\n/** Keeps every text node a text node through HTML serialization and parsing. */\nfunction protectTexts(parent: Node): void {\n for (const n of Array.from(parent.childNodes)) {\n if (n.nodeType === 3) {\n if ((n as Text).data === \"\") n.replaceWith(mark(\"wcs-e\"));\n else if (n.nextSibling !== null && n.nextSibling.nodeType === 3) n.after(mark(\"wcs-s\"));\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n protectTexts(n);\n }\n }\n}\n\nfunction json(value: unknown): string {\n return JSON.stringify(value).replace(/[<>&\\u2028\\u2029]/g, (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`);\n}\n\n/** The state's own data (no `$` keys, no accessors, no functions). */\nfunction data(target: Record<string, any>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(target)) {\n if (key[0] === \"$\") continue;\n const d = Object.getOwnPropertyDescriptor(target, key)!;\n if (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\") continue;\n out[key] = d.value;\n }\n return out;\n}\n\nlet ids = 0;\n\nfunction snapshot(el: Element, engine: Engine): void {\n const root = el.getRootNode() as Document | ShadowRoot;\n // the page's engine, and those of the Light DOM components in it: their walkers' anchors are in\n // the page too (a Shadow DOM component's are in its own shadow root)\n const engines = [engine];\n for (const E of enginesByRoot.get(root) ?? []) {\n if (E !== engine && (E.element as Element | null)?.hasAttribute(\"bind-component\") === true) engines.push(E);\n }\n const map = new Map<Node, Element>();\n for (const E of engines) {\n const own = anchors.get(E);\n if (own === undefined) continue;\n // the views the walker made, top down (a nested view's region stays inside its row's)\n const byAnchor = new Map<Node, ForView | IfView>();\n for (const l of E.rootLists.values()) {\n if (l.view !== null) byAnchor.set(l.view.anchor, l.view);\n if (l.extra !== null) for (const v of l.extra) byAnchor.set(v.anchor, v);\n }\n for (const bs of E.rootBindings.values()) {\n for (const b of bs) if (b.chain !== null) for (const br of b.chain.branches) byAnchor.set(br.anchor, b.chain);\n }\n const done = new Set<ForView | IfView>();\n for (const [anchor, template] of own) {\n map.set(anchor, template);\n const v = byAnchor.get(anchor);\n if (v !== undefined && !done.has(v) && anchor.isConnected) {\n done.add(v);\n visitView(v);\n }\n }\n }\n for (const h of Array.from(root.querySelectorAll(\"*\"))) {\n const own = kept.get(h);\n if (own !== undefined) {\n // what the client does not walk is left: what `skip` has, and — the page's — a Light DOM\n // component (bound later, by its own engine). A text without `{{` is no markup to the client,\n // whoever wrote it; one the page wrote is left as it was written, and a mustache's where the\n // client puts its expression back: right after its mark (the client replaces what follows it),\n // or in a text element (`data-wcs-raw`). Elsewhere it goes: an element may drop comments, or\n // move a text element's text out, and its value would be the client's markup\n const w = document.createTreeWalker(h, 133, {\n acceptNode: (n) => (skip.has(n) || (n.nodeType === 1 && own.has(n) && scoped(n as Element)) ? 2 : 1),\n });\n const out: ChildNode[] = [];\n for (let n = w.nextNode(); n !== null; n = w.nextNode()) {\n const p = n.previousSibling!;\n if (n.nodeType === 3\n ? (n as Text).data.includes(\"{{\")\n && !(raw(n.parentNode as Element) ? rawTexts.has(n) : own.has(p) && startsMark(p, \"wcs-t:\"))\n && (rawTexts.has(n) || own.get(n) !== (n as Text).data)\n : !own.has(n)) out.push(n as ChildNode);\n }\n for (const n of out) n.remove();\n }\n const cs = Array.from(h.childNodes);\n if (raw(h) && cs.some((c) => rawTexts.has(c))) {\n // (a comment there — a server's DOM may parse one in a <textarea> — is text to a browser)\n h.setAttribute(RAW_ATTR, cs.map((c) => (rawTexts.has(c) ? `{{ ${rawTexts.get(c)} }}` : c.nodeType === 8 ? `<!--${(c as Comment).data}-->` : c.textContent)).join(\"\"));\n }\n }\n protectTexts(root.nodeType === 9 ? (root as Document).body : root);\n const ssr = document.createElement(tag());\n ssr.setAttribute(\"version\", VERSION);\n const script = document.createElement(\"script\");\n script.type = \"application/json\";\n script.textContent = json(data(engine.target));\n ssr.append(script);\n for (const [anchor, template] of map) {\n if (!anchor.isConnected) continue;\n // the anchor's context, by name (a server's DOM may not know <foreignObject> leads back to HTML):\n // SVG under <svg> — its id says so (`wcs-s…`) — and HTML under <foreignObject>\n let e = anchor.parentNode as Element | null;\n while (e !== null && e.localName !== \"svg\" && e.localName !== \"foreignObject\") e = e.parentElement;\n const svg = e?.localName === \"svg\";\n const id = `wcs-${svg ? \"s\" : \"t\"}${ids++}`;\n (anchor as ChildNode).replaceWith(mark(`wcs-p:${id}`));\n let c: Node = document.importNode(templateContent(template as HTMLTemplateElement), true);\n // a template in it that is an SVG element goes as an HTML one, which a serializer reads (the\n // client's parser reads it back in its context)\n for (const x of Array.from((c as Element).querySelectorAll(\"template\"))) {\n // by namespace, not `instanceof SVGElement`: a server window (@wcstack/server) need not expose that global\n if (x.namespaceURI === \"http://www.w3.org/2000/svg\") x.replaceWith(attrs(x, document.createElement(\"template\"), ...x.childNodes));\n }\n // an SVG template's content goes in <svg>, so the client's parser reads it as SVG\n if (svg) {\n const w = document.createElementNS(e!.namespaceURI, \"svg\");\n w.append(c);\n c = w;\n }\n const t = document.createElement(\"template\");\n t.id = id;\n ssr.append(attrs(template, t, c));\n }\n el.before(ssr);\n}\n\n/**\n * The form controls' current state into their markup, as 3.x wrote it: an input's value (its\n * `value` attribute) and checkedness (`checked`), a textarea's value (its text), the options a\n * select has selected (`selected`) — whatever set them (a `value:` / `checked:` / `selectedIndex:`\n * binding, `radio:`, a row's), where it differs from what the markup gives back. The page then shows\n * the server's values before the client binds it, or without JS; the client's bindings find them\n * there, and write over them from then on. On a page with a `<wcs-state>` only (enable-ssr or not).\n * A password's value never goes into the HTML (3.x wrote it): the client's binding fills it in.\n */\nfunction forms(doc: Document): void {\n if (doc.querySelector(config.tagNames.state) === null) return;\n for (const n of Array.from(doc.querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n // (a single select without a marked option, its first enabled one selected: what a parser selects)\n if (n.multiple || o.some((x) => x.hasAttribute(\"selected\")) || o[n.selectedIndex] !== o.find((x) => !x.disabled)) {\n for (const x of o) x.toggleAttribute(\"selected\", x.selected);\n }\n } else if (n.localName === \"textarea\") {\n // (a value with `{{` in it would be the client's markup there, a mustache; a mustache in it is\n // the client's to put back — see snapshot: both left to the client)\n if (n.value !== n.defaultValue && !n.value.includes(\"{{\") && !Array.from(n.childNodes).some((c) => rawTexts.has(c as Node))) n.textContent = n.value;\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n n.toggleAttribute(\"checked\", n.checked);\n } else if (n.type !== \"password\" && n.value !== n.defaultValue) {\n n.setAttribute(\"value\", n.value);\n }\n }\n}\n\n/** The builder the server calls before it serializes (protocol wcs-ssr-snapshot v1). */\nfunction build(doc: Document): void {\n // first: moving the rows into their regions (snapshot) may change what a select has selected\n forms(doc);\n for (const el of Array.from(doc.querySelectorAll(`${config.tagNames.state}[enable-ssr]`))) {\n if (el.hasAttribute(\"mount\") || el.hasAttribute(\"bind-component\")) continue;\n if (el.previousElementSibling?.localName === tag()) continue;\n const engine = (el as any).engine as Engine | null;\n if (engine !== null && engine !== undefined) snapshot(el, engine);\n }\n}\n\n/** Where the builder finds this module: the latest evaluation (a server may load one per render). */\nconst IMPL = Symbol.for(\"wcstack.state.ssr.impl\");\n\nexport function installBuilder(): void {\n const g = globalThis as any;\n g[IMPL] = { build, reset() { ids = 0; } };\n // another engine's builder (the current @wcstack/state) is not replaced\n if (g[BUILDER] === undefined) {\n g[BUILDER] = { protocol: \"wcs-ssr-snapshot\", version: 1, build: (doc: Document) => g[IMPL].build(doc), reset: () => g[IMPL].reset() };\n }\n}\n\n// ---------------------------------------------------------------- client\n\ninterface Region {\n /** The branch the region renders (null: a list). */\n readonly branch: number | null;\n /** Each row's nodes, where the server put them (a region in the row included). */\n readonly rows: Node[][];\n /**\n * The region's end mark, after its rows: the server put a view's rows after its anchor, and the view\n * renders them before it — the anchor goes here when the view takes the first row (null after).\n */\n tail: ChildNode | null;\n}\n\n/** Regions waiting for their view, by the node right before them (a view's anchor). */\nconst held = new Map<Node, Region>();\n\n/**\n * The Light DOM components of a page being hydrated, by host: their content is bound by their own\n * engine, which starts later (once its host is wired, or its class defined), so it keeps the\n * server's nodes until then and is prepared when that engine binds it (adoptScope).\n */\nconst deferred = new WeakMap<Node, { ssr: Element; adopt: boolean }>();\nconst scoped = (el: Element): boolean => hooks.componentScope?.(el) === true;\n\n/** An element regions may be in: not a text element, nor a Light DOM component (its engine reads its own). */\nconst enters = (n: Node): boolean => n.nodeType === 1 && !raw(n as Element) && !scoped(n as Element);\n\n/** A region's nodes: its rows', and its end mark. */\nconst nodesOf = (r: Region): Node[] => r.rows.flat().concat(r.tail ?? []);\n\n/** Takes a region's nodes out of the page (rows no view took, or not the plan's). */\nconst drop = (r: Region): void => {\n for (const n of nodesOf(r)) (n as ChildNode).remove();\n};\n\n/**\n * Reads the region `start` opens where it is: its marks go but its end mark, and its nodes stay (no\n * custom element in them is disconnected). It is held by the node before it, its view's anchor (the\n * page's walk then passes its nodes by: its blocks bind them where they are), or dropped (`keep`\n * false, or no node before it). A region in it — in a row, after a view's anchor of the row, or in an\n * element of it — is read in turn. Its nodes go in `row` (the row it is in); returns the node after it.\n */\nfunction read(start: Comment, keep: boolean, row?: Node[]): Node | null {\n const m = /^wcs-\\[(?::(\\d+))?/.exec(start.data)!;\n const key = start.previousSibling;\n const parent = start.parentNode!;\n const rows: Node[][] = [];\n let n: Node | null = start.nextSibling;\n start.remove();\n while (n !== null && !isMark(n, \"wcs-]\")) {\n let next: Node | null = n.nextSibling;\n if (isMark(n, \"wcs-|\")) {\n rows.push([]);\n (n as ChildNode).remove();\n } else {\n // (a branch has no row marks; a list's node before its first one is a value's)\n if (rows.length === 0) rows.push([]);\n const own = rows[rows.length - 1];\n if (startsMark(n, \"wcs-[\")) next = read(n as Comment, keep, own);\n else {\n own.push(n);\n if (enters(n)) strip(n, keep);\n }\n }\n n = next;\n }\n // (cut short — a parser moved its end mark into an element (see mend): it ends with its parent)\n const r: Region = { branch: m[1] === undefined ? null : Number(m[1]), rows, tail: (n ?? parent.appendChild(mark(\"wcs-]\"))) as ChildNode };\n const nodes = nodesOf(r);\n n = r.tail!.nextSibling;\n // (not spread: a region may have more nodes than a call takes arguments)\n for (const x of nodes) {\n row?.push(x);\n if (keep) walked.add(x);\n }\n if (keep && key !== null) {\n held.set(key, r);\n } else {\n drop(r);\n }\n return n;\n}\n\n/** Reads every region under `parent` (see read). */\nfunction strip(parent: Node, keep: boolean): void {\n for (let n: Node | null = parent.firstChild; n !== null; ) {\n if (startsMark(n, \"wcs-[\")) {\n n = read(n as Comment, keep);\n } else {\n if (enters(n)) strip(n, keep);\n n = n.nextSibling;\n }\n }\n}\n\n/** Texts and templates back to what the page was written with; the regions read (see strip). */\nfunction prepare(container: Node, ssr: Element, adopt: boolean): void {\n const walk = (parent: Node): void => {\n for (const n of Array.from(parent.childNodes)) {\n // a text marker takes the nodes up to its end with it\n if (n.parentNode !== parent) continue;\n if (n.nodeType === 8) {\n const d = (n as Comment).data;\n // (a mark the server did not write — in a value — that does not parse is left as it is;\n // a string given to replaceWith goes in as a text node)\n try {\n if (d === \"wcs-s\") n.remove();\n else if (d === \"wcs-e\") n.replaceWith(\"\");\n else if (d.startsWith(\"wcs-t:\")) {\n // the value between the markers, back to a text binding: a comment binding, which binds\n // whether or not the page's mustaches are on (it was a mustache, or a comment binding)\n const text = mark(`@@:${decodeURIComponent(d.slice(6))}`);\n let e: ChildNode | null = n.nextSibling;\n while (e !== null && !isMark(e, \"wcs-/t\")) {\n const next = e.nextSibling;\n e.remove();\n e = next;\n }\n e?.remove();\n n.replaceWith(text);\n } else if (d.startsWith(\"wcs-p:\")) {\n const t = ssr.querySelector(`template[id=\"${d.slice(6)}\"]`) as HTMLTemplateElement | null;\n if (t !== null) {\n const p = n.parentNode as Element;\n // an SVG template (`wcs-s…`): its content came in <svg> (so parsed as SVG)\n const copy = d[10] === \"s\"\n ? attrs(t, document.createElementNS(p.namespaceURI, \"template\"), ...document.importNode(t.content.firstChild!, true).childNodes)\n : document.importNode(t, true);\n copy.removeAttribute(\"id\");\n p.replaceChild(copy, n);\n }\n }\n } catch { /* */ }\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n if (scoped(n as Element)) deferred.set(n, { ssr, adopt });\n else walk(n);\n }\n }\n };\n walk(container);\n mend(container);\n strip(container, adopt);\n}\n\n/**\n * A region a parser cut: its start mark in a <table>, its rows and end mark in the <tbody> the parser\n * added at its first <tr> (the regions after it with them). The comments and templates right before\n * the <tbody> that the cut region starts with go into it — its anchor and marks: nothing in them\n * connects — and the rows stay where they are. A <tbody> written in the page (a row of a list of\n * them, a branch) holds no end mark of a region that starts before it, and is left alone.\n */\nfunction mend(container: Node): void {\n for (const body of Array.from((container as ParentNode).querySelectorAll(\"table > tbody\"))) {\n const run: Node[] = [];\n for (let p = body.previousSibling; p !== null && (p.nodeType === 8 || isBlank(p) || (p as Element).localName === \"template\"); p = p.previousSibling) run.unshift(p);\n // the regions the run leaves open (an end mark whose start is before the run — past an element —\n // closes a region that stays where it is, with what comes before the mark)\n let from = 0;\n let open = 0;\n run.forEach((n, i) => {\n if (startsMark(n, \"wcs-[\")) open++;\n else if (isMark(n, \"wcs-]\") && --open < 0) {\n open = 0;\n from = i + 1;\n }\n });\n if (open === 0) continue;\n // ... and the <tbody> ends one: the parser moved its rows in\n let depth = 0;\n for (let c = body.firstChild; c !== null; c = c.nextSibling) {\n if (startsMark(c, \"wcs-[\")) depth++;\n else if (isMark(c, \"wcs-]\") && depth-- === 0) {\n body.prepend(...run.slice(from));\n break;\n }\n }\n }\n}\n\n/**\n * The `adoptScope` hook: a Light DOM component's engine binds its host. Its content is prepared\n * now, and its blocks take the server's nodes while its walk runs (a walk adopts synchronously).\n * What it did not adopt is dropped after the walk: the regions held then are its own (a page's are\n * read and adopted in one go too, and dropped before anything else runs).\n */\nexport function adoptScope(host: Node, engine: Engine): (() => void) | null {\n const d = deferred.get(host);\n if (d === undefined) return null;\n deferred.delete(host);\n const undo = (c: Node): void => prepare(c, d.ssr, d.adopt);\n // (a snapshot discarded: planned on a copy first, as the page — see hydrate)\n if (!d.adopt) plan(engine, host, host, undo);\n undo(host);\n if (!d.adopt) return null;\n const prev = hooks.adopt;\n hooks.adopt = adopt;\n return () => {\n hooks.adopt = prev;\n release();\n };\n}\n\n/** Drops the held regions: rows no view took. */\nfunction release(): void {\n for (const r of held.values()) drop(r);\n held.clear();\n}\n\n/** The comments under `scope`, in document order. */\nfunction comments(scope: Node): Comment[] {\n const out: Comment[] = [];\n for (const w = document.createTreeWalker(scope, 128); w.nextNode(); ) out.push(w.currentNode as Comment);\n return out;\n}\n\n/**\n * A Light DOM component's wiring, one entry per mapping: [the page's path (null: not known — a key\n * private to the component around), its own path (\"\" for a whole mount, `state: user`), the path as\n * its host wrote it (null at the top: the page's)].\n */\ntype Wiring = (string | null)[][];\n\n/** `path` from column `from` of `wiring` to column `to`, by the longest it is or starts with; null: none. */\nfunction across(wiring: Wiring, path: string, from: number, to: number): string | null {\n let best: (string | null)[] | null = null;\n for (const w of wiring) {\n const k = w[from];\n if (k !== null && (k === \"\" || path === k || path.startsWith(`${k}.`)) && (best === null || k.length > best[from]!.length)) best = w;\n }\n const v = best?.[to];\n if (v == null) return null;\n const k = best![from]!;\n const rest = k === \"\" ? path : path.slice(k.length + 1);\n return v === \"\" ? rest : rest === \"\" ? v : `${v}.${rest}`;\n}\n\n/**\n * The output of @wcstack/server 3.x back to the page as written, as 3.x's own fallback did\n * (`Ssr.cleanupDom`): a row or a branch (`<!--@@wcs-for-start:…-->` up to its `-end` mark among its\n * siblings) goes, a text between its marks becomes a comment binding of what the mark holds (before\n * 3.5.3 the path alone, its filters lost: the warning says so; from 3.5.3, `fresh`, the binding's\n * expression as written: wcstack#373), a template's mark (`<!--@@wcs-for:ID-->`) becomes the template\n * `<wcs-ssr>` keeps under that id (whose content has the marks of the templates in it), and the\n * elements lose `data-wcs-ssr-id`.\n *\n * In a Light DOM component, 3.x wrote a template's own path as the page's (`state: user` makes `name`\n * `user.name`; a private key `user.#m1.name`, or `#m2.name` in a partial mount; in a component in a\n * component, through both), and so the marks' paths before 3.5.3: they go back to the component's own\n * through its host's wiring (the content of a template is the component's already). A mark from 3.5.3\n * is the component's own text, not mapped (it may name a key that is one of the page's wired paths\n * too: `state.x: v; state.v: w`). An expression a comment cannot hold (one with a `--`) falls back to\n * its path, unfiltered. From 3.5.4 (wcstack#427) that is the path the component wrote, read as written\n * like any other mark: the value shows, without its filters. 3.5.3 wrote the page's path there\n * instead, which is mapped back when it names a private key (`#mN.`: never in the component's own\n * text, so the mapping cannot misread a 3.5.4 mark); a wired one cannot be told from the component's\n * own text, and is read as it — a component key of that name shows its value, the right one only when\n * the wiring keeps the name, else the text stays empty (a limit of 3.5.3 output only: migration guide\n * §3.6).\n */\nfunction legacy(container: Node, ssr: Element, fresh: boolean): void {\n const wirings = new Map<Element, Wiring>();\n /** The wiring of the Light DOM component `n` is in (a nested one's composed with the one around), or null. */\n const wiringOf = (n: Node): Wiring | null => {\n let h = n.parentElement;\n while (h !== null && !scoped(h)) h = h.parentElement;\n if (h === null) return null;\n let wiring = wirings.get(h);\n if (wiring === undefined) {\n const up = wiringOf(h);\n const prop = h.querySelector(`:scope > ${config.tagNames.state}[bind-component]`)!.getAttribute(\"bind-component\");\n wirings.set(h, (wiring = []));\n for (const b of parseBindTextsForElement(h.getAttribute(config.bindAttributeName) ?? \"\")) {\n const at = b.statePathName;\n if (b.propSegments[0] === prop) wiring.push([up ? across(up, at, 1, 0) : at, b.propSegments.slice(1).join(\".\"), up && at]);\n }\n }\n return wiring;\n };\n /**\n * A path 3.x wrote at `n`, as the component's own there (`asIs`: a text mark from 3.5.3, left as it\n * is but for a private key's path, which 3.5.3's fallback writes).\n */\n const own = (n: Node, path: string, asIs?: boolean): string => {\n const wiring = wiringOf(n);\n if (wiring === null) return path;\n // (no `|`: a mark with filters, from 3.5.3, is the component's own text, a `#m1.` in it an argument's)\n const m = /^([^|]*)#m\\d+\\.([^|]*)$/.exec(path);\n if (m === null) return asIs ? path : across(wiring, path, 0, 1) ?? path;\n // after the last private key mark, a component's own path: this one's when what comes before the\n // mark is this one's mount path (`user.#m1.name`, `user.profile.#m3.name`, `#m2.box.#m4.name` with\n // `state: box`; nothing for a partial mount, `#m2.name`), else the one's around it, which this one\n // is mounted on (`#m2.box.k` with `state: box`)\n const at = m[1].replace(/#m\\d+\\./g, \"\").slice(0, -1);\n return wiring.some((w) => w[1] === \"\" && (w[0] === at || w[2] === at)) ? m[2] : across(wiring, m[2], 2, 1) ?? m[2];\n };\n // from the last: a row's own marks go before the row does\n for (const c of comments(container).reverse()) {\n const m = /^@@wcs-(\\w+)-start:([\\s\\S]*)/.exec(c.data);\n if (m === null) continue;\n // (no end among its siblings — an output cut short: left as it is)\n let e = c.nextSibling;\n while (e !== null && !isMark(e, `@@wcs-${m[1]}-end:${m[2]}`)) e = e.nextSibling;\n if (e === null) continue;\n while (c.nextSibling !== e) c.nextSibling!.remove();\n e.remove();\n c.replaceWith(...(m[1] === \"text\" ? [mark(`@@:${own(c, m[2], fresh)}`)] : []));\n }\n const restore = (scope: Node, at?: Node): void => {\n for (const c of comments(scope)) {\n const id = /^@@wcs-(?:for|if|elseif|else):(\\S+)$/.exec(c.data)?.[1];\n const t = Array.from(ssr.querySelectorAll(\"template\")).find((x) => x.id === id);\n if (t === undefined) continue;\n const copy = document.importNode(t, true);\n const a = config.bindAttributeName;\n copy.removeAttribute(\"id\");\n copy.setAttribute(a, copy.getAttribute(a)!.replace(/^(\\s*\\w+\\s*:\\s*)([^\\s|]+)/, (_, k: string, p: string) => k + own(at ?? c, p)));\n restore(copy.content, at ?? c);\n // 3.x made each `elseif` an `if` in an `else` of its own (whose content starts with it): back\n // to the chain of templates it was written as\n const f = copy.content.firstChild as Element | null;\n c.replaceWith(...(/^\\s*elseif\\s*:/.test(f?.getAttribute?.(a) ?? \"\") ? copy.content.childNodes : [copy]));\n }\n };\n restore(container);\n for (const e of Array.from((container as ParentNode).querySelectorAll(\"[data-wcs-ssr-id]\"))) e.removeAttribute(\"data-wcs-ssr-id\");\n}\n\n/**\n * What the reader typed before the client bound the page — the server's HTML is usable at once, the\n * bundles may take seconds: the form controls whose value is not the one their markup gives (a\n * browser restoring a form on reload counts too). Binding the page writes the state's values over\n * them, and the text was lost without a word (docs/seam-apps.md, ssr-news; the author's decision,\n * docs/v4-direction-2026-10.md §5.1). Returns what gives each its value back and sends it an\n * `input` and a `change`, as the reader's own edit would: a two-way binding writes it to the state.\n */\nfunction typed(container: Node): () => void {\n const edits: [HTMLElement, () => void][] = [];\n for (const n of Array.from((container as ParentNode).querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n const sel = o.map((x) => x.selected);\n // a single select's markup selects its last marked option, or its first enabled one (the mark\n // is read as the attribute: a server's DOM need not have defaultSelected)\n const marked = o.map((x) => x.hasAttribute(\"selected\"));\n let at = marked.lastIndexOf(true);\n if (at < 0) at = o.findIndex((x) => !x.disabled);\n if (n.multiple ? o.some((x, i) => sel[i] !== marked[i]) : n.selectedIndex !== at) edits.push([n, () => o.forEach((x, i) => (x.selected = sel[i]))]);\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n // (a radio: the one the reader chose; the group's others follow it)\n const c = n.checked;\n if (c !== n.defaultChecked && (c || n.type === \"checkbox\")) edits.push([n, () => (n.checked = c)]);\n } else if (n.type !== \"file\" && n.value !== n.defaultValue) {\n const v = n.value;\n edits.push([n, () => (n.value = v)]);\n }\n }\n return () => {\n for (const [n, put] of edits) {\n if (!n.isConnected) continue;\n put();\n n.dispatchEvent(new Event(\"input\", { bubbles: true }));\n n.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n };\n}\n\n/**\n * Walks a copy of `container` — in a template's content, where no custom element is created — as the\n * mount of `root` walks it, once `undo` put it back as written: what this client cannot plan (a newer\n * minor's markup, a filter argument it does not know) fails its initialization while the server's\n * rows and branches are still in the page, not after they went (docs/seam-apps.md, ssr-news). (An\n * event binding puts its listener on the root at once: the mount's walk finds it there)\n */\nfunction plan(engine: Engine, root: Node, container: Node, undo: (c: Node) => void): void {\n const copy = document.createElement(\"template\").content;\n for (const n of container.childNodes) copy.appendChild(copy.ownerDocument.importNode(n, true));\n undo(copy);\n engine.root = root;\n const none = (): void => {};\n walkBindings(engine, [...copy.childNodes], null, true, none, none, none, (_, expr) => textSpec(engine, expr, null, 0));\n}\n\n/** The `element` hook, \"mounting\": a client root with a server snapshot adopts the server's DOM. */\nexport function hydrate(engine: Engine): void {\n const el = engine.element as Element;\n if (!el.hasAttribute(\"enable-ssr\") || isServer()) return;\n const ssr = el.previousElementSibling;\n const found = ssr?.localName === tag();\n const version = found ? ssr!.getAttribute(\"version\") : null;\n const same = version === null || majorMinor(version) === majorMinor(VERSION);\n if (same) {\n // the server ran $connectedCallback; the client does not\n const e = engine as any;\n const callHook = e.callHook;\n e.callHook = (name: string, args?: unknown[]) => (name === \"$connectedCallback\" ? undefined : callHook.call(engine, name, args));\n }\n if (!found) return;\n // @wcstack/server 3.x's output: marks of its own; from 3.5.3 on a text mark holds the binding's\n // expression (see legacy). A prerelease, or a version that does not parse, counts as older\n const old = !same && parseInt(version!) < 4;\n const v = /^3\\.(\\d+)\\.(\\d+)$/.exec(version!);\n const fresh = v !== null && (+v[1] - 5 || +v[2] - 3) >= 0;\n if (!same) {\n // (the filters' sentence: output before 3.5.3 only)\n console.warn(`[@wcstack/state] <${tag()} version=\"${version}\"> does not match ${VERSION}: its snapshot is discarded, and the page renders on the client from its own state.${old && !fresh\n ? \" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.\"\n : \"\"}`);\n }\n const script = same ? ssr!.querySelector('script[type=\"application/json\"]') : null;\n if (script !== null) {\n const snap = JSON.parse(script.textContent || \"{}\") as Record<string, unknown>;\n const target = engine.target;\n for (const key of Object.keys(snap)) {\n const d = Object.getOwnPropertyDescriptor(target, key);\n if (d !== undefined && (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\")) continue;\n target[key] = snap[key];\n }\n // the snapshot holds the server's volume data too: a volume adopts it (scopes/volume.ts)\n (engine as any).hydrated = true;\n }\n const root = el.getRootNode() as Document | ShadowRoot;\n for (const r of Array.from(root.querySelectorAll(`[${RAW_ATTR}]`))) {\n r.textContent = r.getAttribute(RAW_ATTR);\n r.removeAttribute(RAW_ATTR);\n }\n const container = root.nodeType === 9 ? (root as Document).body : root;\n // (its templates are not the page's markup: out before the page is walked)\n ssr!.remove();\n // back to the page as written (see prepare, legacy)\n const undo = (c: Node): void => (old ? legacy(c, ssr!, fresh) : prepare(c, ssr!, same));\n if (!same) plan(engine, root, container, undo);\n // (taken before the page is bound, which writes the state's values; given back right after)\n queueMicrotask(typed(container));\n undo(container);\n if (same) {\n // only while the page is adopted — its walk, which runs now: every other block is built with one\n // null check. What no view took then goes before anything else runs\n hooks.adopt = adopt;\n queueMicrotask(() => {\n release();\n hooks.adopt = null;\n });\n }\n}\n\n/**\n * The `ssrMark` hook: on the server, records (and leaves `outerHTML:` / `outerText:` to the client); on the client,\n * a held region follows its template's anchor.\n */\nexport function ssrMark(engine: Engine, node: Node, source: Element | string | Spec[]): void {\n if (isServer()) {\n if (source instanceof Array) {\n // `outerHTML:` / `outerText:` replace the element with the value: the client would find no\n // binding there, and walk the value as the page's markup. The server renders the element as\n // written; the client binds it and applies the value\n for (let i = source.length; i-- > 0; ) if (isOuter(source[i])) source.splice(i, 1);\n // a custom element (a Light DOM component binds its own) whose content no binding sets: what\n // is in it now is the page's (see kept)\n const el = node as Element;\n if (source.some(setsContent)) skip.add(el);\n else if (el.localName.includes(\"-\") && !scoped(el)) {\n const own = new Map<Node, string>();\n for (const w = document.createTreeWalker(el, 133); w.nextNode(); ) own.set(w.currentNode, (w.currentNode as Text).data);\n kept.set(el, own);\n }\n return;\n }\n if (typeof source === \"string\") {\n rawTexts.set(node, source);\n if (raw(node.parentNode as Element)) return;\n const open = mark(`wcs-t:${encodeURIComponent(source)}`);\n const close = mark(\"wcs-/t\");\n (node as Text).before(open);\n (node as Text).after(close);\n return;\n }\n let map = anchors.get(engine);\n if (map === undefined) anchors.set(engine, (map = new Map()));\n map.set(node, source);\n const root = node.getRootNode();\n let es = enginesByRoot.get(root);\n if (es === undefined) enginesByRoot.set(root, (es = new Set()));\n es.add(engine);\n return;\n }\n // (an element's specs are never a key: the templates the anchors replaced are)\n if (typeof source !== \"string\" && held.size > 0) {\n const r = held.get(source as Element);\n if (r !== undefined) {\n held.delete(source as Element);\n held.set(node, r);\n }\n }\n}\n\n/** An anchor of an `if` / `elseif` / `else` chain (the core names them by config). */\nconst isIfAnchor = (n: Node | null): boolean =>\n n !== null && n.nodeType === 8 && [config.commentIfPrefix, config.commentElseIfPrefix, config.commentElsePrefix].includes((n as Comment).data);\nconst isBlank = (n: Node): boolean => n.nodeType === 3 && (n as Text).data.trim() === \"\";\n\n/** The next of the plan's nodes after `n`: a held region after an anchor is the anchor's view's. */\nconst after = (n: Node): Node | null => {\n const x = held.get(n)?.tail ?? n;\n return (beside(x) ?? x).nextSibling;\n};\n\n/**\n * Whether a row's top-level nodes `own` have the plan's nodes where a binding lands — not so when a\n * Light DOM element added children before them, or a parser moved them (see mend); puts them\n * in `plan.scratch` for the block.\n */\nfunction fits(plan: RowPlan, own: Node[]): boolean {\n if (own.length !== plan.fragment.childNodes.length) return false;\n const paths = plan.nodePaths;\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i];\n let a: Node = plan.fragment;\n let b: Node | null | undefined = own[path[0]];\n for (let j = 0; ; ) {\n a = a.childNodes[path[j]];\n if (b?.nodeName !== a.nodeName) return false;\n if (++j === path.length) break;\n b = (beside(b) ?? b).firstChild;\n for (let k = path[j]; k > 0 && b !== null; k--) b = after(b);\n }\n plan.scratch[i] = b;\n }\n return true;\n}\n\n/**\n * The `adopt` hook: the next server row (or branch) of the view anchored at `anchor` — its top-level\n * nodes, left where they are (the view inserts nothing, and no custom element in them is disconnected).\n */\nexport function adopt(plan: RowPlan, anchor: Node, isFor: boolean): ChildNode[] | null {\n if (held.size === 0) return null;\n let key = anchor;\n let branch = 0;\n if (!isFor) {\n // only this chain: an `if` anchor starts one (a chain right before or after is another). No\n // element is between its anchors: whitespace, comments (readChain) and the text a comment binding\n // there renders may be\n const head = config.commentIfPrefix;\n if (!isMark(anchor, head)) {\n for (let p = anchor.previousSibling; p !== null && p.nodeType !== 1; p = p.previousSibling) {\n if (isIfAnchor(p)) branch++;\n if (isMark(p, head)) break;\n }\n }\n // up to the anchor its region follows (the branch's nodes come right after it)\n for (let n = anchor.nextSibling; !held.has(key) && n !== null && !isMark(n, head) && n.nodeType !== 1; n = n.nextSibling) {\n if (isIfAnchor(n)) key = n;\n }\n }\n const r = held.get(key);\n if (r === undefined) return null;\n if (!isFor && r.branch !== branch) {\n // the server rendered another branch: it goes, this one is built\n held.delete(key);\n drop(r);\n return null;\n }\n const nodes = r.rows.shift();\n if (r.rows.length === 0) held.delete(key);\n // a view renders before its anchor (a branch before its own: the chain's anchors from it on), and\n // the server put its rows after: the anchors go where the rows end\n r.tail?.replaceWith(...range(anchor, key));\n r.tail = null;\n if (nodes === undefined) return null;\n // the row's own top-level nodes (a region in it is a nested view's, a link's anchor the link's)\n let own: Node[] = [];\n for (let i = 0; i < nodes.length; i++) {\n const inner = held.get(nodes[i]);\n own.push(nodes[i]);\n // (its nodes follow it, up to its end mark)\n if (inner !== undefined) while (i < nodes.length && nodes[i] !== inner.tail) i++;\n else if (beside(nodes[i]) === nodes[i + 1]) i++;\n }\n if (!fits(plan, own)) {\n // rendered anew, in its place (the rows around it stay; an empty one's place is before the next\n // row, or the anchor): its nodes found before it is in the page (a custom element in it may add\n // children as it connects)\n const fresh = (plan.single ? plan.root! : plan.fragment).cloneNode(true);\n own = plan.single ? [fresh] : [...fresh.childNodes];\n fits(plan, own);\n ((nodes[0] ?? r.rows.find((x) => x.length > 0)?.[0] ?? anchor) as ChildNode).before(fresh);\n for (const n of nodes) (n as ChildNode).remove();\n }\n return own as ChildNode[];\n}\n","/**\n * The SSR add-on (@wcstack/state/features/ssr): `<wcs-state enable-ssr>` with @wcstack/server —\n * see src/ssr/ssr.ts.\n */\nimport { chain, hooks, type Feature } from \"../hooks\";\nimport { adoptScope, hydrate, installBuilder, ssrMark } from \"../ssr/ssr\";\nimport { defineSsr } from \"../ssr/element\";\nimport { registries } from \"../element\";\n\nexport const ssr: Feature = {\n name: \"ssr\",\n hooks,\n install(): void {\n hooks.ssrMark = ssrMark;\n hooks.adoptScope = adoptScope;\n // the snapshot first, before what is installed (in any order) runs at \"mounting\": a volume\n // grafting there adopts it, and its $connectedCallback writes over it (3.x D14)\n const prev = hooks.element;\n hooks.element = (engine, phase) => {\n if (phase === \"mounting\") hydrate(engine);\n prev?.(engine, phase);\n };\n installBuilder();\n // `<wcs-ssr>` in every registry `<wcs-state>` is defined in, now and later\n hooks.tags = chain(hooks.tags, defineSsr);\n for (const r of registries()) defineSsr(r);\n },\n};\nexport default ssr;\n"],"mappings":"ugBAwBO,IAAMA,EAAcC,GAAsBA,EAAEC,MAAM,KAAKC,MAAM,EAAG,GAAGC,KAAK,KAElEC,EAAN,cAAkBC,EAEvB,WAAOC,CAAKC,GACV,OAASA,EAAoBC,gBAAgBC,EAAOC,SAASC,MAAuB,IACtF,CAEA,WAAIC,GACF,OAAOC,KAAKC,aAAa,YAAc,EACzC,CAEA,aAAIC,GACF,IAAMC,EAASH,KAAKL,cAAc,mCAClC,OAAkB,OAAXQ,EAAkB,CAAC,EAAIC,KAAKC,MAAMF,EAAOG,aAAe,KACjE,CAEA,aAAIC,GACF,IAAMC,EAAM,IAAIC,IAEhB,QAAWC,KAAKC,MAAMC,KAAKZ,KAAKa,UAAkC,aAAhBH,EAAEI,WAA0BN,EAAIO,IAAIL,EAAEM,GAAIN,GAC5F,OAAOF,CACT,CAEA,gBAAIS,GACF,MAAO,CAAC,CACV,CAEA,WAAAC,CAAYF,GACV,OAAOhB,KAAKO,UAAUY,IAAIH,IAAO,IACnC,CAEA,aAAAI,GACE,OAAOlC,EAAWc,KAAKD,WAAab,EAAWmC,EACjD,GAIK,SAASC,EAAUC,GACxB,IAAMC,EAAM5B,EAAOC,SAASC,SACF,IAAtByB,EAASJ,IAAIK,IAAoBD,EAASE,OAAOD,EAAK,cAAcjC,IAC1E,CCrBA,IAAMiC,EAAM,IAAc5B,EAAOC,SAASC,IACpC4B,EAAUC,OAAOC,IAAI,+BAEdC,EAAW,KAA6E,IAA9DC,SAASC,iBAAiBC,aAAa,mBAExEC,EAAQC,GAA0BJ,SAASK,cAAcD,GACzDE,EAAS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L,IAAMwC,EAAIC,WACVD,EAAErI,GAAQ,CAAEd,QAAO,KAAAqJ,GAAU/M,EAAM,CAAG,QAEnB,IAAf6M,EAAEtR,KACJsR,EAAEtR,GAAW,CAAEyR,SAAU,mBAAoBpT,QAAS,EAAG8J,MAAQC,GAAkBkJ,EAAErI,GAAMd,MAAMC,GAAMoJ,MAAO,IAAMF,EAAErI,GAAMuI,SAEhI,CC3SIE,GAEAtI,EAAMuI,GAAOlM,EAAM2D,EAAMuI,GAAM/R,GAC/B,QAAW4J,KAAKoI,IAAchS,EAAU4J,EAC1C,GAEKqI,GAAQzT","ignoreList":[]}
1
+ {"version":3,"names":["majorMinor","v","split","slice","join","Ssr","HTMLElementBase","find","root","querySelector","config","tagNames","ssr","version","this","getAttribute","stateData","script","JSON","parse","textContent","templates","map","Map","t","Array","from","children","localName","set","id","hydrateProps","getTemplate","get","verifyVersion","VERSION","defineSsr","registry","tag","define","BUILDER","Symbol","for","isServer","document","documentElement","hasAttribute","mark","data","createComment","isMark","n","nodeType","startsMark","prefix","startsWith","anchors","WeakMap","enginesByRoot","kept","skip","WeakSet","rawTexts","range","to","out","push","nextSibling","attrs","content","a","attributes","setAttribute","name","value","append","beside","anchorElement","region","blocks","branch","open","close","length","head","before","after","b","last","nodes","first","lastOf","add","visitView","ForView","anchor","rowViews","visitBlock","cur","current","branches","index","c","RAW","Set","RAW_ATTR","raw","el","has","protectTexts","parent","childNodes","replaceWith","ids","snapshot","engine","getRootNode","engines","E","element","own","byAnchor","l","rootLists","values","view","extra","bs","rootBindings","chain","br","done","template","isConnected","h","querySelectorAll","w","createTreeWalker","acceptNode","scoped","nextNode","p","previousSibling","includes","parentNode","remove","cs","some","body","createElement","type","stringify","replace","charCodeAt","toString","padStart","json","target","key","Object","keys","d","getOwnPropertyDescriptor","e","parentElement","svg","importNode","templateContent","x","namespaceURI","createElementNS","build","doc","state","o","options","multiple","selectedIndex","disabled","toggleAttribute","selected","defaultValue","checked","forms","previousElementSibling","IMPL","held","deferred","hooks","componentScope","enters","nodesOf","r","rows","flat","concat","tail","drop","read","start","keep","row","m","exec","next","strip","Number","appendChild","walked","firstChild","prepare","container","adopt","walk","text","decodeURIComponent","copy","removeAttribute","replaceChild","run","isBlank","unshift","forEach","i","depth","prepend","mend","adoptScope","host","delete","undo","plan","prev","release","clear","comments","scope","currentNode","across","wiring","path","best","k","rest","ownerDocument","none","walkBindings","_","expr","textSpec","ssrMark","node","source","isOuter","splice","setsContent","encodeURIComponent","es","size","isIfAnchor","commentIfPrefix","commentElseIfPrefix","commentElsePrefix","trim","fits","fragment","paths","nodePaths","j","nodeName","scratch","isFor","shift","inner","fresh","single","cloneNode","install","phase","found","same","callHook","args","call","old","parseInt","console","warn","snap","hydrated","wirings","wiringOf","up","prop","parseBindTextsForElement","bindAttributeName","at","statePathName","propSegments","asIs","reverse","restore","f","test","legacy","queueMicrotask","edits","sel","marked","lastIndexOf","findIndex","defaultChecked","put","dispatchEvent","Event","bubbles","typed","hydrate","g","globalThis","reset","protocol","installBuilder","tags","registries","ssr_default"],"sources":["../../../src/ssr/element.ts","../../../src/ssr/ssr.ts","../../../src/features/ssr.ts"],"sourcesContent":["/**\n * `<wcs-ssr>` (`config.tagNames.ssr`): the server's snapshot before a `<wcs-state enable-ssr>` —\n * `version`, the state's data (a JSON `<script>`) and the page-level templates. The SSR add-on\n * defines the tag; this class only reads the snapshot (the add-on hydrates from it and removes it).\n */\nimport { config } from \"../config\";\nimport { VERSION } from \"../version\";\nimport { HTMLElementBase } from \"../element\";\n\nexport interface ISsrElement {\n /** The @wcstack/state version that rendered the page. */\n readonly version: string;\n /** The state's data the server rendered with. */\n readonly stateData: Record<string, any>;\n /** The page-level templates, by id. */\n readonly templates: Map<string, HTMLTemplateElement>;\n /** Always empty: every binding is applied when the client adopts the server's DOM (3.x kept a value table here). */\n readonly hydrateProps: Record<string, Record<string, unknown>>;\n getTemplate(id: string): HTMLTemplateElement | null;\n /** The snapshot is adoptable: the same major.minor as this build. */\n verifyVersion(): boolean;\n}\n\n/** `4.0.1` → `4.0`: a snapshot is adoptable by the same major.minor. */\nexport const majorMinor = (v: string): string => v.split(\".\").slice(0, 2).join(\".\");\n\nexport class Ssr extends HTMLElementBase implements ISsrElement {\n /** The first snapshot element under `root`, or null. */\n static find(root: Node): ISsrElement | null {\n return ((root as ParentNode).querySelector?.(config.tagNames.ssr) as Ssr | null) ?? null;\n }\n\n get version(): string {\n return this.getAttribute(\"version\") ?? \"\";\n }\n\n get stateData(): Record<string, any> {\n const script = this.querySelector('script[type=\"application/json\"]');\n return script === null ? {} : JSON.parse(script.textContent || \"{}\");\n }\n\n get templates(): Map<string, HTMLTemplateElement> {\n const map = new Map<string, HTMLTemplateElement>();\n // quoted: `children` is an internal name the bundles shorten (mangle.mjs)\n for (const t of Array.from(this[\"children\"])) if (t.localName === \"template\") map.set(t.id, t as HTMLTemplateElement);\n return map;\n }\n\n get hydrateProps(): Record<string, Record<string, unknown>> {\n return {};\n }\n\n getTemplate(id: string): HTMLTemplateElement | null {\n return this.templates.get(id) ?? null;\n }\n\n verifyVersion(): boolean {\n return majorMinor(this.version) === majorMinor(VERSION);\n }\n}\n\n/** Defines `<wcs-ssr>` in `registry` (once per registry). */\nexport function defineSsr(registry: CustomElementRegistry): void {\n const tag = config.tagNames.ssr;\n if (registry.get(tag) === undefined) registry.define(tag, class extends Ssr {});\n}\n","/**\n * Server-side rendering with @wcstack/server (README \"Server-Side Rendering\"), for\n * `<wcs-state enable-ssr>` roots.\n *\n * Server (`<html data-wcs-server>`): the page renders as usual; the snapshot builder\n * (`Symbol.for(\"wcstack.ssr.snapshotBuilder\")`, called by the server before it serializes)\n * then makes the DOM adoptable:\n * - every view's rows / branch move right after its anchor, between `<!--wcs-[-->` and\n * `<!--wcs-]-->`, each row opened by `<!--wcs-|-->` (a branch region carries its index,\n * `<!--wcs-[:i-->`, and follows the chain's last anchor so the chain's templates stay adjacent);\n * - a page-level anchor becomes `<!--wcs-p:ID-->`, its template kept in `<wcs-ssr>` as\n * `<template id=ID>`; a page-level text binding (a mustache, a comment binding) is wrapped in\n * `<!--wcs-t:EXPR-->…<!--wcs-/t-->` (the client puts a comment binding back);\n * - adjacent text nodes are separated (`<!--wcs-s-->`) and empty ones kept (`<!--wcs-e-->`), so\n * parsing the HTML gives back the rows' exact structure;\n * - `<wcs-ssr version>` before the element holds the state's data (JSON) and the templates.\n *\n * Client: before the page is bound, the texts and templates are restored and the regions read where\n * they are (their marks go; the page's walk passes their nodes by); each block the engine builds\n * takes its region's next row instead of a clone (a row's nested regions wait for its nested views\n * in turn). The server's nodes never leave the page — no custom element in a row or a branch is\n * disconnected — and get their bindings; a view's anchors move after its rows instead. A row that\n * does not fit its plan is built anew in its place, and the rows no view took go once the page is\n * bound. `$connectedCallback` does not run (the server ran it).\n *\n * A snapshot of another major.minor is discarded, and the page renders on the client as it would\n * without a server: the state comes from its own source, `$connectedCallback` runs, and the server's\n * rows and marks give way to the templates they came from — those of @wcstack/server 3.x's output\n * too (`legacy`). They give way only once the page was planned on a copy: markup this client cannot\n * plan fails its initialization with the server's HTML left as it was.\n *\n * Not carried over from @wcstack/state 3.3 (approved): the inline snapshot for servers without\n * the builder protocol, and the property value table (every binding is applied on adoption).\n */\nimport type { Engine } from \"../engine\";\nimport { ForView, type Block, type IfView, type RowPlan, type Spec } from \"../dom/view\";\nimport { config } from \"../config\";\nimport { hooks } from \"../hooks\";\n\nimport { VERSION } from \"../version\";\nimport { isOuter, setsContent, templateContent, textSpec, walkBindings, walked } from \"../dom/plan\";\nimport { majorMinor } from \"./element\";\nimport { parseBindTextsForElement } from \"../parser/parseBindTextsForElement\";\n/** The snapshot element's tag (`config.tagNames.ssr`, `wcs-ssr` by default). */\nconst tag = (): string => config.tagNames.ssr;\nconst BUILDER = Symbol.for(\"wcstack.ssr.snapshotBuilder\");\n\nexport const isServer = (): boolean => document.documentElement?.hasAttribute(\"data-wcs-server\") === true;\n\nconst mark = (data: string): Comment => document.createComment(data);\nconst isMark = (n: Node | null, data: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data === data;\nconst startsMark = (n: Node | null, prefix: string): boolean => n !== null && n.nodeType === 8 && (n as Comment).data.startsWith(prefix);\n\n// ---------------------------------------------------------------- server\n\n/** Page-level anchors (the walker's) and the template each replaced, by engine. */\nconst anchors = new WeakMap<Engine, Map<Node, Element>>();\n/** The engines that recorded anchors in a page (its root node): the page's, and its Light DOM components'. */\nconst enginesByRoot = new WeakMap<Node, Set<Engine>>();\n/**\n * The custom elements the page's walker bound, with the nodes in them then (and a text's data): the\n * walk is post-order, so its anchors, text marks and rows are there, and the element's own bindings\n * have not written yet. What an element renders from a value comes later: in the server's HTML the\n * client would walk it as the page's markup (a user's `{{ … }}`, a `data-wcs` in sanitized HTML),\n * so the snapshot leaves it — and a text with `{{` that it was not then (a value's, in a node of\n * its own or one the page wrote) — to the client.\n */\nconst kept = new WeakMap<Node, Map<Node, string>>();\n/** What the client does not walk: a region (rows it adopts), an element whose content a binding sets. */\nconst skip = new WeakSet<Node>();\n/**\n * Mustache texts: their expressions. In an element whose content is text (`<textarea>`, `<title>`),\n * a mark would be text to the browser, and the value the client's markup: the element takes its\n * template along instead (`data-wcs-raw`), and the client puts it back before binding the page.\n */\nconst rawTexts = new WeakMap<Node, string>();\n\n/** Nodes from `from` to `to`, siblings, inclusive. */\nfunction range(from: Node, to: Node): Node[] {\n const out: Node[] = [];\n for (let n: Node | null = from; n !== null; n = n.nextSibling) {\n out.push(n);\n if (n === to) break;\n }\n return out;\n}\n\n/** `to` with `from`'s attributes, and `content` (into a template's content when it has one). */\nfunction attrs<T extends Element>(from: Element, to: T, ...content: Node[]): T {\n for (const a of Array.from(from.attributes)) to.setAttribute(a.name, a.value);\n ((to as unknown as HTMLTemplateElement).content ?? to).append(...content);\n return to;\n}\n\nconst lastOf = (b: Block): Node => (b.nodes === null ? b.first : b.nodes[b.nodes.length - 1]);\n\n/**\n * The anchor `<wcs-link>` (@wcstack/router) renders right after itself, its children moved into it:\n * the server's is marked `data-wcs-ssr-link`, and is the link's `anchorElement` once the router took\n * it (dropping the mark). In a row it is the link's: the link's children are there.\n */\nconst beside = (n: Node): Node | null => {\n const a = n.nextSibling as Element | null;\n return n.nodeType === 1 && a?.localName === \"a\" && (a.hasAttribute(\"data-wcs-ssr-link\") || (n as any).anchorElement === a) ? a : null;\n};\n\n/**\n * Makes the blocks one region right after the anchors `from` … `to` (a view renders its blocks before\n * its anchor; a branch before its own, the chain's later anchors after it). The anchors move, not the\n * blocks: a custom element in a row is not disconnected, so what it rendered as it connected stays\n * (`<wcs-link>` renders its anchor a microtask later, and would not again before the server serializes).\n */\nfunction region(from: Node, to: Node, blocks: Block[], branch: number | null): void {\n const open = mark(branch === null ? \"wcs-[\" : `wcs-[:${branch}`);\n const close = mark(\"wcs-]\");\n if (blocks.length > 0) (blocks[0].head() as ChildNode).before(...range(from, to));\n (to as ChildNode).after(open);\n for (const b of blocks) if (branch === null) b.head().before(mark(\"wcs-|\"));\n const last = blocks.length > 0 ? lastOf(blocks[blocks.length - 1]) : open;\n ((beside(last) ?? last) as ChildNode).after(close);\n for (const n of range(open, close)) skip.add(n);\n}\n\nfunction visitView(v: ForView | IfView): void {\n if (v instanceof ForView) {\n region(v.anchor, v.anchor, v.rowViews, null);\n for (const b of v.rowViews) visitBlock(b);\n return;\n }\n const cur = v.current;\n if (cur === null) return;\n region(v.branches[v.index].anchor, v.branches[v.branches.length - 1].anchor, [cur], v.index);\n visitBlock(cur);\n}\n\nfunction visitBlock(b: Block): void {\n if (b.children !== null) for (const c of b.children) visitView(c);\n}\n\nconst RAW = new Set([\"script\", \"style\", \"template\", \"textarea\", \"title\"]);\nconst RAW_ATTR = \"data-wcs-raw\";\nconst raw = (el: Element): boolean => RAW.has(el.localName) || el.localName === tag();\n\n/** Keeps every text node a text node through HTML serialization and parsing. */\nfunction protectTexts(parent: Node): void {\n for (const n of Array.from(parent.childNodes)) {\n if (n.nodeType === 3) {\n if ((n as Text).data === \"\") n.replaceWith(mark(\"wcs-e\"));\n else if (n.nextSibling !== null && n.nextSibling.nodeType === 3) n.after(mark(\"wcs-s\"));\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n protectTexts(n);\n }\n }\n}\n\nfunction json(value: unknown): string {\n return JSON.stringify(value).replace(/[<>&\\u2028\\u2029]/g, (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`);\n}\n\n/** The state's own data (no `$` keys, no accessors, no functions). */\nfunction data(target: Record<string, any>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(target)) {\n if (key[0] === \"$\") continue;\n const d = Object.getOwnPropertyDescriptor(target, key)!;\n if (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\") continue;\n out[key] = d.value;\n }\n return out;\n}\n\nlet ids = 0;\n\nfunction snapshot(el: Element, engine: Engine): void {\n const root = el.getRootNode() as Document | ShadowRoot;\n // the page's engine, and those of the Light DOM components in it: their walkers' anchors are in\n // the page too (a Shadow DOM component's are in its own shadow root)\n const engines = [engine];\n for (const E of enginesByRoot.get(root) ?? []) {\n if (E !== engine && (E.element as Element | null)?.hasAttribute(\"bind-component\") === true) engines.push(E);\n }\n const map = new Map<Node, Element>();\n for (const E of engines) {\n const own = anchors.get(E);\n if (own === undefined) continue;\n // the views the walker made, top down (a nested view's region stays inside its row's)\n const byAnchor = new Map<Node, ForView | IfView>();\n for (const l of E.rootLists.values()) {\n if (l.view !== null) byAnchor.set(l.view.anchor, l.view);\n if (l.extra !== null) for (const v of l.extra) byAnchor.set(v.anchor, v);\n }\n for (const bs of E.rootBindings.values()) {\n for (const b of bs) if (b.chain !== null) for (const br of b.chain.branches) byAnchor.set(br.anchor, b.chain);\n }\n const done = new Set<ForView | IfView>();\n for (const [anchor, template] of own) {\n map.set(anchor, template);\n const v = byAnchor.get(anchor);\n if (v !== undefined && !done.has(v) && anchor.isConnected) {\n done.add(v);\n visitView(v);\n }\n }\n }\n for (const h of Array.from(root.querySelectorAll(\"*\"))) {\n const own = kept.get(h);\n if (own !== undefined) {\n // what the client does not walk is left: what `skip` has, and — the page's — a Light DOM\n // component (bound later, by its own engine). A text without `{{` is no markup to the client,\n // whoever wrote it; one the page wrote is left as it was written, and a mustache's where the\n // client puts its expression back: right after its mark (the client replaces what follows it),\n // or in a text element (`data-wcs-raw`). Elsewhere it goes: an element may drop comments, or\n // move a text element's text out, and its value would be the client's markup\n const w = document.createTreeWalker(h, 133, {\n acceptNode: (n) => (skip.has(n) || (n.nodeType === 1 && own.has(n) && scoped(n as Element)) ? 2 : 1),\n });\n const out: ChildNode[] = [];\n for (let n = w.nextNode(); n !== null; n = w.nextNode()) {\n const p = n.previousSibling!;\n if (n.nodeType === 3\n ? (n as Text).data.includes(\"{{\")\n && !(raw(n.parentNode as Element) ? rawTexts.has(n) : own.has(p) && startsMark(p, \"wcs-t:\"))\n && (rawTexts.has(n) || own.get(n) !== (n as Text).data)\n : !own.has(n)) out.push(n as ChildNode);\n }\n for (const n of out) n.remove();\n }\n const cs = Array.from(h.childNodes);\n if (raw(h) && cs.some((c) => rawTexts.has(c))) {\n // (a comment there — a server's DOM may parse one in a <textarea> — is text to a browser)\n h.setAttribute(RAW_ATTR, cs.map((c) => (rawTexts.has(c) ? `{{ ${rawTexts.get(c)} }}` : c.nodeType === 8 ? `<!--${(c as Comment).data}-->` : c.textContent)).join(\"\"));\n }\n }\n protectTexts(root.nodeType === 9 ? (root as Document).body : root);\n const ssr = document.createElement(tag());\n ssr.setAttribute(\"version\", VERSION);\n const script = document.createElement(\"script\");\n script.type = \"application/json\";\n script.textContent = json(data(engine.target));\n ssr.append(script);\n for (const [anchor, template] of map) {\n if (!anchor.isConnected) continue;\n // the anchor's context, by name (a server's DOM may not know <foreignObject> leads back to HTML):\n // SVG under <svg> — its id says so (`wcs-s…`) — and HTML under <foreignObject>\n let e = anchor.parentNode as Element | null;\n while (e !== null && e.localName !== \"svg\" && e.localName !== \"foreignObject\") e = e.parentElement;\n const svg = e?.localName === \"svg\";\n const id = `wcs-${svg ? \"s\" : \"t\"}${ids++}`;\n (anchor as ChildNode).replaceWith(mark(`wcs-p:${id}`));\n let c: Node = document.importNode(templateContent(template as HTMLTemplateElement), true);\n // a template in it that is an SVG element goes as an HTML one, which a serializer reads (the\n // client's parser reads it back in its context)\n for (const x of Array.from((c as Element).querySelectorAll(\"template\"))) {\n // by namespace, not `instanceof SVGElement`: a server window (@wcstack/server) need not expose that global\n if (x.namespaceURI === \"http://www.w3.org/2000/svg\") x.replaceWith(attrs(x, document.createElement(\"template\"), ...x.childNodes));\n }\n // an SVG template's content goes in <svg>, so the client's parser reads it as SVG\n if (svg) {\n const w = document.createElementNS(e!.namespaceURI, \"svg\");\n w.append(c);\n c = w;\n }\n const t = document.createElement(\"template\");\n t.id = id;\n ssr.append(attrs(template, t, c));\n }\n el.before(ssr);\n}\n\n/**\n * The form controls' current state into their markup, as 3.x wrote it: an input's value (its\n * `value` attribute) and checkedness (`checked`), a textarea's value (its text), the options a\n * select has selected (`selected`) — whatever set them (a `value:` / `checked:` / `selectedIndex:`\n * binding, `radio:`, a row's), where it differs from what the markup gives back. The page then shows\n * the server's values before the client binds it, or without JS; the client's bindings find them\n * there, and write over them from then on. On a page with a `<wcs-state>` only (enable-ssr or not).\n * A password's value never goes into the HTML (3.x wrote it): the client's binding fills it in.\n */\nfunction forms(doc: Document): void {\n if (doc.querySelector(config.tagNames.state) === null) return;\n for (const n of Array.from(doc.querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n // (a single select without a marked option, its first enabled one selected: what a parser selects)\n if (n.multiple || o.some((x) => x.hasAttribute(\"selected\")) || o[n.selectedIndex] !== o.find((x) => !x.disabled)) {\n for (const x of o) x.toggleAttribute(\"selected\", x.selected);\n }\n } else if (n.localName === \"textarea\") {\n // (a value with `{{` in it would be the client's markup there, a mustache; a mustache in it is\n // the client's to put back — see snapshot: both left to the client)\n if (n.value !== n.defaultValue && !n.value.includes(\"{{\") && !Array.from(n.childNodes).some((c) => rawTexts.has(c as Node))) n.textContent = n.value;\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n n.toggleAttribute(\"checked\", n.checked);\n } else if (n.type !== \"password\" && n.value !== n.defaultValue) {\n n.setAttribute(\"value\", n.value);\n }\n }\n}\n\n/** The builder the server calls before it serializes (protocol wcs-ssr-snapshot v1). */\nfunction build(doc: Document): void {\n // first: moving the rows into their regions (snapshot) may change what a select has selected\n forms(doc);\n for (const el of Array.from(doc.querySelectorAll(`${config.tagNames.state}[enable-ssr]`))) {\n if (el.hasAttribute(\"mount\") || el.hasAttribute(\"bind-component\")) continue;\n if (el.previousElementSibling?.localName === tag()) continue;\n const engine = (el as any).engine as Engine | null;\n if (engine !== null && engine !== undefined) snapshot(el, engine);\n }\n}\n\n/** Where the builder finds this module: the latest evaluation (a server may load one per render). */\nconst IMPL = Symbol.for(\"wcstack.state.ssr.impl\");\n\nexport function installBuilder(): void {\n const g = globalThis as any;\n g[IMPL] = { build, reset() { ids = 0; } };\n // another engine's builder (the current @wcstack/state) is not replaced\n if (g[BUILDER] === undefined) {\n g[BUILDER] = { protocol: \"wcs-ssr-snapshot\", version: 1, build: (doc: Document) => g[IMPL].build(doc), reset: () => g[IMPL].reset() };\n }\n}\n\n// ---------------------------------------------------------------- client\n\ninterface Region {\n /** The branch the region renders (null: a list). */\n readonly branch: number | null;\n /** Each row's nodes, where the server put them (a region in the row included). */\n readonly rows: Node[][];\n /**\n * The region's end mark, after its rows: the server put a view's rows after its anchor, and the view\n * renders them before it — the anchor goes here when the view takes the first row (null after).\n */\n tail: ChildNode | null;\n}\n\n/** Regions waiting for their view, by the node right before them (a view's anchor). */\nconst held = new Map<Node, Region>();\n\n/**\n * The Light DOM components of a page being hydrated, by host: their content is bound by their own\n * engine, which starts later (once its host is wired, or its class defined), so it keeps the\n * server's nodes until then and is prepared when that engine binds it (adoptScope).\n */\nconst deferred = new WeakMap<Node, { ssr: Element; adopt: boolean }>();\nconst scoped = (el: Element): boolean => hooks.componentScope?.(el) === true;\n\n/** An element regions may be in: not a text element, nor a Light DOM component (its engine reads its own). */\nconst enters = (n: Node): boolean => n.nodeType === 1 && !raw(n as Element) && !scoped(n as Element);\n\n/** A region's nodes: its rows', and its end mark. */\nconst nodesOf = (r: Region): Node[] => r.rows.flat().concat(r.tail ?? []);\n\n/** Takes a region's nodes out of the page (rows no view took, or not the plan's). */\nconst drop = (r: Region): void => {\n for (const n of nodesOf(r)) (n as ChildNode).remove();\n};\n\n/**\n * Reads the region `start` opens where it is: its marks go but its end mark, and its nodes stay (no\n * custom element in them is disconnected). It is held by the node before it, its view's anchor (the\n * page's walk then passes its nodes by: its blocks bind them where they are), or dropped (`keep`\n * false, or no node before it). A region in it — in a row, after a view's anchor of the row, or in an\n * element of it — is read in turn. Its nodes go in `row` (the row it is in); returns the node after it.\n */\nfunction read(start: Comment, keep: boolean, row?: Node[]): Node | null {\n const m = /^wcs-\\[(?::(\\d+))?/.exec(start.data)!;\n const key = start.previousSibling;\n const parent = start.parentNode!;\n const rows: Node[][] = [];\n let n: Node | null = start.nextSibling;\n start.remove();\n while (n !== null && !isMark(n, \"wcs-]\")) {\n let next: Node | null = n.nextSibling;\n if (isMark(n, \"wcs-|\")) {\n rows.push([]);\n (n as ChildNode).remove();\n } else {\n // (a branch has no row marks; a list's node before its first one is a value's)\n if (rows.length === 0) rows.push([]);\n const own = rows[rows.length - 1];\n if (startsMark(n, \"wcs-[\")) next = read(n as Comment, keep, own);\n else {\n own.push(n);\n if (enters(n)) strip(n, keep);\n }\n }\n n = next;\n }\n // (cut short — a parser moved its end mark into an element (see mend): it ends with its parent)\n const r: Region = { branch: m[1] === undefined ? null : Number(m[1]), rows, tail: (n ?? parent.appendChild(mark(\"wcs-]\"))) as ChildNode };\n const nodes = nodesOf(r);\n n = r.tail!.nextSibling;\n // (not spread: a region may have more nodes than a call takes arguments)\n for (const x of nodes) {\n row?.push(x);\n if (keep) walked.add(x);\n }\n if (keep && key !== null) {\n held.set(key, r);\n } else {\n drop(r);\n }\n return n;\n}\n\n/** Reads every region under `parent` (see read). */\nfunction strip(parent: Node, keep: boolean): void {\n for (let n: Node | null = parent.firstChild; n !== null; ) {\n if (startsMark(n, \"wcs-[\")) {\n n = read(n as Comment, keep);\n } else {\n if (enters(n)) strip(n, keep);\n n = n.nextSibling;\n }\n }\n}\n\n/** Texts and templates back to what the page was written with; the regions read (see strip). */\nfunction prepare(container: Node, ssr: Element, adopt: boolean): void {\n const walk = (parent: Node): void => {\n for (const n of Array.from(parent.childNodes)) {\n // a text marker takes the nodes up to its end with it\n if (n.parentNode !== parent) continue;\n if (n.nodeType === 8) {\n const d = (n as Comment).data;\n // (a mark the server did not write — in a value — that does not parse is left as it is;\n // a string given to replaceWith goes in as a text node)\n try {\n if (d === \"wcs-s\") n.remove();\n else if (d === \"wcs-e\") n.replaceWith(\"\");\n else if (d.startsWith(\"wcs-t:\")) {\n // the value between the markers, back to a text binding: a comment binding, which binds\n // whether or not the page's mustaches are on (it was a mustache, or a comment binding)\n const text = mark(`@@:${decodeURIComponent(d.slice(6))}`);\n let e: ChildNode | null = n.nextSibling;\n while (e !== null && !isMark(e, \"wcs-/t\")) {\n const next = e.nextSibling;\n e.remove();\n e = next;\n }\n e?.remove();\n n.replaceWith(text);\n } else if (d.startsWith(\"wcs-p:\")) {\n const t = ssr.querySelector(`template[id=\"${d.slice(6)}\"]`) as HTMLTemplateElement | null;\n if (t !== null) {\n const p = n.parentNode as Element;\n // an SVG template (`wcs-s…`): its content came in <svg> (so parsed as SVG)\n const copy = d[10] === \"s\"\n ? attrs(t, document.createElementNS(p.namespaceURI, \"template\"), ...document.importNode(t.content.firstChild!, true).childNodes)\n : document.importNode(t, true);\n copy.removeAttribute(\"id\");\n p.replaceChild(copy, n);\n }\n }\n } catch { /* */ }\n } else if (n.nodeType === 1 && !raw(n as Element)) {\n if (scoped(n as Element)) deferred.set(n, { ssr, adopt });\n else walk(n);\n }\n }\n };\n walk(container);\n mend(container);\n strip(container, adopt);\n}\n\n/**\n * A region a parser cut: its start mark in a <table>, its rows and end mark in the <tbody> the parser\n * added at its first <tr> (the regions after it with them). The comments and templates right before\n * the <tbody> that the cut region starts with go into it — its anchor and marks: nothing in them\n * connects — and the rows stay where they are. A <tbody> written in the page (a row of a list of\n * them, a branch) holds no end mark of a region that starts before it, and is left alone.\n */\nfunction mend(container: Node): void {\n for (const body of Array.from((container as ParentNode).querySelectorAll(\"table > tbody\"))) {\n const run: Node[] = [];\n for (let p = body.previousSibling; p !== null && (p.nodeType === 8 || isBlank(p) || (p as Element).localName === \"template\"); p = p.previousSibling) run.unshift(p);\n // the regions the run leaves open (an end mark whose start is before the run — past an element —\n // closes a region that stays where it is, with what comes before the mark)\n let from = 0;\n let open = 0;\n run.forEach((n, i) => {\n if (startsMark(n, \"wcs-[\")) open++;\n else if (isMark(n, \"wcs-]\") && --open < 0) {\n open = 0;\n from = i + 1;\n }\n });\n if (open === 0) continue;\n // ... and the <tbody> ends one: the parser moved its rows in\n let depth = 0;\n for (let c = body.firstChild; c !== null; c = c.nextSibling) {\n if (startsMark(c, \"wcs-[\")) depth++;\n else if (isMark(c, \"wcs-]\") && depth-- === 0) {\n body.prepend(...run.slice(from));\n break;\n }\n }\n }\n}\n\n/**\n * The `adoptScope` hook: a Light DOM component's engine binds its host. Its content is prepared\n * now, and its blocks take the server's nodes while its walk runs (a walk adopts synchronously).\n * What it did not adopt is dropped after the walk: the regions held then are its own (a page's are\n * read and adopted in one go too, and dropped before anything else runs).\n */\nexport function adoptScope(host: Node, engine: Engine): (() => void) | null {\n const d = deferred.get(host);\n if (d === undefined) return null;\n deferred.delete(host);\n const undo = (c: Node): void => prepare(c, d.ssr, d.adopt);\n // (a snapshot discarded: planned on a copy first, as the page — see hydrate)\n if (!d.adopt) plan(engine, host, host, undo);\n undo(host);\n if (!d.adopt) return null;\n const prev = hooks.adopt;\n hooks.adopt = adopt;\n return () => {\n hooks.adopt = prev;\n release();\n };\n}\n\n/** Drops the held regions: rows no view took. */\nfunction release(): void {\n for (const r of held.values()) drop(r);\n held.clear();\n}\n\n/** The comments under `scope`, in document order. */\nfunction comments(scope: Node): Comment[] {\n const out: Comment[] = [];\n for (const w = document.createTreeWalker(scope, 128); w.nextNode(); ) out.push(w.currentNode as Comment);\n return out;\n}\n\n/**\n * A Light DOM component's wiring, one entry per mapping: [the page's path (null: not known — a key\n * private to the component around), its own path (\"\" for a whole mount, `state: user`), the path as\n * its host wrote it (null at the top: the page's)].\n */\ntype Wiring = (string | null)[][];\n\n/** `path` from column `from` of `wiring` to column `to`, by the longest it is or starts with; null: none. */\nfunction across(wiring: Wiring, path: string, from: number, to: number): string | null {\n let best: (string | null)[] | null = null;\n for (const w of wiring) {\n const k = w[from];\n if (k !== null && (k === \"\" || path === k || path.startsWith(`${k}.`)) && (best === null || k.length > best[from]!.length)) best = w;\n }\n const v = best?.[to];\n if (v == null) return null;\n const k = best![from]!;\n const rest = k === \"\" ? path : path.slice(k.length + 1);\n return v === \"\" ? rest : rest === \"\" ? v : `${v}.${rest}`;\n}\n\n/**\n * The output of @wcstack/server 3.x back to the page as written, as 3.x's own fallback did\n * (`Ssr.cleanupDom`): a row or a branch (`<!--@@wcs-for-start:…-->` up to its `-end` mark among its\n * siblings) goes, a text between its marks becomes a comment binding of what the mark holds (before\n * 3.5.3 the path alone, its filters lost: the warning says so; from 3.5.3, `fresh`, the binding's\n * expression as written: wcstack#373), a template's mark (`<!--@@wcs-for:ID-->`) becomes the template\n * `<wcs-ssr>` keeps under that id (whose content has the marks of the templates in it), and the\n * elements lose `data-wcs-ssr-id`.\n *\n * In a Light DOM component, 3.x wrote a template's own path as the page's (`state: user` makes `name`\n * `user.name`; a private key `user.#m1.name`, or `#m2.name` in a partial mount; in a component in a\n * component, through both), and so the marks' paths before 3.5.3: they go back to the component's own\n * through its host's wiring (the content of a template is the component's already). A mark from 3.5.3\n * is the component's own text, not mapped (it may name a key that is one of the page's wired paths\n * too: `state.x: v; state.v: w`). An expression a comment cannot hold (one with a `--`) falls back to\n * its path, unfiltered. From 3.5.4 (wcstack#427) that is the path the component wrote, read as written\n * like any other mark: the value shows, without its filters. 3.5.3 wrote the page's path there\n * instead, which is mapped back when it names a private key (`#mN.`: never in the component's own\n * text, so the mapping cannot misread a 3.5.4 mark); a wired one cannot be told from the component's\n * own text, and is read as it — a component key of that name shows its value, the right one only when\n * the wiring keeps the name, else the text stays empty (a limit of 3.5.3 output only: migration guide\n * §3.6).\n */\nfunction legacy(container: Node, ssr: Element, fresh: boolean): void {\n const wirings = new Map<Element, Wiring>();\n /** The wiring of the Light DOM component `n` is in (a nested one's composed with the one around), or null. */\n const wiringOf = (n: Node): Wiring | null => {\n let h = n.parentElement;\n while (h !== null && !scoped(h)) h = h.parentElement;\n if (h === null) return null;\n let wiring = wirings.get(h);\n if (wiring === undefined) {\n const up = wiringOf(h);\n const prop = h.querySelector(`:scope > ${config.tagNames.state}[bind-component]`)!.getAttribute(\"bind-component\");\n wirings.set(h, (wiring = []));\n for (const b of parseBindTextsForElement(h.getAttribute(config.bindAttributeName) ?? \"\")) {\n const at = b.statePathName;\n if (b.propSegments[0] === prop) wiring.push([up ? across(up, at, 1, 0) : at, b.propSegments.slice(1).join(\".\"), up && at]);\n }\n }\n return wiring;\n };\n /**\n * A path 3.x wrote at `n`, as the component's own there (`asIs`: a text mark from 3.5.3, left as it\n * is but for a private key's path, which 3.5.3's fallback writes).\n */\n const own = (n: Node, path: string, asIs?: boolean): string => {\n const wiring = wiringOf(n);\n if (wiring === null) return path;\n // (no `|`: a mark with filters, from 3.5.3, is the component's own text, a `#m1.` in it an argument's)\n const m = /^([^|]*)#m\\d+\\.([^|]*)$/.exec(path);\n if (m === null) return asIs ? path : across(wiring, path, 0, 1) ?? path;\n // after the last private key mark, a component's own path: this one's when what comes before the\n // mark is this one's mount path (`user.#m1.name`, `user.profile.#m3.name`, `#m2.box.#m4.name` with\n // `state: box`; nothing for a partial mount, `#m2.name`), else the one's around it, which this one\n // is mounted on (`#m2.box.k` with `state: box`)\n const at = m[1].replace(/#m\\d+\\./g, \"\").slice(0, -1);\n return wiring.some((w) => w[1] === \"\" && (w[0] === at || w[2] === at)) ? m[2] : across(wiring, m[2], 2, 1) ?? m[2];\n };\n // from the last: a row's own marks go before the row does\n for (const c of comments(container).reverse()) {\n const m = /^@@wcs-(\\w+)-start:([\\s\\S]*)/.exec(c.data);\n if (m === null) continue;\n // (no end among its siblings — an output cut short: left as it is)\n let e = c.nextSibling;\n while (e !== null && !isMark(e, `@@wcs-${m[1]}-end:${m[2]}`)) e = e.nextSibling;\n if (e === null) continue;\n while (c.nextSibling !== e) c.nextSibling!.remove();\n e.remove();\n c.replaceWith(...(m[1] === \"text\" ? [mark(`@@:${own(c, m[2], fresh)}`)] : []));\n }\n const restore = (scope: Node, at?: Node): void => {\n for (const c of comments(scope)) {\n const id = /^@@wcs-(?:for|if|elseif|else):(\\S+)$/.exec(c.data)?.[1];\n const t = Array.from(ssr.querySelectorAll(\"template\")).find((x) => x.id === id);\n if (t === undefined) continue;\n const copy = document.importNode(t, true);\n const a = config.bindAttributeName;\n copy.removeAttribute(\"id\");\n copy.setAttribute(a, copy.getAttribute(a)!.replace(/^(\\s*\\w+\\s*:\\s*)([^\\s|]+)/, (_, k: string, p: string) => k + own(at ?? c, p)));\n restore(copy.content, at ?? c);\n // 3.x made each `elseif` an `if` in an `else` of its own (whose content starts with it): back\n // to the chain of templates it was written as\n const f = copy.content.firstChild as Element | null;\n c.replaceWith(...(/^\\s*elseif\\s*:/.test(f?.getAttribute?.(a) ?? \"\") ? copy.content.childNodes : [copy]));\n }\n };\n restore(container);\n for (const e of Array.from((container as ParentNode).querySelectorAll(\"[data-wcs-ssr-id]\"))) e.removeAttribute(\"data-wcs-ssr-id\");\n}\n\n/**\n * What the reader typed before the client bound the page — the server's HTML is usable at once, the\n * bundles may take seconds: the form controls whose value is not the one their markup gives (a\n * browser restoring a form on reload counts too). Binding the page writes the state's values over\n * them, and the text was lost without a word (docs/seam-apps.md, ssr-news; the author's decision,\n * docs/v4-direction-2026-10.md §5.1). Returns what gives each its value back and sends it an\n * `input` and a `change`, as the reader's own edit would: a two-way binding writes it to the state.\n */\nfunction typed(container: Node): () => void {\n const edits: [HTMLElement, () => void][] = [];\n for (const n of Array.from((container as ParentNode).querySelectorAll<any>(\"input,textarea,select\"))) {\n if (n.localName === \"select\") {\n const o: HTMLOptionElement[] = Array.from(n.options);\n const sel = o.map((x) => x.selected);\n // a single select's markup selects its last marked option, or its first enabled one (the mark\n // is read as the attribute: a server's DOM need not have defaultSelected)\n const marked = o.map((x) => x.hasAttribute(\"selected\"));\n let at = marked.lastIndexOf(true);\n if (at < 0) at = o.findIndex((x) => !x.disabled);\n if (n.multiple ? o.some((x, i) => sel[i] !== marked[i]) : n.selectedIndex !== at) edits.push([n, () => o.forEach((x, i) => (x.selected = sel[i]))]);\n } else if (n.type === \"checkbox\" || n.type === \"radio\") {\n // (a radio: the one the reader chose; the group's others follow it)\n const c = n.checked;\n if (c !== n.defaultChecked && (c || n.type === \"checkbox\")) edits.push([n, () => (n.checked = c)]);\n } else if (n.type !== \"file\" && n.value !== n.defaultValue) {\n const v = n.value;\n edits.push([n, () => (n.value = v)]);\n }\n }\n return () => {\n for (const [n, put] of edits) {\n if (!n.isConnected) continue;\n put();\n n.dispatchEvent(new Event(\"input\", { bubbles: true }));\n n.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n };\n}\n\n/**\n * Walks a copy of `container` — in a template's content, where no custom element is created — as the\n * mount of `root` walks it, once `undo` put it back as written: what this client cannot plan (a newer\n * minor's markup, a filter argument it does not know) fails its initialization while the server's\n * rows and branches are still in the page, not after they went (docs/seam-apps.md, ssr-news). (An\n * event binding puts its listener on the root at once: the mount's walk finds it there)\n */\nfunction plan(engine: Engine, root: Node, container: Node, undo: (c: Node) => void): void {\n const copy = document.createElement(\"template\").content;\n for (const n of container.childNodes) copy.appendChild(copy.ownerDocument.importNode(n, true));\n undo(copy);\n engine.root = root;\n const none = (): void => {};\n walkBindings(engine, [...copy.childNodes], null, true, none, none, none, (_, expr) => textSpec(engine, expr, null, 0));\n}\n\n/** The `element` hook, \"mounting\": a client root with a server snapshot adopts the server's DOM. */\nexport function hydrate(engine: Engine): void {\n const el = engine.element as Element;\n if (!el.hasAttribute(\"enable-ssr\") || isServer()) return;\n const ssr = el.previousElementSibling;\n const found = ssr?.localName === tag();\n const version = found ? ssr!.getAttribute(\"version\") : null;\n const same = version === null || majorMinor(version) === majorMinor(VERSION);\n if (same) {\n // the server ran $connectedCallback; the client does not\n const e = engine as any;\n const callHook = e.callHook;\n e.callHook = (name: string, args?: unknown[]) => (name === \"$connectedCallback\" ? undefined : callHook.call(engine, name, args));\n }\n if (!found) return;\n // @wcstack/server 3.x's output: marks of its own; from 3.5.3 on a text mark holds the binding's\n // expression (see legacy). A prerelease, or a version that does not parse, counts as older\n const old = !same && parseInt(version!) < 4;\n const v = /^3\\.(\\d+)\\.(\\d+)$/.exec(version!);\n const fresh = v !== null && (+v[1] - 5 || +v[2] - 3) >= 0;\n if (!same) {\n // (the filters' sentence: output before 3.5.3 only)\n console.warn(`[@wcstack/state] <${tag()} version=\"${version}\"> does not match ${VERSION}: its snapshot is discarded, and the page renders on the client from its own state.${old && !fresh\n ? \" 3.x output keeps only the path of a text binding outside a template, so such a binding loses its filters: deploy @wcstack/server 4.0 with this client.\"\n : \"\"}`);\n }\n const script = same ? ssr!.querySelector('script[type=\"application/json\"]') : null;\n if (script !== null) {\n const snap = JSON.parse(script.textContent || \"{}\") as Record<string, unknown>;\n const target = engine.target;\n for (const key of Object.keys(snap)) {\n const d = Object.getOwnPropertyDescriptor(target, key);\n if (d !== undefined && (d.get !== undefined || d.set !== undefined || typeof d.value === \"function\")) continue;\n target[key] = snap[key];\n }\n // the snapshot holds the server's volume data too: a volume adopts it (scopes/volume.ts)\n (engine as any).hydrated = true;\n }\n const root = el.getRootNode() as Document | ShadowRoot;\n for (const r of Array.from(root.querySelectorAll(`[${RAW_ATTR}]`))) {\n r.textContent = r.getAttribute(RAW_ATTR);\n r.removeAttribute(RAW_ATTR);\n }\n const container = root.nodeType === 9 ? (root as Document).body : root;\n // (its templates are not the page's markup: out before the page is walked)\n ssr!.remove();\n // back to the page as written (see prepare, legacy)\n const undo = (c: Node): void => (old ? legacy(c, ssr!, fresh) : prepare(c, ssr!, same));\n if (!same) plan(engine, root, container, undo);\n // (taken before the page is bound, which writes the state's values; given back right after)\n queueMicrotask(typed(container));\n undo(container);\n if (same) {\n // only while the page is adopted — its walk, which runs now: every other block is built with one\n // null check. What no view took then goes before anything else runs\n hooks.adopt = adopt;\n queueMicrotask(() => {\n release();\n hooks.adopt = null;\n });\n }\n}\n\n/**\n * The `ssrMark` hook: on the server, records (and leaves `outerHTML:` / `outerText:` to the client); on the client,\n * a held region follows its template's anchor.\n */\nexport function ssrMark(engine: Engine, node: Node, source: Element | string | Spec[]): void {\n if (isServer()) {\n if (source instanceof Array) {\n // `outerHTML:` / `outerText:` replace the element with the value: the client would find no\n // binding there, and walk the value as the page's markup. The server renders the element as\n // written; the client binds it and applies the value\n for (let i = source.length; i-- > 0; ) if (isOuter(source[i])) source.splice(i, 1);\n // a custom element (a Light DOM component binds its own) whose content no binding sets: what\n // is in it now is the page's (see kept)\n const el = node as Element;\n if (source.some(setsContent)) skip.add(el);\n else if (el.localName.includes(\"-\") && !scoped(el)) {\n const own = new Map<Node, string>();\n for (const w = document.createTreeWalker(el, 133); w.nextNode(); ) own.set(w.currentNode, (w.currentNode as Text).data);\n kept.set(el, own);\n }\n return;\n }\n if (typeof source === \"string\") {\n rawTexts.set(node, source);\n if (raw(node.parentNode as Element)) return;\n const open = mark(`wcs-t:${encodeURIComponent(source)}`);\n const close = mark(\"wcs-/t\");\n (node as Text).before(open);\n (node as Text).after(close);\n return;\n }\n let map = anchors.get(engine);\n if (map === undefined) anchors.set(engine, (map = new Map()));\n map.set(node, source);\n const root = node.getRootNode();\n let es = enginesByRoot.get(root);\n if (es === undefined) enginesByRoot.set(root, (es = new Set()));\n es.add(engine);\n return;\n }\n // (an element's specs are never a key: the templates the anchors replaced are)\n if (typeof source !== \"string\" && held.size > 0) {\n const r = held.get(source as Element);\n if (r !== undefined) {\n held.delete(source as Element);\n held.set(node, r);\n }\n }\n}\n\n/** An anchor of an `if` / `elseif` / `else` chain (the core names them by config). */\nconst isIfAnchor = (n: Node | null): boolean =>\n n !== null && n.nodeType === 8 && [config.commentIfPrefix, config.commentElseIfPrefix, config.commentElsePrefix].includes((n as Comment).data);\nconst isBlank = (n: Node): boolean => n.nodeType === 3 && (n as Text).data.trim() === \"\";\n\n/** The next of the plan's nodes after `n`: a held region after an anchor is the anchor's view's. */\nconst after = (n: Node): Node | null => {\n const x = held.get(n)?.tail ?? n;\n return (beside(x) ?? x).nextSibling;\n};\n\n/**\n * Whether a row's top-level nodes `own` have the plan's nodes where a binding lands — not so when a\n * Light DOM element added children before them, or a parser moved them (see mend); puts them\n * in `plan.scratch` for the block.\n */\nfunction fits(plan: RowPlan, own: Node[]): boolean {\n if (own.length !== plan.fragment.childNodes.length) return false;\n const paths = plan.nodePaths;\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i];\n let a: Node = plan.fragment;\n let b: Node | null | undefined = own[path[0]];\n for (let j = 0; ; ) {\n a = a.childNodes[path[j]];\n if (b?.nodeName !== a.nodeName) return false;\n if (++j === path.length) break;\n b = (beside(b) ?? b).firstChild;\n for (let k = path[j]; k > 0 && b !== null; k--) b = after(b);\n }\n plan.scratch[i] = b;\n }\n return true;\n}\n\n/**\n * The `adopt` hook: the next server row (or branch) of the view anchored at `anchor` — its top-level\n * nodes, left where they are (the view inserts nothing, and no custom element in them is disconnected).\n */\nexport function adopt(plan: RowPlan, anchor: Node, isFor: boolean): ChildNode[] | null {\n if (held.size === 0) return null;\n let key = anchor;\n let branch = 0;\n if (!isFor) {\n // only this chain: an `if` anchor starts one (a chain right before or after is another). No\n // element is between its anchors: whitespace, comments (readChain) and the text a comment binding\n // there renders may be\n const head = config.commentIfPrefix;\n if (!isMark(anchor, head)) {\n for (let p = anchor.previousSibling; p !== null && p.nodeType !== 1; p = p.previousSibling) {\n if (isIfAnchor(p)) branch++;\n if (isMark(p, head)) break;\n }\n }\n // up to the anchor its region follows (the branch's nodes come right after it)\n for (let n = anchor.nextSibling; !held.has(key) && n !== null && !isMark(n, head) && n.nodeType !== 1; n = n.nextSibling) {\n if (isIfAnchor(n)) key = n;\n }\n }\n const r = held.get(key);\n if (r === undefined) return null;\n if (!isFor && r.branch !== branch) {\n // the server rendered another branch: it goes, this one is built\n held.delete(key);\n drop(r);\n return null;\n }\n const nodes = r.rows.shift();\n if (r.rows.length === 0) held.delete(key);\n // a view renders before its anchor (a branch before its own: the chain's anchors from it on), and\n // the server put its rows after: the anchors go where the rows end\n r.tail?.replaceWith(...range(anchor, key));\n r.tail = null;\n if (nodes === undefined) return null;\n // the row's own top-level nodes (a region in it is a nested view's, a link's anchor the link's)\n let own: Node[] = [];\n for (let i = 0; i < nodes.length; i++) {\n const inner = held.get(nodes[i]);\n own.push(nodes[i]);\n // (its nodes follow it, up to its end mark)\n if (inner !== undefined) while (i < nodes.length && nodes[i] !== inner.tail) i++;\n else if (beside(nodes[i]) === nodes[i + 1]) i++;\n }\n if (!fits(plan, own)) {\n // rendered anew, in its place (the rows around it stay; an empty one's place is before the next\n // row, or the anchor): its nodes found before it is in the page (a custom element in it may add\n // children as it connects)\n const fresh = (plan.single ? plan.root! : plan.fragment).cloneNode(true);\n own = plan.single ? [fresh] : [...fresh.childNodes];\n fits(plan, own);\n ((nodes[0] ?? r.rows.find((x) => x.length > 0)?.[0] ?? anchor) as ChildNode).before(fresh);\n for (const n of nodes) (n as ChildNode).remove();\n }\n return own as ChildNode[];\n}\n","/**\n * The SSR add-on (@wcstack/state/features/ssr): `<wcs-state enable-ssr>` with @wcstack/server —\n * see src/ssr/ssr.ts.\n */\nimport { chain, hooks, type Feature } from \"../hooks\";\nimport { adoptScope, hydrate, installBuilder, ssrMark } from \"../ssr/ssr\";\nimport { defineSsr } from \"../ssr/element\";\nimport { registries } from \"../element\";\n\nexport const ssr: Feature = {\n name: \"ssr\",\n hooks,\n install(): void {\n hooks.ssrMark = ssrMark;\n hooks.adoptScope = adoptScope;\n // the snapshot first, before what is installed (in any order) runs at \"mounting\": a volume\n // grafting there adopts it, and its $connectedCallback writes over it (3.x D14)\n const prev = hooks.element;\n hooks.element = (engine, phase) => {\n if (phase === \"mounting\") hydrate(engine);\n prev?.(engine, phase);\n };\n installBuilder();\n // `<wcs-ssr>` in every registry `<wcs-state>` is defined in, now and later\n hooks.tags = chain(hooks.tags, defineSsr);\n for (const r of registries()) defineSsr(r);\n },\n};\nexport default ssr;\n"],"mappings":"4gBAwBO,IAAMA,EAAcC,GAAsBA,EAAEC,MAAM,KAAKC,MAAM,EAAG,GAAGC,KAAK,KAElEC,EAAN,cAAkBC,EAEvB,WAAOC,CAAKC,GACV,OAASA,EAAoBC,gBAAgBC,EAAOC,SAASC,MAAuB,IACtF,CAEA,WAAIC,GACF,OAAOC,KAAKC,aAAa,YAAc,EACzC,CAEA,aAAIC,GACF,IAAMC,EAASH,KAAKL,cAAc,mCAClC,OAAkB,OAAXQ,EAAkB,CAAC,EAAIC,KAAKC,MAAMF,EAAOG,aAAe,KACjE,CAEA,aAAIC,GACF,IAAMC,EAAM,IAAIC,IAEhB,QAAWC,KAAKC,MAAMC,KAAKZ,KAAKa,UAAkC,aAAhBH,EAAEI,WAA0BN,EAAIO,IAAIL,EAAEM,GAAIN,GAC5F,OAAOF,CACT,CAEA,gBAAIS,GACF,MAAO,CAAC,CACV,CAEA,WAAAC,CAAYF,GACV,OAAOhB,KAAKO,UAAUY,IAAIH,IAAO,IACnC,CAEA,aAAAI,GACE,OAAOlC,EAAWc,KAAKD,WAAab,EAAWmC,EACjD,GAIK,SAASC,EAAUC,GACxB,IAAMC,EAAM5B,EAAOC,SAASC,SACF,IAAtByB,EAASJ,IAAIK,IAAoBD,EAASE,OAAOD,EAAK,cAAcjC,IAC1E,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,CAoEiBC,CAAMzG,IACrBmB,EAAKnB,GACDqE,IAGF5F,EAAMwB,GAAQA,GACd6F,eAAe,KACbxE,IACA7C,EAAMwB,GAAQ,OAGpB,CC5uBgCyG,CAAQ1M,GAClCqH,IAAOrH,EAAQmK,IDsSd,WACL,IAAMwC,EAAIC,WACVD,EAAErI,GAAQ,CAAEd,QAAO,KAAAqJ,GAAU/M,EAAM,CAAG,QAEnB,IAAf6M,EAAEtR,KACJsR,EAAEtR,GAAW,CAAEyR,SAAU,mBAAoBpT,QAAS,EAAG8J,MAAQC,GAAkBkJ,EAAErI,GAAMd,MAAMC,GAAMoJ,MAAO,IAAMF,EAAErI,GAAMuI,SAEhI,CC3SIE,GAEAtI,EAAMuI,GAAOlM,EAAM2D,EAAMuI,GAAM/R,GAC/B,QAAW4J,KAAKoI,IAAchS,EAAU4J,EAC1C,GAEKqI,GAAQzT","ignoreList":[]}
@@ -1,2 +1,2 @@
1
- import{a as t,c as e}from"../chunks/chunk-MZVF2WEY.js";import{a as n,b as r,c as i,d as s,e as l,j as a,k as o}from"../chunks/chunk-SJRJALR4.js";var h={},f=/\.\d/,u=new Set(Object.getOwnPropertyNames(Object.prototype)),c=0,p=!1,d=null,m=()=>{p=!1,c++};function g(){if(null===d)if("function"==typeof MessageChannel){let t=new MessageChannel;t.port1.onmessage=m,t.port1.unref?.(),d=()=>t.port2.postMessage(0)}else d=()=>setTimeout(m,0);return p||(p=!0,d()),c}function y(t,e){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let n of t.Q){for(let r of e)if(n.ee(r)&&(n.n===r.n||!(r.n<t.n&&t.h[r.n+1].ee(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var v=class{constructor(t,e){this.active=!1,this.Fe=new Map,this.early=[],this.n=0,this.Io=-1,this._n=new Set,this.qe=null,this.engine=t,this.De=e}pr(){let t=this.engine;this.Fe.clear();let e=this.early;this.early=[];for(let e of this.De)e.getter=null!==e.p.getter||e.p.ae,e.s=new WeakMap,this.prime(e,()=>{0===e.p.n?e.getter&&e.s.set(h,t.v(e.p,null)):this.Vn(e.p,1,null,n=>{e.getter&&this.prime(e,()=>e.s.set(n,t.v(e.p,n)))})});this.active=!0;let n=new Set;for(let[r,i,s,l]of e)if((null===i||i.w)&&Object.is(t.v(r,i),l)){n.add(r);for(let t of this.De)t.p===r&&this.ft(t,i,s,!0)}for(let t of this.De)t.getter&&0===t.p.n&&!this.Fe.has(t)&&y($(t.p),n)&&this.ft(t,null,void 0,!0);this.Fe.size>0&&t.ve()}prime(t,e){try{e()}catch(e){o(e,`[@wcstack/state] $watch initial evaluation of "${t.t}" threw.`),n.ct?.(this.engine,{type:"state:watch-error",phase:"prime",path:t.t,error:e})}}Do(){this.active=!1,this.Fe.clear(),this.early=[]}Vn(t,e,n,r){let i=this.engine.Ke(n,t.h[e]);for(let n of i.f)e===t.n?r(n):this.Vn(t,e+1,n,r)}ft(t,e,n,r){let i=this.Fe.get(t);void 0===i&&this.Fe.set(t,i=new Map);let s=i.get(e);void 0===s?i.set(e,[n,this.n,r]):(s[1]<this.n&&(s[1]=this.n),s[2]||=r)}re(t,e,n,r,i,s){if(this.active){(this.qe??=new Set).add(t);for(let s of this.De){let l=s.p;l.n!==t.n||!l.ee(t)||this.ft(s,e,s.getter?s.s.get(e??h):l===t&&i&&this.engine.Vt&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}else s&&this.early.push([t,e,n,r])}Se(t,e){if(this.active)for(let n of this.De)(n.getter||=null!==n.p.getter||n.p.ae)&&n.p.n===t.n&&n.p.ee(t)&&this.ft(n,e,n.s.get(e??h),!1)}Qt(t,e){if(!this.active)return;let n=null;for(let r of this.De){let i=r.p;if(!(i.n<t.n||i.h[t.n]!==t.o)){n??=new Set(e);for(let e of t.f)n.has(e)||(i.n===t.n?this.ft(r,e,void 0,!0):this.Vn(i,t.n+1,e,t=>this.ft(r,t,void 0,!0)))}}}me(){let t=this.qe;if(this.qe=null,!this.active||0===this.Fe.size)return;let e=this.Fe;this.Fe=new Map;let r=this.engine,i=[];for(let s of this.De){let l=e.get(s);if(void 0===l)continue;let a,u=[...l].filter(([t])=>null===t||t.w);u.length>1&&u.sort((t,e)=>w(t[0],e[0]));for(let[e,[l,c,p]]of u){let u,d="evaluate",m=r.d;this.n=c+1,r.Ce++;try{if(u=r.v(s.p,e),s.getter&&(s.s.set(e??h,u),Object.is(u,l)&&(f.test(s.t)||null!==e&&!p&&!(a??=null!==t&&y($(s.p),t)))))continue;if(c>32){i.includes(s.t)||i.push(s.t);continue}r.d=e,n.ct?.(r,{type:"state:watch-fired",path:s.t}),d="handler",s.handler.call(r.proxy,u,l,...r.H(e))}catch(t){o(t,`[@wcstack/state] $watch "${s.t}" failed; the other watches still run.`),n.ct?.(r,{type:"state:watch-error",phase:d,path:s.t,error:t})}finally{r.d=m,this.n=0,r.Ce--}}}i.length>0&&this.jo(i)}jo(t){let e=g();e!==this.Io&&(this.Io=e,this._n.clear());let r=t.filter(t=>!this._n.has(t));if(0!==r.length){for(let t of r)this._n.add(t);o("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),n.ct?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:r})}}};function $(t){for(;null===t.getter&&null!==t.a;)t=t.a;return t}function w(t,e){let n=[],r=[];for(let e=t;null!==e;e=e.l.ce)n.unshift(e.y);for(let t=e;null!==t;t=t.l.ce)r.unshift(t.y);for(let t=0;t<n.length&&t<r.length;t++)if(n[t]!==r[t])return n[t]-r[t];return n.length-r.length}var b="$streamStatus",M="$streamError",j=new Set(Object.getOwnPropertyNames(Object.prototype)),D=!1;function S(t,e){for(let n=t;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return void 0!==t.get||void 0!==t.set||"function"==typeof t.value}return!1}var k=class{constructor(t,e,n){this.engine=t,this.entries=e,this.M=n}set(t,e,n){D=!0;try{this.engine.A(this.engine.o(`${t}.${e}`),null,n)}finally{D=!1}}mr(){for(let t of this.entries)this.start(t,!0)}hr(){for(let t of this.entries)t.pt=!1,t.J?.abort(),t.J=null}gr(){for(let t of this.entries)t.pt=!1,null!==t.J&&(t.J.abort(),t.J=null),this.set(b,t.name,"idle")}Se(t){let e=this.M.n;for(let n of this.entries)n.g===t&&(n.n=n.pt?Math.max(n.n,e):e,n.pt=!0)}me(){let t=this.engine,n=this.M,r=[];for(let i of this.entries){if(!i.pt)continue;let s=i.n;if(i.pt=!1,s>32)r.push(i.name),i.g.Y=e;else{n.n=s+1,t.Ce++;try{this.start(i,!1)}finally{t.Ce--,n.n=0}}}r.length>0&&n.jo(r)}start(t,n){let r,i=this.engine;if(null!==t.J&&t.J.abort(),t.J=null,null!==t.g){let s=t.g;s.getter=t.args;let l=s.Q.slice();O(s);try{r=i.read(s,null),function(t,e,n){null!==n&&"function"==typeof n?.then&&a(`$stream "${t}": args must be synchronous (it returned a Promise).`);for(let n of e.Q)n.n>0&&a(`$stream "${t}": args must not read a wildcard path ("${n.t}").`),(n.t===t||n.t===`${b}.${t}`||n.t===`${M}.${t}`)&&a(`$stream "${t}": args must not read the stream itself ("${n.t}").`)}(t.name,s,r)}catch(r){O(s);for(let t of l)t.Hn(s);if(s.Y=e,n)throw r;return this.set(M,t.name,r),void this.set(b,t.name,"error")}}let s=new AbortController;t.J=s,i.A(i.o(t.name),null,t.K),this.set(M,t.name,null),this.set(b,t.name,"active"),this.yr(t,s,r)}async yr(t,e,n){let r=this.engine,i=e.signal,s=()=>!i.aborted&&t.J===e,l=r.o(t.name),a=this.M.n,o=g(),h=t=>{g()===o&&(this.M.n=a);try{t()}finally{this.M.n=0}},f=t.K;try{let e=await t.source(n,i);if(!s())return;let a=e=>{f=void 0!==t.Lo?t.Lo(f,e):e,h(()=>r.A(l,null,f))};if(null!==e&&"function"==typeof e?.getReader){let t=e.getReader();for(i.addEventListener("abort",()=>{t.cancel().catch(()=>{})});;){let e=await t.read();if(!s())return;if(e.done)break;a(e.value)}}else{if(null===e||"function"!=typeof e?.[Symbol.asyncIterator])throw new TypeError(`$stream "${t.name}": source must return an async iterable or a ReadableStream`);{let t=e[Symbol.asyncIterator]();for(i.addEventListener("abort",()=>{t.return?.()});;){let e=await t.next();if(!s())return;if(e.done)break;a(e.value)}}}if(!s())return;t.J=null,h(()=>this.set(b,t.name,"done"))}catch(n){if(!s())return;t.J=null,e.abort(),h(()=>{this.set(M,t.name,n),this.set(b,t.name,"error")})}}};function O(e){for(let t of e.Q){let n=t.B.indexOf(e);n>=0&&t.B.splice(n,1),t.yt.delete(e)}e.Q.length=0,e.Y=t}var J=new WeakMap;function Q(t){let e=J.get(t);return e?.target===t.target?e:void 0}function F(t,e){let r=new v(t,function(t,e){if(void 0===e)return[];(null===e||"object"!=typeof e)&&a("$watch must be an object mapping paths to handler functions.");let r=[];for(let i of Object.keys(e)){let s=e[i];(""===i||"$"===i[0]||i.includes("@")||u.has(i))&&a(`$watch path "${i}" is not a path of the state tree.`),"function"!=typeof s&&a(`$watch entry "${i}" must be a function.`);let l=t.o(i);n.xo?.(t,l,!0),r.push({t:i,p:l,handler:s,getter:!1,s:new WeakMap})}return r}(t,e.$watch)),i=new k(t,function(t,e){let n=e.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&a("$stream must be an object mapping stream names to definitions.");let r=[],i={},s={};for(let l of Object.keys(n)){let o=n[l];(""===l||"$"===l[0]||/[.*]/.test(l)||j.has(l))&&a(`$stream entry "${l}" must be a flat property name.`),(null===o||"object"!=typeof o)&&a(`$stream entry "${l}" must be an object.`);let h=o.source,f=o.fold,u=o.args,c=o.initial;"function"!=typeof h&&a(`$stream entry "${l}" needs a source function.`),void 0!==f&&"function"!=typeof f&&a(`$stream entry "${l}": fold must be a function.`),void 0!==f&&!("initial"in o)&&a(`$stream entry "${l}": fold needs an initial value.`),void 0!==u&&"function"!=typeof u&&a(`$stream entry "${l}": args must be a function.`),S(e,l)&&a(`$stream entry "${l}" collides with a getter, setter or method of the state.`),void 0===e[l]&&(e[l]=c),i[l]="idle",s[l]=null,r.push({name:l,source:h,Lo:f,K:c,J:null,pt:!1,n:0,g:void 0===u?null:t.o(`$streamArgs.${l}`),args:void 0===u?null:function(){return u(this)}})}return e[b]=i,e[M]=s,r}(t,e),r),s=J.get(t);void 0!==s&&(s.M.Do(),s.Dt.hr()),J.set(t,{M:r,Dt:i,Qe:s?.Qe??!1,target:e})}function A(t,e){let n=J.get(t);if(void 0!==n&&"mounting"!==e&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==e&&(n.Qe="connected"===e),n.target===t.target)){if("disconnected"===e)return n.M.Do(),void n.Dt.gr();n.Qe&&(n.M.pr(),n.Dt.mr())}}var C=["$streamStatus","$streamError"],x={name:"temporal",hooks:n,install(){n.fe=r(n.fe,F),n.element=r(n.element,A),n.re=r(n.re,(t,e,n,r,i,s,l)=>Q(t)?.M.re(e,n,r,i,s,l)),n.Se=r(n.Se,(t,e,n)=>{let r=Q(t);void 0!==r&&(r.M.Se(e,n),r.Dt.Se(e))}),n.Qt=r(n.Qt,(t,e,n)=>Q(t)?.M.Qt(e,n)),n.me=r(n.me,t=>{let e=Q(t);void 0!==e&&(e.M.me(),e.Dt.me())}),n.it=i(l,n.it,(t,e)=>{let n=e.split(".",1)[0];if(C.includes(n))return n===e?t.target[e]:t.read(t.o(e),null)}),n.Ie=i(s,n.Ie,(t,e)=>(!D&&36===e.t.charCodeAt(0)&&C.includes(e.t.split(".",1)[0])&&a(`"${e.t}" is read-only (the stream runtime owns it).`),!1))}},E=x;export{E as default,x as temporal};
1
+ import{a as t,c as e}from"../chunks/chunk-NAV7FBTI.js";import{a as n,b as r,c as s,d as i,e as l,j as o,k as a}from"../chunks/chunk-LPJFTEVT.js";var h={},f=/\.\d/,u=new Set(Object.getOwnPropertyNames(Object.prototype)),c=0,p=!1,m=null,d=()=>{p=!1,c++};function g(){if(null===m)if("function"==typeof MessageChannel){let t=new MessageChannel;t.port1.onmessage=d,t.port1.unref?.(),m=()=>t.port2.postMessage(0)}else m=()=>setTimeout(d,0);return p||(p=!0,m()),c}function y(t,e){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let n of t.Z){for(let r of e)if(n.te(r)&&(n.n===r.n||!(r.n<t.n&&t.h[r.n+1].te(r))))return!0;null!==n.getter&&r.push(n)}}}return!1}var $=class{constructor(t,e){this.active=!1,this.Fe=new Map,this.early=[],this.n=0,this.Do=-1,this._n=new Set,this.qe=null,this.engine=t,this.De=e}pr(){let t=this.engine;this.Fe.clear();let e=this.early;this.early=[];for(let e of this.De)e.getter=null!==e.p.getter||e.p.ue,e.s=new WeakMap,this.prime(e,()=>{0===e.p.n?e.getter&&e.s.set(h,t.v(e.p,null)):this.Vn(e.p,1,null,n=>{e.getter&&this.prime(e,()=>e.s.set(n,t.v(e.p,n)))})});this.active=!0;let n=new Set;for(let[r,s,i,l]of e)if((null===s||s.w)&&Object.is(t.v(r,s),l)){n.add(r);for(let t of this.De)t.p===r&&this.pt(t,s,i,!0)}for(let t of this.De)t.getter&&0===t.p.n&&!this.Fe.has(t)&&y(v(t.p),n)&&this.pt(t,null,void 0,!0);this.Fe.size>0&&t.$e()}prime(t,e){try{e()}catch(e){a(e,`[@wcstack/state] $watch initial evaluation of "${t.t}" threw.`),n.ut?.(this.engine,{type:"state:watch-error",phase:"prime",path:t.t,error:e})}}jo(){this.active=!1,this.Fe.clear(),this.early=[]}Vn(t,e,n,r){let s=this.engine.Ke(n,t.h[e]);for(let n of s.d)e===t.n?r(n):this.Vn(t,e+1,n,r)}pt(t,e,n,r){let s=this.Fe.get(t);void 0===s&&this.Fe.set(t,s=new Map);let i=s.get(e);void 0===i?s.set(e,[n,this.n,r]):(i[1]<this.n&&(i[1]=this.n),i[2]||=r)}se(t,e,n,r,s,i){if(this.active){(this.qe??=new Set).add(t);for(let i of this.De){let l=i.p;l.n!==t.n||!l.te(t)||this.pt(i,e,i.getter?i.s.get(e??h):l===t&&s&&this.engine.Ut&&(null===r||"object"!=typeof r&&"function"!=typeof r)?n:void 0,!0)}}else i&&this.early.push([t,e,n,r])}Ne(t,e){if(this.active)for(let n of this.De)(n.getter||=null!==n.p.getter||n.p.ue)&&n.p.n===t.n&&n.p.te(t)&&this.pt(n,e,n.s.get(e??h),!1)}st(t,e){if(!this.active)return;let n=null;for(let r of this.De){let s=r.p;if(!(s.n<t.n||s.h[t.n]!==t.o)){n??=new Set(e);for(let e of t.d)n.has(e)||(s.n===t.n?this.pt(r,e,void 0,!0):this.Vn(s,t.n+1,e,t=>this.pt(r,t,void 0,!0)))}}}me(){let t=this.qe;if(this.qe=null,!this.active||0===this.Fe.size)return;let e=this.Fe;this.Fe=new Map;let r=this.engine,s=[];for(let i of this.De){let l=e.get(i);if(void 0===l)continue;let o,u=[...l].filter(([t])=>null===t||t.w);u.length>1&&u.sort((t,e)=>w(t[0],e[0]));for(let[e,[l,c,p]]of u){let u,m="evaluate",d=r.f;this.n=c+1,r.Ce++;try{if(u=r.v(i.p,e),i.getter&&(i.s.set(e??h,u),Object.is(u,l)&&(f.test(i.t)||null!==e&&!p&&!(o??=null!==t&&y(v(i.p),t)))))continue;if(c>32){s.includes(i.t)||s.push(i.t);continue}r.f=e,n.ut?.(r,{type:"state:watch-fired",path:i.t}),m="handler",i.handler.call(r.proxy,u,l,...r.K(e))}catch(t){a(t,`[@wcstack/state] $watch "${i.t}" failed; the other watches still run.`),n.ut?.(r,{type:"state:watch-error",phase:m,path:i.t,error:t})}finally{r.f=d,this.n=0,r.Ce--}}}s.length>0&&this.Lo(s)}Lo(t){let e=g();e!==this.Do&&(this.Do=e,this._n.clear());let r=t.filter(t=>!this._n.has(t));if(0!==r.length){for(let t of r)this._n.add(t);a("[@wcstack/state] $watch handlers / $stream restarts kept writing for 32 batches; the chain is cut (nothing is rolled back)."),n.ut?.(this.engine,{type:"state:watch-chain-limit",maxDepth:32,paths:r})}}};function v(t){for(;null===t.getter&&null!==t.c;)t=t.c;return t}function w(t,e){let n=[],r=[];for(let e=t;null!==e;e=e.l.oe)n.unshift(e.y);for(let t=e;null!==t;t=t.l.oe)r.unshift(t.y);for(let t=0;t<n.length&&t<r.length;t++)if(n[t]!==r[t])return n[t]-r[t];return n.length-r.length}var b="$streamStatus",j="$streamError",_=new Set(Object.getOwnPropertyNames(Object.prototype)),k=!1;function Q(t,e){for(let n=t;null!==n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return void 0!==t.get||void 0!==t.set||"function"==typeof t.value}return!1}var O=class{constructor(t,e,n){this.engine=t,this.entries=e,this._=n}set(t,e,n){k=!0;try{this.engine.F(this.engine.o(`${t}.${e}`),null,n)}finally{k=!1}}mr(){for(let t of this.entries)this.start(t,!0)}hr(){for(let t of this.entries)t.mt=!1,t.Q?.abort(),t.Q=null}gr(){for(let t of this.entries)t.mt=!1,null!==t.Q&&(t.Q.abort(),t.Q=null),this.set(b,t.name,"idle")}Ne(t){let e=this._.n;for(let n of this.entries)n.g===t&&(n.n=n.mt?Math.max(n.n,e):e,n.mt=!0)}me(){let t=this.engine,n=this._,r=[];for(let s of this.entries){if(!s.mt)continue;let i=s.n;if(s.mt=!1,i>32)r.push(s.name),s.g.G=e;else{n.n=i+1,t.Ce++;try{this.start(s,!1)}finally{t.Ce--,n.n=0}}}r.length>0&&n.Lo(r)}start(t,n){let r,s=this.engine;if(null!==t.Q&&t.Q.abort(),t.Q=null,null!==t.g){let i=t.g;i.getter=t.args;let l=i.Z.slice();F(i);try{r=s.read(i,null),function(t,e,n){null!==n&&"function"==typeof n?.then&&o(`$stream "${t}": args must be synchronous (it returned a Promise).`);for(let n of e.Z)n.n>0&&o(`$stream "${t}": args must not read a wildcard path ("${n.t}").`),(n.t===t||n.t===`${b}.${t}`||n.t===`${j}.${t}`)&&o(`$stream "${t}": args must not read the stream itself ("${n.t}").`)}(t.name,i,r)}catch(r){F(i);for(let t of l)t.Hn(i);if(i.G=e,n)throw r;return this.set(j,t.name,r),void this.set(b,t.name,"error")}}let i=new AbortController;t.Q=i,s.F(s.o(t.name),null,t.z),this.set(j,t.name,null),this.set(b,t.name,"active"),this.yr(t,i,r)}async yr(t,e,n){let r=this.engine,s=e.signal,i=()=>!s.aborted&&t.Q===e,l=r.o(t.name),o=this._.n,a=g(),h=t=>{g()===a&&(this._.n=o);try{t()}finally{this._.n=0}},f=t.z;try{let e=await t.source(n,s);if(!i())return;let o=e=>{f=void 0!==t.Bo?t.Bo(f,e):e,h(()=>r.F(l,null,f))};if(null!==e&&"function"==typeof e?.getReader){let t=e.getReader();for(s.addEventListener("abort",()=>{t.cancel().catch(()=>{})});;){let e=await t.read();if(!i())return;if(e.done)break;o(e.value)}}else{if(null===e||"function"!=typeof e?.[Symbol.asyncIterator])throw new TypeError(`$stream "${t.name}": source must return an async iterable or a ReadableStream`);{let t=e[Symbol.asyncIterator]();for(s.addEventListener("abort",()=>{t.return?.()});;){let e=await t.next();if(!i())return;if(e.done)break;o(e.value)}}}if(!i())return;t.Q=null,h(()=>this.set(b,t.name,"done"))}catch(n){if(!i())return;t.Q=null,e.abort(),h(()=>{this.set(j,t.name,n),this.set(b,t.name,"error")})}}};function F(e){for(let t of e.Z){let n=t.M.indexOf(e);n>=0&&t.M.splice(n,1),t.wt.delete(e)}e.Z.length=0,e.G=t}var D=new WeakMap;function L(t){let e=D.get(t);return e?.target===t.target?e:void 0}function M(t,e){let r=new $(t,function(t,e){if(void 0===e)return[];(null===e||"object"!=typeof e)&&o("$watch must be an object mapping paths to handler functions.");let r=[];for(let s of Object.keys(e)){let i=e[s];(""===s||"$"===s[0]||s.includes("@")||u.has(s))&&o(`$watch path "${s}" is not a path of the state tree.`),"function"!=typeof i&&o(`$watch entry "${s}" must be a function.`);let l=t.o(s);n.Ro?.(t,l,!0),r.push({t:s,p:l,handler:i,getter:!1,s:new WeakMap})}return r}(t,e.$watch)),s=new O(t,function(t,e){let n=e.$stream;if(void 0===n)return[];(null===n||"object"!=typeof n)&&o("$stream must be an object mapping stream names to definitions.");let r=[],s={},i={};for(let l of Object.keys(n)){let a=n[l];(""===l||"$"===l[0]||/[.*]/.test(l)||_.has(l))&&o(`$stream entry "${l}" must be a flat property name.`),(null===a||"object"!=typeof a)&&o(`$stream entry "${l}" must be an object.`);let h=a.source,f=a.fold,u=a.args,c=a.initial;"function"!=typeof h&&o(`$stream entry "${l}" needs a source function.`),void 0!==f&&"function"!=typeof f&&o(`$stream entry "${l}": fold must be a function.`),void 0!==f&&!("initial"in a)&&o(`$stream entry "${l}": fold needs an initial value.`),void 0!==u&&"function"!=typeof u&&o(`$stream entry "${l}": args must be a function.`),Q(e,l)&&o(`$stream entry "${l}" collides with a getter, setter or method of the state.`),void 0===e[l]&&(e[l]=c),s[l]="idle",i[l]=null,r.push({name:l,source:h,Bo:f,z:c,Q:null,mt:!1,n:0,g:void 0===u?null:t.o(`$streamArgs.${l}`),args:void 0===u?null:function(){return u(this)}})}return e[b]=s,e[j]=i,r}(t,e),r),i=D.get(t);void 0!==i&&(i._.jo(),i.Lt.hr()),D.set(t,{_:r,Lt:s,Qe:i?.Qe??!1,target:e})}function S(t,e){let n=D.get(t);if(void 0!==n&&"mounting"!==e&&!document.documentElement?.hasAttribute("data-wcs-server")&&("reset"!==e&&(n.Qe="connected"===e),n.target===t.target)){if("disconnected"===e)return n._.jo(),void n.Lt.gr();n.Qe&&(n._.pr(),n.Lt.mr())}}var N=["$streamStatus","$streamError"],C={name:"temporal",hooks:n,install(){n.fe=r(n.fe,M),n.element=r(n.element,S),n.se=r(n.se,(t,e,n,r,s,i,l)=>L(t)?._.se(e,n,r,s,i,l)),n.Ne=r(n.Ne,(t,e,n)=>{let r=L(t);void 0!==r&&(r._.Ne(e,n),r.Lt.Ne(e))}),n.st=r(n.st,(t,e,n)=>L(t)?._.st(e,n)),n.me=r(n.me,t=>{let e=L(t);void 0!==e&&(e._.me(),e.Lt.me())}),n.it=s(l,n.it,(t,e)=>{let n=e.split(".",1)[0];if(N.includes(n))return n===e?t.target[e]:t.read(t.o(e),null)}),n.Ie=s(i,n.Ie,(t,e)=>(!k&&36===e.t.charCodeAt(0)&&N.includes(e.t.split(".",1)[0])&&o(`"${e.t}" is read-only (the stream runtime owns it).`),!1))}},E=C;export{E as default,C as temporal};
2
2
  //# sourceMappingURL=temporal.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wcstack/state",
3
- "version": "4.10.1",
3
+ "version": "4.11.1",
4
4
  "description": "Reactive state management with declarative data binding for Web Components. Zero dependencies, buildless.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.esm.js",
@@ -1,2 +0,0 @@
1
- import{p as n,r as t}from"./chunk-IWY3I2DG.js";import{a as l,b as e,c as r}from"./chunk-MZVF2WEY.js";import{a as o}from"./chunk-SJRJALR4.js";var i=Symbol.for("wcstack.binder"),u=Symbol.for("wcstack.binder.pending"),s=Symbol.for("wcstack.binder.taken");var a=new Map;function f(l,e){if(1!==l.nodeType||!l.isConnected)return;let r=n.get(l.getRootNode());void 0===r||!1===r.element?.isConnected?a.set(l,e):t(r,l,e?.range)}function c(){let n=[...a];a.clear();for(let[t,l]of n)f(t,l);!function(){let n=function(){let n=globalThis[i];return null==n||"wcs-binder"!==n.protocol||"number"!=typeof n.version||n.version<1||"function"!=typeof n.bind?null:n}();if(null===n)return;let t=function(){let n=globalThis,t=n[u];return void 0===t&&(t=[],n[u]=t),t}();if(0===t.length)return;let l=t.splice(0,t.length),e=function(){let n=globalThis,t=n[s];return void 0===t&&(t=new WeakSet,n[s]=t),t}();for(let t of l)e.add(t),n.bind(t)}()}function d(){let n=globalThis;void 0===n[i]&&(n[i]={protocol:"wcs-binder",version:1,bind:f})}var b=class{constructor(){this.name="dirty",this.Z=(n,t)=>{if(0===n.n){let t=n.Y;return t!==l&&t!==e&&(n.Y=e,!0)}let r=null===t?null:t.vt;if(null===r)return!1;let o=r[n.F];return o!==l&&o!==e&&(r[n.F]=e,!0)}}er(n,t,l){null!==t.getter&&this.Z(t,l),n.xt(t,l),n.Rn(t,l,this.Z)}qo(n,t){let l=t.l.o.Lt;if(null!==l)for(let e of l)e.n===t.l.n?n.at(e,t,this.Z):n.en(t,e,t=>n.at(e,t,this.Z))}ke(n,t,l){this.Z(t,l),o.Se?.(n,t,l),n.xt(t,l),n.Rn(t,l,this.Z)}zo(n,t,o){let i=0===t.n;if(!i&&null===o)return;let u=i?null:o.vt??=new Array(n.Le).fill(l),s=null===u?t.Y:u[t.F];if(s!==l&&s!==e&&s!==r&&(null===u||t.F in u))return s;s=r;try{return s=n.Yo(t,null===u?null:o)}finally{null===u?t.Y=s:u[t.F]=s}}Gt(n){n.vt=null}nt(n){for(let t of n.O.all())null!==t.getter&&(0===t.n?t.Y===e&&(t.Y=r):n.nn(t.h[t.n],n=>{let l=n.vt;null!==l&&l[t.F]===e&&(l[t.F]=r)}))}};export{f as a,c as b,d as c,b as d};
2
- //# sourceMappingURL=chunk-65B2K2XD.js.map