@jasonshimmy/custom-elements-runtime 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./ssr-DtD9e5iA.cjs");function v(t,o,i){if(!i)return t;if(t.trimStart().toLowerCase().startsWith("<html")||t.includes("</html>")){const c=o??"",r=t.startsWith("<!DOCTYPE")?t:`<!DOCTYPE html>${t}`;return c&&r.includes("</head>")?r.replace("</head>",`${c}</head>`):r}return`<!DOCTYPE html><html><head>${o??""}</head><body>${t}</body></html>`}function b(t,o){const i={dsd:!0,...o?.render},{head:c,document:r=!0}=o??{};return async(f,n)=>{try{const e=typeof t=="function"?await t(f):t,d=e!==null&&typeof e=="object"&&"vnode"in e,m=d?e.vnode:e,p=d?e.router:void 0,s=d?e.head:void 0,{htmlWithStyles:l}=y.renderToStringWithJITCSS(m,{...i,router:p}),a=v(l,[c,s].filter(Boolean).join(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./ssr-DRsGduIK.cjs");function v(t,o,i){if(!i)return t;if(t.trimStart().toLowerCase().startsWith("<html")||t.includes("</html>")){const c=o??"",r=t.startsWith("<!DOCTYPE")?t:`<!DOCTYPE html>${t}`;return c&&r.includes("</head>")?r.replace("</head>",`${c}</head>`):r}return`<!DOCTYPE html><html><head>${o??""}</head><body>${t}</body></html>`}function b(t,o){const i={dsd:!0,...o?.render},{head:c,document:r=!0}=o??{};return async(f,n)=>{try{const e=typeof t=="function"?await t(f):t,d=e!==null&&typeof e=="object"&&"vnode"in e,m=d?e.vnode:e,p=d?e.router:void 0,s=d?e.head:void 0,{htmlWithStyles:l}=y.renderToStringWithJITCSS(m,{...i,router:p}),a=v(l,[c,s].filter(Boolean).join(`
2
2
  `)||void 0,r);n.setHeader("Content-Type","text/html; charset=utf-8"),n.end(a)}catch(e){try{n.setHeader("Content-Type","text/plain; charset=utf-8"),n.end("Internal Server Error")}catch{}throw e}}}function C(t,o){const i={dsd:!0,...o?.render},{head:c,document:r=!0}=o??{};return async(f,n)=>{try{const e=typeof t=="function"?await t(f):t,d=e!==null&&typeof e=="object"&&"vnode"in e,m=d?e.vnode:e,p=d?e.router:void 0,s=[c,d?e.head:void 0].filter(Boolean).join(`
3
3
  `)||void 0;n.setHeader("Content-Type","text/html; charset=utf-8");const l=y.renderToStream(m,{...i,router:p}).getReader();if(n.write){n.setHeader("Transfer-Encoding","chunked"),r&&n.write(`<!DOCTYPE html><html><head>${s??""}</head><body>`);let a=!1;for(;!a;){const{value:u,done:h}=await l.read();u&&n.write(u),a=h}r?n.end("</body></html>"):n.end()}else{const a=[];let u=!1;for(;!u;){const{value:w,done:T}=await l.read();w&&a.push(w),u=T}const h=a.join(""),S=r?`<!DOCTYPE html><html><head>${s??""}</head><body>${h}</body></html>`:h;n.end(S)}}catch(e){try{n.setHeader("Content-Type","text/plain; charset=utf-8"),n.end("Internal Server Error")}catch{}throw e}}}exports.createSSRHandler=b;exports.createStreamingSSRHandler=C;
4
4
 
