@verajs/ssr 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +507 -390
  2. package/dist/vera/diagnostics.d.ts +20 -0
  3. package/dist/vera/diagnostics.js +98 -0
  4. package/dist/vera/escaping.d.ts +142 -0
  5. package/dist/vera/escaping.js +267 -0
  6. package/dist/vera/events.d.ts +41 -0
  7. package/dist/vera/events.js +162 -0
  8. package/dist/vera/frames.d.ts +38 -0
  9. package/dist/vera/frames.js +195 -0
  10. package/dist/vera/index.d.ts +48 -0
  11. package/dist/vera/index.js +480 -0
  12. package/{types → dist/vera}/nodes.d.ts +389 -302
  13. package/dist/vera/nodes.js +2322 -0
  14. package/dist/vera/parse.d.ts +37 -0
  15. package/dist/vera/parse.js +390 -0
  16. package/dist/vera/reflections.d.ts +566 -0
  17. package/dist/vera/reflections.js +820 -0
  18. package/dist/vera/registry.d.ts +14 -0
  19. package/{src → dist}/vera/registry.js +5 -1
  20. package/dist/vera/report.d.ts +27 -0
  21. package/dist/vera/report.js +56 -0
  22. package/dist/vera/scan.d.ts +37 -0
  23. package/dist/vera/scan.js +143 -0
  24. package/dist/vera/select.d.ts +40 -0
  25. package/dist/vera/select.js +261 -0
  26. package/dist/vera/serializer.d.ts +39 -0
  27. package/dist/vera/serializer.js +1372 -0
  28. package/dist/vera/shim.d.ts +42 -0
  29. package/dist/vera/shim.js +853 -0
  30. package/dist/vera/slots.d.ts +5 -0
  31. package/dist/vera/slots.js +104 -0
  32. package/dist/vera/stylesheets.d.ts +62 -0
  33. package/dist/vera/stylesheets.js +180 -0
  34. package/dist/vera/tokenizer.d.ts +32 -0
  35. package/dist/vera/tokenizer.js +528 -0
  36. package/dist/vera/types.d.ts +117 -0
  37. package/dist/vera/views.d.ts +63 -0
  38. package/dist/vera/views.js +245 -0
  39. package/package.json +12 -13
  40. package/src/vera/escaping.js +0 -135
  41. package/src/vera/events.js +0 -164
  42. package/src/vera/frames.js +0 -102
  43. package/src/vera/index.js +0 -1187
  44. package/src/vera/nodes.js +0 -2294
  45. package/src/vera/parse.js +0 -381
  46. package/src/vera/reflections.js +0 -811
  47. package/src/vera/select.js +0 -234
  48. package/src/vera/serializer.js +0 -1080
  49. package/src/vera/shim.js +0 -761
  50. package/src/vera/stylesheets.js +0 -155
  51. package/src/vera/views.js +0 -240
  52. package/types/escaping.d.ts +0 -27
  53. package/types/events.d.ts +0 -4
  54. package/types/frames.d.ts +0 -12
  55. package/types/index.d.ts +0 -13
  56. package/types/parse.d.ts +0 -19
  57. package/types/reflections.d.ts +0 -657
  58. package/types/registry.d.ts +0 -8
  59. package/types/select.d.ts +0 -5
  60. package/types/serializer.d.ts +0 -26
  61. package/types/shim.d.ts +0 -23
  62. package/types/stylesheets.d.ts +0 -53
  63. package/types/views.d.ts +0 -26
