@verajs/ssr 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { escapeHtml } from './shim.js';
1
+ import { escapeHtml, escapeRawText } from './shim.js';
2
2
 
3
3
  /**
4
4
  * The vera-native template serializer: flattens core's `html` template objects to markup with
@@ -22,8 +22,75 @@ import { escapeHtml } from './shim.js';
22
22
  /** `.prop` bindings whose server-side truth belongs in an attribute. */
23
23
  const FORM_ATTRIBUTES = ['value', 'checked', 'selected'];
24
24
 
25
- const SIGIL_TAIL = /([.?@&])([a-zA-Z][\w-]*)=("?)$/;
26
- const PLAIN_ATTRIBUTE_TAIL = /[a-zA-Z][\w-]*=$/;
25
+ /**
26
+ * `checked` and `selected` are **boolean** properties; `value` is a string one.
27
+ *
28
+ * The element coerces on assignment, so `.checked=${0}` leaves a browser with `checked === false`
29
+ * while `.value=${0}` leaves it with `"0"`. All three were treated as string-ish here — present
30
+ * unless nullish or exactly `false` — so every falsy-but-not-false value (`0`, `''`, `NaN`) served
31
+ * a **ticked** checkbox against a browser's unticked one, and hydration then had to throw the
32
+ * server's markup away to correct it.
33
+ */
34
+ const BOOLEAN_FORM_PROPERTIES = new Set(['checked', 'selected']);
35
+
36
+ /**
37
+ * …and the elements where that is true.
38
+ *
39
+ * Mirroring `.value` to an attribute exists so hydration can read form state back out of the
40
+ * markup, which only means anything on a form control. Applied to every element, `.value` on a
41
+ * `<b>` wrote `value="…"` server-side where the client sets a plain JS property and no attribute at
42
+ * all — a difference in the rendered DOM for no benefit. Anywhere else a `.prop` is client state,
43
+ * which is what it already was.
44
+ */
45
+ const FORM_ELEMENTS = new Set(['input', 'textarea', 'select', 'option']);
46
+
47
+ /** The name of the tag currently being built, read back out of the markup so far. */
48
+ const openTagName = (out) => {
49
+ const start = out.lastIndexOf('<');
50
+ return start === -1 ? '' : (/^<([a-z][\w-]*)/.exec(out.slice(start))?.[1] ?? '');
51
+ };
52
+
53
+ /**
54
+ * A sigil binding, however the author quoted it — `"`, `'`, or not at all.
55
+ *
56
+ * Only the double-quoted and unquoted forms were recognised, and the client supports all three
57
+ * because it hands the markup to the platform's parser. So `<input .value='${v}' />` set a property
58
+ * in the browser and emitted a literal attribute named `.value` on the server; `?hidden='${true}'`
59
+ * hid the element on one side and printed `?hidden='true'` on the other. Visible difference on a
60
+ * static page, guaranteed mismatch on a hydrated one.
61
+ */
62
+ /**
63
+ * `!name` is here alongside `.name` because a **live** property is still a property: the sigil only
64
+ * changes *when the client re-writes it*, and a server has nothing to re-write against. It is
65
+ * serialized exactly as `.name` is, so the first paint is right and the client takes over.
66
+ *
67
+ * A sigil the server does not know is not inert — it falls through to the plain-attribute path and
68
+ * emits `! checked="true"`, which is an attribute named `!` and a second one beside it. That is why
69
+ * every sigil has to be added here in the same pass it is added to the renderer.
70
+ */
71
+ /**
72
+ * A sigil binding's tail, as it appears at the end of the static before the value.
73
+ *
74
+ * The name is **optional after `&`**, and only after `&`: `&=${ref}` is a legal element ref with no
75
+ * name at all — the renderer's scanner back-reads the name `&`, and `AttrPart` maps that to a ref.
76
+ * The client therefore drops it and renders nothing, while this pattern did not match it and left
77
+ * `&=` in the tag with the value stringified after it: `<p &=[object Object]>`, which is malformed
78
+ * markup that also prints the object.
79
+ *
80
+ * The name is optional for all five rather than only `&`, which costs nothing: a nameless `.=`,
81
+ * `?=`, `@=` or `!=` has no meaning either, and dropping such a binding is a better answer than
82
+ * writing it into the tag with its value stringified beside it.
83
+ */
84
+ const SIGIL_TAIL = /([.?@&!])([a-zA-Z][\w:-]*)?=(["']?)$/;
85
+
86
+ /** `onClick=${fn}` — the React-shaped event binding, quoted the same three ways. */
87
+ const EVENT_TAIL = /on[A-Z][\w:-]*=(["']?)$/;
88
+
89
+ /**
90
+ * An **unquoted** plain attribute, which is the only one that needs quotes adding. A quoted one
91
+ * carries its quotes in the statics either side, so the value is just escaped text between them.
92
+ */
93
+ const PLAIN_ATTRIBUTE_TAIL = /[a-zA-Z][\w:-]*=$/;
27
94
 
28
95
  /** Slot kinds: text, boolean, form-prop, dropped binding, plain attribute. */
29
96
  const TEXT = 0;
@@ -35,84 +102,567 @@ const ATTRIBUTE = 4;
35
102
  /** strings identity -> { parts, kinds, names } — computed once per call site, ever. */
36
103
  const plans = new WeakMap();
37
104
 
105
+ /**
106
+ * Whether the text so far leaves us inside an open tag — the question every sigil test below
107
+ * silently assumed the answer to.
108
+ *
109
+ * Without it a slot was classified by what the static happened to *end* with, wherever it sat.
110
+ * `html\`<p>total=${n}</p>\`` is text, but ends in `total=`, so it was written as an unquoted
111
+ * attribute and the server produced `<p>total="5"</p>` against the client's `<p>total=5</p>` — a
112
+ * visible difference on a static page and a discarded hydration on a live one. The client never had
113
+ * the bug because it hands the markup to the platform's parser, which knows where it is.
114
+ *
115
+ * A raw `<` in text (`a < b`) reads as an open tag here, as it does to a lenient HTML parser in
116
+ * some positions; escape it, as HTML has always asked.
117
+ */
118
+ const closesTag = (text, inTag) => {
119
+ const open = text.lastIndexOf('<');
120
+ const close = text.lastIndexOf('>');
121
+ if (open > close) return true;
122
+ if (close > open) return false;
123
+ return inTag;
124
+ };
125
+
126
+ /**
127
+ * Where a static leaves us: inside a tag, and if so, inside an attribute **value**.
128
+ *
129
+ * The two are different questions and only the second separates `<input ${ref} />` from
130
+ * `<b class="a ${x} c">`. Both are values inside a tag; only the first is an *element position*,
131
+ * where the renderer hands the element to a ref or a spread and there is no markup to write. The
132
+ * second is text between two halves of an attribute the statics already carry.
133
+ *
134
+ * A tail test cannot answer it, because the quote that opened the value may be several statics
135
+ * back — `class="a ` ends in a space and is still inside a value. So the state is carried, one
136
+ * character at a time, and only at compile time: this runs once per template, ever.
137
+ */
138
+ /**
139
+ * The two **RAWTEXT** elements. A browser does not decode a character reference inside either, so
140
+ * escaping their content does not protect anything and does corrupt it — `<style>` gets `.a &#62; .b`
141
+ * for `.a > .b`, a selector that matches nothing, and a `<script>` gets broken source.
142
+ *
143
+ * `<title>` and `<textarea>` are **RCDATA**, not RAWTEXT: references *are* decoded there, so those
144
+ * two keep ordinary escaping, which is also what the client produces. They are deliberately not in
145
+ * this set.
146
+ */
147
+ const RAWTEXT = new Set(['style', 'script']);
148
+
149
+ const scanTag = (text, state) => {
150
+ let { inTag, inValue, quote, rawTag, tagName, naming } = state;
151
+ for (let i = 0; i < text.length; i++) {
152
+ const character = text[i];
153
+ /**
154
+ * Inside `<style>` or `<script>` nothing is markup until that element's own end tag, so the
155
+ * attribute machinery below must not run — and a binding here is **raw text**, which the render
156
+ * pass has to know about.
157
+ */
158
+ if (rawTag) {
159
+ const close = '</' + rawTag;
160
+ if (
161
+ character === '<' &&
162
+ text.slice(i, i + close.length).toLowerCase() === close &&
163
+ (i + close.length >= text.length || /[\s/>]/.test(text[i + close.length]))
164
+ ) {
165
+ i += close.length - 1;
166
+ rawTag = '';
167
+ inTag = true;
168
+ tagName = '';
169
+ naming = false;
170
+ }
171
+ continue;
172
+ }
173
+ if (inValue) {
174
+ /** An unquoted value ends at whitespace or the tag's own `>`. */
175
+ if (quote ? character === quote : /[\s>]/.test(character)) {
176
+ inValue = false;
177
+ if (!quote && character === '>') inTag = false;
178
+ quote = '';
179
+ }
180
+ continue;
181
+ }
182
+ if (!inTag) {
183
+ if (character === '<') {
184
+ inTag = true;
185
+ /** Collected as it is scanned, so a tag split across two statics keeps its name. */
186
+ tagName = '';
187
+ naming = true;
188
+ }
189
+ continue;
190
+ }
191
+ if (character === '>') {
192
+ inTag = false;
193
+ /** A self-closing tag has no content to be raw, and a closing tag opens nothing. */
194
+ if (text[i - 1] !== '/' && RAWTEXT.has(tagName)) rawTag = tagName;
195
+ tagName = '';
196
+ naming = false;
197
+ } else if (character === '=') {
198
+ naming = false;
199
+ let next = i + 1;
200
+ while (next < text.length && /\s/.test(text[next])) next++;
201
+ quote = text[next] === '"' || text[next] === "'" ? text[next] : '';
202
+ inValue = true;
203
+ i = quote ? next : next - 1;
204
+ } else if (naming) {
205
+ /** The name runs until the first character that cannot be in one; `/` means a closing tag. */
206
+ if (/[a-zA-Z0-9-]/.test(character)) tagName += character.toLowerCase();
207
+ else {
208
+ naming = false;
209
+ if (character === '/' && tagName === '') tagName = '\u0000';
210
+ }
211
+ }
212
+ }
213
+ return { inTag, inValue, quote, rawTag, tagName, naming };
214
+ };
215
+
216
+ /** Attribute names written into the statics, so a duplicate can be spotted before a render. */
217
+ /**
218
+ * Preceded by whitespace, so a **tag name** is not counted as an attribute of itself, and allowed to
219
+ * end the string, because the emitted static of an unfinished tag has no `>` yet — `<b hidden` is
220
+ * how `<b hidden ?hidden=${x}>` arrives here, and its bare `hidden` is exactly the duplicate that
221
+ * has to be seen.
222
+ */
223
+ const STATIC_ATTRIBUTE = /\s([a-zA-Z][\w:-]*)(?==|[\s>]|$)/g;
224
+
38
225
  const compile = (strings) => {
39
226
  const parts = [];
40
227
  const kinds = [];
41
228
  const names = [];
42
- let skipQuote = false;
229
+ /**
230
+ * Whether a slot has to scan the open tag for an earlier write of its own name, and the tag it
231
+ * sits in.
232
+ *
233
+ * Both are properties of the *template*, not of a render: an attribute can only be duplicated by
234
+ * the statics around it, by an earlier binding in the same tag, or by a spread — and every one of
235
+ * those is visible here. Computing them per render cost 0.03–0.06 µs on every attribute, boolean
236
+ * and form-property binding, which is 18–68% of what those bindings cost in total. Almost no tag
237
+ * writes a name twice, so almost every one of those scans found nothing.
238
+ */
239
+ const strip = [];
240
+ const owners = [];
241
+ /** Which RAWTEXT element each binding sits inside, `''` when none. See `RAWTEXT`. */
242
+ const raws = [];
243
+ /** Per part: this binding sits inside a quoted attribute value, so the attribute rule applies. */
244
+ const attrValues = [];
245
+ /**
246
+ * Whether each slot is an **element position** — inside a tag but not inside an attribute value.
247
+ *
248
+ * `<b title="${x}">` is also a value inside a tag, and it is *not* an element position: the
249
+ * statics carry `title="` and `">` around it and the value is simply written between them. The
250
+ * difference is what the static ends with, so it is settled here rather than guessed at render.
251
+ */
252
+ const elementPositions = [];
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
+
259
+ /** The quote character a binding opened with, to be stripped off the front of the next static. */
260
+ let openQuote = '';
261
+ let inTag = false;
262
+ /** Carried across statics — see `scanTag`. */
263
+ let tagState = { inTag: false, inValue: false, quote: '', rawTag: '', tagName: '', naming: false };
43
264
 
44
265
  for (let i = 0; i < strings.length - 1; i++) {
45
266
  let part = strings[i];
46
- if (skipQuote) part = part.startsWith('"') ? part.slice(1) : part;
267
+ if (openQuote && part.startsWith(openQuote)) part = part.slice(1);
268
+ const wasInTag = inTag;
269
+ inTag = closesTag(part, inTag);
270
+ /**
271
+ * Scanned from the **author's** static, not the trimmed one.
272
+ *
273
+ * `part` has already had a binding's opening quote removed by the `openQuote` handling above, so
274
+ * `?hidden='${x}'` reaches the scanner as `?hidden=` followed by `>bs</b>` — the closing quote
275
+ * gone. The scanner then waits for a `'` that never comes and reads the whole rest of the
276
+ * template as one attribute value, which made every element position after it invisible.
277
+ */
278
+ tagState = scanTag(strings[i], tagState);
279
+ /** A new tag starts wherever the text opens one; what the previous tag held is irrelevant. */
280
+ const opensTag = part.lastIndexOf('<') > part.lastIndexOf('>');
281
+ if (opensTag || (!inTag && wasInTag)) {
282
+ written = new Set();
283
+ dynamicTag = false;
284
+ owner = openTagName(part);
285
+ }
286
+ /**
287
+ * Names in the statics are recorded from the text that is actually **emitted**, which is the
288
+ * part with this binding's own name already trimmed off. Scanning the raw part instead counts
289
+ * `title=` — the binding's own name — as a prior write, and in `<b title="a" title=${x}>` the
290
+ * two collapse into one entry, so the real duplicate goes unnoticed.
291
+ */
292
+ const record = (staticText) => {
293
+ if (inTag) for (const [, found] of staticText.matchAll(STATIC_ATTRIBUTE)) written.add(found.toLowerCase());
294
+ };
47
295
 
48
- const sigil = SIGIL_TAIL.exec(part);
296
+ const sigil = inTag && SIGIL_TAIL.exec(part);
49
297
  if (sigil) {
50
298
  /** The space that preceded the binding goes with it, so dropped bindings leave no residue. */
51
- parts.push(part.slice(0, sigil.index).replace(/ $/, ''));
52
- skipQuote = sigil[3] === '"';
299
+ const before = part.slice(0, sigil.index).replace(/ $/, '');
300
+ record(before);
301
+ parts.push(before);
302
+ openQuote = sigil[3];
53
303
  const kind = sigil[1];
304
+ /** Absent after a bare `&=`, which is an element ref with no name. */
305
+ const sigilName = sigil[2] ?? '';
54
306
  if (kind === '?') {
55
307
  kinds.push(BOOLEAN);
56
- } else if (kind === '.' && FORM_ATTRIBUTES.includes(sigil[2])) {
308
+ } else if ((kind === '.' || kind === '!') && FORM_ATTRIBUTES.includes(sigilName)) {
57
309
  kinds.push(FORM_PROP);
58
310
  } else {
59
311
  kinds.push(DROPPED);
60
312
  }
61
- names.push(sigil[2]);
313
+ names.push(sigilName);
314
+ strip.push(dynamicTag || written.has(sigilName.toLowerCase()));
315
+ owners.push(owner);
316
+ raws.push(tagState.rawTag);
317
+ attrValues.push(false);
318
+ elementPositions.push(false);
319
+ if (sigilName) written.add(sigilName.toLowerCase());
62
320
  continue;
63
321
  }
64
322
 
65
- skipQuote = false;
66
- const attribute = PLAIN_ATTRIBUTE_TAIL.exec(part);
67
- if (attribute && /^on[A-Z]/.test(attribute[0])) {
68
- /** `onClick=${fn}` — the React-shaped event binding; a client concern, dropped like `@`. */
69
- parts.push(part.slice(0, attribute.index).replace(/ $/, ''));
323
+ openQuote = '';
324
+
325
+ const event = inTag && EVENT_TAIL.exec(part);
326
+ if (event) {
327
+ /** A client concern, dropped like `@` — and it may be quoted, so remember which. */
328
+ const before = part.slice(0, event.index).replace(/ $/, '');
329
+ record(before);
330
+ parts.push(before);
331
+ openQuote = event[1];
70
332
  kinds.push(DROPPED);
71
333
  names.push('');
334
+ strip.push(false);
335
+ owners.push(owner);
336
+ raws.push(tagState.rawTag);
337
+ attrValues.push(false);
338
+ elementPositions.push(false);
339
+ continue;
340
+ }
341
+
342
+ const attribute = inTag && PLAIN_ATTRIBUTE_TAIL.exec(part);
343
+ if (attribute) {
344
+ /**
345
+ * The name comes off the static and is re-attached at render time, because a nullish value
346
+ * has to take the whole attribute with it — `title=${null}` removes it on the client, exactly
347
+ * as lit does, and this emitted `title=""`. Adoption still succeeded (the statics matched), so
348
+ * the jsdom matrix passed on identity while the two sides disagreed about the attribute; the
349
+ * browser suite adopting through real declarative shadow DOM is what saw it.
350
+ */
351
+ const before = part.slice(0, attribute.index).replace(/ $/, '');
352
+ record(before);
353
+ parts.push(before);
354
+ kinds.push(ATTRIBUTE);
355
+ const name = attribute[0].slice(0, -1);
356
+ names.push(name);
357
+ strip.push(dynamicTag || written.has(name.toLowerCase()));
358
+ owners.push(owner);
359
+ raws.push(tagState.rawTag);
360
+ attrValues.push(false);
361
+ elementPositions.push(false);
362
+ written.add(name.toLowerCase());
72
363
  continue;
73
364
  }
365
+ record(part);
74
366
  parts.push(part);
75
- kinds.push(attribute ? ATTRIBUTE : TEXT);
367
+ kinds.push(TEXT);
76
368
  names.push('');
369
+ strip.push(false);
370
+ owners.push(owner);
371
+ raws.push(tagState.rawTag);
372
+ /**
373
+ * `<p title="a ${x} b">` reaches here as TEXT — the name is in the static, so there is no sigil
374
+ * and no `name=` tail to match — and it is emitted straight into the stream between the
375
+ * statics. That made it take the **child-position** rule while `title=${x}` took the attribute
376
+ * rule, so an array served `a 12 b` where the client, which builds the string and calls
377
+ * `setAttribute`, produced `a 1,2 b`.
378
+ */
379
+ attrValues.push(tagState.inTag && tagState.inValue);
380
+ /** Inside a tag, and not inside an attribute value: `<input ${ref} />`, `<b ${spread(…)}>`. */
381
+ const elementPosition = tagState.inTag && !tagState.inValue;
382
+ elementPositions.push(elementPosition);
383
+ /** A spread's keys are unknown until it runs, so its tag can no longer be settled here. */
384
+ if (elementPosition) dynamicTag = true;
77
385
  }
78
386
 
79
387
  let last = strings[strings.length - 1];
80
- if (skipQuote) last = last.startsWith('"') ? last.slice(1) : last;
388
+ if (openQuote && last.startsWith(openQuote)) last = last.slice(1);
81
389
  parts.push(last);
82
390
 
83
- const plan = { parts, kinds, names };
391
+ const plan = { parts, kinds, names, strip, owners, raws, attrValues, elementPositions };
84
392
  plans.set(strings, plan);
85
393
  return plan;
86
394
  };
87
395
 
88
396
  export const serializeTemplate = (template) => {
89
397
  const { strings, values } = template;
90
- const { parts, kinds, names } = plans.get(strings) ?? compile(strings);
398
+ const { parts, kinds, names, strip, owners, raws, attrValues, elementPositions } = plans.get(strings) ?? compile(strings);
91
399
  let out = '';
400
+ /**
401
+ * Content that belongs *after* the tag being built rather than inside it — a `<textarea>`'s
402
+ * value, which is text and not an attribute. Written into the next static right after the `>`
403
+ * that closes the tag, replacing whatever the author wrote there, exactly as assigning `.value`
404
+ * does on the client.
405
+ */
406
+ let pendingText = null;
407
+ /**
408
+ * Values bound to a `<select>`'s `.value`, resolved into `<option selected>` after the loop —
409
+ * the options are usually a nested template, so nothing can be decided until the string is whole.
410
+ */
411
+ const selectValues = [];
92
412
 
93
413
  for (let i = 0; i < kinds.length; i++) {
94
- out += parts[i];
414
+ if (pendingText === null) out += parts[i];
415
+ else {
416
+ out += insertContent(parts[i], pendingText);
417
+ pendingText = null;
418
+ }
95
419
  const value = values[i];
96
420
  switch (kinds[i]) {
97
421
  case TEXT:
98
422
  /** A spread rewrites the open tag it sits in, so it is folded rather than appended. */
99
- if (value !== null && typeof value === 'object' && value._$attrs$) out = foldSpread(out, value._$attrs$());
423
+ if (value !== null && typeof value === 'object' && value._$attrs$) {
424
+ const folded = foldSpread(out, value._$attrs$());
425
+ out = folded.out;
426
+ if (folded.text !== null) pendingText = folded.text;
427
+ if (folded.select !== null) out += ` ${SELECT_MARK}="${selectValues.push(folded.select) - 1}"`;
428
+ }
429
+ /**
430
+ * An **element-position** expression that is not a spread is a ref — `<input ${myRef} />`,
431
+ * where the renderer hands the element to a function or assigns it to `.value`. It is
432
+ * client state, like `@event`, and has no markup.
433
+ *
434
+ * It used to be stringified into the open tag, so `<input ${ref(null)} />` served
435
+ * `<input [object Object]>` — which the parser then read as two attributes named
436
+ * `[object` and `object]`. A value in this position never has markup; only a spread does.
437
+ */
438
+ else if (elementPositions[i]) {
439
+ /**
440
+ * **A dynamic attribute *name* is refused rather than dropped.**
441
+ *
442
+ * `<b ${name}="x">` puts the slot at an element position with an `=` immediately after it,
443
+ * which is the one shape here that is not a ref. Dropping the value emitted `<b="x">` —
444
+ * not an attribute, not a tag, markup no browser would produce from that template. The
445
+ * client is no better off: it hands the template to the platform's parser and a marker is
446
+ * not a name. Since both halves are broken, saying so is more use than serving either
447
+ * one's version of broken.
448
+ */
449
+ if (/^=/.test(parts[i + 1] ?? ''))
450
+ throw new Error(
451
+ `ssr: an attribute name cannot be an expression — \`<b \${name}="x">\` is malformed ` +
452
+ `markup in the browser too, because the parser sees the marker before the value ` +
453
+ `exists. Use \`@verajs/renderer/spread\`, which is built for names that are not known ` +
454
+ `until runtime and which this serializer understands.`
455
+ );
456
+ /**
457
+ * The space that introduced the binding goes with it, exactly as a dropped sigil binding's
458
+ * does. Leaving it served `<p >r</p>` where the client renders `<p>r</p>` — harmless to a
459
+ * parser, and still a difference between the two halves for something neither of them
460
+ * renders at all.
461
+ */
462
+ out = out.replace(/ $/, '');
463
+ break;
464
+ }
465
+ /**
466
+ * **Raw text is written raw, and its own end tag is neutralised.**
467
+ *
468
+ * A browser does not decode a character reference inside `<style>` or `<script>`, so
469
+ * escaping there protects nothing and corrupts the content: `<style>${'.a > .b'}</style>`
470
+ * served `.a &#62; .b`, a selector that matches nothing, while the client — which sets text
471
+ * through the DOM and never re-parses — rendered `.a > .b`. Every interpolated stylesheet
472
+ * was broken server-side and correct client-side, which is also a hydration divergence.
473
+ *
474
+ * Not escaping means the element's end tag has to be taken out of the value instead, or it
475
+ * closes the element and everything after it parses as markup. `<\/style` is valid CSS and
476
+ * `<\/script` is the canonical form in JavaScript; both render identically and neither is
477
+ * seen by the tokenizer.
478
+ *
479
+ * `<title>` and `<textarea>` are RCDATA, not RAWTEXT — references *are* decoded there — so
480
+ * they keep ordinary escaping, which is what the client produces for them too.
481
+ */
482
+ else if (raws[i]) out += escapeRawText(serializeValue(value, true), raws[i]);
483
+ /**
484
+ * **Inside a quoted attribute value, the attribute rule applies** — the same rule
485
+ * `title=${x}` takes one case below, and for the same reason: the client builds the whole
486
+ * value as a string and hands it to `setAttribute`, which is ToString and nothing else. The
487
+ * child-position rule renders a value instead, so an array was iterated into `12` against
488
+ * the browser's `1,2`, a `Set` into `12` against `[object Set]`, and a function vanished
489
+ * where the client writes its source. The single-expression form was corrected for exactly
490
+ * this; the form with static text beside it was reached by a different branch and kept it.
491
+ */
492
+ else if (attrValues[i]) out += escapeHtml(serializeValue(value, true));
100
493
  else out += serializeValue(value);
101
494
  break;
102
495
  case BOOLEAN:
496
+ if (strip[i]) out = removeAttribute(out, names[i]);
103
497
  if (value) out += ` ${names[i]}=""`;
104
498
  break;
105
499
  case FORM_PROP:
106
- if (value != null && value !== false) out += ` ${names[i]}="${escapeHtml(value === true ? '' : value)}"`;
500
+ if (!FORM_ELEMENTS.has(owners[i])) break;
501
+ /**
502
+ * A `<textarea>`'s value is its **text content**. `<textarea value="x">` is ignored by
503
+ * every parser, so writing the attribute served an empty control while the client — which
504
+ * sets the property — showed the text. Held until the tag closes, because that is where the
505
+ * content goes; see `pendingText` below.
506
+ */
507
+ /**
508
+ * A `<select>`'s `value` is not an attribute — see `SELECT_MARK`. Marked here and resolved
509
+ * once the options exist; writing ` value="b"` on the tag, which is what this used to do,
510
+ * means nothing to a parser and left the control showing its first option.
511
+ */
512
+ if (owners[i] === 'select' && names[i] === 'value') {
513
+ if (strip[i]) out = removeAttribute(out, names[i]);
514
+ out += ` ${SELECT_MARK}="${selectValues.push(`${value}`) - 1}"`;
515
+ break;
516
+ }
517
+ if (owners[i] === 'textarea' && names[i] === 'value') {
518
+ /**
519
+ * `null` and `undefined` are **not** the same value here, and treating them as one is what
520
+ * this used to do. `value` carries `[LegacyNullToEmptyString]` in its IDL, so assigning
521
+ * `null` gives `''` while `undefined` goes through the ordinary ToString and gives the text
522
+ * `"undefined"` — measured in Chromium, Firefox and WebKit, since that is the platform's
523
+ * rule and not this package's to guess. A `== null` test collapses them.
524
+ *
525
+ * The booleans used to be emptied too, which disagreed with `<input>` **one branch below**
526
+ * — the same property, on the same rule, serialized by a different branch: `true` served an
527
+ * empty `<textarea>` against the browser's `true`.
528
+ */
529
+ pendingText = value === null ? '' : escapeHtml(value);
530
+ break;
531
+ }
532
+ if (strip[i]) out = removeAttribute(out, names[i]);
533
+ if (BOOLEAN_FORM_PROPERTIES.has(names[i])) {
534
+ if (value) out += ` ${names[i]}=""`;
535
+ } else if (value !== null || owners[i] === 'option') {
536
+ /**
537
+ * A string property: `true` is `"true"`, exactly as assigning it to the element gives.
538
+ *
539
+ * Three rules, not one, and they were measured rather than assumed:
540
+ *
541
+ * - `<input>` and `<textarea>` carry `[LegacyNullToEmptyString]`, so `null` means the empty
542
+ * string. Omitting the attribute is how markup says that — a parsed `<input>` with no
543
+ * `value` answers `''`.
544
+ * - `<option>` does **not**. `option.value = null` is the text `"null"` in every engine, and
545
+ * omitting the attribute is worse than wrong there: `option.value` then falls back to the
546
+ * element's own text.
547
+ * - `undefined` is never the empty string on any of them. It is `"undefined"`, which looks
548
+ * like a bug because it *is* one — but it is the client's bug too, and the two sides
549
+ * disagreeing about it is a hydration mismatch on top of it.
550
+ */
551
+ out += ` ${names[i]}="${escapeHtml(value)}"`;
552
+ }
107
553
  break;
108
554
  case ATTRIBUTE:
109
- /** Unquoted `attr=${x}`: quote it so spacey values stay one attribute. */
110
- out += '"' + escapeHtml(serializeValue(value, true)) + '"';
555
+ /** Unquoted `attr=${x}`: quoted so spacey values stay one attribute, absent when nullish. */
556
+ if (strip[i]) out = removeAttribute(out, names[i]);
557
+ if (value != null) out += ` ${names[i]}="${escapeHtml(serializeValue(value, true))}"`;
111
558
  break;
112
- /** DROPPED: '@' and '&' and non-form '.': nothing — client concerns. */
559
+ /** DROPPED: '@' and '&' and a non-form '.' or '!': nothing — client concerns. */
113
560
  }
114
561
  }
115
- return out + parts[kinds.length];
562
+ const tail = parts[kinds.length];
563
+ const finished = pendingText === null ? out + tail : out + insertContent(tail, pendingText);
564
+ return selectValues.length ? resolveSelects(finished, selectValues) : finished;
565
+ };
566
+
567
+ /**
568
+ * Puts `text` inside the element the static closes, replacing what the author wrote there.
569
+ *
570
+ * Only `<textarea>` needs this, and only for `.value` — every other form property is an attribute.
571
+ * `<textarea .value=${x}>anything</textarea>` must serve `x`, because that is what the element
572
+ * will hold on the client the moment the property is assigned.
573
+ */
574
+ /**
575
+ * A `<select>` has **no `value` content attribute**. Assigning the property *selects an option*, so
576
+ * the only way markup can express it is `<option selected>` on the matching one — which is what
577
+ * React's server renderer does, and what this does. Lit's SSR drops the binding entirely and serves
578
+ * a control showing the wrong option.
579
+ *
580
+ * The mark is an index into a per-render list rather than the value itself, so nothing has to be
581
+ * escaped on the way in and unescaped on the way out; it is removed again by `resolveSelects`, and
582
+ * removing it is what terminates that loop.
583
+ */
584
+ const SELECT_MARK = 'data-vm-select';
585
+ const MARKED_SELECT = new RegExp(`<select\\b[^>]*\\s${SELECT_MARK}="(\\d+)"[^>]*>`, 'i');
586
+ const OPTION = /<option\b([^>]*)>([\s\S]*?)<\/option>/gi;
587
+ const OPTION_VALUE = /\bvalue\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
588
+ const SELECTED_ATTR = /(<option\b[^>]*?)\s+selected(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?/gi;
589
+ const NAMED = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
590
+
591
+ /**
592
+ * Enough of a decoder to compare an option against a value.
593
+ *
594
+ * Everything this serializer writes is escaped as a numeric reference, and the five named ones are
595
+ * what an author writes by hand. A full entity table would be several kilobytes to decide which
596
+ * `<option>` is selected, and anything it missed would simply fail to match — which is the same
597
+ * outcome as an option that genuinely does not match, and is already a documented divergence.
598
+ */
599
+ const decodeRefs = (text) =>
600
+ text.replace(/&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|(amp|lt|gt|quot|apos));/g, (whole, dec, hex, name) =>
601
+ dec ? String.fromCodePoint(+dec) : hex ? String.fromCodePoint(parseInt(hex, 16)) : NAMED[name] ?? whole
602
+ );
603
+
604
+ /**
605
+ * What an engine reports for `option.value`: the `value` attribute verbatim if there is one, and
606
+ * otherwise the option's text **stripped and collapsed**. Both halves measured in Chromium, Firefox
607
+ * and WebKit — `tests/browser/select-value.test.js` — because the fallback is easy to assume is the
608
+ * raw text, and it is not.
609
+ */
610
+ const optionValue = (attributes, text) => {
611
+ const attribute = OPTION_VALUE.exec(attributes);
612
+ if (attribute) return decodeRefs(attribute[1] ?? attribute[2] ?? attribute[3]);
613
+ return decodeRefs(text).replace(/[\t\n\f\r ]+/g, ' ').trim();
614
+ };
615
+
616
+ /**
617
+ * Marks the first option matching `wanted`, and clears any `selected` the author wrote.
618
+ *
619
+ * Clearing is not tidiness: a property assignment overrides markup, so `<option selected>` beside a
620
+ * `.value` binding loses on the client and has to lose here too. **First match wins**, which is the
621
+ * engines' rule for duplicate values.
622
+ *
623
+ * When nothing matches, nothing is marked — and that is a divergence markup cannot close. The client
624
+ * leaves `selectedIndex` at `-1` with nothing showing; a parsed `<select>` with no selected option
625
+ * takes its **first**. See the SSR README.
626
+ */
627
+ const markSelected = (content, wanted) => {
628
+ const cleared = content.replace(SELECTED_ATTR, '$1');
629
+ OPTION.lastIndex = 0;
630
+ for (let match = OPTION.exec(cleared); match; match = OPTION.exec(cleared)) {
631
+ if (optionValue(match[1], match[2]) !== wanted) continue;
632
+ const open = match[0].slice(0, match[0].indexOf('>'));
633
+ return (
634
+ cleared.slice(0, match.index) +
635
+ open.replace(/\s*\/?$/, '') +
636
+ ' selected>' +
637
+ match[0].slice(match[0].indexOf('>') + 1) +
638
+ cleared.slice(match.index + match[0].length)
639
+ );
640
+ }
641
+ return cleared;
642
+ };
643
+
644
+ /** Resolves every marked `<select>` once its options are in the string — see `SELECT_MARK`. */
645
+ const resolveSelects = (markup, wanted) => {
646
+ for (let match = MARKED_SELECT.exec(markup); match; match = MARKED_SELECT.exec(markup)) {
647
+ const openTag = match[0].replace(new RegExp(`\\s*${SELECT_MARK}="\\d+"`, 'i'), '');
648
+ const contentStart = match.index + match[0].length;
649
+ const closeAt = markup.toLowerCase().indexOf('</select', contentStart);
650
+ const end = closeAt === -1 ? markup.length : closeAt;
651
+ markup =
652
+ markup.slice(0, match.index) +
653
+ openTag +
654
+ markSelected(markup.slice(contentStart, end), wanted[+match[1]]) +
655
+ markup.slice(end);
656
+ }
657
+ return markup;
658
+ };
659
+
660
+ const insertContent = (staticText, text) => {
661
+ const close = staticText.indexOf('>');
662
+ if (close === -1) return staticText;
663
+ const rest = staticText.slice(close + 1);
664
+ const end = rest.toLowerCase().indexOf('</textarea');
665
+ return staticText.slice(0, close + 1) + text + (end === -1 ? rest : rest.slice(end));
116
666
  };
117
667
 
118
668
  /**
@@ -132,45 +682,247 @@ export const serializeTemplate = (template) => {
132
682
  * Splitting on the last `<` is safe: attribute values are escaped, so no raw `<` can appear inside
133
683
  * one.
134
684
  */
685
+ /**
686
+ * Removes an attribute already written into the open tag being built, so the last write wins.
687
+ *
688
+ * An HTML parser keeps the **first** of a duplicate pair; `setAttribute` on the client overwrites,
689
+ * so the **last** wins there. `<b title="a" title=${x}>` therefore showed `a` on a server-rendered
690
+ * page and `b` in the browser — the same disagreement `foldSpread` was written to fix for spreads,
691
+ * which is where this logic came from. It applies to anything that writes a name into the tag.
692
+ */
693
+ /**
694
+ * One pattern per attribute name, built once. `new RegExp` per binding was 16% of a 100-row render.
695
+ */
696
+ const removalPatterns = new Map();
697
+ /**
698
+ * The name is **escaped** before it becomes a pattern. A spread's keys are runtime data, and an
699
+ * attribute name may legally contain regular-expression metacharacters — `a|b`, `a.b`, `a*` are all
700
+ * names `setAttribute` accepts — so interpolating one raw built a pattern that matched something
701
+ * else entirely. `a|b` compiled to an alternation and removed text nowhere near the attribute it
702
+ * named.
703
+ */
704
+ const escapeForPattern = (name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
705
+ const removalPattern = (name) => {
706
+ let pattern = removalPatterns.get(name);
707
+ if (!pattern)
708
+ removalPatterns.set(
709
+ name,
710
+ (pattern = new RegExp(`\\s${escapeForPattern(name)}(=("[^"]*"|'[^']*'|[^\\s>]*))?`, 'i'))
711
+ );
712
+ return pattern;
713
+ };
714
+
715
+ /**
716
+ * A name that cannot be written into a tag safely.
717
+ *
718
+ * A spread's keys are the one part of a template that is runtime data — that is what the module is
719
+ * for — and they were interpolated into the open tag with no check at all, while every *value*
720
+ * around them was escaped. A key carrying a quote or a `>` therefore closed the attribute, or the
721
+ * element:
722
+ *
723
+ * spread({ 'x><script>alert(1)</script': '1' })
724
+ * -> <b x><script>alert(1)</script="1">x</b>
725
+ *
726
+ * The set is the HTML attribute-name restriction — control characters, whitespace, `"`, `'`, `>`,
727
+ * `/`, `=` — plus `<` and a backtick, which the specification permits and no real name uses.
728
+ *
729
+ * It is deliberately **stricter than `setAttribute`**, which was measured in Chromium and accepts
730
+ * `"`, `'` and `<` while rejecting whitespace, `>`, `=`, `/` and NUL. A name the platform accepts
731
+ * but markup cannot carry is unusable in a framework that server-renders, so `@verajs/renderer/spread`
732
+ * applies this same rule client-side and the two sides agree on every key rather than one of them
733
+ * quietly serving different markup.
734
+ *
735
+ * The control-character range is the point of the rule, not a mistake in it: a name carrying one
736
+ * is exactly what must never reach markup.
737
+ */
738
+ // eslint-disable-next-line no-control-regex
739
+ export const UNSAFE_ATTRIBUTE_NAME = /^$|[\s"'>/=<`]|[\u0000-\u001f\u007f]/;
740
+
741
+ /**
742
+ * Strips one attribute out of an open tag, and the one place that knows how.
743
+ *
744
+ * `foldSpread` had its own copy of this pattern, character for character — so a fix to one was a
745
+ * fix to one. It also rebuilt the pattern on every key of every spread, which is the per-render
746
+ * work `tests/ssr-serializer-work.test.mjs` exists to refuse.
747
+ */
748
+ const stripAttribute = (tag, name) =>
749
+ /**
750
+ * Almost no tag carries the name twice, and a substring search settles that far faster than a
751
+ * pattern match does. Case-insensitive to match the pattern it guards, which HTML requires.
752
+ */
753
+ tag.toLowerCase().includes(name.toLowerCase()) ? tag.replace(removalPattern(name), '') : tag;
754
+
755
+ const removeAttribute = (out, name) => {
756
+ const tagStart = out.lastIndexOf('<');
757
+ if (tagStart === -1) return out;
758
+ return out.slice(0, tagStart) + stripAttribute(out.slice(tagStart), name);
759
+ };
760
+
135
761
  const foldSpread = (out, entries) => {
136
762
  const tagStart = out.lastIndexOf('<');
137
763
  let tag = out.slice(tagStart);
138
764
  let added = '';
765
+ /** A `<textarea>`'s value is its text content, so a `.value` key here is not an attribute. */
766
+ let text = null;
767
+ /** A `<select>`'s value is not an attribute either; the caller marks the tag — see `SELECT_MARK`. */
768
+ let select = null;
139
769
 
770
+ const owner = openTagName(out);
771
+ const isFormElement = FORM_ELEMENTS.has(owner);
140
772
  for (const [kind, name, value] of entries) {
141
- const serializes = kind === 'a' || kind === 'b' || (kind === 'p' && FORM_ATTRIBUTES.includes(name));
773
+ const serializes =
774
+ kind === 'a' || kind === 'b' || (kind === 'p' && isFormElement && FORM_ATTRIBUTES.includes(name));
142
775
  if (!serializes) continue;
143
776
 
777
+ /**
778
+ * Dropped, and dropped **before** anything is done with the name — `stripAttribute` compiles it
779
+ * into a pattern, so an unchecked name is a second way in.
780
+ *
781
+ * Silent here on purpose. A key that reaches this is either a mistake, which the identical check
782
+ * in `@verajs/renderer/spread` reports in development where the author will see it, or it is
783
+ * hostile — and a server that logs a line per hostile key hands an attacker the log file.
784
+ */
785
+ if (UNSAFE_ATTRIBUTE_NAME.test(name)) continue;
786
+
144
787
  /** Quoted, single-quoted, unquoted, or valueless — whatever the template author wrote. */
145
- tag = tag.replace(new RegExp(`\\s${name}(=("[^"]*"|'[^']*'|[^\\s>]*))?`, 'i'), '');
788
+ tag = stripAttribute(tag, name);
146
789
 
147
- if (kind === 'b') {
790
+ /**
791
+ * A `<textarea>`'s `.value` is its **content**, exactly as it is for a written binding — the
792
+ * attribute this would otherwise write is ignored by every parser, so the control arrived empty
793
+ * while the client, which sets the property, showed the text. The written form was fixed and
794
+ * this one was not: a spread key means what the written binding means, always.
795
+ */
796
+ if (kind === 'p' && owner === 'select' && name === 'value') {
797
+ /** A spread key means what the written binding means, always — see `SELECT_MARK`. */
798
+ select = `${value}`;
799
+ continue;
800
+ }
801
+ if (kind === 'p' && owner === 'textarea' && name === 'value') {
802
+ text = value === null ? '' : escapeHtml(value);
803
+ continue;
804
+ }
805
+
806
+ /**
807
+ * Same coercions as a written binding, kind by kind — which is the contract, and which this had
808
+ * only approximately.
809
+ *
810
+ * A **boolean** is truthiness, and so are `checked` and `selected`. A plain **attribute** takes
811
+ * anything that is not nullish, `false` included: `String(false)` is `"false"`, which is what
812
+ * `setAttribute` writes and what the written form already emitted. Treating `false` as removal
813
+ * for every kind meant `${spread({ title: false })}` dropped the attribute while
814
+ * `title=${false}` kept it — the same value, two answers, from the two spellings of one binding.
815
+ */
816
+ if (kind === 'b' || (kind === 'p' && BOOLEAN_FORM_PROPERTIES.has(name))) {
148
817
  if (value) added += ` ${name}=""`;
149
- } else if (value != null && value !== false) {
150
- added += ` ${name}="${escapeHtml(kind === 'p' && value === true ? '' : serializeValue(value, true))}"`;
818
+ } else if (kind === 'p') {
819
+ /**
820
+ * **A string form property and a plain attribute are no longer the same rule**, which is why
821
+ * this branch split. An attribute is removed by either nullish value — the renderer's own
822
+ * documented behaviour, matching lit, on both sides. A `value` property is not: its IDL carries
823
+ * `[LegacyNullToEmptyString]` on `<input>` and `<textarea>`, so `null` alone means the empty
824
+ * string, `undefined` is the text `"undefined"`, and `<option>` has neither rule and takes
825
+ * `"null"`. Written and spread must agree about all of it —
826
+ * `tests/ssr-spread-equivalence.test.mjs` is what caught this one, and it caught it the same
827
+ * afternoon the written form was corrected.
828
+ */
829
+ if (value !== null || owner === 'option') added += ` ${name}="${escapeHtml(value)}"`;
830
+ } else if (value != null) {
831
+ /**
832
+ * A plain attribute takes anything not nullish and is removed by either nullish value.
833
+ * `false` is `"false"` and `true` is `"true"`, because that is what `setAttribute` produces.
834
+ */
835
+ added += ` ${name}="${escapeHtml(serializeValue(value, true))}"`;
151
836
  }
152
837
  }
153
838
 
154
- /** The element-position slot already carries the separating space. */
155
- return out.slice(0, tagStart) + tag + (added ? added.slice(1) : '');
839
+ /**
840
+ * The element-position slot already carries the separating space, so the first addition drops its
841
+ * own. When a spread contributes nothing — every key nullish, or all of them client concerns —
842
+ * that space is left dangling before the `>`, which the parser ignores and which is still a byte
843
+ * in every response and untidy in a view-source.
844
+ */
845
+ return {
846
+ out: out.slice(0, tagStart) + (added ? tag + added.slice(1) : tag.replace(/ $/, '')),
847
+ /** Written into the next static, after the `>` that closes this tag — see `insertContent`. */
848
+ text,
849
+ select,
850
+ };
156
851
  };
157
852
 
158
- const serializeValue = (value, raw = false) => {
159
- if (value == null || value === false) return '';
160
- if (Array.isArray(value)) return value.map((entry) => serializeValue(entry, raw)).join('');
853
+ /**
854
+ * Exported so the renderer can flatten a non-template return the same way a slot does — see
855
+ * `index.js`. Everything about what renders and how it escapes lives here and only here.
856
+ */
857
+ export const serializeValue = (value, raw = false) => {
858
+ /**
859
+ * Only `null` and `undefined` are empty, exactly as on the client — `false` and `0` render.
860
+ * `false` used to serialize as empty here, which made `${cond && 'x'}` emit nothing on the server
861
+ * and the text `false` in the browser: a silent content difference on a static page, and a full
862
+ * re-render on a hydrated one.
863
+ */
864
+ if (value == null) return '';
865
+ /**
866
+ * **An attribute stringifies exactly as the platform does, and nothing else.**
867
+ *
868
+ * A child position renders a value — a template becomes markup, an array renders every item, a
869
+ * function is client state and disappears. An attribute does none of that: it goes through
870
+ * `setAttribute`, which is `String(value)` and only that. The two are different rules and this
871
+ * had one of them.
872
+ *
873
+ * Measured against a browser, every one of these disagreed: `[1, 2]` served `12` against `1,2`
874
+ * (arrays have their own `toString`), a `Set` served `1,2` against `[object Set]`, a function
875
+ * served nothing against its own source, and a **template served its markup into an attribute
876
+ * value** against `[object Object]`. Escaped, so not an injection — and still a completely
877
+ * different page before and after hydration.
878
+ */
879
+ if (raw) return `${value}`;
880
+ if (Array.isArray(value)) return value.map((entry) => serializeValue(entry)).join('');
161
881
  if (typeof value === 'function') return '';
162
882
  if (typeof value === 'object') {
163
- /** Template-shaped (core's html, by shape) recurses. */
883
+ /** Template-shaped (core's html, by shape) recurses. `keyed()` mutates one, so it arrives here. */
164
884
  if (value.strings) return serializeTemplate(value);
165
885
  /**
166
- * A spread (`@verajs/spread`) at element position. It hands back resolved bindings and this
886
+ * `hold(result)` is `{ $h: result }` — a client-renderer construct that keeps the DOM of a
887
+ * toggled-away subtree alive so form values and scroll positions survive the round trip. There
888
+ * is no previous DOM on a server, so the wrapper means nothing here and the template inside it
889
+ * means everything.
890
+ *
891
+ * It used to fall through to `String(value)` and serve the text `[object Object]` into the
892
+ * page. `keyed()` works because it mutates the template and hands the same object back; `hold`
893
+ * wraps one, and nothing unwrapped it.
894
+ */
895
+ if (value.$h) return serializeValue(value.$h, raw);
896
+ /**
897
+ * A spread (`@verajs/renderer/spread`) at element position. It hands back resolved bindings and this
167
898
  * decides what reaches markup: attributes and truthy booleans do, form properties do because
168
899
  * hydration reads them back, and events and other properties are client state. Escaping happens
169
900
  * here and only here — principle #8 puts it at the render boundary, not at the source.
901
+ */
902
+ if (value._$attrs$) return '';
903
+
904
+ /**
905
+ * An iterable renders its entries, exactly as the client's child position does — a `Set` or a
906
+ * `Map` reaching a template is not obviously deliberate, but the two sides have to agree about
907
+ * it or hydration is discarded.
908
+ */
909
+ if (typeof value[Symbol.iterator] === 'function') {
910
+ return [...value].map((entry) => serializeValue(entry)).join('');
911
+ }
912
+
913
+ /**
914
+ * Everything else falls through to `String(value)`, which is what the client does.
915
+ *
916
+ * This used to return `''` for any object that was not template-shaped, and the client has
917
+ * never agreed: a `Date` rendered its full date string there and nothing here, an object with a
918
+ * `toString` rendered its text, a `Promise` rendered `[object Promise]`. Whether any of those is
919
+ * a *sensible* thing to interpolate is beside the point — the two sides disagreeing is a silent
920
+ * hydration mismatch, and matching junk is worth more than differing junk.
170
921
  *
171
- * Anything else at element position is a ref, which is a client concern.
922
+ * A DOM node is the one exception, and it cannot occur: the server has no document to have
923
+ * built one.
172
924
  */
173
- return '';
174
925
  }
175
- return raw ? String(value) : escapeHtml(value);
926
+ /** `raw` cannot be true here — it returned at the top of the function. */
927
+ return escapeHtml(value);
176
928
  };