@verajs/ssr 0.2.1 → 0.3.1

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