@jasonshimmy/custom-elements-runtime 3.1.0 → 3.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/custom-elements-runtime.cjs.js +1 -1
- package/dist/custom-elements-runtime.es.js +3 -3
- package/dist/custom-elements-runtime.jit-css.cjs.js +1 -1
- package/dist/custom-elements-runtime.jit-css.es.js +2 -2
- package/dist/custom-elements-runtime.router.cjs.js +12 -12
- package/dist/custom-elements-runtime.router.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.router.es.js +97 -93
- package/dist/custom-elements-runtime.router.es.js.map +1 -1
- package/dist/custom-elements-runtime.ssr-middleware.cjs.js +1 -1
- package/dist/custom-elements-runtime.ssr-middleware.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.ssr-middleware.es.js +36 -30
- package/dist/custom-elements-runtime.ssr-middleware.es.js.map +1 -1
- package/dist/custom-elements-runtime.ssr.cjs.js +3 -3
- package/dist/custom-elements-runtime.ssr.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.ssr.es.js +121 -100
- package/dist/custom-elements-runtime.ssr.es.js.map +1 -1
- package/dist/{hooks-B50HhrHh.cjs → hooks-x8M4knLc.cjs} +4 -4
- package/dist/hooks-x8M4knLc.cjs.map +1 -0
- package/dist/{hooks-Cze3o-F7.js → hooks-xWZhQHco.js} +202 -199
- package/dist/hooks-xWZhQHco.js.map +1 -0
- package/dist/runtime/render.d.ts +0 -11
- package/dist/runtime/scheduler.d.ts +12 -0
- package/dist/runtime/ssr-context.d.ts +3 -1
- package/dist/runtime/ssr-utils.d.ts +9 -0
- package/dist/runtime/vdom-ssr-dsd.d.ts +25 -1
- package/dist/runtime/vdom-ssr.d.ts +2 -6
- package/dist/template-compiler-CTUhEHr8.cjs +22 -0
- package/dist/template-compiler-CTUhEHr8.cjs.map +1 -0
- package/dist/{template-compiler-DtpNsqE-.js → template-compiler-ZhSg1yPh.js} +902 -922
- package/dist/template-compiler-ZhSg1yPh.js.map +1 -0
- package/package.json +1 -1
- package/dist/hooks-B50HhrHh.cjs.map +0 -1
- package/dist/hooks-Cze3o-F7.js.map +0 -1
- package/dist/template-compiler-Cshhqxyd.cjs +0 -23
- package/dist/template-compiler-Cshhqxyd.cjs.map +0 -1
- package/dist/template-compiler-DtpNsqE-.js.map +0 -1
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { S as
|
|
4
|
-
import { j as
|
|
5
|
-
import { m as
|
|
6
|
-
|
|
1
|
+
import { S as f, T as R, U as L, V as N } from "./hooks-xWZhQHco.js";
|
|
2
|
+
import { W as v, X as tt, Y as rt } from "./hooks-xWZhQHco.js";
|
|
3
|
+
import { S as P, T as w, a as j } from "./namespace-helpers-D4wC2-qA.js";
|
|
4
|
+
import { j as C, e as _ } from "./style-BmyOIMcU.js";
|
|
5
|
+
import { m as x, b as I } from "./css-utils-Cg4o1MqY.js";
|
|
6
|
+
import { a as k } from "./logger-BvkEbVM4.js";
|
|
7
|
+
const T = /* @__PURE__ */ new Set([
|
|
7
8
|
"area",
|
|
8
9
|
"base",
|
|
9
10
|
"br",
|
|
@@ -19,138 +20,158 @@ const _ = /* @__PURE__ */ new Set([
|
|
|
19
20
|
"track",
|
|
20
21
|
"wbr"
|
|
21
22
|
]);
|
|
22
|
-
function
|
|
23
|
+
function A(t, e, r) {
|
|
24
|
+
const n = r.injectSvgNamespace ?? !0, s = r.injectKnownNamespaces ?? n, i = { ...t };
|
|
25
|
+
return n && e === "svg" && !("xmlns" in i) ? i.xmlns = P : s && e in w && !("xmlns" in i) && (i.xmlns = w[e]), Object.entries(i).map(([a, c]) => ` ${a}="${f(String(c))}"`).join("");
|
|
26
|
+
}
|
|
27
|
+
function W(t) {
|
|
28
|
+
return Object.entries(t).map(([e, r]) => ` ${e}="${f(String(r))}"`).join("");
|
|
29
|
+
}
|
|
30
|
+
function y(t, e) {
|
|
23
31
|
if (typeof t == "string") return f(t);
|
|
24
32
|
if (t.tag === "#text")
|
|
25
33
|
return typeof t.children == "string" ? f(t.children) : "";
|
|
26
34
|
if (t.tag === "#anchor")
|
|
27
|
-
return (Array.isArray(t.children) ? t.children.filter((
|
|
35
|
+
return (Array.isArray(t.children) ? t.children.filter((a) => a != null) : []).map((a) => y(a, e)).join("");
|
|
28
36
|
if (t.tag === "#raw")
|
|
29
37
|
return typeof t.children == "string" ? t.children : "";
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
if (_.has(t.tag))
|
|
36
|
-
return `<${t.tag}${s}>`;
|
|
37
|
-
const a = Array.isArray(t.children) ? t.children.filter((o) => o != null).map((o) => m(o, e)).join("") : typeof t.children == "string" ? f(t.children) : t.children ? m(t.children, e) : "";
|
|
38
|
-
return `<${t.tag}${s}>${a}</${t.tag}>`;
|
|
38
|
+
const r = t.props?.attrs ? { ...t.props.attrs } : {}, n = A(r, t.tag, e ?? {});
|
|
39
|
+
if (T.has(t.tag))
|
|
40
|
+
return `<${t.tag}${n}>`;
|
|
41
|
+
const s = Array.isArray(t.children) ? t.children.filter((i) => i != null).map((i) => y(i, e)).join("") : typeof t.children == "string" ? f(t.children) : t.children ? y(t.children, e) : "";
|
|
42
|
+
return `<${t.tag}${n}>${s}</${t.tag}>`;
|
|
39
43
|
}
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
"base",
|
|
43
|
-
"br",
|
|
44
|
-
"col",
|
|
45
|
-
"embed",
|
|
46
|
-
"hr",
|
|
47
|
-
"img",
|
|
48
|
-
"input",
|
|
49
|
-
"link",
|
|
50
|
-
"meta",
|
|
51
|
-
"param",
|
|
52
|
-
"source",
|
|
53
|
-
"track",
|
|
54
|
-
"wbr"
|
|
55
|
-
]), y = "<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>";
|
|
56
|
-
function N(t) {
|
|
44
|
+
const $ = "<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>";
|
|
45
|
+
function B(t) {
|
|
57
46
|
return t.includes("-") && j.has(t);
|
|
58
47
|
}
|
|
59
|
-
function
|
|
60
|
-
const r =
|
|
61
|
-
return s && delete i._tag, r && s === "svg" && !("xmlns" in i) ? i.xmlns = b : n && s && s in p && !("xmlns" in i) && (i.xmlns = p[s]), Object.entries(i).map(([a, o]) => ` ${a}="${f(String(o))}"`).join("");
|
|
62
|
-
}
|
|
63
|
-
function P(t, e) {
|
|
64
|
-
const r = [x];
|
|
48
|
+
function D(t, e) {
|
|
49
|
+
const r = [I];
|
|
65
50
|
t.trim() && r.push(t);
|
|
66
|
-
const n =
|
|
51
|
+
const n = C(e);
|
|
67
52
|
n.trim() && r.push(n);
|
|
68
|
-
const
|
|
53
|
+
const s = x(r.join(`
|
|
69
54
|
`));
|
|
70
|
-
return
|
|
55
|
+
return s ? `<style>${s}</style>` : "";
|
|
56
|
+
}
|
|
57
|
+
let S = null, M = 0;
|
|
58
|
+
function H(t) {
|
|
59
|
+
S = t, M = 0;
|
|
60
|
+
}
|
|
61
|
+
function J() {
|
|
62
|
+
S = null;
|
|
71
63
|
}
|
|
72
|
-
function
|
|
64
|
+
function m(t, e) {
|
|
73
65
|
if (!e.dsd)
|
|
74
|
-
return
|
|
66
|
+
return y(t, e);
|
|
75
67
|
if (typeof t == "string")
|
|
76
68
|
return f(t);
|
|
77
69
|
const r = t.tag;
|
|
78
70
|
if (r === "#text" || r === "#anchor" || r === "#raw")
|
|
79
|
-
return
|
|
80
|
-
if (
|
|
81
|
-
return
|
|
82
|
-
const n = t.props?.attrs ? { ...t.props.attrs
|
|
83
|
-
if (
|
|
84
|
-
return `<${r}${
|
|
85
|
-
const
|
|
86
|
-
return `<${r}${
|
|
71
|
+
return y(t, e);
|
|
72
|
+
if (B(r))
|
|
73
|
+
return V(t, e);
|
|
74
|
+
const n = t.props?.attrs ? { ...t.props.attrs } : {}, s = A(n, r, e);
|
|
75
|
+
if (T.has(r))
|
|
76
|
+
return `<${r}${s}>`;
|
|
77
|
+
const i = g(t.children, e);
|
|
78
|
+
return `<${r}${s}>${i}</${r}>`;
|
|
87
79
|
}
|
|
88
|
-
function
|
|
89
|
-
const r = t.tag, n = j.get(r),
|
|
80
|
+
function V(t, e) {
|
|
81
|
+
const r = t.tag, n = j.get(r), s = t.props?.attrs ?? {}, i = W(s);
|
|
90
82
|
if (!n) {
|
|
91
|
-
const
|
|
92
|
-
return `<${r}${
|
|
83
|
+
const h = g(t.children, e);
|
|
84
|
+
return `<${r}${i}><template shadowrootmode="open"></template>${h}</${r}>`;
|
|
85
|
+
}
|
|
86
|
+
const a = n.hydrate, c = a && a !== "load" ? ` data-cer-hydrate="${a}"` : "", { shadowVNode: o, useStyleCSS: u, asyncPromise: d } = R(n, s, r);
|
|
87
|
+
if (d && S === null && k(
|
|
88
|
+
`[SSR] Component "${r}" has an async render function. In standard SSR the shadow DOM will be empty. Use renderToStream() for incremental async component streaming.`
|
|
89
|
+
), d && S !== null) {
|
|
90
|
+
const h = `cer-stream-${M++}`, b = g(t.children, e);
|
|
91
|
+
return S.push({
|
|
92
|
+
id: h,
|
|
93
|
+
tag: r,
|
|
94
|
+
attrsString: i,
|
|
95
|
+
hydrateAttr: c,
|
|
96
|
+
useStyleCSS: u,
|
|
97
|
+
lightDOM: b,
|
|
98
|
+
opts: e,
|
|
99
|
+
promise: d
|
|
100
|
+
}), `<${r} id="${h}"${i}${c}><template shadowrootmode="open"></template>${b}</${r}>`;
|
|
93
101
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
return `<${r}${s}${o}><template shadowrootmode="open">${u}${c}</template>${S}</${r}>`;
|
|
102
|
+
let l = "";
|
|
103
|
+
o != null && (Array.isArray(o) ? l = o.map((h) => m(h, e)).join("") : l = m(o, e));
|
|
104
|
+
const p = D(u, l), E = g(t.children, e);
|
|
105
|
+
return `<${r}${i}${c}><template shadowrootmode="open">${p}${l}</template>${E}</${r}>`;
|
|
99
106
|
}
|
|
100
|
-
function
|
|
101
|
-
return t ? typeof t == "string" ? f(t) : Array.isArray(t) ? t.filter((r) => r != null).map((r) =>
|
|
107
|
+
function g(t, e) {
|
|
108
|
+
return t ? typeof t == "string" ? f(t) : Array.isArray(t) ? t.filter((r) => r != null).map((r) => m(r, e)).join("") : m(t, e) : "";
|
|
102
109
|
}
|
|
103
|
-
function
|
|
104
|
-
const r = { dsd: !0, ...e }, n =
|
|
105
|
-
return r.dsdPolyfill !== !1 ? n.includes("</body>") ? n.replace("</body>", `${
|
|
110
|
+
function G(t, e) {
|
|
111
|
+
const r = { dsd: !0, ...e }, n = m(t, r);
|
|
112
|
+
return r.dsdPolyfill !== !1 ? n.includes("</body>") ? n.replace("</body>", `${$}</body>`) : n + $ : n;
|
|
106
113
|
}
|
|
107
|
-
function
|
|
108
|
-
const { jit: r, dsd: n, dsdPolyfill:
|
|
109
|
-
r &&
|
|
110
|
-
let a,
|
|
114
|
+
function O(t, e) {
|
|
115
|
+
const { jit: r, dsd: n, dsdPolyfill: s, ...i } = e ?? {};
|
|
116
|
+
r && _(r), L();
|
|
117
|
+
let a, c;
|
|
111
118
|
try {
|
|
112
|
-
n ? a =
|
|
113
|
-
...
|
|
119
|
+
n ? a = G(t, {
|
|
120
|
+
...i,
|
|
114
121
|
dsd: !0,
|
|
115
122
|
dsdPolyfill: !1
|
|
116
|
-
}) : a =
|
|
123
|
+
}) : a = y(t, i);
|
|
117
124
|
} finally {
|
|
118
|
-
|
|
125
|
+
c = N();
|
|
119
126
|
}
|
|
120
|
-
const
|
|
121
|
-
`),
|
|
122
|
-
|
|
123
|
-
let
|
|
124
|
-
if (
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
+
const o = C(a), u = c.join(`
|
|
128
|
+
`), d = [];
|
|
129
|
+
o && d.push(`<style id="cer-ssr-jit">${o}</style>`), u.trim() && d.push(`<style id="cer-ssr-global">${u}</style>`);
|
|
130
|
+
let l = a;
|
|
131
|
+
if (d.length) {
|
|
132
|
+
const p = d.join("");
|
|
133
|
+
l = a.includes("</head>") ? a.replace("</head>", `${p}</head>`) : `${p}${a}`;
|
|
127
134
|
}
|
|
128
|
-
return n &&
|
|
135
|
+
return n && s !== !1 && (l = l.includes("</body>") ? l.replace("</body>", `${$}</body>`) : l + $), { html: a, css: o, globalStyles: u, htmlWithStyles: l };
|
|
129
136
|
}
|
|
130
|
-
function
|
|
131
|
-
return
|
|
137
|
+
function X(t, e) {
|
|
138
|
+
return O(t, { ...e, dsd: !0 });
|
|
132
139
|
}
|
|
133
|
-
function
|
|
140
|
+
function z(t, e) {
|
|
134
141
|
return new ReadableStream({
|
|
135
|
-
start(r) {
|
|
142
|
+
async start(r) {
|
|
143
|
+
const n = [];
|
|
144
|
+
H(n);
|
|
136
145
|
try {
|
|
137
|
-
const { htmlWithStyles:
|
|
138
|
-
r.enqueue(
|
|
139
|
-
} catch (
|
|
140
|
-
r.error(
|
|
146
|
+
const { htmlWithStyles: s } = O(t, e);
|
|
147
|
+
r.enqueue(s);
|
|
148
|
+
} catch (s) {
|
|
149
|
+
r.error(s);
|
|
150
|
+
return;
|
|
151
|
+
} finally {
|
|
152
|
+
J();
|
|
141
153
|
}
|
|
154
|
+
for (const s of n)
|
|
155
|
+
try {
|
|
156
|
+
const i = await s.promise, a = Array.isArray(i) ? i.map((u) => m(u, s.opts)).join("") : m(i, s.opts), o = `${D(s.useStyleCSS, a)}${a}`;
|
|
157
|
+
r.enqueue(
|
|
158
|
+
`<script>(function(){var e=document.getElementById(${JSON.stringify(s.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(o)};e.removeAttribute('id');})();<\/script>`
|
|
159
|
+
);
|
|
160
|
+
} catch {
|
|
161
|
+
}
|
|
162
|
+
r.close();
|
|
142
163
|
}
|
|
143
164
|
});
|
|
144
165
|
}
|
|
145
166
|
export {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
167
|
+
$ as DSD_POLYFILL_SCRIPT,
|
|
168
|
+
v as clearRegisteredEntityMap,
|
|
169
|
+
tt as loadEntityMap,
|
|
170
|
+
rt as registerEntityMap,
|
|
171
|
+
z as renderToStream,
|
|
172
|
+
y as renderToString,
|
|
173
|
+
G as renderToStringDSD,
|
|
174
|
+
O as renderToStringWithJITCSS,
|
|
175
|
+
X as renderToStringWithJITCSSDSD
|
|
155
176
|
};
|
|
156
177
|
//# sourceMappingURL=custom-elements-runtime.ssr.es.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-elements-runtime.ssr.es.js","sources":["../src/lib/runtime/vdom-ssr.ts","../src/lib/runtime/vdom-ssr-dsd.ts","../src/lib/ssr.ts"],"sourcesContent":["import type { VNode } from './types';\nimport { escapeHTML } from './helpers';\nimport { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\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 = {\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\n// HTML void elements that should be self-closing\nconst 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 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 let attrsObj: Record<string, unknown> = {};\n if (vnode.props && vnode.props.attrs) {\n attrsObj = { ...vnode.props.attrs };\n }\n\n const inject = opts?.injectSvgNamespace ?? true;\n const injectKnown = opts?.injectKnownNamespaces ?? inject;\n\n // Inject namespace for well-known tags when missing. By default we\n // preserve previous behavior (SVG injected) and also allow injecting\n // other known namespaces (MathML) when injectKnownNamespaces is true.\n if (inject && vnode.tag === 'svg' && !('xmlns' in attrsObj)) {\n attrsObj.xmlns = SVG_NS;\n } else if (\n injectKnown &&\n vnode.tag in TAG_NAMESPACE_MAP &&\n !('xmlns' in attrsObj)\n ) {\n attrsObj.xmlns = TAG_NAMESPACE_MAP[vnode.tag];\n }\n\n const attrsString = Object.entries(attrsObj)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\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, type RenderOptions } from './vdom-ssr';\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 { TAG_NAMESPACE_MAP, SVG_NS } from './namespace-helpers';\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\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst 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\n/**\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\nfunction buildAttrsString(\n attrs: Record<string, unknown>,\n opts: DSDRenderOptions,\n): string {\n const inject = opts.injectSvgNamespace ?? true;\n const injectKnown = opts.injectKnownNamespaces ?? inject;\n\n const merged = { ...attrs };\n\n // Mirror namespace injection logic from renderToString\n const tag = (merged as { _tag?: string })._tag;\n if (tag) delete merged._tag;\n\n if (inject && tag === 'svg' && !('xmlns' in merged)) {\n merged['xmlns'] = SVG_NS;\n } else if (injectKnown && tag && 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\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 */\nfunction 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// 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, _tag: tag }\n : { _tag: tag };\n\n const attrsString = buildAttrsString(attrsObj, 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 = Object.entries(rawAttrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join('');\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 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}${hydrateAttr}><template shadowrootmode=\"open\"></template>${lightDOM}</${tag}>`;\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 } = runComponentSSRRender(config, rawAttrs, tag);\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 DSD_POLYFILL_SCRIPT,\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 * The current implementation flushes the complete rendered output as a single\n * chunk, providing the streaming API surface for framework adapters. True\n * incremental streaming (flush shell immediately, resolve async components\n * progressively) is planned for a future release.\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 start(controller) {\n try {\n const { htmlWithStyles } = renderToStringWithJITCSS(vnode, options);\n controller.enqueue(htmlWithStyles);\n controller.close();\n } catch (err) {\n controller.error(err);\n }\n },\n });\n}\n"],"names":["VOID_ELEMENTS","renderToString","vnode","opts","escapeHTML","c","attrsObj","inject","injectKnown","SVG_NS","TAG_NAMESPACE_MAP","attrsString","k","v","children","DSD_POLYFILL_SCRIPT","isRegisteredCustomElement","tag","registry","buildAttrsString","attrs","merged","buildShadowStyleBlock","useStyleCSS","shadowHTML","parts","baseReset","jit","jitCSS","combined","minifyCSS","renderToDSD","renderCustomElementDSD","renderChildrenDSD","config","rawAttrs","hydrateStrategy","hydrateAttr","lightDOM","shadowVNode","runComponentSSRRender","n","styleBlock","renderToStringDSD","effectiveOpts","html","renderToStringWithJITCSS","options","dsd","dsdPolyfill","renderOptions","beginSSRGlobalStyleCollection","globalStylesCaptured","_renderToStringDSD","_render","endSSRGlobalStyleCollection","css","globalStyles","styleTags","htmlWithStyles","injection","renderToStringWithJITCSSDSD","renderToStream","controller","err"],"mappings":";;;;;AAmBA,MAAMA,wBAAoB,IAAI;AAAA,EAC5B;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;AACF,CAAC;AAEM,SAASC,EAAeC,GAAcC,GAA8B;AACzE,MAAI,OAAOD,KAAU,SAAU,QAAOE,EAAWF,CAAK;AAEtD,MAAIA,EAAM,QAAQ;AAChB,WAAO,OAAOA,EAAM,YAAa,WAC5BE,EAAWF,EAAM,QAAQ,IAC1B;AAGN,MAAIA,EAAM,QAAQ;AAQhB,YAHiB,MAAM,QAAQA,EAAM,QAAQ,IACzCA,EAAM,SAAS,OAAO,CAACG,MAAMA,KAAM,IAAuB,IAC1D,CAAA,GACY,IAAI,CAACA,MAAMJ,EAAeI,GAAGF,CAAI,CAAC,EAAE,KAAK,EAAE;AAG7D,MAAID,EAAM,QAAQ;AAChB,WAAO,OAAOA,EAAM,YAAa,WAAWA,EAAM,WAAW;AAO/D,MAAII,IAAoC,CAAA;AACxC,EAAIJ,EAAM,SAASA,EAAM,MAAM,UAC7BI,IAAW,EAAE,GAAGJ,EAAM,MAAM,MAAA;AAG9B,QAAMK,IAASJ,GAAM,sBAAsB,IACrCK,IAAcL,GAAM,yBAAyBI;AAKnD,EAAIA,KAAUL,EAAM,QAAQ,SAAS,EAAE,WAAWI,KAChDA,EAAS,QAAQG,IAEjBD,KACAN,EAAM,OAAOQ,KACb,EAAE,WAAWJ,OAEbA,EAAS,QAAQI,EAAkBR,EAAM,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GAAc,gBAAAE,EAAA;AACpC;AAsBO,SAASE,EACd3D,GACA6C,GAIc;AACd,SAAOD,EAAyB5C,GAAO,EAAE,GAAG6C,GAAS,KAAK,IAAM;AAClE;AA+BO,SAASe,EACd5D,GACA6C,GACwB;AACxB,SAAO,IAAI,eAAuB;AAAA,IAChC,MAAMgB,GAAY;AAChB,UAAI;AACF,cAAM,EAAE,gBAAAJ,EAAA,IAAmBb,EAAyB5C,GAAO6C,CAAO;AAClE,QAAAgB,EAAW,QAAQJ,CAAc,GACjCI,EAAW,MAAA;AAAA,MACb,SAASC,GAAK;AACZ,QAAAD,EAAW,MAAMC,CAAG;AAAA,MACtB;AAAA,IACF;AAAA,EAAA,CACD;AACH;"}
|
|
1
|
+
{"version":3,"file":"custom-elements-runtime.ssr.es.js","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\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}\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);\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 });\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 * The current implementation flushes the complete rendered output as a single\n * chunk, providing the streaming API surface for framework adapters. True\n * incremental streaming (flush shell immediately, resolve async components\n * progressively) is planned for a future release.\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"],"names":["VOID_ELEMENTS","buildAttrs","attrs","tag","opts","inject","injectKnown","merged","SVG_NS","TAG_NAMESPACE_MAP","k","v","escapeHTML","buildRawAttrs","renderToString","vnode","c","attrsObj","attrsString","children","DSD_POLYFILL_SCRIPT","isRegisteredCustomElement","registry","buildShadowStyleBlock","useStyleCSS","shadowHTML","parts","baseReset","jit","jitCSS","combined","minifyCSS","_streamingCollector","_streamingCounter","beginStreamingCollection","collector","endStreamingCollection","renderToDSD","renderCustomElementDSD","renderChildrenDSD","config","rawAttrs","lightDOM","hydrateStrategy","hydrateAttr","shadowVNode","asyncPromise","runComponentSSRRender","devWarn","id","n","styleBlock","renderToStringDSD","effectiveOpts","html","renderToStringWithJITCSS","options","dsd","dsdPolyfill","renderOptions","beginSSRGlobalStyleCollection","globalStylesCaptured","_renderToStringDSD","_render","endSSRGlobalStyleCollection","css","globalStyles","styleTags","htmlWithStyles","injection","renderToStringWithJITCSSDSD","renderToStream","controller","asyncEntries","err","entry","resolvedVNodes","shadowContent"],"mappings":";;;;;;AAcO,MAAMA,wBAAoB,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;AACF,CAAC;AAEM,SAASC,EACdC,GACAC,GACAC,GACQ;AACR,QAAMC,IAASD,EAAK,sBAAsB,IACpCE,IAAcF,EAAK,yBAAyBC,GAC5CE,IAAS,EAAE,GAAGL,EAAA;AAEpB,SAAIG,KAAUF,MAAQ,SAAS,EAAE,WAAWI,KAC1CA,EAAO,QAAWC,IACTF,KAAeH,KAAOM,KAAqB,EAAE,WAAWF,OACjEA,EAAO,QAAWE,EAAkBN,CAAG,IAGlC,OAAO,QAAQI,CAAM,EACzB,IAAI,CAAC,CAACG,GAAGC,CAAC,MAAM,IAAID,CAAC,KAAKE,EAAW,OAAOD,CAAC,CAAC,CAAC,GAAG,EAClD,KAAK,EAAE;AACZ;AAEO,SAASE,EAAcX,GAAwC;AACpE,SAAO,OAAO,QAAQA,CAAK,EACxB,IAAI,CAAC,CAACQ,GAAGC,CAAC,MAAM,IAAID,CAAC,KAAKE,EAAW,OAAOD,CAAC,CAAC,CAAC,GAAG,EAClD,KAAK,EAAE;AACZ;AC1CO,SAASG,EAAeC,GAAcX,GAA8B;AACzE,MAAI,OAAOW,KAAU,SAAU,QAAOH,EAAWG,CAAK;AAEtD,MAAIA,EAAM,QAAQ;AAChB,WAAO,OAAOA,EAAM,YAAa,WAC5BH,EAAWG,EA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./css-utils-RqkyBWft.cjs");function z(){const r=(()=>{try{return globalThis.process?.env?.NODE_ENV}catch{return}})(),e=(()=>{try{if(typeof window>"u")return{vitest:!1,cypress:!1};const t=window;return{vitest:!!t.__vitest__,cypress:!!t.Cypress}}catch{return{vitest:!1,cypress:!1}}})();return{isTest:r==="test"||e.vitest||e.cypress,isVitest:e.vitest,isCypress:e.cypress}}class B{pendingUpdates=new Map;isFlushScheduled=!1;isFlushing=!1;testEnv;lastCleanup=0;CLEANUP_INTERVAL=300*1e3;MAX_PENDING_SIZE=1e4;pendingIdleUpdates=new Map;idleCallbackHandle=null;constructor(){this.testEnv=z(),this.schedulePeriodicCleanup()}schedule(e,n){const t=n||e;this.pendingUpdates.size>=this.MAX_PENDING_SIZE&&this.performEmergencyCleanup(),this.pendingUpdates.set(t,e),this.isFlushScheduled||this.scheduleFlush()}scheduleFlush(){this.isFlushScheduled=!0,this.testEnv.isTest&&!this.isFlushing?this.flush():queueMicrotask(()=>this.flush())}flush(){if(this.isFlushing)return;this.isFlushing=!0;const e=this.pendingUpdates;this.pendingUpdates=new Map,this.isFlushScheduled=!1;try{for(const n of e.values())try{n()}catch(t){g.devError("Error in batched update:",t)}}finally{this.isFlushing=!1}}flushImmediately(){this.pendingUpdates.size!==0&&(this.isFlushScheduled=!1,this.flush())}get pendingCount(){return this.pendingUpdates.size}get hasPendingUpdates(){return this.pendingUpdates.size>0}get isFlushingUpdates(){return this.isFlushing}schedulePeriodicCleanup(){if(this.testEnv.isTest)return;const e=()=>{this.performPeriodicCleanup(),this.testEnv.isTest||setTimeout(e,this.CLEANUP_INTERVAL)};setTimeout(e,this.CLEANUP_INTERVAL)}performPeriodicCleanup(){const e=Date.now();e-this.lastCleanup<this.CLEANUP_INTERVAL||(this.pendingUpdates.size>100&&g.devWarn(`Scheduler has ${this.pendingUpdates.size} pending updates. Consider investigating.`),this.lastCleanup=e)}performEmergencyCleanup(e=this.pendingUpdates){g.devWarn("Scheduler emergency cleanup: too many pending updates, clearing oldest entries");const n=Array.from(e.entries()),t=Math.floor(n.length/2);for(let s=0;s<t;s++)e.delete(n[s][0])}scheduleWithPriority(e,n="normal",t){if(n==="immediate"){try{e()}catch(o){g.devError("Error in immediate update:",o)}return}if(n==="idle"){const o=t??e;this.pendingIdleUpdates.size>=this.MAX_PENDING_SIZE&&this.performEmergencyCleanup(this.pendingIdleUpdates),this.pendingIdleUpdates.set(o,e),this.scheduleIdleFlush();return}const s=t??e;this.pendingUpdates.size>=this.MAX_PENDING_SIZE&&this.performEmergencyCleanup(),this.pendingUpdates.set(s,e),this.isFlushScheduled||(this.isFlushScheduled=!0,queueMicrotask(()=>this.flush()))}scheduleIdleFlush(){if(this.idleCallbackHandle===null){if(this.testEnv.isTest){this.idleCallbackHandle=setTimeout(()=>{this.idleCallbackHandle=null,this.flushIdleUpdates(null)},0);return}if(typeof requestIdleCallback<"u"){const e=requestIdleCallback(n=>{this.idleCallbackHandle=null,this.flushIdleUpdates(n)},{timeout:2e3});this.idleCallbackHandle=e}else this.idleCallbackHandle=setTimeout(()=>{this.idleCallbackHandle=null;const e=Date.now();this.flushIdleUpdates({timeRemaining:()=>Math.max(0,50-(Date.now()-e)),didTimeout:!1})},5)}}flushIdleUpdates(e){const n=Array.from(this.pendingIdleUpdates.entries());this.pendingIdleUpdates=new Map;for(let t=0;t<n.length;t++){if(e&&!e.didTimeout&&e.timeRemaining()<=0){for(let s=t;s<n.length;s++)this.pendingIdleUpdates.set(n[s][0],n[s][1]);this.scheduleIdleFlush();return}try{n[t][1]()}catch(s){g.devError("Error in idle update:",s)}}}}const E=new B;function G(r,e){E.schedule(r,e)}function Y(r,e="normal",n){E.scheduleWithPriority(r,e,n)}function J(){E.flushImmediately()}function Q(){return new Promise(r=>{let n=0;for(;E.hasPendingUpdates&&n<100;)E.flushImmediately(),n++;n>=100&&g.devWarn("[nextTick] Maximum flush iterations reached — possible circular update loop. Check for watchers or computed values that unconditionally mutate reactive state."),queueMicrotask(r)})}const U=new WeakSet;class ee{static cache=new WeakMap;static arrayHandlerCache=new WeakMap;static objectHandlerCache=new WeakMap;static getOrCreateProxy(e,n,t=!1){const s=this.cache.get(e);if(s)return s;const o=t?this.getOrCreateArrayHandler(n):this.getOrCreateObjectHandler(n),i=new Proxy(e,o);try{q.markAsProxy(i)}catch{}return this.cache.set(e,i),i}static getOrCreateArrayHandler(e){if(!this.arrayHandlerCache.has(e)){const n={get:(t,s,o)=>{const i=Reflect.get(t,s,o);return typeof i=="function"&&typeof s=="string"&&["push","pop","shift","unshift","splice","sort","reverse","fill","copyWithin"].includes(s)?function(...l){const a=i.apply(t,l);return e.triggerUpdate(),a}:i!==null&&typeof i=="object"&&typeof s=="string"?e.makeReactiveValue(i):i},set:(t,s,o)=>(t[s]=e.makeReactiveValue(o),e.triggerUpdate(),!0),deleteProperty:(t,s)=>(delete t[s],e.triggerUpdate(),!0)};this.arrayHandlerCache.set(e,n)}return this.arrayHandlerCache.get(e)}static getOrCreateObjectHandler(e){if(!this.objectHandlerCache.has(e)){const n={get:(t,s,o)=>{const i=Reflect.get(t,s,o);return i!==null&&typeof i=="object"&&typeof s=="string"?e.makeReactiveValue(i):i},set:(t,s,o)=>(t[s]=e.makeReactiveValue(o),e.triggerUpdate(),!0),deleteProperty:(t,s)=>(delete t[s],e.triggerUpdate(),!0)};this.objectHandlerCache.set(e,n)}return this.objectHandlerCache.get(e)}static hasProxy(e){return this.cache.has(e)}static clear(){this.cache=new WeakMap,this.arrayHandlerCache=new WeakMap,this.objectHandlerCache=new WeakMap}static getStats(){return{hasCachedProxies:this.cache instanceof WeakMap}}}class q{static contextCache=new WeakMap;static createReactiveProxy(e,n,t){try{if(U.has(e))return e}catch{}const s=Array.isArray(e);let o=this.contextCache.get(n);o||(o=new WeakMap,this.contextCache.set(n,o));let i=o.get(t);return i||(i={triggerUpdate:n,makeReactiveValue:t},o.set(t,i)),ee.getOrCreateProxy(e,i,s)}static markAsProxy(e){if(e)try{U.add(e)}catch{}}}let T=!1;function h(){return T}function te(){T&&g.devWarn("[CER] beginDiscoveryRender() called while a discovery render is already active. This usually means a component was registered inside another component's render function. Ensure component() calls are at module top-level."),T=!0}function ne(){T=!1}let re=0;function A(r){return`${r}-${++re}`}class se{currentComponentStack=[];componentData=new Map;stateStorage=new Map;trackingDisabled=!1;setCurrentComponent(e,n){if(this.currentComponentStack.push(e),!this.componentData.has(e))this.componentData.set(e,{dependencies:new Set,renderFn:n,stateIndex:0,lastWarnTime:0,watchers:new Map});else{const t=this.componentData.get(e);if(t.watchers&&t.watchers.size){for(const s of t.watchers.values())try{this.cleanup(s)}catch{}t.watchers.clear()}t.renderFn=n,t.stateIndex=0}}clearCurrentComponent(){this.currentComponentStack.pop()}getCurrentComponentId(){return this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null}registerWatcher(e,n){const t=this.componentData.get(e);t&&t.watchers.set(n,n)}disableTracking(){this.trackingDisabled=!0}enableTracking(){this.trackingDisabled=!1}isRenderingComponent(){return this.currentComponentStack.length>0}shouldEmitRenderWarning(){const e=this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null;if(!e)return!0;const n=this.componentData.get(e);if(!n)return!0;const t=Date.now();return t-n.lastWarnTime<1e3?!1:(n.lastWarnTime=t,!0)}withoutTracking(e){const n=this.trackingDisabled;this.trackingDisabled=!0;try{return e()}finally{this.trackingDisabled=n}}getOrCreateState(e){const n=this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null;if(!n)return new D(e);const t=this.componentData.get(n);if(!t)return new D(e);const s=`${n}:${t.stateIndex++}`;let o=this.stateStorage.get(s);return o||(o=new D(e),this.stateStorage.set(s,o)),o}trackDependency(e){if(this.trackingDisabled)return;const n=this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null;if(!n)return;const t=this.componentData.get(n);t&&(t.dependencies.add(e),e.addDependent(n))}propagateDependencies(e){if(this.trackingDisabled)return;const n=this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null;if(!n||n===e)return;const t=this.componentData.get(e);if(!t)return;const s=this.componentData.get(n);if(s)for(const o of t.dependencies)s.dependencies.add(o),o.addDependent(n)}triggerUpdate(e){const n=e.getDependents();for(const t of n){const s=this.componentData.get(t);s&&G(s.renderFn,t)}}cleanup(e){const n=this.componentData.get(e);if(n){for(const s of n.dependencies)s.removeDependent(e);this.componentData.delete(e)}const t=e+":";for(const s of this.stateStorage.keys())s.startsWith(t)&&this.stateStorage.delete(s)}}const d=new se;class D{_value;_rawValue;dependents=new Set;constructor(e){this._rawValue=e,this._value=this.makeReactive(e);try{Object.defineProperty(this,Symbol.for("@cer/ReactiveState"),{value:!0,enumerable:!1,configurable:!1})}catch{}}get value(){return d.trackDependency(this),this._value}set value(e){Object.is(e,this._rawValue)||(d.isRenderingComponent()&&d.shouldEmitRenderWarning()&&g.devWarn(`🚨 State modification detected during render! This can cause infinite loops.
|
|
2
2
|
• Move state updates to event handlers
|
|
3
3
|
• Use watchEffect/watch for side effects
|
|
4
|
-
• Ensure computed properties don't modify state`),this._rawValue=e,this._value=this.makeReactive(e),d.triggerUpdate(this))}peek(){return this._value}initSilent(e){this._rawValue=e,this._value=e}addDependent(e){this.dependents.add(e)}removeDependent(e){this.dependents.delete(e)}getDependents(){return this.dependents}makeReactive(e){return e===null||typeof e!="object"||e instanceof Node||e instanceof Element||e instanceof HTMLElement?e:G.createReactiveProxy(e,()=>d.triggerUpdate(this),n=>this.makeReactive(n))}}function oe(r){return d.getOrCreateState(r===void 0?null:r)}function C(r){if(!r||typeof r!="object")return!1;try{const e=Symbol.for("@cer/ReactiveState");return Object.prototype.hasOwnProperty.call(r,e)}catch{return!1}}function ie(r){let e,n=!0;const t=A("computed"),s=()=>{n=!0};try{const o=d.getCurrentComponentId();o&&d.registerWatcher(o,t)}catch{}return d.setCurrentComponent(t,s),e=r(),d.clearCurrentComponent(),n=!1,{get value(){return n&&(d.setCurrentComponent(t,s),e=r(),d.clearCurrentComponent(),n=!1),d.propagateDependencies(t),e}}}function ae(r){if(h())return()=>{};const e=A("effect");try{const t=d.getCurrentComponentId();t&&d.registerWatcher(t,e)}catch{}const n=()=>{d.setCurrentComponent(e,n);try{r()}finally{d.clearCurrentComponent()}};return n(),()=>{d.cleanup(e)}}const L=50;function R(r,e=new WeakMap,n=0){if(r===null||typeof r!="object")return r;const t=r;if(e.has(t))return e.get(t);if(n>L)return p.devWarn(`[watch] Deep clone exceeded ${L} nesting levels. Returning a reference at this depth instead of cloning further. Consider restructuring your state or switching to a shallow watch.`),r;if(typeof Node<"u"&&t instanceof Node)return r;if(t instanceof Date)return new Date(t.getTime());if(Array.isArray(t)){const o=[];e.set(t,o);for(let i=0;i<t.length;i++)o.push(R(t[i],e,n+1));return o}const s={};e.set(t,s);for(const o of Object.keys(t))try{s[o]=R(t[o],e,n+1)}catch{}return s}function ce(r,e,n){if(h())return()=>{};let t;const s=C(r)?()=>r.value:r,o=A("watch");try{const a=d.getCurrentComponentId();a&&d.registerWatcher(a,o)}catch{}const i=()=>{d.setCurrentComponent(o,i);const a=s();if(d.clearCurrentComponent(),n?.deep){const u=d.withoutTracking(()=>R(a));e(u,t),t=u}else a!==t&&(e(a,t),t=a)};return d.setCurrentComponent(o,i),t=s(),d.clearCurrentComponent(),n?.deep&&(t=d.withoutTracking(()=>R(t))),n&&n.immediate&&e(t,void 0),()=>{d.cleanup(o)}}const ue=r=>{try{r()}catch{}},v=new Map,_=new Map,M=new Map,O=500;let k,q,W=!1,F=!1,$;const le=!!globalThis.process?.versions?.node;function K(r){if(v.has(r))return v.get(r);const e=r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return v.size<O&&v.set(r,e),e}function x(r){if(_.has(r))return _.get(r);const e=r.replace(/-([a-z])/g,(n,t)=>t.toUpperCase());return _.size<O&&_.set(r,e),e}function de(r){if(typeof r=="string"){if(M.has(r))return M.get(r);const e=r.replace(/[&<>"']/g,n=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[n]);return e!==r&&M.size<O&&M.set(r,e),e}return r}function y(r){if(!r)return"";const e=String(r);if(typeof document<"u"&&typeof document.createElement=="function"){const a=e.replace(/</g,"").replace(/>/g,""),u=$||($=document.createElement("div"));try{y._el=u}catch{}return u.innerHTML=a,(u.textContent||"").replace(new RegExp("","g"),"<").replace(new RegExp("","g"),">")}const n={lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "},t=k??y._namedMap;let s=t;if(!s&&le)try{const o=globalThis.require;if(typeof o=="function"){const i=["@jasonshimmy/custom-elements-runtime/entities.json","../../entities.json","../../../entities.json","../entities.json","./entities.json"];for(const a of i)try{const u=o(a);if(u&&typeof u=="object"){s=u;break}}catch{}}}catch{}if(!s){s=n,W=!0;try{y._usedFallback=!0}catch{}const o=y._namedMapLoader??q;o&&o().then(i=>{k=i;try{y._namedMap=i}catch{}}).catch(()=>{})}if((W||y._usedFallback)&&!(F||y._warnedFallback)){F=!0;try{y._warnedFallback=!0}catch{}try{p.devWarn("decodeEntities: using small SSR fallback entity map. Register the full entities.json via registerEntityMap(entities) on the server to enable full HTML5 named-entity decoding.")}catch{}}return e.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g,(o,i)=>{if(i.charCodeAt(0)===35){const c=(i.charAt(1)||"").toLowerCase()==="x"?parseInt(i.slice(2),16):parseInt(i.slice(1),10);return Number.isNaN(c)?`&${i};`:String.fromCodePoint(c)}const a=s[i]??(t&&t[i]);return a!==void 0?a:`&${i};`})}async function P(){const r=["@jasonshimmy","custom-elements-runtime","entities.json"].join("/");try{const e=await import(r);return e&&(e.default||e)}catch{try{const e=[r,"./entities.json","../../entities.json","../../../entities.json"];for(const n of e)try{const t=await import(n);if(t)return t&&(t.default||t)}catch{}return{lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "}}catch{return{lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "}}}}q=P;y._namedMapLoader=P;function fe(r,e){!r||typeof r!="object"||k&&!e?.overwrite||(k=r)}function he(){k=void 0}function pe(r){const e=String(r);return{__unsafeHTML:e,__rawHTML:e}}function ge(r){return!!r&&(typeof r.__unsafeHTML=="string"||typeof r.__rawHTML=="string")}function me(r,e){if(typeof e=="string"){if(e==="")return;const n=e.split(".");let t=r;for(const s of n){if(t==null||typeof t!="object"){t=void 0;break}t=t[s]}return C(t)?t.value:t}return e}function ye(r,e,n){const t=String(e).split("."),s=t.pop();if(!s)return;const o=t.reduce((i,a)=>(i[a]==null&&(i[a]={}),i[a]),r);C(o[s])?o[s].value=n:o[s]=n}function Ce(r){try{if(r&&typeof r=="object"){if(C(r))return r.value;if("value"in r){const e=r.value;return e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:r}}}catch{}return r}function be(r){const e=Ce(r);if(e==null)return null;const n=typeof e;return n==="string"||n==="number"||n==="boolean"?String(e):null}function we(r){if(!r||typeof r!="string")return!1;if(r==="class"||r.endsWith("Class"))return!0;if(r.includes("-"))try{if(r.split("-").some(n=>n==="class"))return!0}catch{}return!1}let w=null;function Se(){w=[]}function Ee(){const r=w??[];return w=null,r}function ke(r){return w!==null?(r&&!w.includes(r)&&w.push(r),!0):!1}function ve(r,e,n="unknown"){const t={};for(const[u,c]of Object.entries(e??{}))t[x(u)]=c;const s={getAttribute(u){const c=x(u);if(t[c]!==void 0&&t[c]!==null)return String(t[c]);const m=(e??{})[u];return m!=null?String(m):null},hasAttribute(u){return this.getAttribute(u)!==null},shadowRoot:null,tagName:"",parentElement:null},o={...t,_componentId:`cer-ssr-${Object.keys(t).join("-")||"root"}`,requestRender:()=>{},_requestRender:()=>{},emit:()=>!0,refs:{}};Object.defineProperty(o,"_host",{value:s,writable:!0,enumerable:!1,configurable:!0}),N(o);let i=null;try{const u=r.render(o);u instanceof Promise?p.devWarn(`[SSR] Component "${n}" has an async render function. Async renders are not supported in the synchronous SSR pass — the shadow DOM will be empty and hydrated on the client instead.`):i=u}catch(u){p.devWarn(`[SSR] Component "${n}" threw during SSR render. The shadow DOM will be empty. Error:`,u)}finally{H()}const a=String(o._computedStyle??"");return{shadowVNode:i,useStyleCSS:a}}function _e(){return h()}let l=null;const S=Symbol("cer:provides");function N(r){l=r}function H(){l=null}function Me(){return l}function De(){if(!l)throw new Error("useEmit must be called during component render");if(h())return()=>!1;const r=l.emit;if(typeof r!="function")throw new Error("useEmit requires an emit function on the component context");const e=r;return(n,t,s)=>e(n,t,s)}function b(r){r._hookCallbacks||Object.defineProperty(r,"_hookCallbacks",{value:{},writable:!0,enumerable:!1,configurable:!0})}function Te(r){if(!l)throw new Error("useOnConnected must be called during component render");if(h())return;b(l);const e=l._hookCallbacks;e.onConnected||(e.onConnected=[]),e.onConnected.push(r)}function Re(r){if(!l)throw new Error("useOnDisconnected must be called during component render");if(h())return;b(l);const e=l._hookCallbacks;e.onDisconnected||(e.onDisconnected=[]),e.onDisconnected.push(r)}function Ne(r){if(!l)throw new Error("useOnAttributeChanged must be called during component render");if(h())return;b(l);const e=l._hookCallbacks;e.onAttributeChanged||(e.onAttributeChanged=[]),e.onAttributeChanged.push(r)}function xe(r){if(!l)throw new Error("useOnError must be called during component render");if(h())return;b(l);const e=l._hookCallbacks;e.onError||(e.onError=[]),e.onError.push(n=>{try{n instanceof Error?r(n):r(new Error(String(n)))}catch(t){p.devError("[useOnError] The error handler itself threw an exception:",t)}})}function X(r){if(!l)throw new Error("useProps must be called during component render");b(l);const e=l._hookCallbacks;e.props={...e.props||{},...r};const n=l;try{const s=Object.keys(r||{});for(const o of s){if(typeof o!="string"||o.startsWith("_"))continue;const i=Object.getOwnPropertyDescriptor(n,o);if(!(i&&!i.configurable))try{let u=Object.prototype.hasOwnProperty.call(n,o)?n[o]:void 0;Object.defineProperty(n,o,{configurable:!0,enumerable:!0,get(){try{const c=n&&n._host;if(c){const m=K(o),g=c.getAttribute(m);if(g!==null){const f=typeof r[o];return f==="boolean"?g===""||g==="true":f==="number"?Number(g):g}if(typeof c[o]<"u"){const f=c[o];if(C(f)||f&&typeof f=="object"&&"value"in f&&!(f instanceof Node))return f.value;const I=typeof r[o];if(!(I==="string"&&f&&typeof f=="object"))return I==="boolean"&&typeof f=="string"?f===""||f==="true":f}}}catch{}return u},set(c){u=c}})}catch{}}}catch{}return new Proxy({},{get(s,o){if(typeof o!="string")return;const i=r[o];try{const u=n&&n._host;if(u){if(u instanceof HTMLElement||typeof u.getAttribute=="function"&&typeof u.hasAttribute=="function"){const m=o.replace(/([A-Z])/g,"-$1").toLowerCase(),g=u.getAttribute(m);if(g!==null)return typeof i=="boolean"?g===""||g==="true":typeof i=="number"?Number(g):g}const c=u[o];if(typeof c<"u"&&c!==""){const m=c&&typeof c=="object"&&"value"in c&&!(c instanceof Node);if(!(typeof i=="string"&&c&&typeof c=="object"&&!m&&!C(c)))return typeof i=="boolean"&&i===!1&&c===""?i:C(c)||m?c.value:typeof i=="boolean"&&typeof c=="string"?c===""||c==="true":typeof i=="number"&&typeof c=="string"&&!Number.isNaN(Number(c))?Number(c):c}}}catch{}const a=n[o];return typeof i=="boolean"&&a===""?i===!1?i:!0:C(a)||a&&typeof a=="object"&&"value"in a&&!(a instanceof Node)?a.value:a!=null&&a!==""?typeof i=="boolean"&&typeof a=="string"?a==="true":typeof i=="number"&&typeof a=="string"&&!Number.isNaN(Number(a))?Number(a):a:i},has(s,o){return typeof o=="string"&&(o in n||o in r)},ownKeys(){return Array.from(new Set([...Object.keys(r),...Object.keys(n||{})]))},getOwnPropertyDescriptor(){return{configurable:!0,enumerable:!0}}})}function Ae(r){if(!l)throw new Error("useStyle must be called during component render");if(!h()){b(l);try{const e=r();Object.defineProperty(l,"_computedStyle",{value:e,writable:!0,enumerable:!1,configurable:!0})}catch(e){p.devWarn("Error in useStyle callback:",e),Object.defineProperty(l,"_computedStyle",{value:"",writable:!0,enumerable:!1,configurable:!0})}}}const V=new Map;function Oe(r){let e;try{e=r()}catch{return}if(ke(e)||typeof document>"u"||typeof CSSStyleSheet>"u")return;p.devWarn("[useGlobalStyle] Injecting global styles from a component. This escapes Shadow DOM encapsulation — use sparingly.");const n=j.minifyCSS(j.sanitizeCSS(e));if(!(!n||V.has(n)))try{const t=new CSSStyleSheet;t.replaceSync(n),document.adoptedStyleSheets=[...document.adoptedStyleSheets,t],V.set(n,t)}catch{const t=document.createElement("style");t.textContent=n,(document.head??document.documentElement).appendChild(t)}}function Pe(r){if(!l)throw new Error("useDesignTokens must be called during component render");if(h())return;const e=[],n={primary:"--cer-color-primary-500",secondary:"--cer-color-secondary-500",neutral:"--cer-color-neutral-500",success:"--cer-color-success-500",info:"--cer-color-info-500",warning:"--cer-color-warning-500",error:"--cer-color-error-500"},t={fontSans:"--cer-font-sans",fontSerif:"--cer-font-serif",fontMono:"--cer-font-mono"};for(const[u,c]of Object.entries(r))c!==void 0&&(u in n?e.push(`${n[u]}:${c}`):u in t?e.push(`${t[u]}:${c}`):u.startsWith("--")&&e.push(`${u}:${c}`));if(e.length===0)return;const s=`:host{${e.join(";")}}`,i=l._computedStyle??"",a=i?`${i}
|
|
5
|
-
${s}`:s;Object.defineProperty(
|
|
6
|
-
//# sourceMappingURL=hooks-
|
|
4
|
+
• Ensure computed properties don't modify state`),this._rawValue=e,this._value=this.makeReactive(e),d.triggerUpdate(this))}peek(){return this._value}initSilent(e){this._rawValue=e,this._value=e}addDependent(e){this.dependents.add(e)}removeDependent(e){this.dependents.delete(e)}getDependents(){return this.dependents}makeReactive(e){return e===null||typeof e!="object"||e instanceof Node||e instanceof Element||e instanceof HTMLElement?e:q.createReactiveProxy(e,()=>d.triggerUpdate(this),n=>this.makeReactive(n))}}function oe(r){return d.getOrCreateState(r===void 0?null:r)}function C(r){if(!r||typeof r!="object")return!1;try{const e=Symbol.for("@cer/ReactiveState");return Object.prototype.hasOwnProperty.call(r,e)}catch{return!1}}function ie(r){let e,n=!0;const t=A("computed"),s=()=>{n=!0};try{const o=d.getCurrentComponentId();o&&d.registerWatcher(o,t)}catch{}return d.setCurrentComponent(t,s),e=r(),d.clearCurrentComponent(),n=!1,{get value(){return n&&(d.setCurrentComponent(t,s),e=r(),d.clearCurrentComponent(),n=!1),d.propagateDependencies(t),e}}}function ae(r){if(h())return()=>{};const e=A("effect");try{const t=d.getCurrentComponentId();t&&d.registerWatcher(t,e)}catch{}const n=()=>{d.setCurrentComponent(e,n);try{r()}finally{d.clearCurrentComponent()}};return n(),()=>{d.cleanup(e)}}const L=50;function R(r,e=new WeakMap,n=0){if(r===null||typeof r!="object")return r;const t=r;if(e.has(t))return e.get(t);if(n>L)return g.devWarn(`[watch] Deep clone exceeded ${L} nesting levels. Returning a reference at this depth instead of cloning further. Consider restructuring your state or switching to a shallow watch.`),r;if(typeof Node<"u"&&t instanceof Node)return r;if(t instanceof Date)return new Date(t.getTime());if(Array.isArray(t)){const o=[];e.set(t,o);for(let i=0;i<t.length;i++)o.push(R(t[i],e,n+1));return o}const s={};e.set(t,s);for(const o of Object.keys(t))try{s[o]=R(t[o],e,n+1)}catch{}return s}function ce(r,e,n){if(h())return()=>{};let t;const s=C(r)?()=>r.value:r,o=A("watch");try{const c=d.getCurrentComponentId();c&&d.registerWatcher(c,o)}catch{}const i=()=>{d.setCurrentComponent(o,i);const c=s();if(d.clearCurrentComponent(),n?.deep){const l=d.withoutTracking(()=>R(c));e(l,t),t=l}else c!==t&&(e(c,t),t=c)};return d.setCurrentComponent(o,i),t=s(),d.clearCurrentComponent(),n?.deep&&(t=d.withoutTracking(()=>R(t))),n&&n.immediate&&e(t,void 0),()=>{d.cleanup(o)}}const ue=r=>{try{r()}catch{}},v=new Map,_=new Map,M=new Map,O=500;let k,K,W=!1,F=!1,$;const le=!!globalThis.process?.versions?.node;function X(r){if(v.has(r))return v.get(r);const e=r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return v.size<O&&v.set(r,e),e}function x(r){if(_.has(r))return _.get(r);const e=r.replace(/-([a-z])/g,(n,t)=>t.toUpperCase());return _.size<O&&_.set(r,e),e}function de(r){if(typeof r=="string"){if(M.has(r))return M.get(r);const e=r.replace(/[&<>"']/g,n=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[n]);return e!==r&&M.size<O&&M.set(r,e),e}return r}function y(r){if(!r)return"";const e=String(r);if(typeof document<"u"&&typeof document.createElement=="function"){const c=e.replace(/</g,"").replace(/>/g,""),l=$||($=document.createElement("div"));try{y._el=l}catch{}return l.innerHTML=c,(l.textContent||"").replace(new RegExp("","g"),"<").replace(new RegExp("","g"),">")}const n={lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "},t=k??y._namedMap;let s=t;if(!s&&le)try{const o=globalThis.require;if(typeof o=="function"){const i=["@jasonshimmy/custom-elements-runtime/entities.json","../../entities.json","../../../entities.json","../entities.json","./entities.json"];for(const c of i)try{const l=o(c);if(l&&typeof l=="object"){s=l;break}}catch{}}}catch{}if(!s){s=n,W=!0;try{y._usedFallback=!0}catch{}const o=y._namedMapLoader??K;o&&o().then(i=>{k=i;try{y._namedMap=i}catch{}}).catch(()=>{})}if((W||y._usedFallback)&&!(F||y._warnedFallback)){F=!0;try{y._warnedFallback=!0}catch{}try{g.devWarn("decodeEntities: using small SSR fallback entity map. Register the full entities.json via registerEntityMap(entities) on the server to enable full HTML5 named-entity decoding.")}catch{}}return e.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g,(o,i)=>{if(i.charCodeAt(0)===35){const a=(i.charAt(1)||"").toLowerCase()==="x"?parseInt(i.slice(2),16):parseInt(i.slice(1),10);return Number.isNaN(a)?`&${i};`:String.fromCodePoint(a)}const c=s[i]??(t&&t[i]);return c!==void 0?c:`&${i};`})}async function P(){const r=["@jasonshimmy","custom-elements-runtime","entities.json"].join("/");try{const e=await import(r);return e&&(e.default||e)}catch{try{const e=[r,"./entities.json","../../entities.json","../../../entities.json"];for(const n of e)try{const t=await import(n);if(t)return t&&(t.default||t)}catch{}return{lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "}}catch{return{lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "}}}}K=P;y._namedMapLoader=P;function fe(r,e){!r||typeof r!="object"||k&&!e?.overwrite||(k=r)}function he(){k=void 0}function pe(r){const e=String(r);return{__unsafeHTML:e,__rawHTML:e}}function ge(r){return!!r&&(typeof r.__unsafeHTML=="string"||typeof r.__rawHTML=="string")}function me(r,e){if(typeof e=="string"){if(e==="")return;const n=e.split(".");let t=r;for(const s of n){if(t==null||typeof t!="object"){t=void 0;break}t=t[s]}return C(t)?t.value:t}return e}function ye(r,e,n){const t=String(e).split("."),s=t.pop();if(!s)return;const o=t.reduce((i,c)=>(i[c]==null&&(i[c]={}),i[c]),r);C(o[s])?o[s].value=n:o[s]=n}function Ce(r){try{if(r&&typeof r=="object"){if(C(r))return r.value;if("value"in r){const e=r.value;return e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:r}}}catch{}return r}function be(r){const e=Ce(r);if(e==null)return null;const n=typeof e;return n==="string"||n==="number"||n==="boolean"?String(e):null}function we(r){if(!r||typeof r!="string")return!1;if(r==="class"||r.endsWith("Class"))return!0;if(r.includes("-"))try{if(r.split("-").some(n=>n==="class"))return!0}catch{}return!1}let b=null;function Se(){if(b!==null)throw new Error("[CER] Concurrent SSR render detected: beginSSRGlobalStyleCollection() called while a collection is already active. For concurrent request handling, use worker threads or multiple Node.js processes.");b=[]}function Ee(){const r=b??[];return b=null,r}function ke(r){return b!==null?(r&&!b.includes(r)&&b.push(r),!0):!1}function ve(r,e,n="unknown"){const t={};for(const[a,m]of Object.entries(e??{}))t[x(a)]=m;const s={getAttribute(a){const m=x(a);if(t[m]!==void 0&&t[m]!==null)return String(t[m]);const p=(e??{})[a];return p!=null?String(p):null},hasAttribute(a){return this.getAttribute(a)!==null},shadowRoot:null,tagName:"",parentElement:null},o={...t,_componentId:`cer-ssr-${Object.keys(t).join("-")||"root"}`,requestRender:()=>{},_requestRender:()=>{},emit:()=>!0,refs:{}};Object.defineProperty(o,"_host",{value:s,writable:!0,enumerable:!1,configurable:!0}),N(o);let i=null,c;try{const a=r.render(o);a instanceof Promise?c=a:i=a}catch(a){g.devWarn(`[SSR] Component "${n}" threw during SSR render. The shadow DOM will be empty. Error:`,a)}finally{H()}const l=String(o._computedStyle??"");return{shadowVNode:i,useStyleCSS:l,asyncPromise:c}}function _e(){return h()}let u=null;const S=Symbol("cer:provides");function N(r){u=r}function H(){u=null}function Me(){return u}function De(){if(!u)throw new Error("useEmit must be called during component render");if(h())return()=>!1;const r=u.emit;if(typeof r!="function")throw new Error("useEmit requires an emit function on the component context");const e=r;return(n,t,s)=>e(n,t,s)}function w(r){r._hookCallbacks||Object.defineProperty(r,"_hookCallbacks",{value:{},writable:!0,enumerable:!1,configurable:!0})}function Te(r){if(!u)throw new Error("useOnConnected must be called during component render");if(h())return;w(u);const e=u._hookCallbacks;e.onConnected||(e.onConnected=[]),e.onConnected.push(r)}function Re(r){if(!u)throw new Error("useOnDisconnected must be called during component render");if(h())return;w(u);const e=u._hookCallbacks;e.onDisconnected||(e.onDisconnected=[]),e.onDisconnected.push(r)}function Ne(r){if(!u)throw new Error("useOnAttributeChanged must be called during component render");if(h())return;w(u);const e=u._hookCallbacks;e.onAttributeChanged||(e.onAttributeChanged=[]),e.onAttributeChanged.push(r)}function xe(r){if(!u)throw new Error("useOnError must be called during component render");if(h())return;w(u);const e=u._hookCallbacks;e.onError||(e.onError=[]),e.onError.push(n=>{try{n instanceof Error?r(n):r(new Error(String(n)))}catch(t){g.devError("[useOnError] The error handler itself threw an exception:",t)}})}function Z(r){if(!u)throw new Error("useProps must be called during component render");w(u);const e=u._hookCallbacks;e.props={...e.props||{},...r};const n=u;try{const s=Object.keys(r||{});for(const o of s){if(typeof o!="string"||o.startsWith("_"))continue;const i=Object.getOwnPropertyDescriptor(n,o);if(!(i&&!i.configurable))try{let l=Object.prototype.hasOwnProperty.call(n,o)?n[o]:void 0;Object.defineProperty(n,o,{configurable:!0,enumerable:!0,get(){try{const a=n&&n._host;if(a){const m=X(o),p=a.getAttribute(m);if(p!==null){const f=typeof r[o];return f==="boolean"?p===""||p==="true":f==="number"?Number(p):p}if(typeof a[o]<"u"){const f=a[o];if(C(f)||f&&typeof f=="object"&&"value"in f&&!(f instanceof Node))return f.value;const I=typeof r[o];if(!(I==="string"&&f&&typeof f=="object"))return I==="boolean"&&typeof f=="string"?f===""||f==="true":f}}}catch{}return l},set(a){l=a}})}catch{}}}catch{}return new Proxy({},{get(s,o){if(typeof o!="string")return;const i=r[o];try{const l=n&&n._host;if(l){if(l instanceof HTMLElement||typeof l.getAttribute=="function"&&typeof l.hasAttribute=="function"){const m=o.replace(/([A-Z])/g,"-$1").toLowerCase(),p=l.getAttribute(m);if(p!==null)return typeof i=="boolean"?p===""||p==="true":typeof i=="number"?Number(p):p}const a=l[o];if(typeof a<"u"&&a!==""){const m=a&&typeof a=="object"&&"value"in a&&!(a instanceof Node);if(!(typeof i=="string"&&a&&typeof a=="object"&&!m&&!C(a)))return typeof i=="boolean"&&i===!1&&a===""?i:C(a)||m?a.value:typeof i=="boolean"&&typeof a=="string"?a===""||a==="true":typeof i=="number"&&typeof a=="string"&&!Number.isNaN(Number(a))?Number(a):a}}}catch{}const c=n[o];return typeof i=="boolean"&&c===""?i===!1?i:!0:C(c)||c&&typeof c=="object"&&"value"in c&&!(c instanceof Node)?c.value:c!=null&&c!==""?typeof i=="boolean"&&typeof c=="string"?c==="true":typeof i=="number"&&typeof c=="string"&&!Number.isNaN(Number(c))?Number(c):c:i},has(s,o){return typeof o=="string"&&(o in n||o in r)},ownKeys(){return Array.from(new Set([...Object.keys(r),...Object.keys(n||{})]))},getOwnPropertyDescriptor(){return{configurable:!0,enumerable:!0}}})}function Ae(r){if(!u)throw new Error("useStyle must be called during component render");if(!h()){w(u);try{const e=r();Object.defineProperty(u,"_computedStyle",{value:e,writable:!0,enumerable:!1,configurable:!0})}catch(e){g.devWarn("Error in useStyle callback:",e),Object.defineProperty(u,"_computedStyle",{value:"",writable:!0,enumerable:!1,configurable:!0})}}}const V=new Map;function Oe(r){let e;try{e=r()}catch{return}if(ke(e)||typeof document>"u"||typeof CSSStyleSheet>"u")return;g.devWarn("[useGlobalStyle] Injecting global styles from a component. This escapes Shadow DOM encapsulation — use sparingly.");const n=j.minifyCSS(j.sanitizeCSS(e));if(!(!n||V.has(n)))try{const t=new CSSStyleSheet;t.replaceSync(n),document.adoptedStyleSheets=[...document.adoptedStyleSheets,t],V.set(n,t)}catch{const t=document.createElement("style");t.textContent=n,(document.head??document.documentElement).appendChild(t)}}function Pe(r){if(!u)throw new Error("useDesignTokens must be called during component render");if(h())return;const e=[],n={primary:"--cer-color-primary-500",secondary:"--cer-color-secondary-500",neutral:"--cer-color-neutral-500",success:"--cer-color-success-500",info:"--cer-color-info-500",warning:"--cer-color-warning-500",error:"--cer-color-error-500"},t={fontSans:"--cer-font-sans",fontSerif:"--cer-font-serif",fontMono:"--cer-font-mono"};for(const[l,a]of Object.entries(r))a!==void 0&&(l in n?e.push(`${n[l]}:${a}`):l in t?e.push(`${t[l]}:${a}`):l.startsWith("--")&&e.push(`${l}:${a}`));if(e.length===0)return;const s=`:host{${e.join(";")}}`,i=u._computedStyle??"",c=i?`${i}
|
|
5
|
+
${s}`:s;Object.defineProperty(u,"_computedStyle",{value:c,writable:!0,enumerable:!1,configurable:!0})}function He(r,e){if(!u)throw new Error("provide must be called during component render");if(h())return;const n=u;n[S]||Object.defineProperty(n,S,{value:new Map,writable:!1,enumerable:!1,configurable:!0}),n[S].set(r,e)}function Ie(r,e){if(!u)throw new Error("inject must be called during component render");if(h())return e;try{const n=u._host;if(n){let t=n.parentNode;t||(t=n.getRootNode());let s=0;const o=50;for(;t&&s<o;)if(s++,t instanceof ShadowRoot){const i=t.host,c=i.context;if(c){const a=c[S];if(a?.has(r))return a.get(r)}if(t=i.parentNode??i.getRootNode(),t===document||t===i)break}else{if(t instanceof Element){const l=t.context;if(l){const a=l[S];if(a?.has(r))return a.get(r)}}const i=t;if(t=t.parentNode??t.getRootNode?.(),t===document||t===i)break}}}catch{}return e}function je(r){return e=>{const n=e??u;if(!n)throw new Error("createComposable: no component context available. Pass a context explicitly or call inside a render function.");const t=u;N(n);try{return r()}finally{t?N(t):H()}}}function Ue(r){if(!u)throw new Error("useExpose must be called during component render");if(h())return;w(u);const e=u._hookCallbacks;e.expose={...e.expose??{},...r};const n=u._host;if(n)for(const[t,s]of Object.entries(r))try{n[t]=s}catch{}}function Le(){if(!u)throw new Error("useSlots must be called during component render");if(h())return{has:()=>!1,getNodes:()=>[],names:()=>[]};const r=u._host,e=()=>{const n=new Map;if(!r)return n;for(const t of r.children){const s=t.getAttribute("slot")??"default",o=n.get(s);o?o.push(t):n.set(s,[t])}return n};return{has(n){if(!r)return!1;const t=!n||n==="default"?"default":n,s=e().get(t);return s!==void 0&&s.length>0},getNodes(n){if(!r)return[];const t=!n||n==="default"?"default":n;return e().get(t)??[]},names(){return r?Array.from(e().keys()):[]}}}function We(...r){if(!u)throw new Error("defineModel must be called during component render");const e=r.length===2?r[0]:"modelValue",n=r.length===2?r[1]:r.length===1?r[0]:void 0,t=Z({[e]:n}),o=h()?null:(()=>{const c=u.emit;return typeof c!="function"?null:c})(),i={get value(){return t[e]},set value(c){o&&o(`update:${e}`,c)}};try{Object.defineProperty(i,Symbol.for("@cer/ReactiveState"),{value:!0,enumerable:!1,configurable:!1})}catch{}return i}exports.ReactiveState=D;exports.beginDiscoveryRender=te;exports.beginSSRGlobalStyleCollection=Se;exports.clearCurrentComponentContext=H;exports.clearRegisteredEntityMap=he;exports.computed=ie;exports.createComposable=je;exports.decodeEntities=y;exports.defineModel=We;exports.detectTestEnvironment=z;exports.endDiscoveryRender=ne;exports.endSSRGlobalStyleCollection=Ee;exports.escapeHTML=de;exports.flushDOMUpdates=J;exports.getCurrentComponentContext=Me;exports.getNestedValue=me;exports.inject=Ie;exports.isClassLikeAttr=we;exports.isDiscoveryRender=_e;exports.isDiscoveryRender$1=h;exports.isReactiveState=C;exports.isUnsafeHTML=ge;exports.loadEntityMap=P;exports.nextTick=Q;exports.provide=He;exports.reactiveSystem=d;exports.ref=oe;exports.registerEntityMap=fe;exports.runComponentSSRRender=ve;exports.safe=ue;exports.safeSerializeAttr=be;exports.scheduleDOMUpdate=G;exports.scheduleWithPriority=Y;exports.setCurrentComponentContext=N;exports.setNestedValue=ye;exports.toCamel=x;exports.toKebab=X;exports.unsafeHTML=pe;exports.useDesignTokens=Pe;exports.useEmit=De;exports.useExpose=Ue;exports.useGlobalStyle=Oe;exports.useOnAttributeChanged=Ne;exports.useOnConnected=Te;exports.useOnDisconnected=Re;exports.useOnError=xe;exports.useProps=Z;exports.useSlots=Le;exports.useStyle=Ae;exports.watch=ce;exports.watchEffect=ae;
|
|
6
|
+
//# sourceMappingURL=hooks-x8M4knLc.cjs.map
|