@@ -0,0 +1,1372 @@
1
+ import { escapeHtml, escapeRawText } from './shim.js';
2
+ import { INLINE_HANDLER, NEWLINE_TAKERS, SCRIPT_URL, SCRIPT_URL_ITEM, URL_SINK, decodeCodePoint, decodeSchemeReferences, thrownMessage } from './escaping.js';
3
+ import { registry } from './registry.js';
4
+ import { PROSE, TWINS } from './diagnostics.js';
5
+ import { once, own, quoted, ssrMisuse, ssrWarning } from './report.js';
6
+ import { currentRenderingTag } from './stylesheets.js';
7
+ import { INSTANCE_ATTRIBUTE, NodeBaseShim, markPending } from './nodes.js';
8
+ import { PHASE_END_TAG_OPEN as END_TAG_OPEN, INERT_EDIT as EDIT_INERT, RAW_TEXT_TAGS as RAWTEXT, PHASE_TAG_NAME as TAG_NAME, PHASE_TAG_OPEN as TAG_OPEN, TEXT_ONLY_TAGS as TEXT_ONLY, closersOf, freshScan, isTokenizerSpace as isSpace, scanTag } from './tokenizer.js';
9
+ /** Module-local, because serializeValue (the hottest function here) reads it: an imported binding is a live one, which
10
+ * V8 reaches less directly (CLAUDE.md, measured on the tokenizer's constants). */
11
+ const NodeBase = NodeBaseShim;
12
+ /**
13
+ * The vera-native template serializer: flattens core's `html` template objects to markup with
14
+ * the renderer's sigil semantics applied server-side.
15
+ *
16
+ * `?bool=${x}` -> `bool=""` when truthy, nothing when falsy
17
+ * `.prop=${x}` -> on a rendered COMPONENT tag, delivered to the instance the nested scan
18
+ * renders (by identity, never markup); on a form control, mirrored to an
19
+ * attribute (value/checked/selected); else dropped
20
+ * `@event=${fn}` -> dropped (behavior is the client's job)
21
+ * `&ref=${r}` -> dropped
22
+ * `attr=${x}` -> quoted, escaped
23
+ * text `${x}` -> escaped; nested templates and arrays flatten; only null/undefined vanish
24
+ * (`false` renders the word, as the client and as a JS template literal do —
25
+ * measured on both sides; saying otherwise here described a divergence that
26
+ * does not exist and would have sent someone hunting a hydration bug)
27
+ *
28
+ * Like the client renderer, analysis is **per template identity**: each call site's frozen
29
+ * `strings` array is classified once into a plan (slot kinds + pre-trimmed static parts), cached
30
+ * in a WeakMap. Rendering a 100-row list re-uses one plan 100 times instead of re-running the
31
+ * sigil regexes per row — the same template-identity architecture, server-side.
32
+ *
33
+ * `keyed()`/`hold()` wrappers are client-renderer constructs — SSR templates use plain `.map`.
34
+ */
35
+ /** `.prop` bindings whose server-side truth belongs in an attribute. */
36
+ const FORM_ATTRIBUTES = ['value', 'checked', 'selected'];
37
+ /**
38
+ * Whether a property binding on `owner` is one this serializer writes. `selectedIndex` is a form property on a
39
+ * `<select>` only — it chooses an option, exactly as `value` does (see `SELECT_MARK`) — and on anything else it is
40
+ * the client's concern, with no markup. The written form and a spread key ask the same question, here.
41
+ */
42
+ const isFormProperty = (owner, name) => FORM_ATTRIBUTES.includes(name) || (owner === 'select' && name === 'selectedIndex');
43
+ /**
44
+ * `checked` and `selected` are **boolean** properties; `value` is a string one.
45
+ *
46
+ * The element coerces on assignment, so `.checked=${0}` leaves a browser with `checked === false`
47
+ * while `.value=${0}` leaves it with `"0"`. All three were treated as string-ish here — present
48
+ * unless nullish or exactly `false` — so every falsy-but-not-false value (`0`, `''`, `NaN`) served
49
+ * a **ticked** checkbox against a browser's unticked one, and hydration then had to throw the
50
+ * server's markup away to correct it.
51
+ */
52
+ const BOOLEAN_FORM_PROPERTIES = new Set(['checked', 'selected']);
53
+ /**
54
+ * …and the elements where that is true.
55
+ *
56
+ * Mirroring `.value` to an attribute exists so hydration can read form state back out of the
57
+ * markup, which only means anything on a form control. Applied to every element, `.value` on a
58
+ * `<b>` wrote `value="…"` server-side where the client sets a plain JS property and no attribute at
59
+ * all — a difference in the rendered DOM for no benefit. Anywhere else a `.prop` is client state,
60
+ * which is what it already was.
61
+ */
62
+ const FORM_ELEMENTS = new Set(['input', 'textarea', 'select', 'option']);
63
+ /** The first character of a sigil binding's name — see `compile`. */
64
+ const SIGILS = new Set(['.', '?', '@', '&', '!']);
65
+ /**
66
+ * Where a sigil or event binding's name is cut from the static before it: at the one whitespace character before the
67
+ * name, which the binding takes with it so a dropped binding leaves no residue (`compile` then trims one more space).
68
+ */
69
+ const nameCut = (text, nameAt) => (nameAt > 0 && isSpace(text[nameAt - 1]) ? nameAt - 1 : nameAt);
70
+ /**
71
+ * **An expression inside an attribute NAME is refused** — the twin of the client's rule (`nameHole` in the renderer),
72
+ * so the two halves refuse the same templates: inside a tag and outside a value, a hole a name character touches on
73
+ * either side (`<p data-${k}="1">`, `<b ${name}="x">`, `<p ${k}-x>`, `<p a${k}b>`) — never a ref, never the TAG name.
74
+ * Refused at plan time, from statics only: no value ever reaches the message.
75
+ */
76
+ const NAME_CHAR_BEFORE = /[^\s"'>=/]$/;
77
+ const NAME_CHAR_AFTER = /^(?:[^\s"'>=/]|[ \t\n\f\r]*=)/;
78
+ /**
79
+ * A bound `javascript:` URL, refused — said once per process per component and attribute. The VALUE is never printed:
80
+ * it is attacker-shaped by definition, and a server's console is a log pipeline (2026-10-09).
81
+ */
82
+ const refusedScriptUrl = (name) => {
83
+ const tag = currentRenderingTag();
84
+ if (once('script-url', `${tag} ${name}`))
85
+ console.warn(ssrWarning((tag ? `<${tag}>` : 'the page'), 'script-url', TWINS.scriptUrl(name)));
86
+ };
87
+ const nameHole = (before, after) => {
88
+ const prefix = (/[^\s"'>=/]*$/.exec(before) ?? [''])[0];
89
+ const suffix = (/^[^\s"'>=/]*/.exec(after) ?? [''])[0];
90
+ const value = /^[ \t\n\f\r]*=[ \t\n\f\r]*(?:"([^"]*)("?)|'([^']*)('?)|([^\s>]*))/.exec(after.slice(suffix.length));
91
+ const given = value === null ? "''" : value[2] === '"' ? JSON.stringify(value[1]) : value[4] === "'" ? JSON.stringify(value[3]) : value[5] ? JSON.stringify(value[5]) : '…';
92
+ throw own(new Error(ssrMisuse('name-expression', TWINS.nameExpression(`${prefix}${'${…}'}${suffix}`, given))));
93
+ };
94
+ /** Slot kinds: text, boolean, form-prop, dropped binding, plain attribute. */
95
+ const TEXT = 0;
96
+ const BOOLEAN = 1;
97
+ const FORM_PROP = 2;
98
+ const DROPPED = 3;
99
+ const ATTRIBUTE = 4;
100
+ /** `.prop` on a component tag: delivered to the instance the scan will render, never markup. */
101
+ const COMPONENT_PROP = 5;
102
+ /** `.innerHTML`/`.textContent` on a plain element: content written after the open tag, the one sanctioned trusted-markup door. */
103
+ const CONTENT = 6;
104
+ /** The two content properties the server renders; `innerText`/`outerHTML`/`outerText` stay client-only (README). */
105
+ const CONTENT_PROPS = new Set(['innerHTML', 'textContent']);
106
+ /** What `compile` answers for data shaped like a template: no plan, so `serializeTemplate` renders it as text. */
107
+ const FORGED = {};
108
+ const FORGED_TEXT = `${{}}`;
109
+ /** A tagged template literal's strings: an array owning `raw`, which nothing from `JSON.parse` can be (see `compile`). */
110
+ const isLiteral = (strings) => Array.isArray(strings) && Object.hasOwn(strings, 'raw');
111
+ /** strings identity -> { parts, kinds, names } — computed once per call site, ever. */
112
+ const plans = new WeakMap();
113
+ /**
114
+ * strings identity -> foreign depth -> plan, for a template that STARTS inside `<svg>`/`<math>` — an `svg`/`mathml`
115
+ * template, or any template rendered into a foreign-content position. The plan differs because raw text does (see
116
+ * `foreign` in `scanTag`), and the common case — depth 0 — keeps its one lookup.
117
+ */
118
+ const foreignPlans = new WeakMap();
119
+ const claimInstance = (state, ordinal, tag) => {
120
+ let node = state.instances.get(ordinal);
121
+ if (node === undefined) {
122
+ node = new (registry.get(tag))();
123
+ node.localName = tag;
124
+ state.mark += ` ${INSTANCE_ATTRIBUTE}="${markPending(node)}"`;
125
+ state.instances.set(ordinal, node);
126
+ }
127
+ return node;
128
+ };
129
+ /**
130
+ * One delivery, shared by the written form and the spread form. `__proto__` is skipped for the
131
+ * same reason `renderToString`'s own `props` option skips it — `[[Set]]` replaces the element's
132
+ * prototype. What a failed assignment means is decided in the catch below, by the client's rule;
133
+ * `prepareInstance`'s `props` OPTION keeps its stricter throw-on-readonly contract deliberately —
134
+ * an API argument is the caller's explicit data, a template binding is a component boundary.
135
+ */
136
+ const deliverProperty = (node, tag, name, value) => {
137
+ if (name === '__proto__')
138
+ return;
139
+ try {
140
+ /** Any property the component declares, by name: the element is written as the open bag it is to a binding. */
141
+ node[name] = value;
142
+ }
143
+ catch (error) {
144
+ /**
145
+ * The CLIENT's rule, applied here so the two halves resolve the same contested state the same
146
+ * way: a getter with NO setter is a refusal — warned by name, the binding ignored, the render
147
+ * carried on, exactly what `init()`'s adoption does — while a setter that THREW is the
148
+ * component's own error and stays one, named against the tag and property rather than as
149
+ * `Cannot set property x of #<Class>`. Diverging here meant one binding produced a page on
150
+ * the client and an empty render server-side.
151
+ */
152
+ let carrier = node;
153
+ let refusable = false;
154
+ while (carrier !== null) {
155
+ const desc = Object.getOwnPropertyDescriptor(carrier, name);
156
+ if (desc !== undefined) {
157
+ refusable = desc.get !== undefined && desc.set === undefined;
158
+ break;
159
+ }
160
+ carrier = Object.getPrototypeOf(carrier);
161
+ }
162
+ if (refusable) {
163
+ if (once('getter-only-prop', `${tag} ${name}`))
164
+ console.warn(ssrWarning(`<${tag}>`, 'getter-only-prop', TWINS.getterOnlyProp(name)));
165
+ return;
166
+ }
167
+ throw own(new TypeError(ssrMisuse('ssr-setter-threw', PROSE['ssr-setter-threw'](tag, name, quoted(thrownMessage(error)))), { cause: error }));
168
+ }
169
+ };
170
+ /** Attribute names written into the statics, so a duplicate can be spotted before a render. */
171
+ /**
172
+ * Preceded by whitespace, so a **tag name** is not counted as an attribute of itself, and allowed to
173
+ * end the string, because the emitted static of an unfinished tag has no `>` yet — `<b hidden` is
174
+ * how `<b hidden ?hidden=${x}>` arrives here, and its bare `hidden` is exactly the duplicate that
175
+ * has to be seen.
176
+ */
177
+ const STATIC_ATTRIBUTE = /\s([a-zA-Z][\w:-]*)(?==|[\s>]|$)/g;
178
+ /**
179
+ * An author's static, ready to sit inside the DOUBLE quotes the server writes around every bound value.
180
+ * Only a `"` can end them; an entity stays an entity, because the browser decodes one identically in any
181
+ * quoting.
182
+ */
183
+ const forDoubleQuotes = (text, quote) => (quote === '"' || !text.includes('"') ? text : text.replaceAll('"', '&#34;'));
184
+ /**
185
+ * Whether this static's LAST character — a `>`, which the caller has checked — ends a start tag that takes a leading
186
+ * line feed (`NEWLINE_TAKERS`). Only that position matters: content written as static text after the tag is parsed
187
+ * alike on both sides, while what the next binding writes there arrives on the client through the DOM, which takes
188
+ * nothing. Such a static gets one `\n` of its own, ALWAYS: the parser takes exactly one, so whatever comes first —
189
+ * a value, an empty one, a list, a nested template's static, the next static — arrives as the client has it, and the
190
+ * render does nothing at all (measured: 28 tag × content shapes, 2026-10-07). One byte per such element.
191
+ *
192
+ * Asked of the scan itself — the static minus its `>`, from a copy of the state before it — so a `<pre>` inside an
193
+ * attribute value, a comment or raw text is never mistaken for one. Whether it is HTML is the full scan's answer,
194
+ * after the `>`: a `<pre>` breaks out of `<svg>`. Plan time only.
195
+ */
196
+ const takesNewline = (text, before) => {
197
+ const at = scanTag(text.slice(0, -1), { ...before, opens: before.opens.slice() });
198
+ return (at.inTag && !at.closing && !(at.inValue && at.quote !== '') && at.comment === '' && NEWLINE_TAKERS.has(at.tagName));
199
+ };
200
+ const compile = (strings, depth) => {
201
+ /**
202
+ * **A template is a tagged template literal's, never data shaped like one.** Template detection is by shape (`strings`),
203
+ * so `JSON.parse('{"strings":["<img src=x onerror=…>"]}')` — a request body, an API field an attacker can make an
204
+ * object — was rendered as MARKUP wherever it was interpolated. A literal's strings array owns a `raw` property, which
205
+ * JSON cannot give an array (and an object that owns one is not an array): the check Lit makes, here on the plan
206
+ * cache's miss, which a forged array always is — so it costs a cached template nothing. A forgery is answered with
207
+ * `null` — the caller renders it as the ordinary object it is — and never a throw: the value is attacker-controlled
208
+ * by definition, and a throw would trade the injection for the whole response.
209
+ */
210
+ if (!isLiteral(strings)) {
211
+ /** Once per process per component (Brian, 2026-10-09); the forgery itself still renders as the object it is. */
212
+ const tag = currentRenderingTag();
213
+ if (once('forged-template', tag))
214
+ console.warn(ssrWarning((tag ? `<${tag}>` : 'the page'), 'forged-template', TWINS.forgedTemplate()));
215
+ return null;
216
+ }
217
+ const parts = [];
218
+ const kinds = [];
219
+ const names = [];
220
+ /**
221
+ * Whether a slot has to scan the open tag for an earlier write of its own name, and the tag it
222
+ * sits in.
223
+ *
224
+ * Both are properties of the *template*, not of a render: an attribute can only be duplicated by
225
+ * the statics around it, by an earlier binding in the same tag, or by a spread — and every one of
226
+ * those is visible here. Computing them per render cost 0.03–0.06 µs on every attribute, boolean
227
+ * and form-property binding, which is 18–68% of what those bindings cost in total. Almost no tag
228
+ * writes a name twice, so almost every one of those scans found nothing.
229
+ */
230
+ const strip = [];
231
+ const owners = [];
232
+ /** Which RAWTEXT element each binding sits inside, `''` when none. See `RAWTEXT`. */
233
+ const raws = [];
234
+ /** Per child binding (sparse): the foreign-content depth it sits at, which a template rendered there starts from. */
235
+ const depths = [];
236
+ /** Per child binding (sparse): whether it sits in a text-only element, where a template is refused (see `serializeValue`). */
237
+ const texts = [];
238
+ /**
239
+ * Whether each slot is an **element position** — inside a tag but not inside an attribute value.
240
+ *
241
+ * `<b title="${x}">` is also a value inside a tag, and it is *not* an element position: the
242
+ * statics carry `title="` and `">` around it and the value is simply written between them. The
243
+ * difference is what the static ends with, so it is settled here rather than guessed at render.
244
+ */
245
+ const elementPositions = [];
246
+ /**
247
+ * Which ELEMENT each slot belongs to — an ordinal that advances when a tag opens. The owner tag
248
+ * NAME cannot tell two sibling `<x-row .item=${…}>`s apart, and component-prop delivery needs
249
+ * to: every slot sharing an ordinal delivers to one instance, per application.
250
+ */
251
+ const elements = [];
252
+ let elementOrdinal = 0;
253
+ /** Names written so far in the tag being built — statics and earlier bindings alike. */
254
+ let written = new Set();
255
+ /** A spread's keys are runtime values, so a tag holding one can never be settled here. */
256
+ let dynamicTag = false;
257
+ let owner = '';
258
+ /** The quote character a binding opened with, to be stripped off the front of the next static. */
259
+ let openQuote = '';
260
+ let wasInTag = false;
261
+ /** Carried across statics — see `scanTag`. */
262
+ let tagState = freshScan(depth);
263
+ /** Per binding: whether a component property's name is a URL sink. */
264
+ const urls = [];
265
+ /**
266
+ * Per attribute-value binding, by binding index (sparse): its attribute's group (shared by every hole in one value), the static
267
+ * written before the value — ready for double quotes — and that static decoded, for the URL check.
268
+ */
269
+ const groups = [];
270
+ const leads = [];
271
+ const decodedLeads = [];
272
+ for (let i = 0; i < strings.length - 1; i++) {
273
+ let part = strings[i];
274
+ if (openQuote && part.startsWith(openQuote))
275
+ part = part.slice(1);
276
+ /**
277
+ * Scanned from the **author's** static, not the trimmed one.
278
+ *
279
+ * `part` has already had a binding's opening quote removed by the `openQuote` handling above, so
280
+ * `?hidden='${x}'` reaches the scanner as `?hidden=` followed by `>bs</b>` — the closing quote
281
+ * gone. The scanner then waits for a `'` that never comes and reads the whole rest of the
282
+ * template as one attribute value, which made every element position after it invisible.
283
+ */
284
+ /**
285
+ * Whether this static ends with such a start tag. The cheap part is written out here, no call: on a cold server a
286
+ * newly compiled function costs its first render more than the check does (measured 2026-10-07). Only a static
287
+ * ending in `>` that continues such a tag, or holds `<pre`, `<lis` or `<tex` in any case, is asked properly —
288
+ * three letters, because one let `<p>`, `<li>`, `<td>` and `<title>` through and every template paid the scan.
289
+ */
290
+ let taker = false;
291
+ const text = strings[i];
292
+ if (text.charCodeAt(text.length - 1) === 62) {
293
+ const open = tagState.inTag ? tagState.tagName : '';
294
+ let maybe = open === 'pre' || open === 'listing' || open === 'textarea';
295
+ for (let at = text.indexOf('<'); !maybe && at !== -1; at = text.indexOf('<', at + 1)) {
296
+ const a = text.charCodeAt(at + 1);
297
+ const b = text.charCodeAt(at + 2);
298
+ const c = text.charCodeAt(at + 3);
299
+ /** `pre`, `lis` or `tex`, each letter in either case. */
300
+ maybe =
301
+ ((a === 112 || a === 80) && (b === 114 || b === 82) && (c === 101 || c === 69)) ||
302
+ ((a === 108 || a === 76) && (b === 105 || b === 73) && (c === 115 || c === 83)) ||
303
+ ((a === 116 || a === 84) && (b === 101 || b === 69) && (c === 120 || c === 88));
304
+ }
305
+ if (maybe)
306
+ taker = takesNewline(text, tagState);
307
+ }
308
+ tagState = scanTag(strings[i], tagState);
309
+ if (taker && (tagState.foreign !== 0 || tagState.inert !== 0))
310
+ taker = false;
311
+ /**
312
+ * **Every question about where this hole sits is answered by that scan** — whether it is inside a tag, which tag,
313
+ * whether a new one opened, and whether the hole is a sigil binding. They used to be answered beside it, by tests
314
+ * on the static's tail (its last `<` against its last `>`, a sigil pattern, a tag-name pattern), which knew nothing
315
+ * of comments, raw text or the tokenizer's names: `<!-- <div .innerHTML=${v}> -->` honored the binding INSIDE the
316
+ * comment, so a `-->` in `v` ended it, and `<textarea><b .innerHTML=${v}>` broke out of the textarea the same way.
317
+ */
318
+ const inTag = tagState.inTag;
319
+ /** `<template>`'s content: inert markup the client never walks, so it never reaches this
320
+ * binding — it neither renders the value nor keeps the attribute holding it. Nor does this.
321
+ */
322
+ const inert = tagState.inert > 0;
323
+ /** A new tag starts wherever this text opens one that is still open at its end; what the previous tag held is irrelevant. */
324
+ const opensTag = inTag && tagState.tagAt !== -1;
325
+ if (opensTag || (!inTag && wasInTag)) {
326
+ written = new Set();
327
+ dynamicTag = false;
328
+ if (opensTag)
329
+ elementOrdinal++;
330
+ }
331
+ wasInTag = inTag;
332
+ /** The tag a binding belongs to, by the name the tokenizer reads — the element's `localName` on the client. */
333
+ owner = inTag && !tagState.closing ? tagState.tagName : '';
334
+ /**
335
+ * Whether this hole is an attribute's WHOLE value as it opens — `name=${…}`, quoted or not, with space around `=`
336
+ * as the tokenizer allows. Only then can it be a sigil or event binding: a hole later in a value (`title="a
337
+ * .x=${…}"`) is part of that value.
338
+ */
339
+ const whole = inTag && tagState.inValue && tagState.opened && tagState.valueStart === strings[i].length;
340
+ /** Offsets are in the author's static; `part` may have lost a leading quote to the binding before it. */
341
+ const shift = strings[i].length - part.length;
342
+ /**
343
+ * Names in the statics are recorded from the text that is actually **emitted**, which is the
344
+ * part with this binding's own name already trimmed off. Scanning the raw part instead counts
345
+ * `title=` — the binding's own name — as a prior write, and in `<b title="a" title=${x}>` the
346
+ * two collapse into one entry, so the real duplicate goes unnoticed.
347
+ */
348
+ const record = (staticText) => {
349
+ if (inTag)
350
+ for (const [, found] of staticText.matchAll(STATIC_ATTRIBUTE))
351
+ written.add(found.toLowerCase());
352
+ };
353
+ /**
354
+ * **A sigil binding** — `.prop`, `?bool`, `@event`, `&ref`, `!live` — is an attribute whose name starts with the
355
+ * sigil and whose whole value is this hole, however it is quoted. The name after the sigil is any name character,
356
+ * as the client's scanner reads it: `._private` and `@_tap` are sigil bindings, and a sigil INSIDE a name is part
357
+ * of it (`data-x.y` is an attribute). A sigil the server does not know is not inert — it would fall through to the
358
+ * attribute path and emit an attribute named `!` — so every sigil is added here in the same pass it is added to
359
+ * the renderer.
360
+ */
361
+ if (whole && SIGILS.has(tagState.attrRaw[0])) {
362
+ /** The space that preceded the binding goes with it, so dropped bindings leave no residue. */
363
+ const before = part.slice(0, nameCut(strings[i], tagState.nameAt) - shift).replace(/ $/, '');
364
+ record(before);
365
+ parts.push(before);
366
+ openQuote = tagState.quote;
367
+ const kind = tagState.attrRaw[0];
368
+ /**
369
+ * Absent after a bare `&=`, which is an element ref with no name — legal: the renderer back-reads the name `&`
370
+ * and maps it to a ref, so the client renders nothing, and so does this. A nameless `.=`, `?=`, `@=` or `!=` has
371
+ * no meaning either, and is dropped the same way.
372
+ */
373
+ const sigilName = tagState.attrRaw.slice(1);
374
+ if (inert) {
375
+ kinds.push(DROPPED);
376
+ }
377
+ else if (kind === '?') {
378
+ kinds.push(BOOLEAN);
379
+ }
380
+ else if ((kind === '.' || kind === '!') && sigilName && owner.includes('-')) {
381
+ /**
382
+ * A property on a COMPONENT tag is neither markup nor a client concern: it is the data the
383
+ * child renders from, so it is delivered to the instance the nested-component scan will
384
+ * render — before `FORM_ATTRIBUTES`, because `.value` on `<my-input>` is that component's
385
+ * prop, not a form control's dirty value. `!name` is here beside `.name` for the same
386
+ * reason it serializes as `.name` on form controls, and because a spread reports `!` keys
387
+ * as properties — the two spellings of one binding must get one answer. Whether the tag is
388
+ * actually registered is a render-time question (the registry fills as modules execute),
389
+ * answered in the case below.
390
+ */
391
+ kinds.push(COMPONENT_PROP);
392
+ urls[kinds.length - 1] = URL_SINK.test(sigilName);
393
+ }
394
+ else if (kind === '.' && CONTENT_PROPS.has(sigilName)) {
395
+ /**
396
+ * `.innerHTML`/`.textContent` on a plain element is the trusted-markup door (`@verajs/renderer`'s property
397
+ * binding): the value is the element's content, written after the open tag. Its foreign depth is the host's
398
+ * INSIDE — the tag's depth, plus one when the host is itself `<svg>`/`<math>` — so a `<style>` in it is read
399
+ * the way the browser will read it. A custom-element host took the `COMPONENT_PROP` branch above.
400
+ */
401
+ kinds.push(CONTENT);
402
+ depths[kinds.length - 1] = tagState.foreign + (owner === 'svg' || owner === 'math' ? 1 : 0);
403
+ }
404
+ else if ((kind === '.' || kind === '!') && isFormProperty(owner, sigilName)) {
405
+ /**
406
+ * `!name` is a **live** property, and still a property: the sigil only changes when the client re-writes it,
407
+ * and a server has nothing to re-write against — so it serializes exactly as `.name` does, and the first
408
+ * paint is right before the client takes over.
409
+ */
410
+ kinds.push(FORM_PROP);
411
+ }
412
+ else {
413
+ kinds.push(DROPPED);
414
+ }
415
+ names.push(sigilName);
416
+ strip.push(dynamicTag || written.has(sigilName.toLowerCase()));
417
+ owners.push(owner);
418
+ raws.push(tagState.rawTag);
419
+ elementPositions.push(false);
420
+ elements.push(elementOrdinal);
421
+ if (sigilName)
422
+ written.add(sigilName.toLowerCase());
423
+ continue;
424
+ }
425
+ openQuote = '';
426
+ /** `onClick=${fn}` — the React-shaped event binding, named as the client names it: a client concern, dropped like `@`. */
427
+ if (whole && /^on[A-Z]/.test(tagState.attrRaw)) {
428
+ const before = part.slice(0, tagState.nameAt - shift).replace(/ $/, '');
429
+ record(before);
430
+ parts.push(before);
431
+ openQuote = tagState.quote;
432
+ kinds.push(DROPPED);
433
+ names.push('');
434
+ strip.push(false);
435
+ owners.push(owner);
436
+ raws.push(tagState.rawTag);
437
+ elementPositions.push(false);
438
+ elements.push(elementOrdinal);
439
+ continue;
440
+ }
441
+ /**
442
+ * **A bound attribute value, in any position** — double-quoted, single-quoted or unquoted, with space
443
+ * around `=`, with statics beside it, or several holes in one value.
444
+ *
445
+ * The client never lets the tokenizer see a value: it joins the attribute's statics and values and calls
446
+ * `setAttribute`. This streamed each position differently instead — a lone unquoted `title=${x}` was
447
+ * quoted, a quoted value was escaped between the author's quotes, and every other shape went out raw
448
+ * and UNQUOTED: `title=pre${x}`, `title=${a}${b}` and `title = ${x}` let a value carrying
449
+ * ` onmouseover=…` end the attribute and start a live handler, while the client rendered one harmless
450
+ * `title`. So every hole in one value shares ONE group, compiled here from `scanTag`'s state: the
451
+ * attribute's head (name, `=`, opening quote, static prefix) and tail (static suffix, closing quote)
452
+ * come off the statics, and the render writes the whole attribute once, always double-quoted — or not
453
+ * at all. Position stops mattering because nothing a value holds can reach the tokenizer.
454
+ */
455
+ if (tagState.inTag && tagState.inValue && (tagState.opened || groups[kinds.length - 1]?.serial === tagState.serial)) {
456
+ const previous = groups[kinds.length - 1];
457
+ let group;
458
+ if (previous !== undefined && previous.serial === tagState.serial) {
459
+ group = previous;
460
+ group.sole = false;
461
+ parts.push('');
462
+ leads[kinds.length] = forDoubleQuotes(part, group.quote);
463
+ decodedLeads[kinds.length] = decodeSchemeReferences(part);
464
+ }
465
+ else {
466
+ const before = part.slice(0, tagState.attrStart - shift);
467
+ const prefix = part.slice(tagState.valueStart - shift);
468
+ const lower = tagState.attrName;
469
+ /** Whether the name is a URL sink, and which kind (captured: from the start; not: item by item). */
470
+ const sink = URL_SINK.exec(lower);
471
+ record(before);
472
+ parts.push(before);
473
+ group = {
474
+ name: tagState.attrRaw,
475
+ /** Everything the render writes before the value: the separating space, the name, `=` and the quote. */
476
+ open: ` ${tagState.attrRaw}="`,
477
+ serial: tagState.serial,
478
+ quote: tagState.quote,
479
+ first: kinds.length,
480
+ last: kinds.length,
481
+ /**
482
+ * Never served (1): inert content, a bound `srcdoc` (it renders its value as a document) and a bound inline
483
+ * handler (`onclick=${…}` runs its value as code). A URL sink refuses `javascript:` (2), and an animation's
484
+ * value refuses it in any `;`-separated item (3) — as the client does. Above 1: the joined value is checked.
485
+ */
486
+ refuse: inert || lower === 'srcdoc' || INLINE_HANDLER.test(lower) ? 1 : sink === null ? 0 : sink[1] ? 2 : 3,
487
+ /** An earlier write of this name in the tag: the client's `setAttribute` replaces it, so it is removed. */
488
+ strip: dynamicTag || written.has(lower),
489
+ /** The WHOLE value is this one binding — the only shape where a nullish value removes the attribute. */
490
+ sole: prefix === '',
491
+ suffix: '',
492
+ decodedSuffix: '',
493
+ };
494
+ written.add(lower);
495
+ leads[kinds.length] = forDoubleQuotes(prefix, group.quote);
496
+ decodedLeads[kinds.length] = decodeSchemeReferences(prefix);
497
+ }
498
+ group.last = kinds.length;
499
+ groups[kinds.length] = group;
500
+ kinds.push(ATTRIBUTE);
501
+ names.push(group.name);
502
+ strip.push(false);
503
+ owners.push(owner);
504
+ raws.push(tagState.rawTag);
505
+ elementPositions.push(false);
506
+ elements.push(elementOrdinal);
507
+ continue;
508
+ }
509
+ record(part);
510
+ /**
511
+ * A binding dropped inside a comment leaves ONE space where it was, so the statics on either side cannot meet as
512
+ * a different token: `<!${…}--!>` read as a bogus comment, ended by its `>`, while the bare join `<!--!>` OPENS a
513
+ * comment that swallowed the page after it; `-${…}->` joined to `-->` and ended a comment early.
514
+ */
515
+ parts.push(tagState.comment !== '' && !inert ? part + ' ' : taker ? part + '\n' : part);
516
+ if (tagState.foreign)
517
+ depths[kinds.length] = tagState.foreign;
518
+ if (tagState.textTag)
519
+ texts[kinds.length] = true;
520
+ /** A binding inside a comment is dropped, as the client drops it — never written into the comment. */
521
+ kinds.push(inert || tagState.comment ? DROPPED : TEXT);
522
+ names.push('');
523
+ strip.push(false);
524
+ owners.push(owner);
525
+ raws.push(tagState.rawTag);
526
+ /** Inside a tag, and not inside an attribute value: `<input ${ref} />`, `<b ${spread(…)}>`. */
527
+ const elementPosition = tagState.inTag && !tagState.inValue;
528
+ /**
529
+ * A TAG-name hole — right after `<` or `</`, or inside a tag name: refused in every build, the twin of the client's
530
+ * development refusal, one message.
531
+ */
532
+ const tagNameHole = tagState.phase === TAG_OPEN || tagState.phase === END_TAG_OPEN || tagState.phase === TAG_NAME;
533
+ if (tagNameHole)
534
+ throw own(new Error(ssrMisuse('tag-hole', TWINS.tagHole())));
535
+ if (elementPosition && !tagNameHole && (NAME_CHAR_BEFORE.test(part) || NAME_CHAR_AFTER.test(strings[i + 1])))
536
+ nameHole(part, strings[i + 1]);
537
+ elementPositions.push(elementPosition);
538
+ elements.push(elementOrdinal);
539
+ /** A spread's keys are unknown until it runs, so its tag can no longer be settled here. */
540
+ if (elementPosition)
541
+ dynamicTag = true;
542
+ }
543
+ let last = strings[strings.length - 1];
544
+ if (openQuote && last.startsWith(openQuote))
545
+ last = last.slice(1);
546
+ parts.push(last);
547
+ /** Each attribute's tail — its static suffix and closing quote — comes off the static after its last hole. */
548
+ for (let i = 0; i < groups.length; i++) {
549
+ const group = groups[i];
550
+ if (group === undefined || group.last !== i)
551
+ continue;
552
+ const next = parts[i + 1];
553
+ /**
554
+ * An unquoted value ends at the tokenizer's whitespace (never `\s`: a `\v` is value text, and cutting there left
555
+ * the rest to open a quote that never closed, losing the element) or `>` — and at a `/>` RIGHT after its last hole, which is the tag's
556
+ * self-close, not value text: the client's scanner keeps the slash out of the value the same way (`<circle
557
+ * r=${r}/>`). Taken as text, it served `r="5/"` and left the element open, nesting the next one inside it.
558
+ */
559
+ let end = group.quote ? next.indexOf(group.quote) : next.startsWith('/>') ? 0 : next.search(/[\t\n\f\r >]/);
560
+ /** A template that ends inside the value: the rest is the suffix, as the client's parser reads it. */
561
+ const closed = end !== -1;
562
+ if (!closed)
563
+ end = next.length;
564
+ const suffix = next.slice(0, end);
565
+ if (suffix !== '')
566
+ group.sole = false;
567
+ group.suffix = forDoubleQuotes(suffix, group.quote);
568
+ group.decodedSuffix = decodeSchemeReferences(suffix);
569
+ parts[i + 1] = next.slice(closed && group.quote ? end + 1 : end);
570
+ }
571
+ /**
572
+ * **A template ends where it began.** The client parses every template on its own, so whatever one leaves open — a
573
+ * comment, a `<style>`, a `<textarea>`, an `<svg>` — the parser closes at its end. The server concatenates, and
574
+ * left open, that state swallowed the PARENT's markup: `${html`<svg>`}<style>${x}</style>` wrote `x` raw inside what
575
+ * the browser parses as SVG, and `${html`<!--`}` let a `-->` in a later raw value end the comment. So the end closes
576
+ * what this template opened, innermost first — the client's own end-of-input rule, read off the statics once. A
577
+ * template that ends INSIDE a tag is refused, in every build: the client's parser drops an unfinished tag whole,
578
+ * which no closer can reproduce, and left open it swallowed the parent's next markup into its attributes. A bare `<`
579
+ * that never started a tag name, as in `a < b`, is text. The client refuses the same templates in development.
580
+ */
581
+ const end = scanTag(strings[strings.length - 1], tagState);
582
+ if (end.inValue || (end.inTag && end.tagName))
583
+ throw own(new Error(ssrMisuse('ssr-unfinished-tag', PROSE['ssr-unfinished-tag']())));
584
+ const closers = closersOf(end);
585
+ if (closers)
586
+ parts[parts.length - 1] += closers;
587
+ /**
588
+ * Dense, so the render loop reads a value at every binding: both are filled sparsely above, and a hole read falls
589
+ * through to the prototype chain on every child binding of every render — measured at about 3% of a server render.
590
+ */
591
+ const plan = {
592
+ parts, kinds, names, strip, owners, raws,
593
+ depths: Array.from(kinds, (_, i) => depths[i] ?? 0),
594
+ texts: Array.from(kinds, (_, i) => texts[i] === true),
595
+ elementPositions, elements, groups, leads, decodedLeads, urls,
596
+ };
597
+ if (depth === 0)
598
+ plans.set(strings, plan);
599
+ else {
600
+ let byDepth = foreignPlans.get(strings);
601
+ if (byDepth === undefined)
602
+ foreignPlans.set(strings, (byDepth = new Map()));
603
+ byDepth.set(depth, plan);
604
+ }
605
+ return plan;
606
+ };
607
+ /**
608
+ * `depth` is the foreign-content depth of the position the template renders into — 0 at the top and in HTML.
609
+ *
610
+ * **Where a template renders decides how its raw text parses, and the template cannot see it.** The browser parses
611
+ * the ONE string this produces, so `html`<svg>${child}</svg>`` puts `child`'s `<style>` inside SVG, where its
612
+ * content is markup, however `child` was written; and an `svg`/`mathml` template is foreign content wherever it
613
+ * goes, because the client parses it inside an `<svg>`/`<math>` wrapper. Scanning each template as though it began
614
+ * in HTML wrote both as raw text — unescaped — and the browser then parsed a value's `<img onerror>` as an element.
615
+ * So a template starts at its position's depth, and at least 1 if it is foreign itself. Erring deep is the safe
616
+ * direction: an `svg` template rendered outside any `<svg>` is HTML to the browser, and its `<style>` then shows
617
+ * the escapes as text — a visible mismatch, never an injection.
618
+ */
619
+ export const serializeTemplate = (template, depth = 0) => {
620
+ const { strings, values } = template;
621
+ /** Absent on core's `html`, and `undefined > 1` is false — the answer wanted; the `!` only lets the comparison be written. */
622
+ if (template['_$litType$'] > 1 && depth === 0)
623
+ depth = 1;
624
+ /**
625
+ * `strings` is any value here, a forgery's included: the cast only names the key the maps hold, and `WeakMap#get`
626
+ * answers `undefined` for a key it could never hold, which sends a forgery on to `compile`'s refusal.
627
+ */
628
+ const { parts, kinds, names, strip, owners, raws, depths, texts, elementPositions, elements, groups, leads, decodedLeads, urls } = (depth === 0 ? plans.get(strings) : foreignPlans.get(strings)?.get(depth)) ??
629
+ compile(strings, depth) ??
630
+ FORGED;
631
+ /**
632
+ * Not a template — data shaped like one (see `compile`): the text a plain object renders as, the client's very
633
+ * constant. Never the forgery's own conversion: JSON can supply a `"toString"` key, and converting through it throws.
634
+ */
635
+ if (parts === undefined)
636
+ return FORGED_TEXT;
637
+ /** The attribute being built: its escaped value so far, and the value the client would join (for the URL check). */
638
+ let attribute = '';
639
+ let joined = '';
640
+ let out = '';
641
+ /**
642
+ * The instances this application is delivering properties to, allocated on the FIRST
643
+ * component-prop slot — `serializeTemplate` is the hot path the public SSR numbers rest on, and
644
+ * a template with no component props (almost all of them) must pay one `null` local and nothing
645
+ * else. `instances` is keyed by element ordinal, so `<x-row .a=${…} .b=${…}>` builds ONE
646
+ * instance for both keys while a list's N applications build N; `mark` is the marker text for a
647
+ * just-built instance, held rather than appended directly because the spread path folds `out`
648
+ * while delivering — each delivering case flushes it into the open tag it is building.
649
+ */
650
+ let adoption = null;
651
+ /**
652
+ * Content that belongs *after* the tag being built rather than inside it — a `<textarea>`'s
653
+ * value, which is text and not an attribute. Written into the next static right after the `>`
654
+ * that closes the tag, replacing whatever the author wrote there, exactly as assigning `.value`
655
+ * does on the client.
656
+ */
657
+ let pendingText = null;
658
+ /** The close tag `insertContent` strips to when flushing `pendingText` — the host whose content it is (`textarea` for a form value). */
659
+ let pendingStrip = 'textarea';
660
+ /**
661
+ * What each `<select>`'s `.value` or `.selectedIndex` asks for, resolved into `<option selected>` after the loop —
662
+ * the options are usually a nested template, so nothing can be decided until the string is whole.
663
+ */
664
+ const selectValues = [];
665
+ for (let i = 0; i < kinds.length; i++) {
666
+ const part = parts[i];
667
+ if (pendingText === null)
668
+ out += part;
669
+ else {
670
+ out += insertContent(part, pendingText, pendingStrip);
671
+ pendingText = null;
672
+ }
673
+ const value = values[i];
674
+ switch (kinds[i]) {
675
+ case TEXT:
676
+ /** A spread rewrites the open tag it sits in, so it is folded rather than appended. */
677
+ if (value !== null && typeof value === 'object' && typeof value._$attrs$ === 'function') {
678
+ /**
679
+ * A spread's property keys deliver exactly as the written form above does — `props()`
680
+ * IS a spread, so this is the surface the headline API arrives through. Lazily: the
681
+ * receiving instance is built on the spread's first property key, so a spread of plain
682
+ * attributes on a component never builds one.
683
+ */
684
+ const componentTag = owners[i].includes('-') && registry.has(owners[i]) ? owners[i] : '';
685
+ const folded = foldSpread(out, owners[i], value._$attrs$(), componentTag === ''
686
+ ? undefined
687
+ : (name, propValue) => {
688
+ adoption ??= { instances: new Map(), mark: '' };
689
+ deliverProperty(claimInstance(adoption, elements[i], componentTag), componentTag, name, propValue);
690
+ });
691
+ out = folded.out;
692
+ if (adoption !== null && adoption.mark !== '') {
693
+ out += adoption.mark;
694
+ adoption.mark = '';
695
+ }
696
+ /** With its own host: a stale `pendingStrip` from an earlier `.textContent` kept the author's content. */
697
+ if (folded.text !== null) {
698
+ pendingText = folded.text;
699
+ pendingStrip = owners[i];
700
+ }
701
+ if (folded.select !== null)
702
+ out += ` ${SELECT_MARK}="${selectValues.push(folded.select) - 1}"`;
703
+ }
704
+ /**
705
+ * An **element-position** expression that is not a spread is a ref — `<input ${myRef} />`,
706
+ * where the renderer hands the element to a function or assigns it to `.value`. It is
707
+ * client state, like `@event`, and has no markup.
708
+ *
709
+ * It used to be stringified into the open tag, so `<input ${ref(null)} />` served
710
+ * `<input [object Object]>` — which the parser then read as two attributes named
711
+ * `[object` and `object]`. A value in this position never has markup; only a spread does.
712
+ */
713
+ else if (elementPositions[i]) {
714
+ /**
715
+ * The space that introduced the binding goes with it, exactly as a dropped sigil binding's
716
+ * does. Leaving it served `<p >r</p>` where the client renders `<p>r</p>` — harmless to a
717
+ * parser, and still a difference between the two halves for something neither of them
718
+ * renders at all.
719
+ */
720
+ out = out.replace(/ $/, '');
721
+ break;
722
+ }
723
+ /**
724
+ * **Raw text is written raw, and its own end tag is neutralized.**
725
+ *
726
+ * A browser does not decode a character reference inside `<style>` or `<script>`, so
727
+ * escaping there protects nothing and corrupts the content: `<style>${'.a > .b'}</style>`
728
+ * served `.a &#62; .b`, a selector that matches nothing, while the client — which sets text
729
+ * through the DOM and never re-parses — rendered `.a > .b`. Every interpolated stylesheet
730
+ * was broken server-side and correct client-side, which is also a hydration divergence.
731
+ *
732
+ * Not escaping means the element's end tag has to be taken out of the value instead, or it
733
+ * closes the element and everything after it parses as markup. `<\/style` is valid CSS and
734
+ * `<\/script` is the canonical form in JavaScript; both render identically and neither is
735
+ * seen by the tokenizer.
736
+ *
737
+ * `<title>` and `<textarea>` are RCDATA, not RAWTEXT — references *are* decoded there — so
738
+ * they keep ordinary escaping, which is what the client produces for them too.
739
+ */
740
+ else if (raws[i])
741
+ out += escapeRawText(serializeValue(value, true), raws[i]);
742
+ else
743
+ out += serializeValue(value, false, depths[i], texts[i]);
744
+ break;
745
+ case ATTRIBUTE: {
746
+ /** Every ATTRIBUTE slot has its group — `compile` sets the two together. */
747
+ const group = groups[i];
748
+ /**
749
+ * ONE conversion, the platform's own (`String`, as `setAttribute` does): the URL check reads the very
750
+ * string that is written, so a value whose `toString` answers differently each time cannot pass the
751
+ * check with one answer and be written with another.
752
+ */
753
+ const text = serializeValue(value, true);
754
+ /** Assembled two ways — one hole that is the whole value, or holes joined with statics — and escaped by one function. */
755
+ if (group.sole) {
756
+ attribute = group.open + escapeHtml(text);
757
+ joined = text;
758
+ }
759
+ else {
760
+ if (group.first === i) {
761
+ attribute = group.open;
762
+ joined = '';
763
+ }
764
+ attribute += leads[i] + escapeHtml(text);
765
+ /** Only a URL sink needs the value the client would join. */
766
+ if (group.refuse > 1)
767
+ joined += decodedLeads[i] + text;
768
+ if (group.last !== i)
769
+ break;
770
+ attribute += group.suffix;
771
+ if (group.refuse > 1)
772
+ joined += group.decodedSuffix;
773
+ }
774
+ /**
775
+ * ONE decision for every shape, written whole or not at all: a sole nullish value removes the attribute,
776
+ * and a bound srcdoc or a `javascript:` URL is refused — as the client decides each of them.
777
+ */
778
+ if ((group.sole && value == null) || group.refuse === 1)
779
+ break;
780
+ if (group.refuse > 1 && (group.refuse === 3 ? SCRIPT_URL_ITEM : SCRIPT_URL).test(joined)) {
781
+ refusedScriptUrl(group.name);
782
+ break;
783
+ }
784
+ if (group.strip)
785
+ out = removeAttribute(out, group.name);
786
+ out += attribute + '"';
787
+ break;
788
+ }
789
+ case BOOLEAN:
790
+ if (strip[i])
791
+ out = removeAttribute(out, names[i]);
792
+ if (value)
793
+ out += ` ${names[i]}=""`;
794
+ break;
795
+ case CONTENT:
796
+ pendingText = serverContent(value, owners[i], names[i], depths[i]);
797
+ pendingStrip = owners[i];
798
+ break;
799
+ case FORM_PROP:
800
+ if (!FORM_ELEMENTS.has(owners[i]))
801
+ break;
802
+ /**
803
+ * A `<textarea>`'s value is its **text content**. `<textarea value="x">` is ignored by
804
+ * every parser, so writing the attribute served an empty control while the client — which
805
+ * sets the property — showed the text. Held until the tag closes, because that is where the
806
+ * content goes; see `pendingText` below.
807
+ */
808
+ /**
809
+ * A `<select>`'s `value` is not an attribute — see `SELECT_MARK`. Marked here and resolved
810
+ * once the options exist; writing ` value="b"` on the tag, which is what this used to do,
811
+ * means nothing to a parser and left the control showing its first option.
812
+ */
813
+ if (owners[i] === 'select' && (names[i] === 'value' || names[i] === 'selectedIndex')) {
814
+ if (strip[i])
815
+ out = removeAttribute(out, names[i]);
816
+ out += ` ${SELECT_MARK}="${selectValues.push(selection(names[i], value)) - 1}"`;
817
+ break;
818
+ }
819
+ if (owners[i] === 'textarea' && names[i] === 'value') {
820
+ /**
821
+ * `null` and `undefined` are **not** the same value here, and treating them as one is what
822
+ * this used to do. `value` carries `[LegacyNullToEmptyString]` in its IDL, so assigning
823
+ * `null` gives `''` while `undefined` goes through the ordinary ToString and gives the text
824
+ * `"undefined"` — measured in Chromium, Firefox and WebKit, since that is the platform's
825
+ * rule and not this package's to guess. A `== null` test collapses them.
826
+ *
827
+ * The booleans used to be emptied too, which disagreed with `<input>` **one branch below**
828
+ * — the same property, on the same rule, serialized by a different branch: `true` served an
829
+ * empty `<textarea>` against the browser's `true`.
830
+ */
831
+ pendingText = value === null ? '' : escapeHtml(value);
832
+ break;
833
+ }
834
+ if (strip[i])
835
+ out = removeAttribute(out, names[i]);
836
+ if (BOOLEAN_FORM_PROPERTIES.has(names[i])) {
837
+ if (value)
838
+ out += ` ${names[i]}=""`;
839
+ }
840
+ else if (value !== null || owners[i] === 'option') {
841
+ /**
842
+ * A string property: `true` is `"true"`, exactly as assigning it to the element gives.
843
+ *
844
+ * Three rules, not one, and they were measured rather than assumed:
845
+ *
846
+ * - `<input>` and `<textarea>` carry `[LegacyNullToEmptyString]`, so `null` means the empty
847
+ * string. Omitting the attribute is how markup says that — a parsed `<input>` with no
848
+ * `value` answers `''`.
849
+ * - `<option>` does **not**. `option.value = null` is the text `"null"` in every engine, and
850
+ * omitting the attribute is worse than wrong there: `option.value` then falls back to the
851
+ * element's own text.
852
+ * - `undefined` is never the empty string on any of them. It is `"undefined"`, which looks
853
+ * like a bug because it *is* one — but it is the client's bug too, and the two sides
854
+ * disagreeing about it is a hydration mismatch on top of it.
855
+ */
856
+ out += ` ${names[i]}="${escapeHtml(value)}"`;
857
+ }
858
+ break;
859
+ case COMPONENT_PROP:
860
+ /**
861
+ * Delivered only when the tag is REGISTERED — a component this process will render, whose
862
+ * server output should come from the same data its client render gets. An unregistered
863
+ * dashed tag (client-only, autoloaded later) is left exactly as before: the tag passes
864
+ * through as markup, the property is the client's to apply, nothing here to receive it.
865
+ * Registration is asked per render, not per plan, because the registry fills as component
866
+ * modules execute.
867
+ */
868
+ if (registry.has(owners[i]) && !(urls[i] && value != null && SCRIPT_URL.test(`${value}`))) {
869
+ adoption ??= { instances: new Map(), mark: '' };
870
+ deliverProperty(claimInstance(adoption, elements[i], owners[i]), owners[i], names[i], value);
871
+ if (adoption.mark !== '') {
872
+ out += adoption.mark;
873
+ adoption.mark = '';
874
+ }
875
+ }
876
+ break;
877
+ /** DROPPED: '@' and '&' and a non-component, non-form '.' or '!': nothing — client concerns. */
878
+ }
879
+ }
880
+ const tail = parts[kinds.length];
881
+ const finished = pendingText === null ? out + tail : out + insertContent(tail, pendingText, pendingStrip);
882
+ return selectValues.length ? resolveSelects(finished, selectValues) : finished;
883
+ };
884
+ /**
885
+ * Puts `text` inside the element the static closes, replacing what the author wrote there.
886
+ *
887
+ * Only `<textarea>` needs this, and only for `.value` — every other form property is an attribute.
888
+ * `<textarea .value=${x}>anything</textarea>` must serve `x`, because that is what the element
889
+ * will hold on the client the moment the property is assigned.
890
+ */
891
+ /**
892
+ * A `<select>` has **no `value` content attribute**. Assigning the property *selects an option*, so
893
+ * the only way markup can express it is `<option selected>` on the matching one — which is what
894
+ * React's server renderer does, and what this does. Lit's SSR drops the binding entirely and serves
895
+ * a control showing the wrong option.
896
+ *
897
+ * The mark is an index into a per-render list rather than the value itself, so nothing has to be
898
+ * escaped on the way in and unescaped on the way out; it is removed again by `resolveSelects`, and
899
+ * removing it is what terminates that loop.
900
+ *
901
+ * `selectedIndex` chooses an option too, by position rather than by value, so it rides the same mark: the list holds
902
+ * a string for `value` and a number for `selectedIndex`. A tag carrying two marks resolves to its LAST, because on the
903
+ * client the later assignment is the one that stands. Two things each guarantee it, so either may change alone: the
904
+ * greedy `[^>]*` in `MARKED_SELECT` reads a tag's last mark, and a pass removes only one mark, so the tag is resolved
905
+ * again (clearing what the previous pass marked) until its last mark is gone.
906
+ */
907
+ const SELECT_MARK = 'data-vm-select';
908
+ /**
909
+ * What a `<select>` binding asks for: the value's string, or the index as the platform converts it — `selectedIndex`
910
+ * is a WebIDL `long`, and `| 0` is exactly its conversion (ToInt32: `'1'` is 1, `null` and `NaN` are 0, 1.7 is 1).
911
+ */
912
+ // eslint-disable-next-line no-bitwise -- ToInt32, exactly the WebIDL `long` conversion described above
913
+ const selection = (name, value) => (name === 'value' ? `${value}` : value | 0);
914
+ const MARKED_SELECT = new RegExp(`<select\\b[^>]*\\s${SELECT_MARK}="(\\d+)"[^>]*>`, 'i');
915
+ const OPTION = /<option\b([^>]*)>([\s\S]*?)<\/option>/gi;
916
+ const OPTION_VALUE = /\bvalue\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
917
+ const SELECTED_ATTR = /(<option\b[^>]*?)\s+selected(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?/gi;
918
+ const NAMED = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
919
+ /**
920
+ * Enough of a decoder to compare an option against a value.
921
+ *
922
+ * Everything this serializer writes is escaped as a numeric reference, and the five named ones are
923
+ * what an author writes by hand. A full entity table would be several kilobytes to decide which
924
+ * `<option>` is selected, and anything it missed would simply fail to match — which is the same
925
+ * outcome as an option that genuinely does not match, and is already a documented divergence.
926
+ */
927
+ const decodeRefs = (text) => text.replace(/&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|(amp|lt|gt|quot|apos));/g, (whole, dec, hex, name) =>
928
+ /** Neither number matched, so the name did. */
929
+ dec ? decodeCodePoint(+dec) : hex ? decodeCodePoint(parseInt(hex, 16)) : NAMED[name] ?? whole);
930
+ /**
931
+ * What an engine reports for `option.value`: the `value` attribute verbatim if there is one, and
932
+ * otherwise the option's text **stripped and collapsed**. Both halves measured in Chromium, Firefox
933
+ * and WebKit — `tests/browser/select-value.test.js` — because the fallback is easy to assume is the
934
+ * raw text, and it is not.
935
+ */
936
+ const optionValue = (attributes, text) => {
937
+ const attribute = OPTION_VALUE.exec(attributes);
938
+ if (attribute)
939
+ return decodeRefs(attribute[1] ?? attribute[2] ?? attribute[3]);
940
+ return decodeRefs(text).replace(/[\t\n\f\r ]+/g, ' ').trim();
941
+ };
942
+ /**
943
+ * Marks the first option matching `wanted`, and clears any `selected` the author wrote.
944
+ *
945
+ * Clearing is not tidiness: a property assignment overrides markup, so `<option selected>` beside a
946
+ * `.value` binding loses on the client and has to lose here too. **First match wins**, which is the
947
+ * engines' rule for duplicate values.
948
+ *
949
+ * When nothing matches, nothing is marked — and that is a divergence markup cannot close. The client
950
+ * leaves `selectedIndex` at `-1` with nothing showing; a parsed `<select>` with no selected option
951
+ * takes its **first**. See the SSR README. An index is the same: one out of range — `-1` included — selects nothing
952
+ * on the client, and marks nothing here.
953
+ */
954
+ const markSelected = (content, wanted) => {
955
+ const cleared = content.replace(SELECTED_ATTR, '$1');
956
+ OPTION.lastIndex = 0;
957
+ let at = 0;
958
+ for (let match = OPTION.exec(cleared); match; match = OPTION.exec(cleared)) {
959
+ if (typeof wanted === 'number' ? at++ !== wanted : optionValue(match[1], match[2]) !== wanted)
960
+ continue;
961
+ const open = match[0].slice(0, match[0].indexOf('>'));
962
+ return (cleared.slice(0, match.index) +
963
+ open.replace(/\s*\/?$/, '') +
964
+ ' selected>' +
965
+ match[0].slice(match[0].indexOf('>') + 1) +
966
+ cleared.slice(match.index + match[0].length));
967
+ }
968
+ return cleared;
969
+ };
970
+ /** Resolves every marked `<select>` once its options are in the string — see `SELECT_MARK`. */
971
+ const resolveSelects = (markup, wanted) => {
972
+ for (let match = MARKED_SELECT.exec(markup); match; match = MARKED_SELECT.exec(markup)) {
973
+ const openTag = match[0].replace(new RegExp(`\\s*${SELECT_MARK}="\\d+"`, 'i'), '');
974
+ const contentStart = match.index + match[0].length;
975
+ const closeAt = markup.toLowerCase().indexOf('</select', contentStart);
976
+ const end = closeAt === -1 ? markup.length : closeAt;
977
+ markup =
978
+ markup.slice(0, match.index) +
979
+ openTag +
980
+ markSelected(markup.slice(contentStart, end), wanted[+match[1]]) +
981
+ markup.slice(end);
982
+ }
983
+ return markup;
984
+ };
985
+ /** The type that makes a classic script inert; written FIRST, so the parser's first-duplicate-wins rule defeats any author `type`. */
986
+ const INERT_TYPE = ' type="text/x-vera-inert"';
987
+ /**
988
+ * **Trusted `innerHTML` markup, made to behave as an `innerHTML` ASSIGNMENT rather than as parsed page markup** —
989
+ * inert, and self-contained. The two parses differ in exactly two ways a served page would otherwise run: a
990
+ * `<script>` executes when the browser parses it from the response but never when assigned through `innerHTML`, and a
991
+ * `<template shadowrootmode>` attaches a shadow root when parsed but not when assigned. Both are neutralized wherever
992
+ * the tokenizer reads a start tag — never inside a comment, an attribute value or raw text, which `innerHTML` does not
993
+ * act on either — so the served page matches the client's assignment, and hydration (which re-assigns) agrees.
994
+ *
995
+ * **The tags come from `scanTag`, the scan every template gets.** This used to run its own mini-tokenizer, and the two
996
+ * drifted: it read a quote inside an attribute NAME as opening a value, so `<b x"><script>` served live, and it
997
+ * skipped `<style>` content inside `<svg>`, where it is markup, so `<svg><style><script>` served live. Reading a tag
998
+ * where the browser does not is only ever safe in one direction — over-neutralizing a `<script` that was text makes
999
+ * an inert thing inert — and `scanTag` errs that way wherever it is deliberately incomplete (see its foreign depth).
1000
+ *
1001
+ * Whatever the markup leaves open is closed, so it cannot reach the host's parent: its comment, raw-text element and
1002
+ * svg/math/noscript/template (`closersOf`). An UNFINISHED tag is dropped, as an assignment's parser drops it at the
1003
+ * end of input — served, it swallowed the page's next markup into its attributes. A `<` or `</` that never started a
1004
+ * tag is text, written escaped, so the host's own end tag cannot become the rest of it.
1005
+ */
1006
+ const fortify = (markup, depth) => {
1007
+ const edits = [];
1008
+ const end = scanTag(markup, freshScan(depth), edits);
1009
+ let stop = markup.length;
1010
+ let tail = '';
1011
+ if (end.phase === TAG_OPEN || end.phase === END_TAG_OPEN) {
1012
+ stop = end.tagAt;
1013
+ tail = '&lt;' + markup.slice(stop + 1);
1014
+ }
1015
+ else if (end.inTag) {
1016
+ stop = end.tagAt;
1017
+ /** An unfinished END tag of the raw-text element it was ending leaves that element open — so it is closed. */
1018
+ if (end.closing && end.foreign === 0 && (RAWTEXT.has(end.tagName) || TEXT_ONLY.has(end.tagName)))
1019
+ tail = `</${end.tagName}>`;
1020
+ }
1021
+ let out = '';
1022
+ let from = 0;
1023
+ for (let i = 0; i < edits.length && edits[i] < stop; i += 2) {
1024
+ const at = edits[i];
1025
+ out += markup.slice(from, at) + (edits[i + 1] === EDIT_INERT ? INERT_TYPE : 'data-vera-');
1026
+ from = at;
1027
+ }
1028
+ return out + markup.slice(from, stop) + tail + closersOf(end);
1029
+ };
1030
+ /**
1031
+ * The content a `.innerHTML`/`.textContent` binding writes after the host's open tag. `innerHTML` is
1032
+ * `[LegacyNullToEmptyString]` (so `null` is `''` but `undefined` is `"undefined"`); `textContent` is nullable (both
1033
+ * are `''`) — measured against a browser, not guessed. The host decides escaping: a RAWTEXT host (`<style>`,
1034
+ * `<script>`) neutralizes its own close tag and is otherwise raw; a text-only or foreign host, and any
1035
+ * `textContent`, is escaped text; only `innerHTML` on an ordinary HTML host is live markup, made inert first.
1036
+ */
1037
+ const serverContent = (value, owner, property, depth) => {
1038
+ const text = value === null || (value === undefined && property === 'textContent') ? '' : `${value}`;
1039
+ if (RAWTEXT.has(owner))
1040
+ return escapeRawText(text, owner);
1041
+ if (property === 'textContent' || TEXT_ONLY.has(owner) || owner === 'noscript' || depth > 0)
1042
+ return escapeHtml(text);
1043
+ return fortify(text, depth);
1044
+ };
1045
+ const insertContent = (staticText, text, strip) => {
1046
+ const close = staticText.indexOf('>');
1047
+ if (close === -1)
1048
+ return staticText;
1049
+ const rest = staticText.slice(close + 1);
1050
+ const end = rest.toLowerCase().indexOf('</' + strip);
1051
+ /** One line feed for the parser to take, always — the client sets this content through the DOM (see `takesNewline`). */
1052
+ const guard = NEWLINE_TAKERS.has(strip) ? '\n' : '';
1053
+ return staticText.slice(0, close + 1) + guard + text + (end === -1 ? rest : rest.slice(end));
1054
+ };
1055
+ /**
1056
+ * Fold resolved spread bindings into the tag being built, mirroring what the client does.
1057
+ *
1058
+ * Appending is not enough, and the difference is a correctness bug rather than a nicety.
1059
+ * `<input type="text" ${spread({ type: 'number' })}>` appends a second `type`, and an HTML parser
1060
+ * keeps the **first** duplicate — so the server would render `type="text"` while the client, where
1061
+ * `setAttribute` overwrites, renders `type="number"`. Same template, two answers, and a hydration
1062
+ * mismatch between them.
1063
+ *
1064
+ * So a spread key removes any attribute of that name already written into the open tag before
1065
+ * adding its own — including when it adds nothing, because `?disabled: false` and `id: null` both
1066
+ * *remove* on the client and must remove here too. Kinds that never touch attributes client-side
1067
+ * (events, non-form properties) leave the tag alone.
1068
+ *
1069
+ * Splitting on the last `<` is safe: attribute values are escaped, so no raw `<` can appear inside
1070
+ * one.
1071
+ */
1072
+ /**
1073
+ * Removes an attribute already written into the open tag being built, so the last write wins.
1074
+ *
1075
+ * An HTML parser keeps the **first** of a duplicate pair; `setAttribute` on the client overwrites,
1076
+ * so the **last** wins there. `<b title="a" title=${x}>` therefore showed `a` on a server-rendered
1077
+ * page and `b` in the browser — the same disagreement `foldSpread` was written to fix for spreads,
1078
+ * which is where this logic came from. It applies to anything that writes a name into the tag.
1079
+ */
1080
+ /**
1081
+ * One pattern per attribute name, built once. `new RegExp` per binding was 16% of a 100-row render.
1082
+ */
1083
+ const removalPatterns = new Map();
1084
+ /**
1085
+ * The name is **escaped** before it becomes a pattern. A spread's keys are runtime data, and an
1086
+ * attribute name may legally contain regular-expression metacharacters — `a|b`, `a.b`, `a*` are all
1087
+ * names `setAttribute` accepts — so interpolating one raw built a pattern that matched something
1088
+ * else entirely. `a|b` compiled to an alternation and removed text nowhere near the attribute it
1089
+ * named.
1090
+ */
1091
+ const escapeForPattern = (name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1092
+ const removalPattern = (name) => {
1093
+ let pattern = removalPatterns.get(name);
1094
+ if (!pattern)
1095
+ removalPatterns.set(name, (pattern = new RegExp(`\\s${escapeForPattern(name)}(=("[^"]*"|'[^']*'|[^\\s>]*))?`, 'i')));
1096
+ return pattern;
1097
+ };
1098
+ /**
1099
+ * A name that cannot be written into a tag safely.
1100
+ *
1101
+ * A spread's keys are the one part of a template that is runtime data — that is what the module is
1102
+ * for — and they were interpolated into the open tag with no check at all, while every *value*
1103
+ * around them was escaped. A key carrying a quote or a `>` therefore closed the attribute, or the
1104
+ * element:
1105
+ *
1106
+ * spread({ 'x><script>alert(1)</script': '1' })
1107
+ * -> <b x><script>alert(1)</script="1">x</b>
1108
+ *
1109
+ * The set is the HTML attribute-name restriction — control characters, whitespace, `"`, `'`, `>`,
1110
+ * `/`, `=` — plus `<` and a backtick, which the specification permits and no real name uses.
1111
+ *
1112
+ * It is deliberately **stricter than `setAttribute`**, which was measured in Chromium and accepts
1113
+ * `"`, `'` and `<` while rejecting whitespace, `>`, `=`, `/` and NUL. A name the platform accepts
1114
+ * but markup cannot carry is unusable in a framework that server-renders, so `@verajs/renderer/spread`
1115
+ * applies this same rule client-side and the two sides agree on every key rather than one of them
1116
+ * quietly serving different markup.
1117
+ *
1118
+ * The control-character range is the point of the rule, not a mistake in it: a name carrying one
1119
+ * is exactly what must never reach markup.
1120
+ */
1121
+ // eslint-disable-next-line no-control-regex
1122
+ export const UNSAFE_ATTRIBUTE_NAME = /^$|[\s"'>/=<`]|[\u0000-\u001f\u007f]/;
1123
+ /**
1124
+ * Strips one attribute out of an open tag, and the one place that knows how.
1125
+ *
1126
+ * `foldSpread` had its own copy of this pattern, character for character — so a fix to one was a
1127
+ * fix to one. It also rebuilt the pattern on every key of every spread, which is the per-render
1128
+ * work `tests/ssr-serializer-work.test.mjs` exists to refuse.
1129
+ */
1130
+ const stripAttribute = (tag, name) =>
1131
+ /**
1132
+ * Almost no tag carries the name twice, and a substring search settles that far faster than a
1133
+ * pattern match does. Case-insensitive to match the pattern it guards, which HTML requires.
1134
+ */
1135
+ tag.toLowerCase().includes(name.toLowerCase()) ? tag.replace(removalPattern(name), '') : tag;
1136
+ const removeAttribute = (out, name) => {
1137
+ const tagStart = out.lastIndexOf('<');
1138
+ if (tagStart === -1)
1139
+ return out;
1140
+ return out.slice(0, tagStart) + stripAttribute(out.slice(tagStart), name);
1141
+ };
1142
+ const foldSpread = (out,
1143
+ /** The tag the spread sits in, as the template's scan named it (see `compile`). */
1144
+ owner, entries, deliverProp) => {
1145
+ const tagStart = out.lastIndexOf('<');
1146
+ let tag = out.slice(tagStart);
1147
+ let added = '';
1148
+ /** A `<textarea>`'s value is its text content, so a `.value` key here is not an attribute. */
1149
+ let text = null;
1150
+ /** A `<select>`'s value is not an attribute either; the caller marks the tag — see `SELECT_MARK`. */
1151
+ let select = null;
1152
+ const isFormElement = FORM_ELEMENTS.has(owner);
1153
+ for (const [kind, name, value] of entries) {
1154
+ /**
1155
+ * A property key on a rendered component tag is handed to the caller's delivery — the same
1156
+ * door the written `.prop=${…}` form takes, because `props()` IS a spread and a key must mean
1157
+ * the same thing in both spellings. The callback exists only when the owner is a registered
1158
+ * component; everywhere else the key falls through to the rules below unchanged.
1159
+ */
1160
+ if (kind === 'p' && deliverProp !== undefined) {
1161
+ deliverProp(name, value);
1162
+ continue;
1163
+ }
1164
+ const serializes = kind === 'a' || kind === 'b' || (kind === 'p' && isFormElement && isFormProperty(owner, name));
1165
+ if (!serializes)
1166
+ continue;
1167
+ /**
1168
+ * Dropped, and dropped **before** anything is done with the name — `stripAttribute` compiles it
1169
+ * into a pattern, so an unchecked name is a second way in.
1170
+ *
1171
+ * Silent here on purpose. A key that reaches this is either a mistake, which the identical check
1172
+ * in `@verajs/renderer/spread` reports in development where the author will see it, or it is
1173
+ * hostile — and a server that logs a line per hostile key hands an attacker the log file.
1174
+ */
1175
+ if (UNSAFE_ATTRIBUTE_NAME.test(name))
1176
+ continue;
1177
+ /** Quoted, single-quoted, unquoted, or valueless — whatever the template author wrote. */
1178
+ tag = stripAttribute(tag, name);
1179
+ /**
1180
+ * A `<textarea>`'s `.value` is its **content**, exactly as it is for a written binding — the
1181
+ * attribute this would otherwise write is ignored by every parser, so the control arrived empty
1182
+ * while the client, which sets the property, showed the text. The written form was fixed and
1183
+ * this one was not: a spread key means what the written binding means, always.
1184
+ */
1185
+ if (kind === 'p' && owner === 'select' && (name === 'value' || name === 'selectedIndex')) {
1186
+ /** A spread key means what the written binding means, always — see `SELECT_MARK`. */
1187
+ select = selection(name, value);
1188
+ continue;
1189
+ }
1190
+ if (kind === 'p' && owner === 'textarea' && name === 'value') {
1191
+ text = value === null ? '' : escapeHtml(value);
1192
+ continue;
1193
+ }
1194
+ /**
1195
+ * Same coercions as a written binding, kind by kind — which is the contract, and which this had
1196
+ * only approximately.
1197
+ *
1198
+ * A **boolean** is truthiness, and so are `checked` and `selected`. A plain **attribute** takes
1199
+ * anything that is not nullish, `false` included: `String(false)` is `"false"`, which is what
1200
+ * `setAttribute` writes and what the written form already emitted. Treating `false` as removal
1201
+ * for every kind meant `${spread({ title: false })}` dropped the attribute while
1202
+ * `title=${false}` kept it — the same value, two answers, from the two spellings of one binding.
1203
+ */
1204
+ if (kind === 'b' || (kind === 'p' && BOOLEAN_FORM_PROPERTIES.has(name))) {
1205
+ if (value)
1206
+ added += ` ${name}=""`;
1207
+ }
1208
+ else if (kind === 'p') {
1209
+ /**
1210
+ * **A string form property and a plain attribute are no longer the same rule**, which is why
1211
+ * this branch split. An attribute is removed by either nullish value — the renderer's own
1212
+ * documented behavior, matching lit, on both sides. A `value` property is not: its IDL carries
1213
+ * `[LegacyNullToEmptyString]` on `<input>` and `<textarea>`, so `null` alone means the empty
1214
+ * string, `undefined` is the text `"undefined"`, and `<option>` has neither rule and takes
1215
+ * `"null"`. Written and spread must agree about all of it —
1216
+ * `tests/ssr-spread-equivalence.test.mjs` is what caught this one, and it caught it the same
1217
+ * afternoon the written form was corrected.
1218
+ */
1219
+ if (value !== null || owner === 'option')
1220
+ added += ` ${name}="${escapeHtml(value)}"`;
1221
+ }
1222
+ else if (value != null) {
1223
+ /**
1224
+ * A plain attribute takes anything not nullish and is removed by either nullish value.
1225
+ * `false` is `"false"` and `true` is `"true"`, because that is what `setAttribute` produces.
1226
+ */
1227
+ added += ` ${name}="${escapeHtml(serializeValue(value, true))}"`;
1228
+ }
1229
+ }
1230
+ /**
1231
+ * The element-position slot already carries the separating space, so the first addition drops its
1232
+ * own. When a spread contributes nothing — every key nullish, or all of them client concerns —
1233
+ * that space is left dangling before the `>`, which the parser ignores and which is still a byte
1234
+ * in every response and untidy in a view-source.
1235
+ */
1236
+ return {
1237
+ out: out.slice(0, tagStart) + (added ? tag + added.slice(1) : tag.replace(/ $/, '')),
1238
+ /** Written into the next static, after the `>` that closes this tag — see `insertContent`. */
1239
+ text,
1240
+ select,
1241
+ };
1242
+ };
1243
+ /**
1244
+ * **Out of line on purpose: `serializeValue` must stay under V8's inlining budget.** It is inlined into
1245
+ * `serializeTemplate`'s per-binding loop only while its bytecode is at most 460 bytes (`--max-inlined-bytecode-size`), and
1246
+ * it sat at 455: the DOM-node case (2026-10-09) took it to 467 and cost 3.6% steady on renders that never reach the
1247
+ * case — any statement did (a never-taken branch alone measured +4.0%). A refusal's error construction is the cheapest
1248
+ * thing to move out: it runs once, at the throw.
1249
+ */
1250
+ const refuseTemplateInText = () => {
1251
+ throw own(new Error(ssrMisuse('ssr-template-in-text', PROSE['ssr-template-in-text']())));
1252
+ };
1253
+ /**
1254
+ * **A child value that applies itself (`_$child$`) renders on a server what it would show FIRST on a client** (2026-10-26,
1255
+ * found by `@verajs/renderer/until`'s server row: every such value served `[object Object]`). The applier runs against a
1256
+ * server part whose `_$commit$` keeps what it commits; the last SYNCHRONOUS commit is served, as the client's first
1257
+ * frame shows it. A commit that arrives later (a promise settling) lands on a part already served and dropped. Out of
1258
+ * line: `serializeValue` sits near V8's inlining budget (`tests/ssr-inlining-budget.test.mjs`).
1259
+ */
1260
+ const serializeChild = (value, depth, text) => {
1261
+ let committed;
1262
+ value._$child$.call(value, { _$commit$: (next) => { committed = next; }, $R: null }, undefined, false);
1263
+ return serializeValue(committed, false, depth, text);
1264
+ };
1265
+ export const serializeValue = (value, raw = false, depth = 0, text = false) => {
1266
+ /**
1267
+ * Only `null` and `undefined` are empty, exactly as on the client — `false` and `0` render.
1268
+ * `false` used to serialize as empty here, which made `${cond && 'x'}` emit nothing on the server
1269
+ * and the text `false` in the browser: a silent content difference on a static page, and a full
1270
+ * re-render on a hydrated one.
1271
+ */
1272
+ if (value == null)
1273
+ return '';
1274
+ /**
1275
+ * **An attribute stringifies exactly as the platform does, and nothing else.**
1276
+ *
1277
+ * A child position renders a value — a template becomes markup, an array renders every item, a
1278
+ * function is client state and disappears. An attribute does none of that: it goes through
1279
+ * `setAttribute`, which is `String(value)` and only that. The two are different rules and this
1280
+ * had one of them.
1281
+ *
1282
+ * Measured against a browser, every one of these disagreed: `[1, 2]` served `12` against `1,2`
1283
+ * (arrays have their own `toString`), a `Set` served `1,2` against `[object Set]`, a function
1284
+ * served nothing against its own source, and a **template served its markup into an attribute
1285
+ * value** against `[object Object]`. Escaped, so not an injection — and still a completely
1286
+ * different page before and after hydration.
1287
+ */
1288
+ if (raw)
1289
+ return `${value}`;
1290
+ /**
1291
+ * Loops, never `map` with an arrow: an arrow capturing `depth`/`text` makes V8 heap-allocate a context on EVERY call of
1292
+ * this function, whichever branch runs — measured at about 5% of a server render.
1293
+ */
1294
+ if (Array.isArray(value)) {
1295
+ let out = '';
1296
+ for (let i = 0; i < value.length; i++)
1297
+ out += serializeValue(value[i], false, depth, text);
1298
+ return out;
1299
+ }
1300
+ if (typeof value === 'function')
1301
+ return '';
1302
+ if (typeof value === 'object') {
1303
+ /** Template-shaped (core's html, by shape) recurses. `keyed()` mutates one, so it arrives here. */
1304
+ /**
1305
+ * Inside `<textarea>`, `<title>` and the other text-only elements a template is refused: their content is text to
1306
+ * the browser, where the client's elements are never shown, and a template's markup there is the one way a value
1307
+ * can CLOSE the element — `${html`</textarea>`}` — and turn the statics after it into unchecked markup.
1308
+ */
1309
+ if (value.strings) {
1310
+ if (text && isLiteral(value.strings))
1311
+ refuseTemplateInText();
1312
+ return serializeTemplate(value, depth);
1313
+ }
1314
+ /**
1315
+ * `hold(result)` is `{ $h: result }` — a client-renderer construct that keeps the DOM of a
1316
+ * toggled-away subtree alive so form values and scroll positions survive the round trip. There
1317
+ * is no previous DOM on a server, so the wrapper means nothing here and the template inside it
1318
+ * means everything.
1319
+ *
1320
+ * It used to fall through to `String(value)` and serve the text `[object Object]` into the
1321
+ * page. `keyed()` works because it mutates the template and hands the same object back; `hold`
1322
+ * wraps one, and nothing unwrapped it.
1323
+ */
1324
+ if (value.$h)
1325
+ return serializeValue(value.$h, raw, depth, text);
1326
+ /**
1327
+ * A spread (`@verajs/renderer/spread`) at element position. It hands back resolved bindings and this
1328
+ * decides what reaches markup: attributes and truthy booleans do, form properties do because
1329
+ * hydration reads them back, and events and other properties are client state. Escaping happens
1330
+ * here and only here — principle #8 puts it at the render boundary, not at the source.
1331
+ */
1332
+ if (typeof value._$attrs$ === 'function')
1333
+ return '';
1334
+ if (typeof value._$child$ === 'function')
1335
+ return serializeChild(value, depth, text);
1336
+ /**
1337
+ * **A DOM node writes nothing** (2026-10-09). The client inserts the node itself, and hydration's contract is that
1338
+ * the server rendered nothing for it — the renderer README's "the one thing the server cannot have rendered", which
1339
+ * adoption relies on to keep everything around it. This fell through to `String(value)` and served
1340
+ * `[object EventTarget]` into the page, which the client then refused as markup the template does not describe:
1341
+ * junk on the static page AND the whole container's adoption discarded. Before the iterable test, so a fragment
1342
+ * (whose children are a node list) never reads as a list.
1343
+ */
1344
+ if (value instanceof NodeBase)
1345
+ return '';
1346
+ /**
1347
+ * An iterable renders its entries, exactly as the client's child position does — a `Set` or a
1348
+ * `Map` reaching a template is not obviously deliberate, but the two sides have to agree about
1349
+ * it or hydration is discarded.
1350
+ */
1351
+ if (typeof value[Symbol.iterator] === 'function') {
1352
+ let out = '';
1353
+ for (const entry of value)
1354
+ out += serializeValue(entry, false, depth, text);
1355
+ return out;
1356
+ }
1357
+ /**
1358
+ * Everything else falls through to `String(value)`, which is what the client does.
1359
+ *
1360
+ * This used to return `''` for any object that was not template-shaped, and the client has
1361
+ * never agreed: a `Date` rendered its full date string there and nothing here, an object with a
1362
+ * `toString` rendered its text, a `Promise` rendered `[object Promise]`. Whether any of those is
1363
+ * a *sensible* thing to interpolate is beside the point — the two sides disagreeing is a silent
1364
+ * hydration mismatch, and matching junk is worth more than differing junk.
1365
+ *
1366
+ * A DOM node is the one exception, and it cannot occur: the server has no document to have
1367
+ * built one.
1368
+ */
1369
+ }
1370
+ /** `raw` cannot be true here — it returned at the top of the function. */
1371
+ return escapeHtml(value);
1372
+ };