@@ -1,24 +1,24 @@
1
- import { n as v, t as C } from "./ssr-B3lxl1vr.js";
2
- function b(t, r, i) {
1
+ import { r as v, t as C } from "./ssr-H9GDwbTy.js";
2
+ function b(t, o, i) {
3
3
  if (!i) return t;
4
4
  if (t.trimStart().toLowerCase().startsWith("<html") || t.includes("</html>")) {
5
- const c = r ?? "", o = t.startsWith("<!DOCTYPE") ? t : `<!DOCTYPE html>${t}`;
6
- return c && o.includes("</head>") ? o.replace("</head>", `${c}</head>`) : o;
5
+ const c = o ?? "", r = t.startsWith("<!DOCTYPE") ? t : `<!DOCTYPE html>${t}`;
6
+ return c && r.includes("</head>") ? r.replace("</head>", `${c}</head>`) : r;
7
7
  }
8
- return `<!DOCTYPE html><html><head>${r ?? ""}</head><body>${t}</body></html>`;
8
+ return `<!DOCTYPE html><html><head>${o ?? ""}</head><body>${t}</body></html>`;
9
9
  }
10
- function H(t, r) {
10
+ function H(t, o) {
11
11
  const i = {
12
12
  dsd: !0,
13
- ...r?.render
14
- }, { head: c, document: o = !0 } = r ?? {};
13
+ ...o?.render
14
+ }, { head: c, document: r = !0 } = o ?? {};
15
15
  return async (f, n) => {
16
16
  try {
17
17
  const e = typeof t == "function" ? await t(f) : t, d = e !== null && typeof e == "object" && "vnode" in e, m = d ? e.vnode : e, p = d ? e.router : void 0, s = d ? e.head : void 0, { htmlWithStyles: h } = v(m, {
18
18
  ...i,
19
19
  router: p
20
20
  }), a = b(h, [c, s].filter(Boolean).join(`
21
- `) || void 0, o);
21
+ `) || void 0, r);
22
22
  n.setHeader("Content-Type", "text/html; charset=utf-8"), n.end(a);
23
23
  } catch (e) {
24
24
  try {
@@ -29,11 +29,11 @@ function H(t, r) {
29
29
  }
30
30
  };
31
31
  }
32
- function E(t, r) {
32
+ function E(t, o) {
33
33
  const i = {
34
34
  dsd: !0,
35
- ...r?.render
36
- }, { head: c, document: o = !0 } = r ?? {};
35
+ ...o?.render
36
+ }, { head: c, document: r = !0 } = o ?? {};
37
37
  return async (f, n) => {
38
38
  try {
39
39
  const e = typeof t == "function" ? await t(f) : t, d = e !== null && typeof e == "object" && "vnode" in e, m = d ? e.vnode : e, p = d ? e.router : void 0, s = [c, d ? e.head : void 0].filter(Boolean).join(`
@@ -44,13 +44,13 @@ function E(t, r) {
44
44
  router: p
45
45
  }).getReader();
46
46
  if (n.write) {
47
- n.setHeader("Transfer-Encoding", "chunked"), o && n.write(`<!DOCTYPE html><html><head>${s ?? ""}</head><body>`);
47
+ n.setHeader("Transfer-Encoding", "chunked"), r && n.write(`<!DOCTYPE html><html><head>${s ?? ""}</head><body>`);
48
48
  let a = !1;
49
49
  for (; !a; ) {
50
50
  const { value: u, done: l } = await h.read();
51
51
  u && n.write(u), a = l;
52
52
  }
53
- o ? n.end("</body></html>") : n.end();
53
+ r ? n.end("</body></html>") : n.end();
54
54
  } else {
55
55
  const a = [];
56
56
  let u = !1;
@@ -58,7 +58,7 @@ function E(t, r) {
58
58
  const { value: w, done: T } = await h.read();
59
59
  w && a.push(w), u = T;
60
60
  }
61
- const l = a.join(""), y = o ? `<!DOCTYPE html><html><head>${s ?? ""}</head><body>${l}</body></html>` : l;
61
+ const l = a.join(""), y = r ? `<!DOCTYPE html><html><head>${s ?? ""}</head><body>${l}</body></html>` : l;
62
62
  n.end(y);
63
63
  }
64
64
  } catch (e) {
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./hooks-fYQgZk2g.cjs"),r=require("./ssr-DtD9e5iA.cjs");exports.DSD_POLYFILL_SCRIPT=r.DSD_POLYFILL_SCRIPT;exports.clearRegisteredEntityMap=e.clearRegisteredEntityMap;exports.loadEntityMap=e.loadEntityMap;exports.registerEntityMap=e.registerEntityMap;exports.renderToStream=r.renderToStream;exports.renderToString=r.renderToString;exports.renderToStringDSD=r.renderToStringDSD;exports.renderToStringWithJITCSS=r.renderToStringWithJITCSS;exports.renderToStringWithJITCSSDSD=r.renderToStringWithJITCSSDSD;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./hooks-fYQgZk2g.cjs"),r=require("./ssr-DRsGduIK.cjs");exports.DSD_POLYFILL_SCRIPT=r.DSD_POLYFILL_SCRIPT;exports.clearRegisteredEntityMap=e.clearRegisteredEntityMap;exports.loadEntityMap=e.loadEntityMap;exports.registerEntityMap=e.registerEntityMap;exports.renderToStream=r.renderToStream;exports.renderToStreamWithJITCSSDSD=r.renderToStreamWithJITCSSDSD;exports.renderToString=r.renderToString;exports.renderToStringDSD=r.renderToStringDSD;exports.renderToStringWithJITCSS=r.renderToStringWithJITCSS;exports.renderToStringWithJITCSSDSD=r.renderToStringWithJITCSSDSD;
@@ -1,13 +1,14 @@
1
- import { A as t, C as e, k as a } from "./hooks-_3xP4G2N.js";
2
- import { a as n, i as S, n as o, o as s, r as T, t as d } from "./ssr-B3lxl1vr.js";
1
+ import { A as e, C as t, k as a } from "./hooks-_3xP4G2N.js";
2
+ import { a as i, i as n, n as o, o as s, r as T, s as d, t as D } from "./ssr-H9GDwbTy.js";
3
3
  export {
4
- S as DSD_POLYFILL_SCRIPT,
5
- e as clearRegisteredEntityMap,
4
+ i as DSD_POLYFILL_SCRIPT,
5
+ t as clearRegisteredEntityMap,
6
6
  a as loadEntityMap,
7
- t as registerEntityMap,
8
- d as renderToStream,
9
- s as renderToString,
10
- n as renderToStringDSD,
11
- o as renderToStringWithJITCSS,
12
- T as renderToStringWithJITCSSDSD
7
+ e as registerEntityMap,
8
+ D as renderToStream,
9
+ o as renderToStreamWithJITCSSDSD,
10
+ d as renderToString,
11
+ s as renderToStringDSD,
12
+ T as renderToStringWithJITCSS,
13
+ n as renderToStringWithJITCSSDSD
13
14
  };
@@ -1,5 +1,5 @@
1
- const L=require("./logger-BYIN7ysT.cjs"),y=require("./namespace-helpers-Bf7rm9JV.cjs"),u=require("./hooks-fYQgZk2g.cjs"),C=require("./css-utils-mgjmH8qX.cjs"),T=require("./style-Bjn8zDiZ.cjs");var A=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function D(e,r,t){const i=t.injectSvgNamespace??!0,n=t.injectKnownNamespaces??i,s={...e};return i&&r==="svg"&&!("xmlns"in s)?s.xmlns=y.SVG_NS:n&&r in y.TAG_NAMESPACE_MAP&&!("xmlns"in s)&&(s.xmlns=y.TAG_NAMESPACE_MAP[r]),Object.entries(s).map(([a,l])=>` ${a}="${u.escapeHTML(String(l))}"`).join("")}function E(e){return Object.entries(e).map(([r,t])=>` ${r}="${u.escapeHTML(String(t))}"`).join("")}function f(e,r){if(typeof e=="string")return u.escapeHTML(e);if(e.tag==="#text")return typeof e.children=="string"?u.escapeHTML(e.children):"";if(e.tag==="#anchor")return(Array.isArray(e.children)?e.children.filter(n=>n!=null):[]).map(n=>f(n,r)).join("");if(e.tag==="#raw")return typeof e.children=="string"?e.children:"";const t=D(e.props?.attrs?{...e.props.attrs}:{},e.tag,r??{});if(A.has(e.tag))return`<${e.tag}${t}>`;const i=Array.isArray(e.children)?e.children.filter(n=>n!=null).map(n=>f(n,r)).join(""):typeof e.children=="string"?u.escapeHTML(e.children):e.children?f(e.children,r):"";return`<${e.tag}${t}>${i}</${e.tag}>`}var p="<script>(function(){if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;document.querySelectorAll('template[shadowrootmode]').forEach(function(t){var m=t.getAttribute('shadowrootmode');var s=t.parentElement.attachShadow({mode:m});s.appendChild(t.content);t.remove();});})()<\/script>";function R(e){return e.includes("-")&&y.registry.has(e)}function M(e,r){const t=[C.baseReset];e.trim()&&t.push(e);const i=T.jitCSS(r);i.trim()&&t.push(i);const n=C.minifyCSS(t.join(`
2
- `));return n?`<style>${n}</style>`:""}var h=null,_=0;function q(e){h=e,_=0}function I(){h=null}function S(e,r){if(!r.dsd)return f(e,r);if(typeof e=="string")return u.escapeHTML(e);const t=e.tag;if(t==="#text"||t==="#anchor"||t==="#raw")return f(e,r);if(R(t))return H(e,r);const i=D(e.props?.attrs?{...e.props.attrs}:{},t,r);return A.has(t)?`<${t}${i}>`:`<${t}${i}>${b(e.children,r)}</${t}>`}function H(e,r){const t=e.tag,i=y.registry.get(t),n=e.props?.attrs??{},s=E(n);if(!i)return`<${t}${s}><template shadowrootmode="open"></template>${b(e.children,r)}</${t}>`;const a=i.hydrate,l=a&&a!=="load"?` data-cer-hydrate="${a}"`:"",{shadowVNode:o,useStyleCSS:m,asyncPromise:d}=u.runComponentSSRRender(i,n,t,r.router);if(d&&h===null&&L.devWarn(`[SSR] Component "${t}" has an async render function. In standard SSR the shadow DOM will be empty. Use renderToStream() for incremental async component streaming.`),d&&h!==null){const $=`cer-stream-${_++}`,w=b(e.children,r);return h.push({id:$,tag:t,attrsString:s,hydrateAttr:l,useStyleCSS:m,lightDOM:w,opts:r,promise:d,router:r.router}),`<${t} id="${$}"${s}${l}><template shadowrootmode="open"></template>${w}</${t}>`}let c="";o!=null&&(Array.isArray(o)?c=o.map($=>S($,r)).join(""):c=S(o,r));const g=M(m,c),P=b(e.children,r);return`<${t}${s}${l}><template shadowrootmode="open">${g}${c}</template>${P}</${t}>`}function b(e,r){return e?typeof e=="string"?u.escapeHTML(e):Array.isArray(e)?e.filter(t=>t!=null).map(t=>S(t,r)).join(""):S(e,r):""}function O(e,r){const t={dsd:!0,...r},i=S(e,t);return t.dsdPolyfill!==!1?i.includes("</body>")?i.replace("</body>",`${p}</body>`):i+p:i}function j(e,r){const{jit:t,dsd:i,dsdPolyfill:n,...s}=r??{};t&&T.enableJITCSS(t),u.beginSSRGlobalStyleCollection();let a,l;try{i?a=O(e,{...s,dsd:!0,dsdPolyfill:!1}):a=f(e,s)}finally{l=u.endSSRGlobalStyleCollection()}const o=T.jitCSS(a),m=l.join(`
3
- `),d=[];o&&d.push(`<style id="cer-ssr-jit">${o}</style>`),m.trim()&&d.push(`<style id="cer-ssr-global">${m}</style>`);let c=a;if(d.length){const g=d.join("");c=a.includes("</head>")?a.replace("</head>",`${g}</head>`):`${g}${a}`}return i&&n!==!1&&(c=c.includes("</body>")?c.replace("</body>",`${p}</body>`):c+p),{html:a,css:o,globalStyles:m,htmlWithStyles:c}}function N(e,r){return j(e,{...r,dsd:!0})}function J(e,r){return new ReadableStream({async start(t){const i=[];q(i);try{const{htmlWithStyles:n}=j(e,r);t.enqueue(n)}catch(n){t.error(n);return}finally{I()}for(const n of i)try{const s=await n.promise,a=Array.isArray(s)?s.map(o=>S(o,n.opts)).join(""):S(s,n.opts),l=`${M(n.useStyleCSS,a)}${a}`;t.enqueue(`<script>(function(){var e=document.getElementById(${JSON.stringify(n.id)});if(!e)return;var s=e.shadowRoot;if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};if(s)s.innerHTML=${JSON.stringify(l)};e.removeAttribute('id');})();<\/script>`)}catch{}t.close()}})}Object.defineProperty(exports,"DSD_POLYFILL_SCRIPT",{enumerable:!0,get:function(){return p}});Object.defineProperty(exports,"renderToStream",{enumerable:!0,get:function(){return J}});Object.defineProperty(exports,"renderToString",{enumerable:!0,get:function(){return f}});Object.defineProperty(exports,"renderToStringDSD",{enumerable:!0,get:function(){return O}});Object.defineProperty(exports,"renderToStringWithJITCSS",{enumerable:!0,get:function(){return j}});Object.defineProperty(exports,"renderToStringWithJITCSSDSD",{enumerable:!0,get:function(){return N}});
1
+ const E=require("./logger-BYIN7ysT.cjs"),y=require("./namespace-helpers-Bf7rm9JV.cjs"),u=require("./hooks-fYQgZk2g.cjs"),w=require("./css-utils-mgjmH8qX.cjs"),T=require("./style-Bjn8zDiZ.cjs");var D=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function A(e,r,t){const i=t.injectSvgNamespace??!0,n=t.injectKnownNamespaces??i,s={...e};return i&&r==="svg"&&!("xmlns"in s)?s.xmlns=y.SVG_NS:n&&r in y.TAG_NAMESPACE_MAP&&!("xmlns"in s)&&(s.xmlns=y.TAG_NAMESPACE_MAP[r]),Object.entries(s).map(([a,l])=>` ${a}="${u.escapeHTML(String(l))}"`).join("")}function I(e){return Object.entries(e).map(([r,t])=>` ${r}="${u.escapeHTML(String(t))}"`).join("")}function f(e,r){if(typeof e=="string")return u.escapeHTML(e);if(e.tag==="#text")return typeof e.children=="string"?u.escapeHTML(e.children):"";if(e.tag==="#anchor")return(Array.isArray(e.children)?e.children.filter(n=>n!=null):[]).map(n=>f(n,r)).join("");if(e.tag==="#raw")return typeof e.children=="string"?e.children:"";const t=A(e.props?.attrs?{...e.props.attrs}:{},e.tag,r??{});if(D.has(e.tag))return`<${e.tag}${t}>`;const i=Array.isArray(e.children)?e.children.filter(n=>n!=null).map(n=>f(n,r)).join(""):typeof e.children=="string"?u.escapeHTML(e.children):e.children?f(e.children,r):"";return`<${e.tag}${t}>${i}</${e.tag}>`}var p="<script>(function(){if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;document.querySelectorAll('template[shadowrootmode]').forEach(function(t){var m=t.getAttribute('shadowrootmode');var s=t.parentElement.attachShadow({mode:m});s.appendChild(t.content);t.remove();});})()<\/script>";function R(e){return e.includes("-")&&y.registry.has(e)}function M(e,r){const t=[w.baseReset];e.trim()&&t.push(e);const i=T.jitCSS(r);i.trim()&&t.push(i);const n=w.minifyCSS(t.join(`
2
+ `));return n?`<style>${n}</style>`:""}var h=null,O=0;function q(e){h=e,O=0}function H(){h=null}function S(e,r){if(!r.dsd)return f(e,r);if(typeof e=="string")return u.escapeHTML(e);const t=e.tag;if(t==="#text"||t==="#anchor"||t==="#raw")return f(e,r);if(R(t))return N(e,r);const i=A(e.props?.attrs?{...e.props.attrs}:{},t,r);return D.has(t)?`<${t}${i}>`:`<${t}${i}>${b(e.children,r)}</${t}>`}function N(e,r){const t=e.tag,i=y.registry.get(t),n=e.props?.attrs??{},s=I(n);if(!i)return`<${t}${s}><template shadowrootmode="open"></template>${b(e.children,r)}</${t}>`;const a=i.hydrate,l=a&&a!=="load"?` data-cer-hydrate="${a}"`:"",{shadowVNode:o,useStyleCSS:m,asyncPromise:d}=u.runComponentSSRRender(i,n,t,r.router);if(d&&h===null&&E.devWarn(`[SSR] Component "${t}" has an async render function. In standard SSR the shadow DOM will be empty. Use renderToStream() for incremental async component streaming.`),d&&h!==null){const $=`cer-stream-${O++}`,C=b(e.children,r);return h.push({id:$,tag:t,attrsString:s,hydrateAttr:l,useStyleCSS:m,lightDOM:C,opts:r,promise:d,router:r.router}),`<${t} id="${$}"${s}${l}><template shadowrootmode="open"></template>${C}</${t}>`}let c="";o!=null&&(Array.isArray(o)?c=o.map($=>S($,r)).join(""):c=S(o,r));const g=M(m,c),L=b(e.children,r);return`<${t}${s}${l}><template shadowrootmode="open">${g}${c}</template>${L}</${t}>`}function b(e,r){return e?typeof e=="string"?u.escapeHTML(e):Array.isArray(e)?e.filter(t=>t!=null).map(t=>S(t,r)).join(""):S(e,r):""}function P(e,r){const t={dsd:!0,...r},i=S(e,t);return t.dsdPolyfill!==!1?i.includes("</body>")?i.replace("</body>",`${p}</body>`):i+p:i}function j(e,r){const{jit:t,dsd:i,dsdPolyfill:n,...s}=r??{};t&&T.enableJITCSS(t),u.beginSSRGlobalStyleCollection();let a,l;try{i?a=P(e,{...s,dsd:!0,dsdPolyfill:!1}):a=f(e,s)}finally{l=u.endSSRGlobalStyleCollection()}const o=T.jitCSS(a),m=l.join(`
3
+ `),d=[];o&&d.push(`<style id="cer-ssr-jit">${o}</style>`),m.trim()&&d.push(`<style id="cer-ssr-global">${m}</style>`);let c=a;if(d.length){const g=d.join("");c=a.includes("</head>")?a.replace("</head>",`${g}</head>`):`${g}${a}`}return i&&n!==!1&&(c=c.includes("</body>")?c.replace("</body>",`${p}</body>`):c+p),{html:a,css:o,globalStyles:m,htmlWithStyles:c}}function J(e,r){return j(e,{...r,dsd:!0})}function _(e,r){return new ReadableStream({async start(t){const i=[];q(i);try{const{htmlWithStyles:n}=j(e,r);t.enqueue(n)}catch(n){t.error(n);return}finally{H()}for(const n of i)try{const s=await n.promise,a=Array.isArray(s)?s.map(o=>S(o,n.opts)).join(""):S(s,n.opts),l=`${M(n.useStyleCSS,a)}${a}`;t.enqueue(`<script>(function(){var e=document.getElementById(${JSON.stringify(n.id)});if(!e)return;var s=e.shadowRoot;if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};if(s)s.innerHTML=${JSON.stringify(l)};e.removeAttribute('id');})();<\/script>`)}catch{}t.close()}})}function W(e,r){return _(e,{...r,dsd:!0})}Object.defineProperty(exports,"DSD_POLYFILL_SCRIPT",{enumerable:!0,get:function(){return p}});Object.defineProperty(exports,"renderToStream",{enumerable:!0,get:function(){return _}});Object.defineProperty(exports,"renderToStreamWithJITCSSDSD",{enumerable:!0,get:function(){return W}});Object.defineProperty(exports,"renderToString",{enumerable:!0,get:function(){return f}});Object.defineProperty(exports,"renderToStringDSD",{enumerable:!0,get:function(){return P}});Object.defineProperty(exports,"renderToStringWithJITCSS",{enumerable:!0,get:function(){return j}});Object.defineProperty(exports,"renderToStringWithJITCSSDSD",{enumerable:!0,get:function(){return J}});
4
4
 
5
- //# sourceMappingURL=ssr-DtD9e5iA.cjs.map
5
+ //# sourceMappingURL=ssr-DRsGduIK.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-DtD9e5iA.cjs","names":[],"sources":["../src/lib/runtime/ssr-utils.ts","../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["/**\n * Shared utilities for SSR renderers.\n * Imported by vdom-ssr.ts and vdom-ssr-dsd.ts to avoid duplication.\n */\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\n\nexport type RenderOptions = {\n /** Backwards-compatible: whether to inject the SVG namespace on <svg> nodes (default true) */\n injectSvgNamespace?: boolean;\n /** Inject known well-known namespaces for tags like <math> when missing (default follows injectSvgNamespace) */\n injectKnownNamespaces?: boolean;\n};\n\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nexport function buildAttrs(\n attrs: Record<string, unknown>,\n tag: string,\n opts: RenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n const merged = { ...attrs };\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag in TAG_NAMESPACE_MAP && !('xmlns' in merged)) {\n merged['xmlns'] = TAG_NAMESPACE_MAP[tag];\n }\n\n return Object.entries(merged)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n\nexport function buildRawAttrs(attrs: Record<string, unknown>): string {\n return Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n","import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { VOID_ELEMENTS, buildAttrs, type RenderOptions } from './ssr-utils';\n\n/**\n * Render a VNode to a string (SSR).\n * Kept intentionally minimal: only serializes attributes under `props.attrs`\n * to avoid leaking runtime-only values (functions, reactive state, directives).\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport type { RenderOptions } from './ssr-utils';\n\nexport function renderToString(vnode: VNode, opts?: RenderOptions): string {\n if (typeof vnode === 'string') return escapeHTML(vnode) as string;\n\n if (vnode.tag === '#text') {\n return typeof vnode.children === 'string'\n ? (escapeHTML(vnode.children) as string)\n : '';\n }\n\n if (vnode.tag === '#anchor') {\n // Preserve meaningful falsy children (0, false, '') while filtering out\n // only null and undefined. Anchor blocks are normalized by the compiler\n // to exclude null/undefined; SSR should follow the same rule to avoid\n // hydration mismatches where falsy values are significant.\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter((c) => c !== null && c !== undefined)\n : [];\n return children.map((c) => renderToString(c, opts)).join('');\n }\n\n if (vnode.tag === '#raw') {\n return typeof vnode.children === 'string' ? vnode.children : '';\n }\n\n // Collect attributes from props.attrs. For SSR we mirror vnode.attrs\n // but ensure SVG nodes behave like client-side: if this is an <svg>\n // and no xmlns was provided, inject the standard SVG namespace so\n // server markup matches client-created DOM namespace.\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, vnode.tag, opts ?? {});\n\n // Handle void elements (self-closing tags)\n if (VOID_ELEMENTS.has(vnode.tag)) {\n return `<${vnode.tag}${attrsString}>`;\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToString(c, opts))\n .join('')\n : typeof vnode.children === 'string'\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children, opts)\n : '';\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Declarative Shadow DOM (DSD) SSR renderer.\n *\n * When `dsd: true` is passed to the render options, registered custom elements\n * are serialised as:\n *\n * ```html\n * <my-element attr=\"val\">\n * <template shadowrootmode=\"open\">\n * <style>\n * /* baseReset + useStyle() output + JIT utility CSS *\\/\n * </style>\n * <!-- shadow DOM from component render function -->\n * </template>\n * <!-- light DOM / slotted children from vnode.children -->\n * </my-element>\n * ```\n *\n * The browser parses the `<template shadowrootmode=\"open\">` block and attaches\n * a real shadow root before any JavaScript executes. All CSS layers are present\n * at first paint — eliminating both FOUC and layout shift.\n *\n * Non-custom-element VNodes are rendered identically to renderToString() but\n * with DSD recursion active for any custom elements nested inside them.\n */\n\nimport type { VNode } from './types';\nimport { renderToString } from './vdom-ssr';\nimport { VOID_ELEMENTS, buildAttrs, buildRawAttrs, type RenderOptions } from './ssr-utils';\nimport { registry } from './component/registry';\nimport { runComponentSSRRender } from './ssr-context';\nimport { jitCSS } from './style';\nimport { baseReset, minifyCSS } from './css-utils';\nimport { escapeHTML } from './helpers';\nimport { devWarn } from './logger';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type DSDRenderOptions = RenderOptions & {\n /**\n * Emit Declarative Shadow DOM output for registered custom elements.\n * Shadow content is serialised inside `<template shadowrootmode=\"open\">`,\n * with a complete CSS layer stack (`baseReset` + `useStyle` + JIT CSS)\n * injected as a `<style>` block so styles are available at first paint.\n * @default false\n */\n dsd?: boolean;\n /**\n * Append the DSD polyfill `<script>` for browsers without native support\n * (Firefox < 123). Only meaningful when `dsd` is true.\n * @default true\n */\n dsdPolyfill?: boolean;\n /**\n * Router instance to thread through each component's SSR context.\n *\n * When provided, `router-view` reads the current route from this instance\n * instead of the module-level `activeRouterProxy` singleton, making\n * concurrent SSR renders safe — each request carries its own router with\n * its own URL state.\n *\n * In browser mode this option is ignored; components always use\n * `activeRouterProxy` there.\n */\n router?: unknown;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * @internal\n * Minified DSD polyfill for browsers without native Declarative Shadow DOM.\n * Processes all `<template shadowrootmode>` elements synchronously.\n */\nexport const DSD_POLYFILL_SCRIPT =\n '<script>(function(){' +\n \"if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;\" +\n \"document.querySelectorAll('template[shadowrootmode]').forEach(function(t){\" +\n \"var m=t.getAttribute('shadowrootmode');\" +\n 'var s=t.parentElement.attachShadow({mode:m});' +\n 's.appendChild(t.content);t.remove();' +\n '});})()' +\n '</script>';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRegisteredCustomElement(tag: string): boolean {\n return tag.includes('-') && registry.has(tag);\n}\n\n/**\n * Build the combined `<style>` block for a shadow root.\n *\n * Layer order (matches the runtime adoptedStyleSheets order):\n * 1. baseReset — global reset + CSS custom properties\n * 2. useStyle() output — component-defined rules (:host, ::slotted, etc.)\n * 3. JIT CSS — utility classes extracted from the shadow HTML\n */\nexport function buildShadowStyleBlock(\n useStyleCSS: string,\n shadowHTML: string,\n): string {\n const parts: string[] = [baseReset];\n\n if (useStyleCSS.trim()) {\n parts.push(useStyleCSS);\n }\n\n const jit = jitCSS(shadowHTML);\n if (jit.trim()) {\n parts.push(jit);\n }\n\n const combined = minifyCSS(parts.join('\\n'));\n return combined ? `<style>${combined}</style>` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Streaming async component collector\n// ---------------------------------------------------------------------------\n\nexport interface AsyncStreamEntry {\n id: string;\n tag: string;\n attrsString: string;\n hydrateAttr: string;\n useStyleCSS: string;\n lightDOM: string;\n opts: DSDRenderOptions;\n promise: Promise<VNode | VNode[]>;\n /** Router threaded from the originating render pass — propagated to async re-renders. */\n router?: unknown;\n}\n\nlet _streamingCollector: AsyncStreamEntry[] | null = null;\nlet _streamingCounter = 0;\n\n/** @internal Called by renderToStream() before the sync render pass. */\nexport function beginStreamingCollection(collector: AsyncStreamEntry[]): void {\n _streamingCollector = collector;\n _streamingCounter = 0;\n}\n\n/** @internal Called by renderToStream() after the sync render pass. */\nexport function endStreamingCollection(): void {\n _streamingCollector = null;\n}\n\n// ---------------------------------------------------------------------------\n// Core renderer\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to an HTML string with Declarative Shadow DOM output\n * for all registered custom elements encountered in the tree.\n */\nexport function renderToDSD(vnode: VNode, opts: DSDRenderOptions): string {\n if (!opts.dsd) {\n return renderToString(vnode, opts);\n }\n\n // Primitive string nodes\n if (typeof vnode === 'string') {\n return escapeHTML(vnode) as string;\n }\n\n const tag = (vnode as VNode).tag;\n\n // Special virtual node types — delegate entirely to the base renderer\n if (tag === '#text' || tag === '#anchor' || tag === '#raw') {\n return renderToString(vnode, opts);\n }\n\n // Custom element — emit DSD wrapper\n if (isRegisteredCustomElement(tag)) {\n return renderCustomElementDSD(vnode, opts);\n }\n\n // Regular element — recurse with DSD mode on\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, tag, opts);\n\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrsString}>`;\n }\n\n const children = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}>${children}</${tag}>`;\n}\n\nfunction renderCustomElementDSD(vnode: VNode, opts: DSDRenderOptions): string {\n const tag = vnode.tag;\n const config = registry.get(tag);\n\n // Build the plain attribute string (no namespace injection for custom elements)\n const rawAttrs = vnode.props?.attrs ?? {};\n const attrsString = buildRawAttrs(rawAttrs);\n\n // Move the null check BEFORE reading config.* properties for clarity.\n if (!config) {\n // Component not in registry on server (e.g. dynamic import not yet run).\n // Emit a shell with an empty DSD template so the client hydrates normally.\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\n }\n\n // Emit data-cer-hydrate when a non-default strategy is configured.\n // 'load' is the default and doesn't need to be serialised.\n const hydrateStrategy = config.hydrate;\n const hydrateAttr =\n hydrateStrategy && hydrateStrategy !== 'load'\n ? ` data-cer-hydrate=\"${hydrateStrategy}\"`\n : '';\n\n // Run the component's render function in a minimal SSR context to get the\n // shadow DOM VNode tree and capture any useStyle() output.\n const { shadowVNode, useStyleCSS, asyncPromise } = runComponentSSRRender(config, rawAttrs, tag, opts.router);\n\n // When streaming and this component has an async render, emit a placeholder\n // and register the promise for later resolution.\n if (asyncPromise && _streamingCollector === null) {\n devWarn(\n `[SSR] Component \"${tag}\" has an async render function. ` +\n `In standard SSR the shadow DOM will be empty. ` +\n `Use renderToStream() for incremental async component streaming.`,\n );\n }\n if (asyncPromise && _streamingCollector !== null) {\n const id = `cer-stream-${_streamingCounter++}`;\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n _streamingCollector.push({\n id,\n tag,\n attrsString,\n hydrateAttr,\n useStyleCSS,\n lightDOM,\n opts,\n promise: asyncPromise,\n router: opts.router,\n });\n return (\n `<${tag} id=\"${id}\"${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\"></template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n }\n\n // Render the shadow DOM VNode tree to HTML (DSD-recursive for nested elements)\n let shadowHTML = '';\n if (shadowVNode !== null && shadowVNode !== undefined) {\n if (Array.isArray(shadowVNode)) {\n shadowHTML = (shadowVNode as VNode[])\n .map((n) => renderToDSD(n, opts))\n .join('');\n } else {\n shadowHTML = renderToDSD(shadowVNode as VNode, opts);\n }\n }\n\n const styleBlock = buildShadowStyleBlock(useStyleCSS, shadowHTML);\n\n // Light DOM children become slotted content — rendered outside the template\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n\n return (\n `<${tag}${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\">${styleBlock}${shadowHTML}</template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n}\n\nfunction renderChildrenDSD(\n children: VNode['children'],\n opts: DSDRenderOptions,\n): string {\n if (!children) return '';\n if (typeof children === 'string') return escapeHTML(children) as string;\n if (Array.isArray(children)) {\n return children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToDSD(c as VNode, opts))\n .join('');\n }\n return renderToDSD(children as VNode, opts);\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a DSD HTML string and optionally append the\n * DSD polyfill script for older browsers.\n */\nexport function renderToStringDSD(\n vnode: VNode,\n opts?: DSDRenderOptions,\n): string {\n const effectiveOpts: DSDRenderOptions = { dsd: true, ...opts };\n const html = renderToDSD(vnode, effectiveOpts);\n\n if (effectiveOpts.dsdPolyfill !== false) {\n // Inject polyfill before </body> if present, otherwise append\n if (html.includes('</body>')) {\n return html.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`);\n }\n return html + DSD_POLYFILL_SCRIPT;\n }\n\n return html;\n}\n","/**\n * SSR entry point — import from `@jasonshimmy/custom-elements-runtime/ssr`.\n *\n * Provides four rendering modes:\n *\n * 1. **renderToString** — baseline HTML serialisation (no shadow DOM content).\n * Backwards-compatible with the original API.\n *\n * 2. **renderToStringWithJITCSS** — HTML + pre-generated JIT CSS injected into\n * `<head>` to prevent FOUC. Supports `dsd: true` for DSD output.\n *\n * 3. **renderToStringWithJITCSSDSD** — convenience alias for DSD mode.\n * Full Declarative Shadow DOM output with per-shadow-root CSS layer stack\n * (baseReset + useStyle() + JIT CSS). Enables true hydration, zero FOUC.\n *\n * 4. **renderToStream** — ReadableStream variant for streaming SSR.\n *\n * Entity map utilities are also exported for full HTML5 named-entity support.\n *\n * @example DSD usage (recommended)\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * res.send(`<!DOCTYPE html><html><head>${head}</head><body>${htmlWithStyles}</body></html>`);\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Re-exports — backwards-compatible\n// ---------------------------------------------------------------------------\n\nexport { renderToString } from './runtime/vdom-ssr';\nexport type { VNode } from './runtime/types';\nexport type { RenderOptions } from './runtime/vdom-ssr';\n\nexport {\n registerEntityMap,\n loadEntityMap,\n clearRegisteredEntityMap,\n} from './runtime/helpers';\n\nexport {\n renderToStringDSD,\n DSD_POLYFILL_SCRIPT,\n} from './runtime/vdom-ssr-dsd';\nexport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\n\n// ---------------------------------------------------------------------------\n// Internal imports\n// ---------------------------------------------------------------------------\n\nimport { renderToString as _render } from './runtime/vdom-ssr';\nimport {\n renderToStringDSD as _renderToStringDSD,\n renderToDSD,\n buildShadowStyleBlock,\n beginStreamingCollection,\n endStreamingCollection,\n DSD_POLYFILL_SCRIPT,\n type AsyncStreamEntry,\n} from './runtime/vdom-ssr-dsd';\nimport { jitCSS, enableJITCSS, type JITCSSOptions } from './runtime/style';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport {\n beginSSRGlobalStyleCollection,\n endSSRGlobalStyleCollection,\n} from './runtime/ssr-context';\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/**\n * Result of `renderToStringWithJITCSS()` and `renderToStringWithJITCSSDSD()`.\n */\nexport interface SSRJITResult {\n /** The rendered HTML string (styles not yet injected). */\n html: string;\n /**\n * Global JIT CSS extracted from the rendered HTML.\n * For DSD renders, each shadow root embeds its own scoped styles; this field\n * holds any residual light-DOM utility CSS.\n */\n css: string;\n /**\n * CSS captured from `useGlobalStyle()` calls during this render pass\n * (e.g. `@font-face`, `:root` custom properties).\n * Inject in a `<style id=\"cer-ssr-global\">` in `<head>`.\n */\n globalStyles: string;\n /**\n * Convenience: `html` with both `<style>` tags injected before `</head>`.\n * If no `</head>` is found, the styles are prepended.\n */\n htmlWithStyles: string;\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSS — primary API, supports both modes\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side render a VNode tree and simultaneously pre-generate JIT CSS.\n *\n * Pass `dsd: true` to enable Declarative Shadow DOM output with full per-shadow-\n * root CSS layer extraction (recommended for new apps).\n *\n * @example Standard (no DSD)\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode);\n * ```\n *\n * @example With DSD\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode, {\n * dsd: true,\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSS(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): SSRJITResult {\n const { jit, dsd, dsdPolyfill, ...renderOptions } = options ?? {};\n\n if (jit) enableJITCSS(jit);\n\n beginSSRGlobalStyleCollection();\n\n let html!: string;\n let globalStylesCaptured!: string[];\n try {\n if (dsd) {\n // renderToStringDSD handles DSD wrapping but skips the polyfill so we can\n // place it correctly relative to other injected style tags below.\n html = _renderToStringDSD(vnode, {\n ...renderOptions,\n dsd: true,\n dsdPolyfill: false,\n });\n } else {\n html = _render(vnode, renderOptions);\n }\n } finally {\n // Always end collection — even when the render throws — so the collector\n // is never left non-null, which would cause subsequent non-SSR\n // useGlobalStyle() calls to silently skip DOM injection.\n globalStylesCaptured = endSSRGlobalStyleCollection();\n }\n\n const css = jitCSS(html);\n const globalStyles = globalStylesCaptured.join('\\n');\n\n const styleTags: string[] = [];\n if (css) styleTags.push(`<style id=\"cer-ssr-jit\">${css}</style>`);\n if (globalStyles.trim())\n styleTags.push(`<style id=\"cer-ssr-global\">${globalStyles}</style>`);\n\n let htmlWithStyles = html;\n if (styleTags.length) {\n const injection = styleTags.join('');\n htmlWithStyles = html.includes('</head>')\n ? html.replace('</head>', `${injection}</head>`)\n : `${injection}${html}`;\n }\n\n // Append DSD polyfill script inside </body> when in DSD mode\n if (dsd && dsdPolyfill !== false) {\n htmlWithStyles = htmlWithStyles.includes('</body>')\n ? htmlWithStyles.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`)\n : htmlWithStyles + DSD_POLYFILL_SCRIPT;\n }\n\n return { html, css, globalStyles, htmlWithStyles };\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output, full per-shadow-root CSS layer\n * extraction, and the DSD browser polyfill. This is the recommended function\n * for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): SSRJITResult {\n return renderToStringWithJITCSS(vnode, { ...options, dsd: true });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStream — streaming SSR\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a `ReadableStream<string>`.\n *\n * Supports true incremental streaming: synchronous components are flushed as\n * the first chunk, then each async component's resolved output is streamed as\n * an inline swap `<script>` that fills the placeholder's shadow root.\n *\n * @example Node.js\n * ```ts\n * import { renderToStream } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStream(appVNode, { dsd: true });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStream(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n const asyncEntries: AsyncStreamEntry[] = [];\n beginStreamingCollection(asyncEntries);\n\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n } catch (err) {\n controller.error(err);\n return;\n } finally {\n endStreamingCollection();\n }\n\n // Resolve async components and stream swap scripts as they settle.\n // Each resolved component replaces its placeholder via an inline script.\n for (const entry of asyncEntries) {\n try {\n const resolvedVNodes = await entry.promise;\n const shadowHTML = Array.isArray(resolvedVNodes)\n ? (resolvedVNodes as VNode[]).map((n) => renderToDSD(n, entry.opts)).join('')\n : renderToDSD(resolvedVNodes as VNode, entry.opts);\n const styleBlock = buildShadowStyleBlock(entry.useStyleCSS, shadowHTML);\n const shadowContent = `${styleBlock}${shadowHTML}`;\n controller.enqueue(\n `<script>(function(){` +\n `var e=document.getElementById(${JSON.stringify(entry.id)});` +\n `if(!e)return;` +\n // The placeholder already has an empty shadow root attached (native DSD or polyfill).\n // If for some reason it doesn't, attach one now.\n `var s=e.shadowRoot;` +\n `if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};` +\n `if(s)s.innerHTML=${JSON.stringify(shadowContent)};` +\n `e.removeAttribute('id');` +\n `})();</script>`,\n );\n } catch {\n // Async render failed — leave placeholder for client hydration.\n }\n }\n\n controller.close();\n },\n });\n}\n"],"mappings":"iMAcA,IAAa,EAAgB,IAAI,IAAI,CACnC,OACA,OACA,KACA,MACA,QACA,KACA,MACA,QACA,OACA,OACA,QACA,SACA,QACA,MACD,EAED,SAAgB,EACd,EACA,EACA,EACQ,CACR,MAAM,EAAS,EAAK,oBAAsB,GACpC,EAAc,EAAK,uBAAyB,EAC5C,EAAS,CAAE,GAAG,CAAA,EAEpB,OAAI,GAAU,IAAQ,OAAS,EAAE,UAAW,GAC1C,EAAO,MAAW,EAAA,OACT,GAAe,KAAO,EAAA,mBAAqB,EAAE,UAAW,KACjE,EAAO,MAAW,EAAA,kBAAkB,CAAA,GAG/B,OAAO,QAAQ,CAAA,EACnB,IAAA,CAAK,CAAC,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AM,EAAY,CACtB,MAAM,EAAmC,CAAA,EACzC,EAAyB,CAAA,EAEzB,GAAI,CACF,KAAM,CAAE,eAAA,CAAA,EAAmB,EAAyB,EAAO,CAAA,EAC3D,EAAW,QAAQ,CAAA,QACZ,EAAK,CACZ,EAAW,MAAM,CAAA,EACjB,eAEA,EAAA,EAKF,UAAW,KAAS,EAClB,GAAI,CACF,MAAM,EAAiB,MAAM,EAAM,QAC7B,EAAa,MAAM,QAAQ,CAAA,EAC5B,EAA2B,IAAK,GAAM,EAAY,EAAG,EAAM,IAAA,CAAK,EAAE,KAAK,EAAA,EACxE,EAAY,EAAyB,EAAM,IAAA,EAEzC,EAAgB,GADH,EAAsB,EAAM,YAAa,CAAA,CAAW,GACjC,CAAA,GACtC,EAAW,QACT,qDACmC,KAAK,UAAU,EAAM,EAAA,CAAG,4HAMrC,KAAK,UAAU,CAAA,CAAc,0CAAC,OAIhD,CAAA,CAKV,EAAW,MAAA,GAEd"}
1
+ {"version":3,"file":"ssr-DRsGduIK.cjs","names":[],"sources":["../src/lib/runtime/ssr-utils.ts","../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["/**\n * Shared utilities for SSR renderers.\n * Imported by vdom-ssr.ts and vdom-ssr-dsd.ts to avoid duplication.\n */\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\n\nexport type RenderOptions = {\n /** Backwards-compatible: whether to inject the SVG namespace on <svg> nodes (default true) */\n injectSvgNamespace?: boolean;\n /** Inject known well-known namespaces for tags like <math> when missing (default follows injectSvgNamespace) */\n injectKnownNamespaces?: boolean;\n};\n\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nexport function buildAttrs(\n attrs: Record<string, unknown>,\n tag: string,\n opts: RenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n const merged = { ...attrs };\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag in TAG_NAMESPACE_MAP && !('xmlns' in merged)) {\n merged['xmlns'] = TAG_NAMESPACE_MAP[tag];\n }\n\n return Object.entries(merged)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n\nexport function buildRawAttrs(attrs: Record<string, unknown>): string {\n return Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n","import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { VOID_ELEMENTS, buildAttrs, type RenderOptions } from './ssr-utils';\n\n/**\n * Render a VNode to a string (SSR).\n * Kept intentionally minimal: only serializes attributes under `props.attrs`\n * to avoid leaking runtime-only values (functions, reactive state, directives).\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport type { RenderOptions } from './ssr-utils';\n\nexport function renderToString(vnode: VNode, opts?: RenderOptions): string {\n if (typeof vnode === 'string') return escapeHTML(vnode) as string;\n\n if (vnode.tag === '#text') {\n return typeof vnode.children === 'string'\n ? (escapeHTML(vnode.children) as string)\n : '';\n }\n\n if (vnode.tag === '#anchor') {\n // Preserve meaningful falsy children (0, false, '') while filtering out\n // only null and undefined. Anchor blocks are normalized by the compiler\n // to exclude null/undefined; SSR should follow the same rule to avoid\n // hydration mismatches where falsy values are significant.\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter((c) => c !== null && c !== undefined)\n : [];\n return children.map((c) => renderToString(c, opts)).join('');\n }\n\n if (vnode.tag === '#raw') {\n return typeof vnode.children === 'string' ? vnode.children : '';\n }\n\n // Collect attributes from props.attrs. For SSR we mirror vnode.attrs\n // but ensure SVG nodes behave like client-side: if this is an <svg>\n // and no xmlns was provided, inject the standard SVG namespace so\n // server markup matches client-created DOM namespace.\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, vnode.tag, opts ?? {});\n\n // Handle void elements (self-closing tags)\n if (VOID_ELEMENTS.has(vnode.tag)) {\n return `<${vnode.tag}${attrsString}>`;\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToString(c, opts))\n .join('')\n : typeof vnode.children === 'string'\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children, opts)\n : '';\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Declarative Shadow DOM (DSD) SSR renderer.\n *\n * When `dsd: true` is passed to the render options, registered custom elements\n * are serialised as:\n *\n * ```html\n * <my-element attr=\"val\">\n * <template shadowrootmode=\"open\">\n * <style>\n * /* baseReset + useStyle() output + JIT utility CSS *\\/\n * </style>\n * <!-- shadow DOM from component render function -->\n * </template>\n * <!-- light DOM / slotted children from vnode.children -->\n * </my-element>\n * ```\n *\n * The browser parses the `<template shadowrootmode=\"open\">` block and attaches\n * a real shadow root before any JavaScript executes. All CSS layers are present\n * at first paint — eliminating both FOUC and layout shift.\n *\n * Non-custom-element VNodes are rendered identically to renderToString() but\n * with DSD recursion active for any custom elements nested inside them.\n */\n\nimport type { VNode } from './types';\nimport { renderToString } from './vdom-ssr';\nimport { VOID_ELEMENTS, buildAttrs, buildRawAttrs, type RenderOptions } from './ssr-utils';\nimport { registry } from './component/registry';\nimport { runComponentSSRRender } from './ssr-context';\nimport { jitCSS } from './style';\nimport { baseReset, minifyCSS } from './css-utils';\nimport { escapeHTML } from './helpers';\nimport { devWarn } from './logger';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type DSDRenderOptions = RenderOptions & {\n /**\n * Emit Declarative Shadow DOM output for registered custom elements.\n * Shadow content is serialised inside `<template shadowrootmode=\"open\">`,\n * with a complete CSS layer stack (`baseReset` + `useStyle` + JIT CSS)\n * injected as a `<style>` block so styles are available at first paint.\n * @default false\n */\n dsd?: boolean;\n /**\n * Append the DSD polyfill `<script>` for browsers without native support\n * (Firefox < 123). Only meaningful when `dsd` is true.\n * @default true\n */\n dsdPolyfill?: boolean;\n /**\n * Router instance to thread through each component's SSR context.\n *\n * When provided, `router-view` reads the current route from this instance\n * instead of the module-level `activeRouterProxy` singleton, making\n * concurrent SSR renders safe — each request carries its own router with\n * its own URL state.\n *\n * In browser mode this option is ignored; components always use\n * `activeRouterProxy` there.\n */\n router?: unknown;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * @internal\n * Minified DSD polyfill for browsers without native Declarative Shadow DOM.\n * Processes all `<template shadowrootmode>` elements synchronously.\n */\nexport const DSD_POLYFILL_SCRIPT =\n '<script>(function(){' +\n \"if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;\" +\n \"document.querySelectorAll('template[shadowrootmode]').forEach(function(t){\" +\n \"var m=t.getAttribute('shadowrootmode');\" +\n 'var s=t.parentElement.attachShadow({mode:m});' +\n 's.appendChild(t.content);t.remove();' +\n '});})()' +\n '</script>';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRegisteredCustomElement(tag: string): boolean {\n return tag.includes('-') && registry.has(tag);\n}\n\n/**\n * Build the combined `<style>` block for a shadow root.\n *\n * Layer order (matches the runtime adoptedStyleSheets order):\n * 1. baseReset — global reset + CSS custom properties\n * 2. useStyle() output — component-defined rules (:host, ::slotted, etc.)\n * 3. JIT CSS — utility classes extracted from the shadow HTML\n */\nexport function buildShadowStyleBlock(\n useStyleCSS: string,\n shadowHTML: string,\n): string {\n const parts: string[] = [baseReset];\n\n if (useStyleCSS.trim()) {\n parts.push(useStyleCSS);\n }\n\n const jit = jitCSS(shadowHTML);\n if (jit.trim()) {\n parts.push(jit);\n }\n\n const combined = minifyCSS(parts.join('\\n'));\n return combined ? `<style>${combined}</style>` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Streaming async component collector\n// ---------------------------------------------------------------------------\n\nexport interface AsyncStreamEntry {\n id: string;\n tag: string;\n attrsString: string;\n hydrateAttr: string;\n useStyleCSS: string;\n lightDOM: string;\n opts: DSDRenderOptions;\n promise: Promise<VNode | VNode[]>;\n /** Router threaded from the originating render pass — propagated to async re-renders. */\n router?: unknown;\n}\n\nlet _streamingCollector: AsyncStreamEntry[] | null = null;\nlet _streamingCounter = 0;\n\n/** @internal Called by renderToStream() before the sync render pass. */\nexport function beginStreamingCollection(collector: AsyncStreamEntry[]): void {\n _streamingCollector = collector;\n _streamingCounter = 0;\n}\n\n/** @internal Called by renderToStream() after the sync render pass. */\nexport function endStreamingCollection(): void {\n _streamingCollector = null;\n}\n\n// ---------------------------------------------------------------------------\n// Core renderer\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to an HTML string with Declarative Shadow DOM output\n * for all registered custom elements encountered in the tree.\n */\nexport function renderToDSD(vnode: VNode, opts: DSDRenderOptions): string {\n if (!opts.dsd) {\n return renderToString(vnode, opts);\n }\n\n // Primitive string nodes\n if (typeof vnode === 'string') {\n return escapeHTML(vnode) as string;\n }\n\n const tag = (vnode as VNode).tag;\n\n // Special virtual node types — delegate entirely to the base renderer\n if (tag === '#text' || tag === '#anchor' || tag === '#raw') {\n return renderToString(vnode, opts);\n }\n\n // Custom element — emit DSD wrapper\n if (isRegisteredCustomElement(tag)) {\n return renderCustomElementDSD(vnode, opts);\n }\n\n // Regular element — recurse with DSD mode on\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, tag, opts);\n\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrsString}>`;\n }\n\n const children = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}>${children}</${tag}>`;\n}\n\nfunction renderCustomElementDSD(vnode: VNode, opts: DSDRenderOptions): string {\n const tag = vnode.tag;\n const config = registry.get(tag);\n\n // Build the plain attribute string (no namespace injection for custom elements)\n const rawAttrs = vnode.props?.attrs ?? {};\n const attrsString = buildRawAttrs(rawAttrs);\n\n // Move the null check BEFORE reading config.* properties for clarity.\n if (!config) {\n // Component not in registry on server (e.g. dynamic import not yet run).\n // Emit a shell with an empty DSD template so the client hydrates normally.\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\n }\n\n // Emit data-cer-hydrate when a non-default strategy is configured.\n // 'load' is the default and doesn't need to be serialised.\n const hydrateStrategy = config.hydrate;\n const hydrateAttr =\n hydrateStrategy && hydrateStrategy !== 'load'\n ? ` data-cer-hydrate=\"${hydrateStrategy}\"`\n : '';\n\n // Run the component's render function in a minimal SSR context to get the\n // shadow DOM VNode tree and capture any useStyle() output.\n const { shadowVNode, useStyleCSS, asyncPromise } = runComponentSSRRender(config, rawAttrs, tag, opts.router);\n\n // When streaming and this component has an async render, emit a placeholder\n // and register the promise for later resolution.\n if (asyncPromise && _streamingCollector === null) {\n devWarn(\n `[SSR] Component \"${tag}\" has an async render function. ` +\n `In standard SSR the shadow DOM will be empty. ` +\n `Use renderToStream() for incremental async component streaming.`,\n );\n }\n if (asyncPromise && _streamingCollector !== null) {\n const id = `cer-stream-${_streamingCounter++}`;\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n _streamingCollector.push({\n id,\n tag,\n attrsString,\n hydrateAttr,\n useStyleCSS,\n lightDOM,\n opts,\n promise: asyncPromise,\n router: opts.router,\n });\n return (\n `<${tag} id=\"${id}\"${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\"></template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n }\n\n // Render the shadow DOM VNode tree to HTML (DSD-recursive for nested elements)\n let shadowHTML = '';\n if (shadowVNode !== null && shadowVNode !== undefined) {\n if (Array.isArray(shadowVNode)) {\n shadowHTML = (shadowVNode as VNode[])\n .map((n) => renderToDSD(n, opts))\n .join('');\n } else {\n shadowHTML = renderToDSD(shadowVNode as VNode, opts);\n }\n }\n\n const styleBlock = buildShadowStyleBlock(useStyleCSS, shadowHTML);\n\n // Light DOM children become slotted content — rendered outside the template\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n\n return (\n `<${tag}${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\">${styleBlock}${shadowHTML}</template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n}\n\nfunction renderChildrenDSD(\n children: VNode['children'],\n opts: DSDRenderOptions,\n): string {\n if (!children) return '';\n if (typeof children === 'string') return escapeHTML(children) as string;\n if (Array.isArray(children)) {\n return children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToDSD(c as VNode, opts))\n .join('');\n }\n return renderToDSD(children as VNode, opts);\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a DSD HTML string and optionally append the\n * DSD polyfill script for older browsers.\n */\nexport function renderToStringDSD(\n vnode: VNode,\n opts?: DSDRenderOptions,\n): string {\n const effectiveOpts: DSDRenderOptions = { dsd: true, ...opts };\n const html = renderToDSD(vnode, effectiveOpts);\n\n if (effectiveOpts.dsdPolyfill !== false) {\n // Inject polyfill before </body> if present, otherwise append\n if (html.includes('</body>')) {\n return html.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`);\n }\n return html + DSD_POLYFILL_SCRIPT;\n }\n\n return html;\n}\n","/**\n * SSR entry point — import from `@jasonshimmy/custom-elements-runtime/ssr`.\n *\n * Provides four rendering modes:\n *\n * 1. **renderToString** — baseline HTML serialisation (no shadow DOM content).\n * Backwards-compatible with the original API.\n *\n * 2. **renderToStringWithJITCSS** — HTML + pre-generated JIT CSS injected into\n * `<head>` to prevent FOUC. Supports `dsd: true` for DSD output.\n *\n * 3. **renderToStringWithJITCSSDSD** — convenience alias for DSD mode.\n * Full Declarative Shadow DOM output with per-shadow-root CSS layer stack\n * (baseReset + useStyle() + JIT CSS). Enables true hydration, zero FOUC.\n *\n * 4. **renderToStream** — ReadableStream variant for streaming SSR.\n *\n * 5. **renderToStreamWithJITCSSDSD** — convenience alias for streaming DSD mode.\n * Equivalent to `renderToStream(vnode, { dsd: true, ...options })`.\n * Recommended for new server-rendered applications that want true incremental\n * streaming with Declarative Shadow DOM and zero FOUC.\n *\n * Entity map utilities are also exported for full HTML5 named-entity support.\n *\n * @example DSD usage (recommended)\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * res.send(`<!DOCTYPE html><html><head>${head}</head><body>${htmlWithStyles}</body></html>`);\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Re-exports — backwards-compatible\n// ---------------------------------------------------------------------------\n\nexport { renderToString } from './runtime/vdom-ssr';\nexport type { VNode } from './runtime/types';\nexport type { RenderOptions } from './runtime/vdom-ssr';\n\nexport {\n registerEntityMap,\n loadEntityMap,\n clearRegisteredEntityMap,\n} from './runtime/helpers';\n\nexport {\n renderToStringDSD,\n DSD_POLYFILL_SCRIPT,\n} from './runtime/vdom-ssr-dsd';\nexport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\n\n// ---------------------------------------------------------------------------\n// Internal imports\n// ---------------------------------------------------------------------------\n\nimport { renderToString as _render } from './runtime/vdom-ssr';\nimport {\n renderToStringDSD as _renderToStringDSD,\n renderToDSD,\n buildShadowStyleBlock,\n beginStreamingCollection,\n endStreamingCollection,\n DSD_POLYFILL_SCRIPT,\n type AsyncStreamEntry,\n} from './runtime/vdom-ssr-dsd';\nimport { jitCSS, enableJITCSS, type JITCSSOptions } from './runtime/style';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport {\n beginSSRGlobalStyleCollection,\n endSSRGlobalStyleCollection,\n} from './runtime/ssr-context';\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/**\n * Result of `renderToStringWithJITCSS()` and `renderToStringWithJITCSSDSD()`.\n */\nexport interface SSRJITResult {\n /** The rendered HTML string (styles not yet injected). */\n html: string;\n /**\n * Global JIT CSS extracted from the rendered HTML.\n * For DSD renders, each shadow root embeds its own scoped styles; this field\n * holds any residual light-DOM utility CSS.\n */\n css: string;\n /**\n * CSS captured from `useGlobalStyle()` calls during this render pass\n * (e.g. `@font-face`, `:root` custom properties).\n * Inject in a `<style id=\"cer-ssr-global\">` in `<head>`.\n */\n globalStyles: string;\n /**\n * Convenience: `html` with both `<style>` tags injected before `</head>`.\n * If no `</head>` is found, the styles are prepended.\n */\n htmlWithStyles: string;\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSS — primary API, supports both modes\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side render a VNode tree and simultaneously pre-generate JIT CSS.\n *\n * Pass `dsd: true` to enable Declarative Shadow DOM output with full per-shadow-\n * root CSS layer extraction (recommended for new apps).\n *\n * @example Standard (no DSD)\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode);\n * ```\n *\n * @example With DSD\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode, {\n * dsd: true,\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSS(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): SSRJITResult {\n const { jit, dsd, dsdPolyfill, ...renderOptions } = options ?? {};\n\n if (jit) enableJITCSS(jit);\n\n beginSSRGlobalStyleCollection();\n\n let html!: string;\n let globalStylesCaptured!: string[];\n try {\n if (dsd) {\n // renderToStringDSD handles DSD wrapping but skips the polyfill so we can\n // place it correctly relative to other injected style tags below.\n html = _renderToStringDSD(vnode, {\n ...renderOptions,\n dsd: true,\n dsdPolyfill: false,\n });\n } else {\n html = _render(vnode, renderOptions);\n }\n } finally {\n // Always end collection — even when the render throws — so the collector\n // is never left non-null, which would cause subsequent non-SSR\n // useGlobalStyle() calls to silently skip DOM injection.\n globalStylesCaptured = endSSRGlobalStyleCollection();\n }\n\n const css = jitCSS(html);\n const globalStyles = globalStylesCaptured.join('\\n');\n\n const styleTags: string[] = [];\n if (css) styleTags.push(`<style id=\"cer-ssr-jit\">${css}</style>`);\n if (globalStyles.trim())\n styleTags.push(`<style id=\"cer-ssr-global\">${globalStyles}</style>`);\n\n let htmlWithStyles = html;\n if (styleTags.length) {\n const injection = styleTags.join('');\n htmlWithStyles = html.includes('</head>')\n ? html.replace('</head>', `${injection}</head>`)\n : `${injection}${html}`;\n }\n\n // Append DSD polyfill script inside </body> when in DSD mode\n if (dsd && dsdPolyfill !== false) {\n htmlWithStyles = htmlWithStyles.includes('</body>')\n ? htmlWithStyles.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`)\n : htmlWithStyles + DSD_POLYFILL_SCRIPT;\n }\n\n return { html, css, globalStyles, htmlWithStyles };\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output, full per-shadow-root CSS layer\n * extraction, and the DSD browser polyfill. This is the recommended function\n * for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): SSRJITResult {\n return renderToStringWithJITCSS(vnode, { ...options, dsd: true });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStream — streaming SSR\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a `ReadableStream<string>`.\n *\n * Supports true incremental streaming: synchronous components are flushed as\n * the first chunk, then each async component's resolved output is streamed as\n * an inline swap `<script>` that fills the placeholder's shadow root.\n *\n * @example Node.js\n * ```ts\n * import { renderToStream } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStream(appVNode, { dsd: true });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStream(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n const asyncEntries: AsyncStreamEntry[] = [];\n beginStreamingCollection(asyncEntries);\n\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n } catch (err) {\n controller.error(err);\n return;\n } finally {\n endStreamingCollection();\n }\n\n // Resolve async components and stream swap scripts as they settle.\n // Each resolved component replaces its placeholder via an inline script.\n for (const entry of asyncEntries) {\n try {\n const resolvedVNodes = await entry.promise;\n const shadowHTML = Array.isArray(resolvedVNodes)\n ? (resolvedVNodes as VNode[]).map((n) => renderToDSD(n, entry.opts)).join('')\n : renderToDSD(resolvedVNodes as VNode, entry.opts);\n const styleBlock = buildShadowStyleBlock(entry.useStyleCSS, shadowHTML);\n const shadowContent = `${styleBlock}${shadowHTML}`;\n controller.enqueue(\n `<script>(function(){` +\n `var e=document.getElementById(${JSON.stringify(entry.id)});` +\n `if(!e)return;` +\n // The placeholder already has an empty shadow root attached (native DSD or polyfill).\n // If for some reason it doesn't, attach one now.\n `var s=e.shadowRoot;` +\n `if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};` +\n `if(s)s.innerHTML=${JSON.stringify(shadowContent)};` +\n `e.removeAttribute('id');` +\n `})();</script>`,\n );\n } catch {\n // Async render failed — leave placeholder for client hydration.\n }\n }\n\n controller.close();\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStreamWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStream(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output and full JIT CSS extraction,\n * streaming the synchronous render as the first chunk and each resolved async\n * component as a subsequent inline-script swap. This is the recommended\n * function for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStreamWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStreamWithJITCSSDSD(appVNode, { router });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStreamWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): ReadableStream<string> {\n return renderToStream(vnode, { ...options, dsd: true });\n}\n"],"mappings":"iMAcA,IAAa,EAAgB,IAAI,IAAI,CACnC,OACA,OACA,KACA,MACA,QACA,KACA,MACA,QACA,OACA,OACA,QACA,SACA,QACA,MACD,EAED,SAAgB,EACd,EACA,EACA,EACQ,CACR,MAAM,EAAS,EAAK,oBAAsB,GACpC,EAAc,EAAK,uBAAyB,EAC5C,EAAS,CAAE,GAAG,CAAA,EAEpB,OAAI,GAAU,IAAQ,OAAS,EAAE,UAAW,GAC1C,EAAO,MAAW,EAAA,OACT,GAAe,KAAO,EAAA,mBAAqB,EAAE,UAAW,KACjE,EAAO,MAAW,EAAA,kBAAkB,CAAA,GAG/B,OAAO,QAAQ,CAAA,EACnB,IAAA,CAAK,CAAC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AAM,EAAY,CACtB,MAAM,EAAmC,CAAA,EACzC,EAAyB,CAAA,EAEzB,GAAI,CACF,KAAM,CAAE,eAAA,CAAA,EAAmB,EAAyB,EAAO,CAAA,EAC3D,EAAW,QAAQ,CAAA,QACZ,EAAK,CACZ,EAAW,MAAM,CAAA,EACjB,eAEA,EAAA,EAKF,UAAW,KAAS,EAClB,GAAI,CACF,MAAM,EAAiB,MAAM,EAAM,QAC7B,EAAa,MAAM,QAAQ,CAAA,EAC5B,EAA2B,IAAK,GAAM,EAAY,EAAG,EAAM,IAAA,CAAK,EAAE,KAAK,EAAA,EACxE,EAAY,EAAyB,EAAM,IAAA,EAEzC,EAAgB,GADH,EAAsB,EAAM,YAAa,CAAA,CAAW,GACjC,CAAA,GACtC,EAAW,QACT,qDACmC,KAAK,UAAU,EAAM,EAAA,CAAG,4HAMrC,KAAK,UAAU,CAAA,CAAc,0CAAC,OAIhD,CAAA,CAKV,EAAW,MAAA,GAEd,EAgCH,SAAgB,EACd,EACA,EAIwB,CACxB,OAAO,EAAe,EAAO,CAAE,GAAG,EAAS,IAAK,GAAM"}
@@ -1,9 +1,9 @@
1
1
  import { r as O } from "./logger-L25axmB-.js";
2
- import { n as w, o as C, t as L } from "./namespace-helpers-BucDdgz_.js";
3
- import { S as N, T as f, b as P, x as _ } from "./hooks-_3xP4G2N.js";
4
- import { a as x, d as I } from "./css-utils-CC43BbEy.js";
5
- import { i as H, l as j } from "./style-DuDoj_xK.js";
6
- var A = /* @__PURE__ */ new Set([
2
+ import { n as w, o as C, t as I } from "./namespace-helpers-BucDdgz_.js";
3
+ import { S as L, T as f, b as N, x as P } from "./hooks-_3xP4G2N.js";
4
+ import { a as _, d as x } from "./css-utils-CC43BbEy.js";
5
+ import { i as J, l as T } from "./style-DuDoj_xK.js";
6
+ var j = /* @__PURE__ */ new Set([
7
7
  "area",
8
8
  "base",
9
9
  "br",
@@ -19,11 +19,11 @@ var A = /* @__PURE__ */ new Set([
19
19
  "track",
20
20
  "wbr"
21
21
  ]);
22
- function T(t, e, r) {
22
+ function A(t, e, r) {
23
23
  const i = r.injectSvgNamespace ?? !0, n = r.injectKnownNamespaces ?? i, s = { ...t };
24
- return i && e === "svg" && !("xmlns" in s) ? s.xmlns = L : n && e in w && !("xmlns" in s) && (s.xmlns = w[e]), Object.entries(s).map(([a, c]) => ` ${a}="${f(String(c))}"`).join("");
24
+ return i && e === "svg" && !("xmlns" in s) ? s.xmlns = I : n && e in w && !("xmlns" in s) && (s.xmlns = w[e]), Object.entries(s).map(([a, c]) => ` ${a}="${f(String(c))}"`).join("");
25
25
  }
26
- function J(t) {
26
+ function W(t) {
27
27
  return Object.entries(t).map(([e, r]) => ` ${e}="${f(String(r))}"`).join("");
28
28
  }
29
29
  function h(t, e) {
@@ -31,52 +31,52 @@ function h(t, e) {
31
31
  if (t.tag === "#text") return typeof t.children == "string" ? f(t.children) : "";
32
32
  if (t.tag === "#anchor") return (Array.isArray(t.children) ? t.children.filter((n) => n != null) : []).map((n) => h(n, e)).join("");
33
33
  if (t.tag === "#raw") return typeof t.children == "string" ? t.children : "";
34
- const r = T(t.props?.attrs ? { ...t.props.attrs } : {}, t.tag, e ?? {});
35
- if (A.has(t.tag)) return `<${t.tag}${r}>`;
34
+ const r = A(t.props?.attrs ? { ...t.props.attrs } : {}, t.tag, e ?? {});
35
+ if (j.has(t.tag)) return `<${t.tag}${r}>`;
36
36
  const i = Array.isArray(t.children) ? t.children.filter((n) => n != null).map((n) => h(n, e)).join("") : typeof t.children == "string" ? f(t.children) : t.children ? h(t.children, e) : "";
37
37
  return `<${t.tag}${r}>${i}</${t.tag}>`;
38
38
  }
39
39
  var $ = "<script>(function(){if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;document.querySelectorAll('template[shadowrootmode]').forEach(function(t){var m=t.getAttribute('shadowrootmode');var s=t.parentElement.attachShadow({mode:m});s.appendChild(t.content);t.remove();});})()<\/script>";
40
- function W(t) {
40
+ function H(t) {
41
41
  return t.includes("-") && C.has(t);
42
42
  }
43
43
  function D(t, e) {
44
- const r = [x];
44
+ const r = [_];
45
45
  t.trim() && r.push(t);
46
- const i = j(e);
46
+ const i = T(e);
47
47
  i.trim() && r.push(i);
48
- const n = I(r.join(`
48
+ const n = x(r.join(`
49
49
  `));
50
50
  return n ? `<style>${n}</style>` : "";
51
51
  }
52
- var y = null, R = 0;
52
+ var S = null, R = 0;
53
53
  function k(t) {
54
- y = t, R = 0;
54
+ S = t, R = 0;
55
55
  }
56
56
  function G() {
57
- y = null;
57
+ S = null;
58
58
  }
59
- function m(t, e) {
59
+ function d(t, e) {
60
60
  if (!e.dsd) return h(t, e);
61
61
  if (typeof t == "string") return f(t);
62
62
  const r = t.tag;
63
63
  if (r === "#text" || r === "#anchor" || r === "#raw") return h(t, e);
64
- if (W(r)) return V(t, e);
65
- const i = T(t.props?.attrs ? { ...t.props.attrs } : {}, r, e);
66
- return A.has(r) ? `<${r}${i}>` : `<${r}${i}>${g(t.children, e)}</${r}>`;
64
+ if (H(r)) return V(t, e);
65
+ const i = A(t.props?.attrs ? { ...t.props.attrs } : {}, r, e);
66
+ return j.has(r) ? `<${r}${i}>` : `<${r}${i}>${g(t.children, e)}</${r}>`;
67
67
  }
68
68
  function V(t, e) {
69
- const r = t.tag, i = C.get(r), n = t.props?.attrs ?? {}, s = J(n);
69
+ const r = t.tag, i = C.get(r), n = t.props?.attrs ?? {}, s = W(n);
70
70
  if (!i) return `<${r}${s}><template shadowrootmode="open"></template>${g(t.children, e)}</${r}>`;
71
- const a = i.hydrate, c = a && a !== "load" ? ` data-cer-hydrate="${a}"` : "", { shadowVNode: o, useStyleCSS: d, asyncPromise: u } = N(i, n, r, e.router);
72
- if (u && y === null && O(`[SSR] Component "${r}" has an async render function. In standard SSR the shadow DOM will be empty. Use renderToStream() for incremental async component streaming.`), u && y !== null) {
71
+ const a = i.hydrate, c = a && a !== "load" ? ` data-cer-hydrate="${a}"` : "", { shadowVNode: o, useStyleCSS: m, asyncPromise: u } = L(i, n, r, e.router);
72
+ if (u && S === null && O(`[SSR] Component "${r}" has an async render function. In standard SSR the shadow DOM will be empty. Use renderToStream() for incremental async component streaming.`), u && S !== null) {
73
73
  const p = `cer-stream-${R++}`, b = g(t.children, e);
74
- return y.push({
74
+ return S.push({
75
75
  id: p,
76
76
  tag: r,
77
77
  attrsString: s,
78
78
  hydrateAttr: c,
79
- useStyleCSS: d,
79
+ useStyleCSS: m,
80
80
  lightDOM: b,
81
81
  opts: e,
82
82
  promise: u,
@@ -84,23 +84,23 @@ function V(t, e) {
84
84
  }), `<${r} id="${p}"${s}${c}><template shadowrootmode="open"></template>${b}</${r}>`;
85
85
  }
86
86
  let l = "";
87
- o != null && (Array.isArray(o) ? l = o.map((p) => m(p, e)).join("") : l = m(o, e));
88
- const S = D(d, l), M = g(t.children, e);
89
- return `<${r}${s}${c}><template shadowrootmode="open">${S}${l}</template>${M}</${r}>`;
87
+ o != null && (Array.isArray(o) ? l = o.map((p) => d(p, e)).join("") : l = d(o, e));
88
+ const y = D(m, l), M = g(t.children, e);
89
+ return `<${r}${s}${c}><template shadowrootmode="open">${y}${l}</template>${M}</${r}>`;
90
90
  }
91
91
  function g(t, e) {
92
- return t ? typeof t == "string" ? f(t) : Array.isArray(t) ? t.filter((r) => r != null).map((r) => m(r, e)).join("") : m(t, e) : "";
92
+ return t ? typeof t == "string" ? f(t) : Array.isArray(t) ? t.filter((r) => r != null).map((r) => d(r, e)).join("") : d(t, e) : "";
93
93
  }
94
94
  function q(t, e) {
95
95
  const r = {
96
96
  dsd: !0,
97
97
  ...e
98
- }, i = m(t, r);
98
+ }, i = d(t, r);
99
99
  return r.dsdPolyfill !== !1 ? i.includes("</body>") ? i.replace("</body>", `${$}</body>`) : i + $ : i;
100
100
  }
101
101
  function E(t, e) {
102
102
  const { jit: r, dsd: i, dsdPolyfill: n, ...s } = e ?? {};
103
- r && H(r), P();
103
+ r && J(r), N();
104
104
  let a, c;
105
105
  try {
106
106
  i ? a = q(t, {
@@ -109,30 +109,30 @@ function E(t, e) {
109
109
  dsdPolyfill: !1
110
110
  }) : a = h(t, s);
111
111
  } finally {
112
- c = _();
112
+ c = P();
113
113
  }
114
- const o = j(a), d = c.join(`
114
+ const o = T(a), m = c.join(`
115
115
  `), u = [];
116
- o && u.push(`<style id="cer-ssr-jit">${o}</style>`), d.trim() && u.push(`<style id="cer-ssr-global">${d}</style>`);
116
+ o && u.push(`<style id="cer-ssr-jit">${o}</style>`), m.trim() && u.push(`<style id="cer-ssr-global">${m}</style>`);
117
117
  let l = a;
118
118
  if (u.length) {
119
- const S = u.join("");
120
- l = a.includes("</head>") ? a.replace("</head>", `${S}</head>`) : `${S}${a}`;
119
+ const y = u.join("");
120
+ l = a.includes("</head>") ? a.replace("</head>", `${y}</head>`) : `${y}${a}`;
121
121
  }
122
122
  return i && n !== !1 && (l = l.includes("</body>") ? l.replace("</body>", `${$}</body>`) : l + $), {
123
123
  html: a,
124
124
  css: o,
125
- globalStyles: d,
125
+ globalStyles: m,
126
126
  htmlWithStyles: l
127
127
  };
128
128
  }
129
- function z(t, e) {
129
+ function Q(t, e) {
130
130
  return E(t, {
131
131
  ...e,
132
132
  dsd: !0
133
133
  });
134
134
  }
135
- function Q(t, e) {
135
+ function B(t, e) {
136
136
  return new ReadableStream({ async start(r) {
137
137
  const i = [];
138
138
  k(i);
@@ -146,20 +146,27 @@ function Q(t, e) {
146
146
  G();
147
147
  }
148
148
  for (const n of i) try {
149
- const s = await n.promise, a = Array.isArray(s) ? s.map((o) => m(o, n.opts)).join("") : m(s, n.opts), c = `${D(n.useStyleCSS, a)}${a}`;
149
+ const s = await n.promise, a = Array.isArray(s) ? s.map((o) => d(o, n.opts)).join("") : d(s, n.opts), c = `${D(n.useStyleCSS, a)}${a}`;
150
150
  r.enqueue(`<script>(function(){var e=document.getElementById(${JSON.stringify(n.id)});if(!e)return;var s=e.shadowRoot;if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};if(s)s.innerHTML=${JSON.stringify(c)};e.removeAttribute('id');})();<\/script>`);
151
151
  } catch {
152
152
  }
153
153
  r.close();
154
154
  } });
155
155
  }
156
+ function X(t, e) {
157
+ return B(t, {
158
+ ...e,
159
+ dsd: !0
160
+ });
161
+ }
156
162
  export {
157
- q as a,
158
- $ as i,
159
- E as n,
160
- h as o,
161
- z as r,
162
- Q as t
163
+ $ as a,
164
+ Q as i,
165
+ X as n,
166
+ q as o,
167
+ E as r,
168
+ h as s,
169
+ B as t
163
170
  };
164
171
 
165
- //# sourceMappingURL=ssr-B3lxl1vr.js.map
172
+ //# sourceMappingURL=ssr-H9GDwbTy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr-H9GDwbTy.js","names":[],"sources":["../src/lib/runtime/ssr-utils.ts","../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["/**\n * Shared utilities for SSR renderers.\n * Imported by vdom-ssr.ts and vdom-ssr-dsd.ts to avoid duplication.\n */\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\n\nexport type RenderOptions = {\n /** Backwards-compatible: whether to inject the SVG namespace on <svg> nodes (default true) */\n injectSvgNamespace?: boolean;\n /** Inject known well-known namespaces for tags like <math> when missing (default follows injectSvgNamespace) */\n injectKnownNamespaces?: boolean;\n};\n\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nexport function buildAttrs(\n attrs: Record<string, unknown>,\n tag: string,\n opts: RenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n const merged = { ...attrs };\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag in TAG_NAMESPACE_MAP && !('xmlns' in merged)) {\n merged['xmlns'] = TAG_NAMESPACE_MAP[tag];\n }\n\n return Object.entries(merged)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n\nexport function buildRawAttrs(attrs: Record<string, unknown>): string {\n return Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n","import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { VOID_ELEMENTS, buildAttrs, type RenderOptions } from './ssr-utils';\n\n/**\n * Render a VNode to a string (SSR).\n * Kept intentionally minimal: only serializes attributes under `props.attrs`\n * to avoid leaking runtime-only values (functions, reactive state, directives).\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport type { RenderOptions } from './ssr-utils';\n\nexport function renderToString(vnode: VNode, opts?: RenderOptions): string {\n if (typeof vnode === 'string') return escapeHTML(vnode) as string;\n\n if (vnode.tag === '#text') {\n return typeof vnode.children === 'string'\n ? (escapeHTML(vnode.children) as string)\n : '';\n }\n\n if (vnode.tag === '#anchor') {\n // Preserve meaningful falsy children (0, false, '') while filtering out\n // only null and undefined. Anchor blocks are normalized by the compiler\n // to exclude null/undefined; SSR should follow the same rule to avoid\n // hydration mismatches where falsy values are significant.\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter((c) => c !== null && c !== undefined)\n : [];\n return children.map((c) => renderToString(c, opts)).join('');\n }\n\n if (vnode.tag === '#raw') {\n return typeof vnode.children === 'string' ? vnode.children : '';\n }\n\n // Collect attributes from props.attrs. For SSR we mirror vnode.attrs\n // but ensure SVG nodes behave like client-side: if this is an <svg>\n // and no xmlns was provided, inject the standard SVG namespace so\n // server markup matches client-created DOM namespace.\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, vnode.tag, opts ?? {});\n\n // Handle void elements (self-closing tags)\n if (VOID_ELEMENTS.has(vnode.tag)) {\n return `<${vnode.tag}${attrsString}>`;\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToString(c, opts))\n .join('')\n : typeof vnode.children === 'string'\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children, opts)\n : '';\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Declarative Shadow DOM (DSD) SSR renderer.\n *\n * When `dsd: true` is passed to the render options, registered custom elements\n * are serialised as:\n *\n * ```html\n * <my-element attr=\"val\">\n * <template shadowrootmode=\"open\">\n * <style>\n * /* baseReset + useStyle() output + JIT utility CSS *\\/\n * </style>\n * <!-- shadow DOM from component render function -->\n * </template>\n * <!-- light DOM / slotted children from vnode.children -->\n * </my-element>\n * ```\n *\n * The browser parses the `<template shadowrootmode=\"open\">` block and attaches\n * a real shadow root before any JavaScript executes. All CSS layers are present\n * at first paint — eliminating both FOUC and layout shift.\n *\n * Non-custom-element VNodes are rendered identically to renderToString() but\n * with DSD recursion active for any custom elements nested inside them.\n */\n\nimport type { VNode } from './types';\nimport { renderToString } from './vdom-ssr';\nimport { VOID_ELEMENTS, buildAttrs, buildRawAttrs, type RenderOptions } from './ssr-utils';\nimport { registry } from './component/registry';\nimport { runComponentSSRRender } from './ssr-context';\nimport { jitCSS } from './style';\nimport { baseReset, minifyCSS } from './css-utils';\nimport { escapeHTML } from './helpers';\nimport { devWarn } from './logger';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type DSDRenderOptions = RenderOptions & {\n /**\n * Emit Declarative Shadow DOM output for registered custom elements.\n * Shadow content is serialised inside `<template shadowrootmode=\"open\">`,\n * with a complete CSS layer stack (`baseReset` + `useStyle` + JIT CSS)\n * injected as a `<style>` block so styles are available at first paint.\n * @default false\n */\n dsd?: boolean;\n /**\n * Append the DSD polyfill `<script>` for browsers without native support\n * (Firefox < 123). Only meaningful when `dsd` is true.\n * @default true\n */\n dsdPolyfill?: boolean;\n /**\n * Router instance to thread through each component's SSR context.\n *\n * When provided, `router-view` reads the current route from this instance\n * instead of the module-level `activeRouterProxy` singleton, making\n * concurrent SSR renders safe — each request carries its own router with\n * its own URL state.\n *\n * In browser mode this option is ignored; components always use\n * `activeRouterProxy` there.\n */\n router?: unknown;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * @internal\n * Minified DSD polyfill for browsers without native Declarative Shadow DOM.\n * Processes all `<template shadowrootmode>` elements synchronously.\n */\nexport const DSD_POLYFILL_SCRIPT =\n '<script>(function(){' +\n \"if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;\" +\n \"document.querySelectorAll('template[shadowrootmode]').forEach(function(t){\" +\n \"var m=t.getAttribute('shadowrootmode');\" +\n 'var s=t.parentElement.attachShadow({mode:m});' +\n 's.appendChild(t.content);t.remove();' +\n '});})()' +\n '</script>';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRegisteredCustomElement(tag: string): boolean {\n return tag.includes('-') && registry.has(tag);\n}\n\n/**\n * Build the combined `<style>` block for a shadow root.\n *\n * Layer order (matches the runtime adoptedStyleSheets order):\n * 1. baseReset — global reset + CSS custom properties\n * 2. useStyle() output — component-defined rules (:host, ::slotted, etc.)\n * 3. JIT CSS — utility classes extracted from the shadow HTML\n */\nexport function buildShadowStyleBlock(\n useStyleCSS: string,\n shadowHTML: string,\n): string {\n const parts: string[] = [baseReset];\n\n if (useStyleCSS.trim()) {\n parts.push(useStyleCSS);\n }\n\n const jit = jitCSS(shadowHTML);\n if (jit.trim()) {\n parts.push(jit);\n }\n\n const combined = minifyCSS(parts.join('\\n'));\n return combined ? `<style>${combined}</style>` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Streaming async component collector\n// ---------------------------------------------------------------------------\n\nexport interface AsyncStreamEntry {\n id: string;\n tag: string;\n attrsString: string;\n hydrateAttr: string;\n useStyleCSS: string;\n lightDOM: string;\n opts: DSDRenderOptions;\n promise: Promise<VNode | VNode[]>;\n /** Router threaded from the originating render pass — propagated to async re-renders. */\n router?: unknown;\n}\n\nlet _streamingCollector: AsyncStreamEntry[] | null = null;\nlet _streamingCounter = 0;\n\n/** @internal Called by renderToStream() before the sync render pass. */\nexport function beginStreamingCollection(collector: AsyncStreamEntry[]): void {\n _streamingCollector = collector;\n _streamingCounter = 0;\n}\n\n/** @internal Called by renderToStream() after the sync render pass. */\nexport function endStreamingCollection(): void {\n _streamingCollector = null;\n}\n\n// ---------------------------------------------------------------------------\n// Core renderer\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to an HTML string with Declarative Shadow DOM output\n * for all registered custom elements encountered in the tree.\n */\nexport function renderToDSD(vnode: VNode, opts: DSDRenderOptions): string {\n if (!opts.dsd) {\n return renderToString(vnode, opts);\n }\n\n // Primitive string nodes\n if (typeof vnode === 'string') {\n return escapeHTML(vnode) as string;\n }\n\n const tag = (vnode as VNode).tag;\n\n // Special virtual node types — delegate entirely to the base renderer\n if (tag === '#text' || tag === '#anchor' || tag === '#raw') {\n return renderToString(vnode, opts);\n }\n\n // Custom element — emit DSD wrapper\n if (isRegisteredCustomElement(tag)) {\n return renderCustomElementDSD(vnode, opts);\n }\n\n // Regular element — recurse with DSD mode on\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, tag, opts);\n\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrsString}>`;\n }\n\n const children = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}>${children}</${tag}>`;\n}\n\nfunction renderCustomElementDSD(vnode: VNode, opts: DSDRenderOptions): string {\n const tag = vnode.tag;\n const config = registry.get(tag);\n\n // Build the plain attribute string (no namespace injection for custom elements)\n const rawAttrs = vnode.props?.attrs ?? {};\n const attrsString = buildRawAttrs(rawAttrs);\n\n // Move the null check BEFORE reading config.* properties for clarity.\n if (!config) {\n // Component not in registry on server (e.g. dynamic import not yet run).\n // Emit a shell with an empty DSD template so the client hydrates normally.\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\n }\n\n // Emit data-cer-hydrate when a non-default strategy is configured.\n // 'load' is the default and doesn't need to be serialised.\n const hydrateStrategy = config.hydrate;\n const hydrateAttr =\n hydrateStrategy && hydrateStrategy !== 'load'\n ? ` data-cer-hydrate=\"${hydrateStrategy}\"`\n : '';\n\n // Run the component's render function in a minimal SSR context to get the\n // shadow DOM VNode tree and capture any useStyle() output.\n const { shadowVNode, useStyleCSS, asyncPromise } = runComponentSSRRender(config, rawAttrs, tag, opts.router);\n\n // When streaming and this component has an async render, emit a placeholder\n // and register the promise for later resolution.\n if (asyncPromise && _streamingCollector === null) {\n devWarn(\n `[SSR] Component \"${tag}\" has an async render function. ` +\n `In standard SSR the shadow DOM will be empty. ` +\n `Use renderToStream() for incremental async component streaming.`,\n );\n }\n if (asyncPromise && _streamingCollector !== null) {\n const id = `cer-stream-${_streamingCounter++}`;\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n _streamingCollector.push({\n id,\n tag,\n attrsString,\n hydrateAttr,\n useStyleCSS,\n lightDOM,\n opts,\n promise: asyncPromise,\n router: opts.router,\n });\n return (\n `<${tag} id=\"${id}\"${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\"></template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n }\n\n // Render the shadow DOM VNode tree to HTML (DSD-recursive for nested elements)\n let shadowHTML = '';\n if (shadowVNode !== null && shadowVNode !== undefined) {\n if (Array.isArray(shadowVNode)) {\n shadowHTML = (shadowVNode as VNode[])\n .map((n) => renderToDSD(n, opts))\n .join('');\n } else {\n shadowHTML = renderToDSD(shadowVNode as VNode, opts);\n }\n }\n\n const styleBlock = buildShadowStyleBlock(useStyleCSS, shadowHTML);\n\n // Light DOM children become slotted content — rendered outside the template\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n\n return (\n `<${tag}${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\">${styleBlock}${shadowHTML}</template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n}\n\nfunction renderChildrenDSD(\n children: VNode['children'],\n opts: DSDRenderOptions,\n): string {\n if (!children) return '';\n if (typeof children === 'string') return escapeHTML(children) as string;\n if (Array.isArray(children)) {\n return children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToDSD(c as VNode, opts))\n .join('');\n }\n return renderToDSD(children as VNode, opts);\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a DSD HTML string and optionally append the\n * DSD polyfill script for older browsers.\n */\nexport function renderToStringDSD(\n vnode: VNode,\n opts?: DSDRenderOptions,\n): string {\n const effectiveOpts: DSDRenderOptions = { dsd: true, ...opts };\n const html = renderToDSD(vnode, effectiveOpts);\n\n if (effectiveOpts.dsdPolyfill !== false) {\n // Inject polyfill before </body> if present, otherwise append\n if (html.includes('</body>')) {\n return html.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`);\n }\n return html + DSD_POLYFILL_SCRIPT;\n }\n\n return html;\n}\n","/**\n * SSR entry point — import from `@jasonshimmy/custom-elements-runtime/ssr`.\n *\n * Provides four rendering modes:\n *\n * 1. **renderToString** — baseline HTML serialisation (no shadow DOM content).\n * Backwards-compatible with the original API.\n *\n * 2. **renderToStringWithJITCSS** — HTML + pre-generated JIT CSS injected into\n * `<head>` to prevent FOUC. Supports `dsd: true` for DSD output.\n *\n * 3. **renderToStringWithJITCSSDSD** — convenience alias for DSD mode.\n * Full Declarative Shadow DOM output with per-shadow-root CSS layer stack\n * (baseReset + useStyle() + JIT CSS). Enables true hydration, zero FOUC.\n *\n * 4. **renderToStream** — ReadableStream variant for streaming SSR.\n *\n * 5. **renderToStreamWithJITCSSDSD** — convenience alias for streaming DSD mode.\n * Equivalent to `renderToStream(vnode, { dsd: true, ...options })`.\n * Recommended for new server-rendered applications that want true incremental\n * streaming with Declarative Shadow DOM and zero FOUC.\n *\n * Entity map utilities are also exported for full HTML5 named-entity support.\n *\n * @example DSD usage (recommended)\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * res.send(`<!DOCTYPE html><html><head>${head}</head><body>${htmlWithStyles}</body></html>`);\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Re-exports — backwards-compatible\n// ---------------------------------------------------------------------------\n\nexport { renderToString } from './runtime/vdom-ssr';\nexport type { VNode } from './runtime/types';\nexport type { RenderOptions } from './runtime/vdom-ssr';\n\nexport {\n registerEntityMap,\n loadEntityMap,\n clearRegisteredEntityMap,\n} from './runtime/helpers';\n\nexport {\n renderToStringDSD,\n DSD_POLYFILL_SCRIPT,\n} from './runtime/vdom-ssr-dsd';\nexport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\n\n// ---------------------------------------------------------------------------\n// Internal imports\n// ---------------------------------------------------------------------------\n\nimport { renderToString as _render } from './runtime/vdom-ssr';\nimport {\n renderToStringDSD as _renderToStringDSD,\n renderToDSD,\n buildShadowStyleBlock,\n beginStreamingCollection,\n endStreamingCollection,\n DSD_POLYFILL_SCRIPT,\n type AsyncStreamEntry,\n} from './runtime/vdom-ssr-dsd';\nimport { jitCSS, enableJITCSS, type JITCSSOptions } from './runtime/style';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport {\n beginSSRGlobalStyleCollection,\n endSSRGlobalStyleCollection,\n} from './runtime/ssr-context';\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/**\n * Result of `renderToStringWithJITCSS()` and `renderToStringWithJITCSSDSD()`.\n */\nexport interface SSRJITResult {\n /** The rendered HTML string (styles not yet injected). */\n html: string;\n /**\n * Global JIT CSS extracted from the rendered HTML.\n * For DSD renders, each shadow root embeds its own scoped styles; this field\n * holds any residual light-DOM utility CSS.\n */\n css: string;\n /**\n * CSS captured from `useGlobalStyle()` calls during this render pass\n * (e.g. `@font-face`, `:root` custom properties).\n * Inject in a `<style id=\"cer-ssr-global\">` in `<head>`.\n */\n globalStyles: string;\n /**\n * Convenience: `html` with both `<style>` tags injected before `</head>`.\n * If no `</head>` is found, the styles are prepended.\n */\n htmlWithStyles: string;\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSS — primary API, supports both modes\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side render a VNode tree and simultaneously pre-generate JIT CSS.\n *\n * Pass `dsd: true` to enable Declarative Shadow DOM output with full per-shadow-\n * root CSS layer extraction (recommended for new apps).\n *\n * @example Standard (no DSD)\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode);\n * ```\n *\n * @example With DSD\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode, {\n * dsd: true,\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSS(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): SSRJITResult {\n const { jit, dsd, dsdPolyfill, ...renderOptions } = options ?? {};\n\n if (jit) enableJITCSS(jit);\n\n beginSSRGlobalStyleCollection();\n\n let html!: string;\n let globalStylesCaptured!: string[];\n try {\n if (dsd) {\n // renderToStringDSD handles DSD wrapping but skips the polyfill so we can\n // place it correctly relative to other injected style tags below.\n html = _renderToStringDSD(vnode, {\n ...renderOptions,\n dsd: true,\n dsdPolyfill: false,\n });\n } else {\n html = _render(vnode, renderOptions);\n }\n } finally {\n // Always end collection — even when the render throws — so the collector\n // is never left non-null, which would cause subsequent non-SSR\n // useGlobalStyle() calls to silently skip DOM injection.\n globalStylesCaptured = endSSRGlobalStyleCollection();\n }\n\n const css = jitCSS(html);\n const globalStyles = globalStylesCaptured.join('\\n');\n\n const styleTags: string[] = [];\n if (css) styleTags.push(`<style id=\"cer-ssr-jit\">${css}</style>`);\n if (globalStyles.trim())\n styleTags.push(`<style id=\"cer-ssr-global\">${globalStyles}</style>`);\n\n let htmlWithStyles = html;\n if (styleTags.length) {\n const injection = styleTags.join('');\n htmlWithStyles = html.includes('</head>')\n ? html.replace('</head>', `${injection}</head>`)\n : `${injection}${html}`;\n }\n\n // Append DSD polyfill script inside </body> when in DSD mode\n if (dsd && dsdPolyfill !== false) {\n htmlWithStyles = htmlWithStyles.includes('</body>')\n ? htmlWithStyles.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`)\n : htmlWithStyles + DSD_POLYFILL_SCRIPT;\n }\n\n return { html, css, globalStyles, htmlWithStyles };\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output, full per-shadow-root CSS layer\n * extraction, and the DSD browser polyfill. This is the recommended function\n * for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): SSRJITResult {\n return renderToStringWithJITCSS(vnode, { ...options, dsd: true });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStream — streaming SSR\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a `ReadableStream<string>`.\n *\n * Supports true incremental streaming: synchronous components are flushed as\n * the first chunk, then each async component's resolved output is streamed as\n * an inline swap `<script>` that fills the placeholder's shadow root.\n *\n * @example Node.js\n * ```ts\n * import { renderToStream } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStream(appVNode, { dsd: true });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStream(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n const asyncEntries: AsyncStreamEntry[] = [];\n beginStreamingCollection(asyncEntries);\n\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n } catch (err) {\n controller.error(err);\n return;\n } finally {\n endStreamingCollection();\n }\n\n // Resolve async components and stream swap scripts as they settle.\n // Each resolved component replaces its placeholder via an inline script.\n for (const entry of asyncEntries) {\n try {\n const resolvedVNodes = await entry.promise;\n const shadowHTML = Array.isArray(resolvedVNodes)\n ? (resolvedVNodes as VNode[]).map((n) => renderToDSD(n, entry.opts)).join('')\n : renderToDSD(resolvedVNodes as VNode, entry.opts);\n const styleBlock = buildShadowStyleBlock(entry.useStyleCSS, shadowHTML);\n const shadowContent = `${styleBlock}${shadowHTML}`;\n controller.enqueue(\n `<script>(function(){` +\n `var e=document.getElementById(${JSON.stringify(entry.id)});` +\n `if(!e)return;` +\n // The placeholder already has an empty shadow root attached (native DSD or polyfill).\n // If for some reason it doesn't, attach one now.\n `var s=e.shadowRoot;` +\n `if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};` +\n `if(s)s.innerHTML=${JSON.stringify(shadowContent)};` +\n `e.removeAttribute('id');` +\n `})();</script>`,\n );\n } catch {\n // Async render failed — leave placeholder for client hydration.\n }\n }\n\n controller.close();\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStreamWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStream(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output and full JIT CSS extraction,\n * streaming the synchronous render as the first chunk and each resolved async\n * component as a subsequent inline-script swap. This is the recommended\n * function for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStreamWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStreamWithJITCSSDSD(appVNode, { router });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStreamWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): ReadableStream<string> {\n return renderToStream(vnode, { ...options, dsd: true });\n}\n"],"mappings":";;;;;AAcA,IAAa,IAAgB,oBAAI,IAAI;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;CACD;AAED,SAAgB,EACd,GACA,GACA,GACQ;AACR,QAAM,IAAS,EAAK,sBAAsB,IACpC,IAAc,EAAK,yBAAyB,GAC5C,IAAS,EAAE,GAAG,EAAA;AAEpB,SAAI,KAAU,MAAQ,SAAS,EAAE,WAAW,KAC1C,EAAO,QAAW,IACT,KAAe,KAAO,KAAqB,EAAE,WAAW,OACjE,EAAO,QAAW,EAAkB,CAAA,IAG/B,OAAO,QAAQ,CAAA,EACnB,IAAA,CAAK,CAAC,GAAG,CAAA,MAAO,IAAI,CAAA,KAAM,EAAW,OAAO,CAAA,CAAE,CAAC,GAAC,EAChD,KAAK,EAAA;;AAGV,SAAgB,EAAc,GAAwC;AACpE,SA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AgB,EACd,GACA,GACwB;AACxB,SAAO,IAAI,eAAuB,EAChC,MAAM,MAAM,GAAY;AACtB,UAAM,IAAmC,CAAA;AACzC,IAAA,EAAyB,CAAA;AAEzB,QAAI;AACF,YAAM,EAAE,gBAAA,EAAA,IAAmB,EAAyB,GAAO,CAAA;AAC3D,MAAA,EAAW,QAAQ,CAAA;AAAA,aACZ,GAAK;AACZ,MAAA,EAAW,MAAM,CAAA;AACjB;AAAA;AAEA,MAAA,EAAA;AAAA;AAKF,eAAW,KAAS,EAClB,KAAI;AACF,YAAM,IAAiB,MAAM,EAAM,SAC7B,IAAa,MAAM,QAAQ,CAAA,IAC5B,EAA2B,IAAA,CAAK,MAAM,EAAY,GAAG,EAAM,IAAA,CAAK,EAAE,KAAK,EAAA,IACxE,EAAY,GAAyB,EAAM,IAAA,GAEzC,IAAgB,GADH,EAAsB,EAAM,aAAa,CAAA,CAAW,GACjC,CAAA;AACtC,MAAA,EAAW,QACT,qDACmC,KAAK,UAAU,EAAM,EAAA,CAAG,4HAMrC,KAAK,UAAU,CAAA,CAAc,0CAAC;AAAA,YAIhD;AAAA,IAAA;AAKV,IAAA,EAAW,MAAA;AAAA,KAEd;;AAgCH,SAAgB,EACd,GACA,GAIwB;AACxB,SAAO,EAAe,GAAO;AAAA,IAAE,GAAG;AAAA,IAAS,KAAK;AAAA,GAAM"}
package/dist/ssr.d.ts CHANGED
@@ -15,6 +15,11 @@
15
15
  *
16
16
  * 4. **renderToStream** — ReadableStream variant for streaming SSR.
17
17
  *
18
+ * 5. **renderToStreamWithJITCSSDSD** — convenience alias for streaming DSD mode.
19
+ * Equivalent to `renderToStream(vnode, { dsd: true, ...options })`.
20
+ * Recommended for new server-rendered applications that want true incremental
21
+ * streaming with Declarative Shadow DOM and zero FOUC.
22
+ *
18
23
  * Entity map utilities are also exported for full HTML5 named-entity support.
19
24
  *
20
25
  * @example DSD usage (recommended)
@@ -129,3 +134,31 @@ export declare function renderToStringWithJITCSSDSD(vnode: VNode, options?: Omit
129
134
  export declare function renderToStream(vnode: VNode, options?: RenderOptions & DSDRenderOptions & {
130
135
  jit?: JITCSSOptions;
131
136
  }): ReadableStream<string>;
137
+ /**
138
+ * Convenience alias: `renderToStream(vnode, { dsd: true, ...options })`.
139
+ *
140
+ * Renders with Declarative Shadow DOM output and full JIT CSS extraction,
141
+ * streaming the synchronous render as the first chunk and each resolved async
142
+ * component as a subsequent inline-script swap. This is the recommended
143
+ * function for all new server-rendered applications.
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * import { renderToStreamWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';
148
+ *
149
+ * app.get('/', (req, res) => {
150
+ * const stream = renderToStreamWithJITCSSDSD(appVNode, { router });
151
+ * const reader = stream.getReader();
152
+ * const pump = () =>
153
+ * reader.read().then(({ value, done }) => {
154
+ * if (done) { res.end(); return; }
155
+ * res.write(value);
156
+ * pump();
157
+ * });
158
+ * pump();
159
+ * });
160
+ * ```
161
+ */
162
+ export declare function renderToStreamWithJITCSSDSD(vnode: VNode, options?: Omit<RenderOptions & DSDRenderOptions & {
163
+ jit?: JITCSSOptions;
164
+ }, 'dsd'>): ReadableStream<string>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jasonshimmy/custom-elements-runtime",
3
3
  "description": "A powerful, modern, and lightweight runtime for creating reactive web components with TypeScript",
4
- "version": "3.3.0",
4
+ "version": "3.4.0",
5
5
  "type": "module",
6
6
  "keywords": [
7
7
  "web-components",
@@ -1 +0,0 @@
1
- {"version":3,"file":"ssr-B3lxl1vr.js","names":[],"sources":["../src/lib/runtime/ssr-utils.ts","../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["/**\n * Shared utilities for SSR renderers.\n * Imported by vdom-ssr.ts and vdom-ssr-dsd.ts to avoid duplication.\n */\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\n\nexport type RenderOptions = {\n /** Backwards-compatible: whether to inject the SVG namespace on <svg> nodes (default true) */\n injectSvgNamespace?: boolean;\n /** Inject known well-known namespaces for tags like <math> when missing (default follows injectSvgNamespace) */\n injectKnownNamespaces?: boolean;\n};\n\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nexport function buildAttrs(\n attrs: Record<string, unknown>,\n tag: string,\n opts: RenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n const merged = { ...attrs };\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag in TAG_NAMESPACE_MAP && !('xmlns' in merged)) {\n merged['xmlns'] = TAG_NAMESPACE_MAP[tag];\n }\n\n return Object.entries(merged)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n\nexport function buildRawAttrs(attrs: Record<string, unknown>): string {\n return Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\n}\n","import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { VOID_ELEMENTS, buildAttrs, type RenderOptions } from './ssr-utils';\n\n/**\n * Render a VNode to a string (SSR).\n * Kept intentionally minimal: only serializes attributes under `props.attrs`\n * to avoid leaking runtime-only values (functions, reactive state, directives).\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport type { RenderOptions } from './ssr-utils';\n\nexport function renderToString(vnode: VNode, opts?: RenderOptions): string {\n if (typeof vnode === 'string') return escapeHTML(vnode) as string;\n\n if (vnode.tag === '#text') {\n return typeof vnode.children === 'string'\n ? (escapeHTML(vnode.children) as string)\n : '';\n }\n\n if (vnode.tag === '#anchor') {\n // Preserve meaningful falsy children (0, false, '') while filtering out\n // only null and undefined. Anchor blocks are normalized by the compiler\n // to exclude null/undefined; SSR should follow the same rule to avoid\n // hydration mismatches where falsy values are significant.\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter((c) => c !== null && c !== undefined)\n : [];\n return children.map((c) => renderToString(c, opts)).join('');\n }\n\n if (vnode.tag === '#raw') {\n return typeof vnode.children === 'string' ? vnode.children : '';\n }\n\n // Collect attributes from props.attrs. For SSR we mirror vnode.attrs\n // but ensure SVG nodes behave like client-side: if this is an <svg>\n // and no xmlns was provided, inject the standard SVG namespace so\n // server markup matches client-created DOM namespace.\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, vnode.tag, opts ?? {});\n\n // Handle void elements (self-closing tags)\n if (VOID_ELEMENTS.has(vnode.tag)) {\n return `<${vnode.tag}${attrsString}>`;\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToString(c, opts))\n .join('')\n : typeof vnode.children === 'string'\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children, opts)\n : '';\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Declarative Shadow DOM (DSD) SSR renderer.\n *\n * When `dsd: true` is passed to the render options, registered custom elements\n * are serialised as:\n *\n * ```html\n * <my-element attr=\"val\">\n * <template shadowrootmode=\"open\">\n * <style>\n * /* baseReset + useStyle() output + JIT utility CSS *\\/\n * </style>\n * <!-- shadow DOM from component render function -->\n * </template>\n * <!-- light DOM / slotted children from vnode.children -->\n * </my-element>\n * ```\n *\n * The browser parses the `<template shadowrootmode=\"open\">` block and attaches\n * a real shadow root before any JavaScript executes. All CSS layers are present\n * at first paint — eliminating both FOUC and layout shift.\n *\n * Non-custom-element VNodes are rendered identically to renderToString() but\n * with DSD recursion active for any custom elements nested inside them.\n */\n\nimport type { VNode } from './types';\nimport { renderToString } from './vdom-ssr';\nimport { VOID_ELEMENTS, buildAttrs, buildRawAttrs, type RenderOptions } from './ssr-utils';\nimport { registry } from './component/registry';\nimport { runComponentSSRRender } from './ssr-context';\nimport { jitCSS } from './style';\nimport { baseReset, minifyCSS } from './css-utils';\nimport { escapeHTML } from './helpers';\nimport { devWarn } from './logger';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type DSDRenderOptions = RenderOptions & {\n /**\n * Emit Declarative Shadow DOM output for registered custom elements.\n * Shadow content is serialised inside `<template shadowrootmode=\"open\">`,\n * with a complete CSS layer stack (`baseReset` + `useStyle` + JIT CSS)\n * injected as a `<style>` block so styles are available at first paint.\n * @default false\n */\n dsd?: boolean;\n /**\n * Append the DSD polyfill `<script>` for browsers without native support\n * (Firefox < 123). Only meaningful when `dsd` is true.\n * @default true\n */\n dsdPolyfill?: boolean;\n /**\n * Router instance to thread through each component's SSR context.\n *\n * When provided, `router-view` reads the current route from this instance\n * instead of the module-level `activeRouterProxy` singleton, making\n * concurrent SSR renders safe — each request carries its own router with\n * its own URL state.\n *\n * In browser mode this option is ignored; components always use\n * `activeRouterProxy` there.\n */\n router?: unknown;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * @internal\n * Minified DSD polyfill for browsers without native Declarative Shadow DOM.\n * Processes all `<template shadowrootmode>` elements synchronously.\n */\nexport const DSD_POLYFILL_SCRIPT =\n '<script>(function(){' +\n \"if(HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode'))return;\" +\n \"document.querySelectorAll('template[shadowrootmode]').forEach(function(t){\" +\n \"var m=t.getAttribute('shadowrootmode');\" +\n 'var s=t.parentElement.attachShadow({mode:m});' +\n 's.appendChild(t.content);t.remove();' +\n '});})()' +\n '</script>';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRegisteredCustomElement(tag: string): boolean {\n return tag.includes('-') && registry.has(tag);\n}\n\n/**\n * Build the combined `<style>` block for a shadow root.\n *\n * Layer order (matches the runtime adoptedStyleSheets order):\n * 1. baseReset — global reset + CSS custom properties\n * 2. useStyle() output — component-defined rules (:host, ::slotted, etc.)\n * 3. JIT CSS — utility classes extracted from the shadow HTML\n */\nexport function buildShadowStyleBlock(\n useStyleCSS: string,\n shadowHTML: string,\n): string {\n const parts: string[] = [baseReset];\n\n if (useStyleCSS.trim()) {\n parts.push(useStyleCSS);\n }\n\n const jit = jitCSS(shadowHTML);\n if (jit.trim()) {\n parts.push(jit);\n }\n\n const combined = minifyCSS(parts.join('\\n'));\n return combined ? `<style>${combined}</style>` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Streaming async component collector\n// ---------------------------------------------------------------------------\n\nexport interface AsyncStreamEntry {\n id: string;\n tag: string;\n attrsString: string;\n hydrateAttr: string;\n useStyleCSS: string;\n lightDOM: string;\n opts: DSDRenderOptions;\n promise: Promise<VNode | VNode[]>;\n /** Router threaded from the originating render pass — propagated to async re-renders. */\n router?: unknown;\n}\n\nlet _streamingCollector: AsyncStreamEntry[] | null = null;\nlet _streamingCounter = 0;\n\n/** @internal Called by renderToStream() before the sync render pass. */\nexport function beginStreamingCollection(collector: AsyncStreamEntry[]): void {\n _streamingCollector = collector;\n _streamingCounter = 0;\n}\n\n/** @internal Called by renderToStream() after the sync render pass. */\nexport function endStreamingCollection(): void {\n _streamingCollector = null;\n}\n\n// ---------------------------------------------------------------------------\n// Core renderer\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to an HTML string with Declarative Shadow DOM output\n * for all registered custom elements encountered in the tree.\n */\nexport function renderToDSD(vnode: VNode, opts: DSDRenderOptions): string {\n if (!opts.dsd) {\n return renderToString(vnode, opts);\n }\n\n // Primitive string nodes\n if (typeof vnode === 'string') {\n return escapeHTML(vnode) as string;\n }\n\n const tag = (vnode as VNode).tag;\n\n // Special virtual node types — delegate entirely to the base renderer\n if (tag === '#text' || tag === '#anchor' || tag === '#raw') {\n return renderToString(vnode, opts);\n }\n\n // Custom element — emit DSD wrapper\n if (isRegisteredCustomElement(tag)) {\n return renderCustomElementDSD(vnode, opts);\n }\n\n // Regular element — recurse with DSD mode on\n const attrsObj: Record<string, unknown> = vnode.props?.attrs\n ? { ...vnode.props.attrs }\n : {};\n\n const attrsString = buildAttrs(attrsObj, tag, opts);\n\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrsString}>`;\n }\n\n const children = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}>${children}</${tag}>`;\n}\n\nfunction renderCustomElementDSD(vnode: VNode, opts: DSDRenderOptions): string {\n const tag = vnode.tag;\n const config = registry.get(tag);\n\n // Build the plain attribute string (no namespace injection for custom elements)\n const rawAttrs = vnode.props?.attrs ?? {};\n const attrsString = buildRawAttrs(rawAttrs);\n\n // Move the null check BEFORE reading config.* properties for clarity.\n if (!config) {\n // Component not in registry on server (e.g. dynamic import not yet run).\n // Emit a shell with an empty DSD template so the client hydrates normally.\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n return `<${tag}${attrsString}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\n }\n\n // Emit data-cer-hydrate when a non-default strategy is configured.\n // 'load' is the default and doesn't need to be serialised.\n const hydrateStrategy = config.hydrate;\n const hydrateAttr =\n hydrateStrategy && hydrateStrategy !== 'load'\n ? ` data-cer-hydrate=\"${hydrateStrategy}\"`\n : '';\n\n // Run the component's render function in a minimal SSR context to get the\n // shadow DOM VNode tree and capture any useStyle() output.\n const { shadowVNode, useStyleCSS, asyncPromise } = runComponentSSRRender(config, rawAttrs, tag, opts.router);\n\n // When streaming and this component has an async render, emit a placeholder\n // and register the promise for later resolution.\n if (asyncPromise && _streamingCollector === null) {\n devWarn(\n `[SSR] Component \"${tag}\" has an async render function. ` +\n `In standard SSR the shadow DOM will be empty. ` +\n `Use renderToStream() for incremental async component streaming.`,\n );\n }\n if (asyncPromise && _streamingCollector !== null) {\n const id = `cer-stream-${_streamingCounter++}`;\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n _streamingCollector.push({\n id,\n tag,\n attrsString,\n hydrateAttr,\n useStyleCSS,\n lightDOM,\n opts,\n promise: asyncPromise,\n router: opts.router,\n });\n return (\n `<${tag} id=\"${id}\"${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\"></template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n }\n\n // Render the shadow DOM VNode tree to HTML (DSD-recursive for nested elements)\n let shadowHTML = '';\n if (shadowVNode !== null && shadowVNode !== undefined) {\n if (Array.isArray(shadowVNode)) {\n shadowHTML = (shadowVNode as VNode[])\n .map((n) => renderToDSD(n, opts))\n .join('');\n } else {\n shadowHTML = renderToDSD(shadowVNode as VNode, opts);\n }\n }\n\n const styleBlock = buildShadowStyleBlock(useStyleCSS, shadowHTML);\n\n // Light DOM children become slotted content — rendered outside the template\n const lightDOM = renderChildrenDSD(vnode.children, opts);\n\n return (\n `<${tag}${attrsString}${hydrateAttr}>` +\n `<template shadowrootmode=\"open\">${styleBlock}${shadowHTML}</template>` +\n `${lightDOM}` +\n `</${tag}>`\n );\n}\n\nfunction renderChildrenDSD(\n children: VNode['children'],\n opts: DSDRenderOptions,\n): string {\n if (!children) return '';\n if (typeof children === 'string') return escapeHTML(children) as string;\n if (Array.isArray(children)) {\n return children\n .filter((c) => c !== null && c !== undefined)\n .map((c) => renderToDSD(c as VNode, opts))\n .join('');\n }\n return renderToDSD(children as VNode, opts);\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a DSD HTML string and optionally append the\n * DSD polyfill script for older browsers.\n */\nexport function renderToStringDSD(\n vnode: VNode,\n opts?: DSDRenderOptions,\n): string {\n const effectiveOpts: DSDRenderOptions = { dsd: true, ...opts };\n const html = renderToDSD(vnode, effectiveOpts);\n\n if (effectiveOpts.dsdPolyfill !== false) {\n // Inject polyfill before </body> if present, otherwise append\n if (html.includes('</body>')) {\n return html.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`);\n }\n return html + DSD_POLYFILL_SCRIPT;\n }\n\n return html;\n}\n","/**\n * SSR entry point — import from `@jasonshimmy/custom-elements-runtime/ssr`.\n *\n * Provides four rendering modes:\n *\n * 1. **renderToString** — baseline HTML serialisation (no shadow DOM content).\n * Backwards-compatible with the original API.\n *\n * 2. **renderToStringWithJITCSS** — HTML + pre-generated JIT CSS injected into\n * `<head>` to prevent FOUC. Supports `dsd: true` for DSD output.\n *\n * 3. **renderToStringWithJITCSSDSD** — convenience alias for DSD mode.\n * Full Declarative Shadow DOM output with per-shadow-root CSS layer stack\n * (baseReset + useStyle() + JIT CSS). Enables true hydration, zero FOUC.\n *\n * 4. **renderToStream** — ReadableStream variant for streaming SSR.\n *\n * Entity map utilities are also exported for full HTML5 named-entity support.\n *\n * @example DSD usage (recommended)\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * res.send(`<!DOCTYPE html><html><head>${head}</head><body>${htmlWithStyles}</body></html>`);\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Re-exports — backwards-compatible\n// ---------------------------------------------------------------------------\n\nexport { renderToString } from './runtime/vdom-ssr';\nexport type { VNode } from './runtime/types';\nexport type { RenderOptions } from './runtime/vdom-ssr';\n\nexport {\n registerEntityMap,\n loadEntityMap,\n clearRegisteredEntityMap,\n} from './runtime/helpers';\n\nexport {\n renderToStringDSD,\n DSD_POLYFILL_SCRIPT,\n} from './runtime/vdom-ssr-dsd';\nexport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\n\n// ---------------------------------------------------------------------------\n// Internal imports\n// ---------------------------------------------------------------------------\n\nimport { renderToString as _render } from './runtime/vdom-ssr';\nimport {\n renderToStringDSD as _renderToStringDSD,\n renderToDSD,\n buildShadowStyleBlock,\n beginStreamingCollection,\n endStreamingCollection,\n DSD_POLYFILL_SCRIPT,\n type AsyncStreamEntry,\n} from './runtime/vdom-ssr-dsd';\nimport { jitCSS, enableJITCSS, type JITCSSOptions } from './runtime/style';\nimport type { VNode } from './runtime/types';\nimport type { RenderOptions } from './runtime/vdom-ssr';\nimport type { DSDRenderOptions } from './runtime/vdom-ssr-dsd';\nimport {\n beginSSRGlobalStyleCollection,\n endSSRGlobalStyleCollection,\n} from './runtime/ssr-context';\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/**\n * Result of `renderToStringWithJITCSS()` and `renderToStringWithJITCSSDSD()`.\n */\nexport interface SSRJITResult {\n /** The rendered HTML string (styles not yet injected). */\n html: string;\n /**\n * Global JIT CSS extracted from the rendered HTML.\n * For DSD renders, each shadow root embeds its own scoped styles; this field\n * holds any residual light-DOM utility CSS.\n */\n css: string;\n /**\n * CSS captured from `useGlobalStyle()` calls during this render pass\n * (e.g. `@font-face`, `:root` custom properties).\n * Inject in a `<style id=\"cer-ssr-global\">` in `<head>`.\n */\n globalStyles: string;\n /**\n * Convenience: `html` with both `<style>` tags injected before `</head>`.\n * If no `</head>` is found, the styles are prepended.\n */\n htmlWithStyles: string;\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSS — primary API, supports both modes\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side render a VNode tree and simultaneously pre-generate JIT CSS.\n *\n * Pass `dsd: true` to enable Declarative Shadow DOM output with full per-shadow-\n * root CSS layer extraction (recommended for new apps).\n *\n * @example Standard (no DSD)\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode);\n * ```\n *\n * @example With DSD\n * ```ts\n * const { htmlWithStyles } = renderToStringWithJITCSS(appVNode, {\n * dsd: true,\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSS(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): SSRJITResult {\n const { jit, dsd, dsdPolyfill, ...renderOptions } = options ?? {};\n\n if (jit) enableJITCSS(jit);\n\n beginSSRGlobalStyleCollection();\n\n let html!: string;\n let globalStylesCaptured!: string[];\n try {\n if (dsd) {\n // renderToStringDSD handles DSD wrapping but skips the polyfill so we can\n // place it correctly relative to other injected style tags below.\n html = _renderToStringDSD(vnode, {\n ...renderOptions,\n dsd: true,\n dsdPolyfill: false,\n });\n } else {\n html = _render(vnode, renderOptions);\n }\n } finally {\n // Always end collection — even when the render throws — so the collector\n // is never left non-null, which would cause subsequent non-SSR\n // useGlobalStyle() calls to silently skip DOM injection.\n globalStylesCaptured = endSSRGlobalStyleCollection();\n }\n\n const css = jitCSS(html);\n const globalStyles = globalStylesCaptured.join('\\n');\n\n const styleTags: string[] = [];\n if (css) styleTags.push(`<style id=\"cer-ssr-jit\">${css}</style>`);\n if (globalStyles.trim())\n styleTags.push(`<style id=\"cer-ssr-global\">${globalStyles}</style>`);\n\n let htmlWithStyles = html;\n if (styleTags.length) {\n const injection = styleTags.join('');\n htmlWithStyles = html.includes('</head>')\n ? html.replace('</head>', `${injection}</head>`)\n : `${injection}${html}`;\n }\n\n // Append DSD polyfill script inside </body> when in DSD mode\n if (dsd && dsdPolyfill !== false) {\n htmlWithStyles = htmlWithStyles.includes('</body>')\n ? htmlWithStyles.replace('</body>', `${DSD_POLYFILL_SCRIPT}</body>`)\n : htmlWithStyles + DSD_POLYFILL_SCRIPT;\n }\n\n return { html, css, globalStyles, htmlWithStyles };\n}\n\n// ---------------------------------------------------------------------------\n// renderToStringWithJITCSSDSD — convenience alias\n// ---------------------------------------------------------------------------\n\n/**\n * Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ...options })`.\n *\n * Renders with Declarative Shadow DOM output, full per-shadow-root CSS layer\n * extraction, and the DSD browser polyfill. This is the recommended function\n * for all new server-rendered applications.\n *\n * @example\n * ```ts\n * import { renderToStringWithJITCSSDSD } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * const { htmlWithStyles } = renderToStringWithJITCSSDSD(appVNode, {\n * jit: { extendedColors: true },\n * });\n * ```\n */\nexport function renderToStringWithJITCSSDSD(\n vnode: VNode,\n options?: Omit<\n RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n 'dsd'\n >,\n): SSRJITResult {\n return renderToStringWithJITCSS(vnode, { ...options, dsd: true });\n}\n\n// ---------------------------------------------------------------------------\n// renderToStream — streaming SSR\n// ---------------------------------------------------------------------------\n\n/**\n * Render a VNode tree to a `ReadableStream<string>`.\n *\n * Supports true incremental streaming: synchronous components are flushed as\n * the first chunk, then each async component's resolved output is streamed as\n * an inline swap `<script>` that fills the placeholder's shadow root.\n *\n * @example Node.js\n * ```ts\n * import { renderToStream } from '@jasonshimmy/custom-elements-runtime/ssr';\n *\n * app.get('/', (req, res) => {\n * const stream = renderToStream(appVNode, { dsd: true });\n * const reader = stream.getReader();\n * const pump = () =>\n * reader.read().then(({ value, done }) => {\n * if (done) { res.end(); return; }\n * res.write(value);\n * pump();\n * });\n * pump();\n * });\n * ```\n */\nexport function renderToStream(\n vnode: VNode,\n options?: RenderOptions & DSDRenderOptions & { jit?: JITCSSOptions },\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n const asyncEntries: AsyncStreamEntry[] = [];\n beginStreamingCollection(asyncEntries);\n\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n } catch (err) {\n controller.error(err);\n return;\n } finally {\n endStreamingCollection();\n }\n\n // Resolve async components and stream swap scripts as they settle.\n // Each resolved component replaces its placeholder via an inline script.\n for (const entry of asyncEntries) {\n try {\n const resolvedVNodes = await entry.promise;\n const shadowHTML = Array.isArray(resolvedVNodes)\n ? (resolvedVNodes as VNode[]).map((n) => renderToDSD(n, entry.opts)).join('')\n : renderToDSD(resolvedVNodes as VNode, entry.opts);\n const styleBlock = buildShadowStyleBlock(entry.useStyleCSS, shadowHTML);\n const shadowContent = `${styleBlock}${shadowHTML}`;\n controller.enqueue(\n `<script>(function(){` +\n `var e=document.getElementById(${JSON.stringify(entry.id)});` +\n `if(!e)return;` +\n // The placeholder already has an empty shadow root attached (native DSD or polyfill).\n // If for some reason it doesn't, attach one now.\n `var s=e.shadowRoot;` +\n `if(!s&&e.attachShadow)try{s=e.attachShadow({mode:'open'});}catch(_){};` +\n `if(s)s.innerHTML=${JSON.stringify(shadowContent)};` +\n `e.removeAttribute('id');` +\n `})();</script>`,\n );\n } catch {\n // Async render failed — leave placeholder for client hydration.\n }\n }\n\n controller.close();\n },\n });\n}\n"],"mappings":";;;;;AAcA,IAAa,IAAgB,oBAAI,IAAI;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;CACD;AAED,SAAgB,EACd,GACA,GACA,GACQ;AACR,QAAM,IAAS,EAAK,sBAAsB,IACpC,IAAc,EAAK,yBAAyB,GAC5C,IAAS,EAAE,GAAG,EAAA;AAEpB,SAAI,KAAU,MAAQ,SAAS,EAAE,WAAW,KAC1C,EAAO,QAAW,IACT,KAAe,KAAO,KAAqB,EAAE,WAAW,OACjE,EAAO,QAAW,EAAkB,CAAA,IAG/B,OAAO,QAAQ,CAAA,EACnB,IAAA,CAAK,CAAC,GAAG,CAAA,MAAO,IAAI,CAAA,KAAM,EAAW,OAAO,CAAA,CAAE,CAAC,GAAC,EAChD,KAAK,EAAA;;AAGV,SAAgB,EAAc,GAAwC;AACpE,SAAO,OAAO,QAAQ,CAAA,EACnB,IAAA,CAAK,CAAC,GAAG,CAAA,MAAO,IAAI,CAAA,KAAM,EAAW,OAAO,CAAA,CAAE,CAAC,GAAC,EAChD,KAAK,EAAA;;ACzCV,SAAgB,EAAe,GAAc,GAA8B;AACzE,MAAI,OAAO,KAAU,SAAU,QAAO,EAAW,CAAA;AAEjD,MAAI,EAAM,QAA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