@verajs/ssr 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +507 -390
  2. package/dist/vera/diagnostics.d.ts +20 -0
  3. package/dist/vera/diagnostics.js +98 -0
  4. package/dist/vera/escaping.d.ts +142 -0
  5. package/dist/vera/escaping.js +267 -0
  6. package/dist/vera/events.d.ts +41 -0
  7. package/dist/vera/events.js +162 -0
  8. package/dist/vera/frames.d.ts +38 -0
  9. package/dist/vera/frames.js +195 -0
  10. package/dist/vera/index.d.ts +48 -0
  11. package/dist/vera/index.js +480 -0
  12. package/{types → dist/vera}/nodes.d.ts +389 -302
  13. package/dist/vera/nodes.js +2322 -0
  14. package/dist/vera/parse.d.ts +37 -0
  15. package/dist/vera/parse.js +390 -0
  16. package/dist/vera/reflections.d.ts +566 -0
  17. package/dist/vera/reflections.js +820 -0
  18. package/dist/vera/registry.d.ts +14 -0
  19. package/{src → dist}/vera/registry.js +5 -1
  20. package/dist/vera/report.d.ts +27 -0
  21. package/dist/vera/report.js +56 -0
  22. package/dist/vera/scan.d.ts +37 -0
  23. package/dist/vera/scan.js +143 -0
  24. package/dist/vera/select.d.ts +40 -0
  25. package/dist/vera/select.js +261 -0
  26. package/dist/vera/serializer.d.ts +39 -0
  27. package/dist/vera/serializer.js +1372 -0
  28. package/dist/vera/shim.d.ts +42 -0
  29. package/dist/vera/shim.js +853 -0
  30. package/dist/vera/slots.d.ts +5 -0
  31. package/dist/vera/slots.js +104 -0
  32. package/dist/vera/stylesheets.d.ts +62 -0
  33. package/dist/vera/stylesheets.js +180 -0
  34. package/dist/vera/tokenizer.d.ts +32 -0
  35. package/dist/vera/tokenizer.js +528 -0
  36. package/dist/vera/types.d.ts +117 -0
  37. package/dist/vera/views.d.ts +63 -0
  38. package/dist/vera/views.js +245 -0
  39. package/package.json +12 -13
  40. package/src/vera/escaping.js +0 -135
  41. package/src/vera/events.js +0 -164
  42. package/src/vera/frames.js +0 -102
  43. package/src/vera/index.js +0 -1187
  44. package/src/vera/nodes.js +0 -2294
  45. package/src/vera/parse.js +0 -381
  46. package/src/vera/reflections.js +0 -811
  47. package/src/vera/select.js +0 -234
  48. package/src/vera/serializer.js +0 -1080
  49. package/src/vera/shim.js +0 -761
  50. package/src/vera/stylesheets.js +0 -155
  51. package/src/vera/views.js +0 -240
  52. package/types/escaping.d.ts +0 -27
  53. package/types/events.d.ts +0 -4
  54. package/types/frames.d.ts +0 -12
  55. package/types/index.d.ts +0 -13
  56. package/types/parse.d.ts +0 -19
  57. package/types/reflections.d.ts +0 -657
  58. package/types/registry.d.ts +0 -8
  59. package/types/select.d.ts +0 -5
  60. package/types/serializer.d.ts +0 -26
  61. package/types/shim.d.ts +0 -23
  62. package/types/stylesheets.d.ts +0 -53
  63. package/types/views.d.ts +0 -26
package/README.md CHANGED
@@ -1,403 +1,520 @@
1
1
  # @verajs/ssr
2
2
 
3
- Vera-native server-side rendering. Node-only, plain ESM, **zero dependencies** — no wcc, no lit,
4
- no acorn, no parse5.
5
-
6
- Nested components are found by walking the emitted markup for tags the registry knows. The walk is
7
- state-aware, not a regex: it respects quoted attribute values (a `>` is legal inside one), and it
8
- leaves the contents of comments, `<script>`, `<style>`, `<textarea>` and `<title>` alone, because
9
- those are text and a scan for elements has no business reading them.
10
-
11
- import { renderToString } from '@verajs/ssr';
12
- const { html, styles, title } = await renderToString(new URL('./components/app.js', import.meta.url), {
13
- attributes: { 'user-id': id }, // an object — values are escaped
14
- props: { rows }, // structured data; an attribute can only carry a string
15
- children: '<p>slotted</p>', // what a <slot> in the component renders
16
- location: request.url, // this request's URL — see below
17
- seen, // a Set carried across renders — see below
18
- });
19
-
20
- `title` is `document.title` as that render left it — a component setting it is how a shell names its
21
- page — and it is **returned rather than left on the global**, for the same reason `location` is
22
- passed rather than assigned: a process global cannot belong to one request. The document's own title
23
- is restored afterwards, so a concurrent render never sees it.
24
-
25
- For a shell assembled from several islands, carry one `Set` through every call. Each render returns
26
- the styles of what *it* rendered, so two islands sharing a component would otherwise each carry that
27
- component's CSS and the page would ship it twice.
28
-
29
- **Pass `location` rather than assigning to `globalThis.location`.** A component that reads the URL —
30
- any routed shell does — needs the request's, and `globalThis.location` is process-global while a
31
- request is not. Assigning to it and then calling `renderToString` is safe only until two requests
32
- overlap: the call awaits `import()`, and on a module's first import that await yields, so whichever
33
- request assigned last wins for every render after it. Measured with three concurrent first-time
34
- imports, **two of three rendered another request's path**. The option applies the URL after every
35
- await and restores it afterwards, in a stretch that is synchronous end to end and therefore cannot
36
- interleave. A path or a full URL both work.
37
-
38
- **`children`, and the string form of `attributes`, are raw markup.** Both are written through
39
- untouched — that is what they are for — so neither may carry anything from a request without being
40
- sanitized first. Everything else is checked at the render boundary: the object form of
41
- `attributes` cannot escape the tag it describes **and cannot add a second attribute inside it** — a
42
- name carrying a space, a quote, `/`, `=` or `>` is refused, which is the same set `setAttribute`
43
- refuses in the browser — and every interpolated value in a template is escaped as it is written. A
44
- `__proto__` key in `props` is skipped rather than assigned, so handing the option a parsed request
45
- body cannot replace the component's prototype. Reach for the string form of `attributes` only when you must produce markup an object cannot
46
- describe.
47
-
48
- - Node resolves the component's module graph natively (the `.ts`-via-`.js` convention included);
49
- execution registers classes through `customElements.define` — no AST walking.
50
- - **The lifecycle runs the way it does in a browser.** `attributeChangedCallback` fires on upgrade
51
- for every present observed attribute and again on every later change; there is no animation frame
52
- to wait for — frames are queued and drained once `connectedCallback` returns, and again for
53
- whatever those schedule, so a re-render and every `useEffect` land before the markup is
54
- serialized, coalesced exactly as a browser coalesces them. An endless animation loop is bounded
55
- rather than run forever. `tests/lifecycle-parity.test.mjs` renders each case on both sides and
56
- compares the DOM.
57
- - **A failure during a render rejects — it is never markup.** Core isolates a hook error so one bad
58
- effect cannot take out the hooks beside it, which is right in a browser because the next render
59
- can recover. There is no next render here, so `renderToString` collects those failures and throws,
60
- naming the component. Catch it to fall back to a client-rendered shell, as you would with React or
61
- Vue.
62
- - **`renderToStringAsync` awaits the component's lifecycle.** `renderToString` is synchronous end to
63
- end, so an `async connectedCallback` is refused — its markup would be empty, and saying so beats
64
- shipping it. `renderToStringAsync` waits: for the callback, and for promises to settle between
65
- frame rounds. That is what a component loading data needs, and what puts **a routed component's
66
- first view in the first response** rather than only after hydration.
67
-
68
- Everything that decides *what* to emit is shared with `renderToString` — the scanner, the
69
- serializer, the instance preparation, the page assembly — and
70
- `tests/ssr-async-parity.test.mjs` renders every fixture through both and compares. The scan itself
71
- stays synchronous in both: a component tag becomes a placeholder and its render a promise, and the
72
- placeholders are substituted once everything settles. Awaiting inside the scan would have meant a
73
- second copy of the parser, and an async recursion measures 2.45x even when nothing suspends —
74
- which the synchronous path is not going to pay for a feature it never uses.
75
-
76
- **Asynchronous renders take a turn each.** The per-render bookkeeping is module-level, and being
77
- synchronous end to end is what makes concurrent `renderToString` calls safe; a render that pauses
78
- does not have that protection, so two overlapping ones would read each other's. One at a time is
79
- the version that cannot be wrong — and the turn covers **both** entry points, because a
80
- synchronous render fired inside an asynchronous one's suspension window would run to completion
81
- on the shared state and the async render would resume into the wreckage. Every caller already
82
- awaits, so the turn is invisible; when nothing is in flight it costs one microtask.
83
-
84
- - **`static: true` renders a page that will not be interactive, about 3x faster.** A server render is
85
- one shot — the subscriptions built while it runs are never fired afterwards — so tracking every
86
- property read to create them is pure cost. Measured on a component rendering twenty rows, the proxy
87
- behind `createStore` is the *entire* reactivity overhead: about 40 µs against a 15 µs baseline,
88
- where effects and the scheduler cost nothing detectable. With `static` on, `createStore` hands back
89
- a plain object and reads are ordinary property access.
90
-
91
- **The markup is identical** — that is the whole safety of it, and it is not asserted on an example:
92
- `tests/ssr-static-mode.test.mjs` renders *every* fixture in the suite both ways and compares markup,
93
- styles and title. A mode that cannot drift is why this is a flag rather than a second renderer.
94
-
95
- **A store written to during a static render throws**, naming the option, rather than rendering
96
- markup that reflects none of the writes. That guard is *not* development-only, unlike most of this
97
- framework's diagnostics: a server runs the production build, so folding it away would remove it
98
- from the only place it matters.
99
-
100
- - **Events are real, and they propagate** — `EventTarget` semantics on elements, shadow roots,
101
- `document` and `window`, including `once`, `handleEvent` objects, `event.target` and a
102
- `dispatchEvent` return value that reflects `preventDefault` — plus the capture, target and bubble
103
- phases, `stopPropagation`, `stopImmediatePropagation`, `composedPath()`, and a shadow boundary
104
- crossed only by a `composed` event. Bubbling used to be absent because this DOM held children as a
105
- string and there was no ancestor chain to walk; children are nodes now, so there is. The walk is
106
- over the node tree — an event does not continue into `document` or `window`, which are not part of
107
- it here.
108
- - **The properties only *some* elements have are there too, and reach the markup.** `input.disabled`,
109
- `a.href`, `td.colSpan`, `option.selected` — 273 of them across 44 tags, measured from Chromium,
110
- Firefox and WebKit rather than written from memory (`scripts/measure-element-reflections.mjs`).
111
- Each tag gets a prototype carrying exactly its own interface, so `'disabled' in paragraph` stays
112
- `false`: an element answering for members it does not have is the same lie as one missing the
113
- members it does. Without this layer `button.disabled = true` stored a plain JavaScript property —
114
- it read back `true`, wrote no attribute, and **served a button that was not disabled** until the
115
- bundle landed. A property is only in the table when all three engines agree on every measured cell
116
- *and* reading the attribute back gives what was written, which excludes the ones resolved against a
117
- document URL (`form.action`), read out of layout (`input.width`) or clamped (`meter.value`); those
118
- are listed with the measurement that produced each. `value`, `checked` and `selected` are the
119
- deliberate exception — a browser keeps them off the markup, and on a server the markup is the whole
120
- output, so they are mirrored exactly as `serializer.js` already mirrors the same three for template
121
- bindings.
122
- - **A parsed `<template>`'s content is opaque, and `template.content` is `undefined` here.** The
123
- element itself is modelled — found by `querySelector`, styled, serialised back byte for byte — and
124
- a query on the host correctly does not descend into it, which is what a real DOM does too. What is
125
- missing is reaching INTO one: `template.content.querySelector(…)` answers nothing on the server
126
- and a fragment in the browser.
127
- It used to be far worse. Markup containing a `<template>` was refused outright, so the host had no
128
- nodes at all and EVERY query on it answered emptily — one empty `<template>` turned
129
- `querySelectorAll('*')` from three elements into none, silently, and cost light-DOM slots their
130
- whole server render. Keeping the interior opaque, exactly as `<svg>` already was, fixed that.
131
- Implementing `content` is a contained follow-up if anything needs it: the interior is already
132
- retained verbatim, so the getter is a lazy `parseFragment` of the string it already holds.
133
-
134
- - **The server DOM is complete, and checked twice.** Every member a real element, shadow root,
135
- document, `CSSStyleSheet`, `DOMTokenList` **or window** exposes in Chromium, Firefox and WebKit is
136
- either implemented or listed as out of scope with a reason — and every member that *is* implemented
137
- is then compared against a real DOM, member by member, so one that exists and answers differently
138
- fails too. That second check is the one that earns its keep: enumerating presence found a single
139
- gap, while comparing behaviour found `tabIndex` defaulting to 0, `draggable` defaulting to true,
140
- `role` answering `''` where the platform answers `null`, `textContent = null` writing the word
141
- "null", and a closed shadow root handed straight back. **That comparison checks a member's *shape*
142
- — the type it answers with — not its answer to every input**, so it is a net rather than a proof:
143
- an empty array and a full one look the same to it. Three separate classes of defect were found by
144
- going around it deliberately — passing values nobody would pass (a symbol, where the platform
145
- throws), checking the members jsdom does not implement at all (which it must skip), and asking
146
- whether a member that answers *emptily* should have answered at all. The window's ~700 interface constructors are
147
- covered by a rule rather than a list: every interface this DOM implements is exposed, so
148
- `instanceof` answers for anything it hands you — the list is checked in (`tests/dom-surface.mjs`, no dependency involved) and
149
- both halves are enforced, so a gap fails a test instead of a render. That includes the sixty reflected
150
- properties (`id`, `className`, `hidden`, `tabIndex`, `role`, the whole `aria*` family), which are
151
- views of an attribute and therefore reach the markup, and `attachInternals()`, so a
152
- form-associated custom element runs, and the objects those members hand back — `classList`,
153
- `style`, `dataset` — are held to the same list rather than assumed complete once the property
154
- exists. `attachShadow({ mode: 'closed' })` behaves as it does in a browser: `element.shadowRoot`
155
- is `null`, and the root is serialized anyway, because declarative shadow DOM expresses `closed`
156
- and the client re-creates it just as hidden. **Where the platform throws, this throws** — an
157
- attribute or tag name that cannot be written, a second `attachShadow` or `attachInternals`, an
158
- invalid custom-element name, `appendChild` of a non-node. A server that is lenient about an error
159
- does not make anything work; it moves the failure to the client and strips the context. The
160
- exceptions are deliberate: **a selector this DOM cannot answer honestly throws** rather than
161
- answering `null`. It matches type, class, id, every attribute operator, `:not()` and all four
162
- combinators — descendant, `>`, `+` and `~`. Everything else raises instead of quietly reporting no
163
- match, for **two different reasons**: `:hover`, `:checked`, `:visible` and `:root` need user state,
164
- layout or a document a server does not have, while `:first-child`, `:nth-child()`, `:empty`,
165
- `:first-of-type`, `:is()` and `:has()` are answerable here and simply are not implemented. That
166
- second group used to be covered by the first reason, which made a limit of this matcher read as a
167
- property of servers — and predicted, wrongly, that `:first-child` would work;
168
- **A collection is a plain array**, not a live `NodeList` or `HTMLCollection` — `childNodes`,
169
- `children`, `querySelectorAll` and the `getElementsBy*` family all answer with one. There is nothing
170
- to be live *over* while a render is a single pass, and an array is more useful to a caller than a
171
- collection they have to spread. `item()` and `namedItem()` are provided anyway, because losing them
172
- was a side effect of that choice rather than part of it: `list.item(0)` is ordinary code, and threw.
173
- **`checkVisibility()` is always `false`**, since nothing here is laid out and a
174
- server cannot know what CSS will do, a constructed sheet holds its CSS as **text** rather
175
- than a parsed rule list — so `cssRules` is empty whatever the sheet contains, which is all the
176
- markup needs and is why `deleteRule` says so rather than pretending, and `insertAdjacentHTML` with `beforebegin` or
177
- `afterend` raises a message explaining that a server-rendered component has no parent, which is
178
- more use than the platform's bare `SyntaxError`. A `style` value is stored as it was
179
- written rather than re-serialized, so `url("data:…")` keeps its quotes where a browser's CSS
180
- serializer drops them — equivalent CSS, and a semicolon inside a value does not split the
181
- declaration, which is what matters for an inline `data:` URI. Layout reads as zero because that is what a
182
- detached element answers in a browser too. **Names fold the way the platform folds
183
- them**: an HTML element lower-cases its tag and its attribute names, so `setAttribute('Data-Flag', …)`
184
- and `getAttribute('data-flag')` are one attribute and an `attributes` entry spelled `User-ID`
185
- still matches an `observedAttributes` entry spelled `user-id`; an element created through
186
- `createElementNS` outside the HTML namespace keeps its case, so an SVG `viewBox` survives.
3
+ Server-side rendering for VeraJS components. Node only, plain ESM, **zero dependencies** — no jsdom,
4
+ no parse5, no lit, no acorn. Components render to **declarative shadow DOM**, and the renderer's
5
+ `hydration` module (`wire([renderer, hydration])`) adopts that markup in the browser without re-creating it.
6
+
7
+ **Light-DOM slots** are distributed on the server while `@verajs/renderer/slots` is wired: each filled slot is written
8
+ with the two comments the client keeps around it (`<!--[-->` … `<!--]-->`), and the host states its light tree in
9
+ `data-vm-light`. A hydrating page reads that through one more module, wired only where both are used:
10
+ `wire([renderer, hydration, slots, hydrateSlots])` (`@verajs/renderer/hydrate-slots`). Render and hydrate with
11
+ matching releases of `@verajs/ssr` and `@verajs/renderer` — the statement carries a format number, and a page in
12
+ another format renders fresh, its content kept.
13
+
14
+ **Hydrate what this renders: wire `hydration` on the client** (`wire([renderer, hydration])`). Without it the client renders
15
+ beside the server's markup — two copies — except a light-slots host, which re-renders once or, holding light content,
16
+ stands as served with `hydration-unwired`.
17
+
18
+ **Wire `slots` on the client AND here:** without it this server writes no light-tree statement, so the client takes
19
+ every component it rendered for client-made and renders it fresh — its markup kept, hidden — with no warning possible.
20
+
21
+ **Serve the HTML unmodified — comments included.** Hydration adopts those slot comments. An HTML minifier that strips
22
+ comments removes them, and hydration then treats that component as a mismatch: the standard fallback warning and a
23
+ fresh render, as React, Lit and Solid treat a missing marker of theirs.
24
+
25
+ ```js
26
+ import { renderToString } from '@verajs/ssr'; // first — it installs the DOM the renderer needs
27
+
28
+ const { html, styles, title } = await renderToString(new URL('./components/app.js', import.meta.url), {
29
+ attributes: { 'user-id': id }, // an object: names checked, values escaped
30
+ props: { rows }, // structured data — an attribute can only carry a string
31
+ location: request.url, // this request's URL, for anything that reads one
32
+ });
33
+
34
+ response.end(`<!doctype html><title>${escape(title)}</title><style>${styles}</style>${html}`);
35
+ ```
36
+
37
+ `html` is the component's markup, its shadow root serialized as `<template shadowrootmode>`. `styles`
38
+ is the light-DOM CSS for the page's `<style>` (already escaped for that element — see
39
+ [Styles](#styles)). `title` is `document.title` as the render left it, which is how a shell names its
40
+ page. `examples/ssr-node/server-native.mjs` is a complete server on bare `node:http` serving the whole
41
+ round trip, hydration included.
42
+
43
+ The package is TypeScript, compiled file by file to `dist` (no bundling, no minification), with its `.d.ts` files
44
+ beside it for TypeScript consumers.
45
+
46
+ ## Two entry points
47
+
48
+ | | |
49
+ | --- | --- |
50
+ | `renderToString(url, options?)` | synchronous end to end; the fastest path, and the right one for most components |
51
+ | `renderToStringAsync(url, options?)` | **awaits** the lifecycle — an `async connectedCallback`, and work a frame starts — so a component that loads data, or **a routed app's first view**, is in the first response |
52
+
53
+ Both take the same options, return the same `{ html, styles, title }`, and share everything that
54
+ decides what to emit — scanner, serializer, instance preparation, page assembly.
55
+ `tests/ssr-async-parity.test.mjs` renders every fixture through both and compares.
56
+
57
+ **Use the async one for a router.** `initRouter` works on the server, and the router's first
58
+ navigation runs on a frame and awaits its route. `renderToString` serializes before that settles, so it
59
+ serves the shell with an empty `[view]` outlet for the client to fill; `renderToStringAsync` waits, and
60
+ serves the route the request's `location` names. `renderToString` **refuses** an `async
61
+ connectedCallback` rather than serve its empty markup.
62
+
63
+ **Renders take turns** — one at a time, across both entry points. The per-render bookkeeping is
64
+ module-level, so two renders interleaving would read each other's; queueing is the version that
65
+ cannot be wrong, costs one microtask when nothing is in flight, and is invisible because every caller
66
+ already awaits. A render that throws does not stop the queue.
67
+
68
+ ## Options
69
+
70
+ | Option | |
71
+ | --- | --- |
72
+ | `tag` | which element to render when the module defines several. Otherwise the module's exported class is matched against the registry — so **export the class**, or pass `tag` |
73
+ | `attributes` | the entry tag's attributes. **An object** — values escaped, names checked. A string is written through untouched (a sink: see [Security](#security)) |
74
+ | `props` | properties assigned to the instance before `connectedCallback`, by identity. A `__proto__` key is skipped, and a read-only property is refused by name |
75
+ | `children` | markup placed inside the entry tag, where a client parser would have put it — what a `<slot>` renders. **Raw markup** |
76
+ | `location` | this request's URL — a path or a full URL — applied for the render and restored after |
77
+ | `seen` | a `Set` carried across renders, so a page of islands ships each component's styles once |
78
+ | `base` | a directory the module URL must resolve inside. Pass it whenever **any part of the URL came from a request** |
79
+ | `static` | `true` for a page that will not be interactive: reactivity is skipped, about 3x faster, identical markup |
80
+ | `timeout` | how long `renderToStringAsync` waits on promises a component starts, in milliseconds (default 2000), before serving what it has and warning — see below. **`0` waits for nothing** (it is not "no limit", which this option cannot express): every such promise is abandoned at once |
81
+
82
+ A wrong type is refused with a `TypeError` naming the option (`children: 5` used to surface as
83
+ `markup.includes is not a function`).
84
+
85
+ **Pass `location`; never assign `globalThis.location` yourself.** The global belongs to the process
86
+ and a request does not: the call awaits `import()`, which yields on a module's first import, so
87
+ whichever request assigned last wins for every render after it. Measured with three concurrent
88
+ first-time imports, two of three rendered another request's path. The option is applied inside the
89
+ render's turn and restored in a `finally`. `title` is returned rather than left on the global for the
90
+ same reason, and the document's own title is restored afterwards. **Renders take turns**, process-wide: two
91
+ calls made together run one after the other, so no render ever sees another's frames, adopted stylesheets or
92
+ globals (measured: two `renderToStringAsync` calls started at once finish at 154 ms and 255 ms, the second's
93
+ budget starting at its turn).
94
+
95
+ **No render waits unboundedly on a component's promise.** `renderToStringAsync` awaits what a component starts
96
+ — an `async connectedCallback`, a promise a frame callback returns — for at most `timeout` milliseconds (2000 by
97
+ default) from the start of its turn. One that never settles, such as a wait on a child the server never defines,
98
+ used to hold the request open forever, and because renders take turns, every request after it as well. When the
99
+ budget runs out the render serves what it has and warns, in every build, naming the component — once per component
100
+ for the life of the process, as every ssr warning is: the page served is not the one its code describes, so raise
101
+ `timeout` if the wait is real or find the promise that never settles.
102
+ There is deliberately no way to wait without limit: `timeout: 0` means wait for nothing, and the largest value is
103
+ 2147483647 ms.
104
+
105
+ **What ssr says, and how.** Every line ends with its code — the full explanation of a code is at
106
+ `https://verajs.dev/e/<code>` — and keeps its whole sentence in every build, since a server's log is read by its
107
+ developer. Two rules make it safe on a server: **a warning is said once per process per key** (the component, and the
108
+ attribute or event where that tells two facts apart), because a server renders per request and a per-render warning
109
+ would flood the log at request rate; and **text from outside — an error's message, a URL, a selector — is
110
+ JSON-quoted and cut to 80 characters**, so a newline or an escape sequence in it can neither forge nor hide a log line.
111
+ A refused `javascript:` URL is reported without its value at all, and data shaped like a template is reported and
112
+ rendered as the object it is. The errors the shim throws in the platform's own words (`Failed to execute 'appendChild'
113
+ on 'Node'…`) stay exactly those: this is a DOM, and it answers as the browser does.
114
+
115
+ **A wait on a child only the browser defines costs the whole `timeout`, on every request** — and since renders take
116
+ turns, every request queued behind it waits too. The warning names the component waiting and the child it waits on.
117
+ Don't make the setup wait for it — write the result into state when it arrives:
118
+
119
+ ```js
120
+ connectedCallback() {
121
+ init({ host: this, shadow: 'open' }, () => {
122
+ const state = createStore({ ready: false });
123
+ customElements.whenDefined('x-map').then(() => (state.ready = true)); // not awaited: the server serves 'loading map'
124
+ return () => html`<p>${state.ready ? 'map ready' : 'loading map'}</p><x-map></x-map>`;
125
+ });
126
+ }
127
+ ```
128
+
129
+ That serves the component's state from before the wait, which is exactly what the browser shows first, so hydrating
130
+ changes nothing — and it takes no time and prints no warning. Skipping only the `await`
131
+ (`if (!globalThis.__veraSsrShimmed) await …`) serves the state *after* it, which the browser then replaces with its own
132
+ starting state: a visible flash. A stand-in class defined on the server does the same.
133
+
134
+ **`globalThis.__veraSsrShimmed` is the supported way to tell the server render from a browser**, here and for guarding
135
+ client wiring: `@verajs/ssr` sets it to `true` when it is imported, before any component runs, and nothing sets it in a
136
+ browser. `typeof window` cannot tell them apart, because the server provides a `window`.
137
+
138
+ ## What runs, and when
139
+
140
+ **The lifecycle runs the way it does in a browser.** The class is constructed through the registry,
141
+ the markup's attributes are set, `attributeChangedCallback` fires for each observed one on upgrade and
142
+ again on every later change, and then `connectedCallback` runs. `tests/lifecycle-parity.test.mjs`
143
+ renders each case on both sides and compares the DOM. What a component does to itself there — a
144
+ `setAttribute`, an `aria-*`, a class, a reflected property — reaches the markup.
145
+
146
+ **Frames are drained before the markup is read.** A server never paints, so `requestAnimationFrame`
147
+ (and `requestIdleCallback`) callbacks are queued and run once `connectedCallback` returns, then again
148
+ for whatever those schedule — so a re-render and every `effect` land in the markup, coalesced
149
+ exactly as a browser coalesces them.
150
+
151
+ - **An endless animation loop is bounded**: 20 rounds, then the render ships. What the loop left
152
+ queued is dropped, never run inside the next component's render.
153
+ - **The async chain lets promises settle between rounds.** A frame that returns a promise is awaited,
154
+ whatever it awaits; work a frame starts without returning it is caught if it lands within three idle
155
+ microtask turns (measured: a chain four microtasks deep).
156
+ - **a `'layout'` effect runs on a microtask.** Through `renderToStringAsync` its state reaches the
157
+ markup, as on the client. Through `renderToString` it runs — a side effect inside one *happens* on the
158
+ server — but after the template was serialized, so state it settles is not in the markup: settle it
159
+ before `render()`, or use `renderToStringAsync`.
160
+
161
+ **A failure rejects the render — it is never markup.** In a browser, core isolates a hook's error so
162
+ one bad effect cannot take out its neighbors, because the next render can recover. There is no next
163
+ render here, so every failure — a throwing hook or `connectedCallback`, a `settle` handler that
164
+ throws — rejects the render, naming the component (and how many more failed), with the original
165
+ error as `cause`. Catch it to fall back to a client-rendered shell, as you would with React or Vue.
166
+
167
+ **A component's render owns its own range and nothing else**, as in a browser: content already in the
168
+ container stays before it, a node the component appends to its own root stays after it, and both
169
+ survive every re-render. So `children` reach a light-DOM component and are still there after it
170
+ renders.
171
+
172
+ ## Nested components
173
+
174
+ After a component renders, its markup is scanned for tags the registry knows, and each is rendered in
175
+ place — **exactly where the browser creates an element the definition upgrades**, read by the same tag scanner
176
+ every template goes through. It respects quoted attribute values (a `>` is legal inside one), leaves comments,
177
+ raw text (`<script>`, `<style>`, `<textarea>`, `<title>`…) and `<template>` content alone, and renders nothing
178
+ inside `<svg>` or `<math>`, where a dashed tag is a foreign element no definition upgrades — except inside an
179
+ HTML integration point (`<svg><foreignObject>`, `<math><mtext>`…), or after a tag that breaks out of foreign
180
+ content (`<svg><p><my-comp>`), both of which the browser reads as HTML. A tag's name is the whole name the tokenizer
181
+ reads, so `<my-comp.x>` is another, unregistered element and is left exactly as written. After `<font color>` inside
182
+ `<svg>` (a breakout this scan does not track) a component is not rendered on the server, and renders on the client.
183
+
187
184
  - **A component can build another component.** `document.createElement('my-comp')` constructs the
188
- registered class, so its field initialisers have run and `instanceof` answers, and appending it
189
- renders **that instance** — everything the parent assigned to it, `kid.rows = data` included,
190
- survives. The nested-component scan used to re-create the child from its markup, where an
191
- attribute is the only thing that can carry a value.
192
- - **`render()` owns its own range and nothing else**, exactly as it does in a browser. Content
193
- already in the container stays before the rendered range, a node the component appends to its own
194
- root stays after it, and both survive every re-render — so a component that mixes `render()` with
195
- its own `appendChild` produces the same DOM on both sides. It also means `children` reach a
196
- light-DOM component and are still there after it renders.
197
- - **A `<select>`'s value is served as `<option selected>`.** And a value matching no option cannot be served —
198
- see the exception below, which has no fix. A `<select>` has no `value` content attribute — assigning the property *selects an
199
- option* — so the only thing markup can say is which option is chosen, and that is what the
200
- serializer writes (React's server renderer does the same; `@lit-labs/ssr` drops the binding and
201
- serves a control showing its first option). Matching follows the platform: the `value` attribute
202
- verbatim if an option has one, otherwise the option's text **stripped and collapsed**, first match
203
- wins, and a `selected` the author wrote is cleared because a property assignment overrides markup.
204
- All of it is asserted against Chromium, Firefox and WebKit in
205
- `tests/browser/select-value.test.js`.
206
-
207
- The exception is real and has no fix. When the value matches **no** option the client leaves
208
- `selectedIndex` at `-1` with nothing showing, and a parsed `<select>` whose options carry no
209
- `selected` takes its **first** — there is no markup for "none of them", and inserting a hidden
210
- placeholder would change the control the author wrote.
211
-
212
- - **Component nesting is capped at 256 levels, and the client has no such cap.** A component that
213
- renders itself recurses without bound, which on a server is a hung request rather than a hung tab,
214
- so `renderToString` refuses past 256 and says so. This is a real divergence, and 256 is chosen to
215
- sit *below where the client breaks*: the client managed about 340 levels before `RangeError`
216
- (reported through the `'error'` insert), so the server still fails first and fails with a sentence.
217
- That ~340 is engine-dependent, which is why the server does not wait for it.
218
- - **A carriage return survives, as `&#13;` — everywhere except `<style>` and `<script>`.** The HTML
219
- input-stream preprocessor collapses CR and CRLF to a single LF *before* tokenization, so a raw
220
- `\r` written into markup does not come back — the server would render `a\r\nb` and the client read
221
- `a\nb`, which is a silent hydration mismatch on every render of a `<textarea>` value, a CSV cell, or
222
- any string from a Windows-authored source. Character references are resolved *after* preprocessing,
223
- so the escaped form does survive; verified identical in Chromium, Firefox and WebKit.
224
-
225
- **RAWTEXT is the exception, and it is not fixable.** A browser does not decode a character
226
- reference inside `<style>` or `<script>` — that is what makes them RAWTEXT — so `&#13;` there is
227
- the literal six characters, while the preprocessor still collapses the raw CR. There is no spelling
228
- of a carriage return that survives in those two elements. `<title>` and `<textarea>` are RCDATA,
229
- which *does* decode references, which is why they round-trip correctly. All three behaviours are
230
- asserted against Chromium, Firefox and WebKit in `tests/browser/rawtext-carriage-return.test.js`.
231
-
232
- In practice this reaches an interpolated stylesheet or inline script whose source has Windows line
233
- endings — a repository checked out with `core.autocrlf=true` puts CRLF inside every template
234
- literal, `css` blocks included. CR and LF are interchangeable whitespace to both CSS and
235
- JavaScript, so nothing renders wrongly; the two sides simply hold different strings.
236
- - **Three things cannot survive a server round trip, and are the only three.** Two are characters and
237
- one is a character in a position — see the carriage return above, which round-trips everywhere
238
- except inside `<style>` and `<script>`.
239
- - **NUL** (`\u0000`) is dropped in text, rewritten to U+FFFD in an attribute **and inside
240
- RAWTEXT**, and `&#0;` is a parse error that also yields U+FFFD. No spelling round-trips, so it is left alone rather than
241
- silently turned into U+FFFD — that would make the markup lie about what the component rendered
242
- without making the two sides agree.
243
- - **A lone surrogate** (`\uD800` with no pair) is not encodable in UTF-8, so the *transport*
244
- replaces it with U+FFFD — a real HTTP response does exactly what `Buffer.toString('utf8')` does.
245
- Nothing server-side can prevent that.
246
-
247
- Both are covered by `tests/ssr-text-boundary.test.mjs`, alongside astral pairs, combining marks,
248
- bidi controls, noncharacters and 20 other cases that *do* round-trip exactly.
249
- - **What a component does to itself in `connectedCallback` reaches the markup** — a `setAttribute`,
250
- an `aria-*`, a class, a reflected property.
251
- - **`<style>` and `<script>` content is written raw**, and their own end tags are neutralised
252
- (`<\/style`, `<\/script` — valid CSS and JavaScript, invisible to the tokenizer). A browser does
253
- not decode a character reference inside either, so escaping there protects nothing and corrupts
254
- the content: an interpolated `.a > .b` used to serve `.a &#62; .b`, a selector matching nothing,
255
- while the client rendered it correctly. `<title>` and `<textarea>` are RCDATA rather than RAWTEXT
256
- — references *are* decoded there — so those keep ordinary escaping, which is also what the client
257
- produces for them.
258
- - Templates flatten through a sigil-aware serializer with per-template-identity plan caching:
259
- `?bool` resolved by truthiness, `.value`/`.checked`/`.selected` mirrored to attributes on form
260
- controls, `@event`/`&ref` stripped without residue, every interpolated value escaped at the
261
- boundary.
262
- - **A property bound on a rendered component tag is DELIVERED, not dropped**: written
263
- (`<props-row .item=${row}>`) or spread (`props({ item })`), the value reaches the instance the
264
- nested-component scan renders — by identity, before its lifecycle, exactly where
265
- `renderToString`'s own `props` option puts the entry component's. The markup never changes (a
266
- property is not an attribute), so the child's server output comes from the same data its client
267
- render will get, which is the hydration contract. An **unregistered** dashed tag passes through
268
- untouched — its properties stay the client's to apply. Values that cannot exist server-side
269
- (a DOM node, a callback into browser state) are the component's to guard, as in every SSR
270
- framework.
271
- - Output is declarative shadow DOM with **zero framework comments**; light-DOM `@scope` styles are
272
- returned separately for the page shell.
273
- - Client-side, `@verajs/renderer/hydrate` adopts the server DOM markerlessly (swap one import).
274
- - Measured (`node bench/ssr.mjs`, fastest of 7 rounds), against lit on both comparisons it
275
- supports — µs per render, small component / 100-row table:
276
-
277
- | | small | table |
278
- | --- | --- | --- |
279
- | **template serialization** — `serializeTemplate` vs `@lit-labs/ssr` on a template | **0.3** | **35** |
280
- | | lit 2.4 | lit 312 |
281
- | **whole component** — `renderToString` vs a real `LitElement` | **4.3** | **49** |
282
- | | lit 5.7 | lit 414 |
283
-
284
- Vue's compiled SSR is 7.9 / 61 µs and React 6.2 / 453 µs, neither of which renders a
285
- component. The `lit element` row runs in a separate process because `@lit-labs/ssr` and this
286
- package both install DOM globals and cannot share one.
287
- - **Most of a component render is core's lifecycle, not this package.** Rendering the same component
288
- with its `connectedCallback` emptied — which removes core's `init`, store, hooks and re-render and
289
- leaves the shim, the serializer and the nested scan — costs **1.0 µs of a 6.4 µs render**, so
290
- everything this package does is about a sixth of it and the component's own lifecycle is the rest.
291
- (Those two figures come from a plain `await` loop rather than `bench/ssr.mjs`'s batched rounds, so
292
- they are higher than the table above and only their *ratio* is comparable.)
293
-
294
- `examples/ssr-node/server-native.mjs` is a complete server on bare `node:http`, serving the whole
295
- round trip — the page it returns ships a client module that imports `@verajs/renderer/hydrate` and
296
- adopts the markup in place.
297
-
298
- **No streaming.** `renderToString` returns a string, where `@lit-labs/ssr` yields a stream. That
299
- buys time-to-first-byte in proportion to how long a render takes, and a 100-row table here is 47 µs
300
- — the response is built before a streaming implementation would have flushed its first chunk. It is
301
- a real difference in shape, and worth revisiting for a page big enough that it stops being one.
302
-
303
- **Importing `@verajs/ssr` installs a DOM on `globalThis`.** That is what it is for, and it means the
304
- import is not passive: `document`, `customElements`, `HTMLElement` and the rest are *replaced*, so a
305
- process that already has a DOM — jsdom in a test, say — loses it the moment this module is loaded,
306
- however late. A component defined afterwards is never upgraded and nothing says why. **Exercise both
307
- sides in separate processes**, which is what this repo's own tests do; `tests/lifecycle-parity.test.mjs`
308
- renders the server half in a subprocess for exactly this reason.
309
-
310
- **And import it first**, before anything that imports `@verajs/renderer`.
311
-
312
- The module that actually needs the shims is the renderer, not core: it builds two shared
313
- `TreeWalker`s at import time, so importing it against a bare Node global object throws before your
314
- component ever runs. A component reaches it through `keyed` or `hold`, which is why the rule reads
315
- as "import this first" — measured, core, `@verajs/styles` and `@verajs/router` are all order-
316
- independent, and only `@verajs/renderer` is not.
317
-
318
- **The entry component is found by matching the module's exports against the registry**, so export
319
- the class (`export default class …`) or pass `{ tag }`. It used to guess by diffing the registry
320
- around the import, which two concurrent renders could not share: both saw both modules' new
321
- registrations, and a request could be answered with another component's markup.
322
-
323
- `renderToString` executes the module you name, so **pass `base` whenever any part of the URL came
324
- from a request**:
325
-
326
- renderToString(new URL(`${page}.js`, components), { base: components });
327
-
328
- Anything resolving outside it is refused. `new URL` applies `../` before `renderToString` sees the
329
- string, so without this the traversal has already happened by the time the call is made — and
330
- mapping a route to a component file is the obvious way to use a server renderer. Same containment,
331
- and the same wording, as `@verajs/autoloader` uses for the URLs it derives.
332
-
333
- It is opt-in because most calls name a constant, and a check that is always trivially satisfied
334
- stops being read.
335
-
336
- The globals a component reaches for are here too — `matchMedia` (matching nothing, as every server
337
- renderer answers), `getComputedStyle` (empty, as a detached element gives in a browser),
338
- `IntersectionObserver`/`ResizeObserver`/`MutationObserver`/`PerformanceObserver` (inert, because
339
- they observe things a server does not have, but constructing one must not throw), `requestIdleCallback`
340
- (which joins the frame queue), and the DOM interfaces themselves so `instanceof Node` answers rather
341
- than throwing.
342
-
343
- **`localStorage`, `sessionStorage`, `indexedDB` and `caches` are deliberately absent.** They are one
344
- browser's state, and a server that invented an empty one would render a logged-out shell that the
345
- client immediately replaces, with nothing failing anywhere. `typeof localStorage === 'undefined'` is
346
- the guard the ecosystem already writes, and it only works if this does not lie. The same list is
347
- enforced in `tests/ssr-dom-surface.test.mjs`, in both directions.
348
-
349
- Known limits:
350
-
351
- - **`connectedCallback` must be synchronous.** Rendering recurses inside `String.replace`, which
352
- cannot await, so an `async connectedCallback` is refused with an error rather than rendered empty.
353
- Load data before `renderToString` and pass it in as attributes.
354
- - **`useLayoutEffect` runs, but too late to reach the template it sits beside.** It is coalesced on
355
- a microtask, and `renderToString` is asynchronous, so it *does* execute — a `setAttribute` or an
356
- API call inside one happens on the server, which is worth knowing before you put one there. What
357
- it cannot do is change what the template already rendered: state settled in a layout effect is not
358
- in the markup. Settle it before `render()`, or use `useEffect`, whose frame is drained repeatedly
359
- and does reach the markup. `tests/lifecycle-parity.test.mjs` pins both halves of that.
360
- - `keyed`/`hold` are client constructs; use plain `.map` in SSR templates.
361
- - **A routed component renders its shell, not its route.** `initRouter` works server-side — the
362
- shim provides enough `window` for it — so the nav and the `[view]` outlet reach the markup and the
363
- client fills the outlet on hydration. The route's own content does not, **for the same reason an
364
- `async connectedCallback` is refused**: rendering is synchronous end to end and `navigate` is
365
- `async`. The initial navigation is scheduled on a frame, the frame runs, `navigate` is called and
366
- returns a promise — and the markup is serialized before that promise settles, so the component
367
- behind the route is never called. The outlet itself *is* found, and awaiting `navigate` outside a
368
- render works. Render the route yourself and pass it as `children` if it has to be in the first
369
- response.
370
- - **A dynamic attribute *name* is refused.** `<b ${name}="x">` is malformed on both sides: the
371
- client hands the template to the platform's parser and a marker is not a name, and this serializer
372
- used to emit `<b="x">`, which is not an attribute either. Rather than write markup no browser would
373
- produce, it throws and names the alternative — `@verajs/renderer/spread`, which exists for names
374
- that are not known until runtime and which this serializer understands.
375
- - **`slotAssignment` cannot be server-rendered.** Declarative shadow DOM can express `mode`,
376
- `delegatesFocus`, `clonable` and `serializable` — all of which are serialized — but has no form
377
- for manual slot assignment, and `attachShadow` **ignores the options it is handed** when it reuses
378
- a declarative root, so the client cannot repair what the markup left out.
185
+ registered class — field initializers run, `instanceof` answers — and appending it renders **that
186
+ instance**, so everything the parent assigned (`kid.rows = data`) survives.
187
+ - **A property bound on a component tag is delivered**, not dropped: written (`<props-row .item=${row}>`)
188
+ or spread (`props({ item })`), the value reaches the instance the scan renders — by identity, before
189
+ its lifecycle, exactly where the `props` option puts the entry component's. The markup never carries
190
+ it (a property is not an attribute), so the child renders from the same data its client render will
191
+ get: that is the hydration contract. An **unregistered** dashed tag passes through untouched.
192
+ - Both ride on a marker attribute that crosses the string boundary and is removed before the page is
193
+ returned. **It only ever produces the component it was written for**: a copy of it on another tag is
194
+ ignored, and a copy on a second element of the same tag renders the instance once, not twice.
195
+ - **Nesting is capped at 256 levels, and the client has no such cap.** A component that renders itself
196
+ recurses without bound, which on a server is a hung request, so the render refuses past 256 and says
197
+ so. 256 sits *below* where the client breaks (about 340 levels before a `RangeError`, engine-
198
+ dependent), so the server still fails first, and with a sentence.
199
+
200
+ ## Static pages
201
+
202
+ `static: true` renders a page that will not be interactive, **about 3x faster** — 16 µs against
203
+ 42–50 µs for a component rendering twenty rows. A server render is one shot: the subscriptions a store
204
+ builds while it runs are never fired afterwards, so tracking every read to create them is the whole of
205
+ the cost. With `static` on, a store's property reads skip tracking.
206
+
207
+ - **The markup is identical**, and not on a chosen example: `tests/ssr-static-mode.test.mjs` renders
208
+ *every* fixture in the suite both ways and compares markup, styles and title. A mode that cannot
209
+ drift is why this is an option rather than a second renderer.
210
+ - **A store written during a static render throws**, naming the option, rather than serving markup
211
+ that reflects none of the writes. In both builds — a server runs the production build, so a
212
+ development-only guard would be missing from the only place it matters.
213
+ - It applies to the render, not to the process: a render queued behind a static one, and any store
214
+ written outside a render, are reactive as ever.
215
+
216
+ It is `@verajs/ssr`'s own `'store'` insert — core knows nothing about it.
217
+
218
+ ## Security
219
+
220
+ **Escaping happens at the render boundary, always.** Every interpolated value in a template is
221
+ escaped as it is written; `<style>` and `<script>` content is written raw with its own end tag
222
+ neutralized (`<\/style`, `<\/script` — valid CSS and JavaScript, invisible to the tokenizer), because a
223
+ browser does not decode a character reference inside either: escaping there protects nothing and
224
+ corrupts the content (`.a > .b` used to serve as `.a &#62; .b`, a selector matching nothing).
225
+ `<title>` and `<textarea>` decode references, so they keep ordinary escaping. **The same rule holds for content
226
+ a component writes through the server DOM**: `textContent`, `value`, `innerHTML` or a text node in any of those
227
+ elements is stored as text and written by its parent's rule, so data can never close the element it is in. **Raw is decided by where
228
+ the browser will parse the element, not by its name**: inside `<svg>` or `<math>` a `<style>` is an SVG or
229
+ MathML element whose content is markup, and `<noscript>` is markup to a browser with scripting off — so
230
+ inside any of them every value is escaped, and so is every value in a template rendered into one (an
231
+ `svg`/`mathml` template included, wherever it renders) — except inside an HTML integration point, which the
232
+ browser reads as HTML: SVG `<foreignObject>`, `<desc>` and `<title>`, MathML `<mi>`, `<mo>`, `<mn>`, `<ms>` and
233
+ `<mtext>`, and an `<annotation-xml>` whose `encoding` is HTML, each only in its own namespace and only when not
234
+ self-closed (`<math><mi><mglyph>` is MathML again) — and after a tag that ENDS foreign content, which the browser
235
+ reads as HTML again (`<svg><p>`, `<math><b>`, `</p>`; the standard's breakout list). Inside `<xmp>`, `<noembed>`, `<noframes>` and
236
+ `<plaintext>`, which the browser reads as text whole, nothing is raw either. **And a tag is read where the
237
+ browser's tokenizer reads one**: a tag's name is the whole run up to whitespace, `/` or `>` (`<script.x>` is an
238
+ unknown element, never a `<script>`), a `<` before anything but a letter is text, `<!x>` and `<?x>` are comments,
239
+ and a quote or `=` inside a name is part of the name.
240
+
241
+ **Two options are raw markup, on purpose: `children`, and the string form of `attributes`.** Both are
242
+ written through untouched — that is what they are for — so neither may carry anything from a request
243
+ unsanitized. Everything else is checked:
244
+
245
+ - **The object form of `attributes` cannot leave the tag or add a second attribute.** A name carrying
246
+ whitespace, a quote, `/`, `=` or `>` is refused — the set `setAttribute` refuses in a browser — and
247
+ every value is escaped. `false`, `null` and `undefined` omit the attribute; `true` writes it empty (`name=""`).
248
+ - **`.innerHTML` and `.textContent` render on the server**, so trusted markup bound the sanctioned way
249
+ (`<div .innerHTML=${markup}>`) is in the served page rather than filled in after hydration. It is made to behave
250
+ as an `innerHTML` assignment, not as parsed page markup: a `<script>` in it is served with an inert `type` (an
251
+ assignment never runs one), and a `<template shadowrootmode>` cannot attach a shadow root (an assignment never
252
+ does) — wherever the tokenizer reads a start tag, which the server finds with the same scanner it reads every
253
+ template with. Whatever the markup leaves open is closed before the element's own end tag, and an unfinished tag
254
+ at its end is dropped, as an assignment drops it, so it cannot reach the markup after it. On a `<style>`/`<script>` host the value is raw text with its end tag neutralized; on a
255
+ `<textarea>`, `<title>` or other text-only host, inside `<svg>`/`<math>`, and for any `.textContent`, it is
256
+ escaped text. A `<script .textContent=${code}>` host is the one code-execution door this opens, and it is the
257
+ author's: it runs on the served page as it runs on the client. `.innerText`, `.outerHTML` and `.outerText` stay
258
+ client-only — the server serves the element's template content.
259
+ - **Data shaped like a template is text.** A value renders as markup only when its strings came from a tagged
260
+ template literal; a `{"strings": [...]}` from `JSON.parse` — or a real template sent through JSON, or a
261
+ hand-built `html([markup])` — is served as `[object Object]`, as the client renders it, and never throws.
262
+ - **A `__proto__` key in `props` is skipped**, so handing the option a parsed request body cannot
263
+ replace the component's prototype.
264
+ - **Every bound attribute value is served double-quoted, whatever quoting the template used.** A value
265
+ shares its attribute with any statics and other holes around it — `title=pre${x}`, `title=${a}${b}`,
266
+ `title = ${x}`, single or double quotes — and the server writes that whole attribute once, the way the
267
+ client's `setAttribute` stores it, so nothing a value holds can end the attribute or start another.
268
+ A hole that is the whole value omits the attribute for `null` and `undefined`, as the client does; a
269
+ hole joined with statics contributes empty text.
270
+ - **A bound `javascript:` URL is never served.** A template value bound where a browser navigates
271
+ (`href`, `src`, `action`, `formaction`, `xlink:href`, `data`, and an SVG animation's `to`, `from`,
272
+ `by` and `values`, item by item) is dropped when it parses as a `javascript:` URL — judged on the attribute's whole value, statics and character references
273
+ included, as the browser will read it — and a bound `srcdoc` attribute is never served. The client
274
+ renderer refuses exactly the same values, so the two agree.
275
+ - **`base` contains the module URL.** `renderToString` executes the module it is given, and mapping
276
+ a route to a component file is the obvious way to use a server renderer — so pass `base` whenever
277
+ any part of the URL came from a request:
278
+
279
+ ```js
280
+ renderToString(new URL(`${page}.js`, components), { base: components });
281
+ ```
282
+
283
+ Anything resolving outside it is refused. `new URL` applies `../` before `renderToString` sees the
284
+ string, so without this the traversal has already happened by the time the call is made. It is
285
+ opt-in because most calls name a constant, and a check that is always trivially satisfied stops
286
+ being read.
287
+ - **`styles` comes back escaped for a `<style>` element**, since that is where a page shell puts it.
288
+ - **A dynamic attribute *name* is refused** — by the server in every build, and by the client renderer in
289
+ development. `<b ${name}="x">`, `<p data-${k}="1">`, `<p ${k}-x>`: the parser reads a name before any
290
+ value exists, so no position can hold it. Both throw at the template's first use, and the message shows
291
+ the `@verajs/renderer/spread` rewrite — `${spread({ [`data-${k}`]: '1' })}` — which applies the refusals
292
+ a runtime name needs. The same holds for a value in TAG position (`<${x}>`, `<my-${x}>`), which names
293
+ `@verajs/renderer/tag` — a runtime tag name is a tag value from that entry. The server refuses in production too, so a production server render of such a
294
+ template throws even though the client's production build would not — render it once in development
295
+ and it never gets that far.
296
+ - **A template ending inside a tag is refused** (`<b title="${x}` with no `>`), and so is **a template rendered
297
+ inside a text-only element** (`<textarea>`, `<title>`, …): both on the server in every build, the first also by
298
+ the client renderer in development. The client's parser drops an unfinished tag whole, so nothing can match it,
299
+ and a template's markup inside a text-only element is the one way a value could close that element. Strings,
300
+ numbers and arrays of them render in a `<textarea>` as always.
301
+
302
+ ## Styles
303
+
304
+ `@verajs/styles` is wired on import, because `static styles` are part of what a browser renders.
305
+
306
+ - **Shadow DOM:** markup cannot carry a constructed sheet, so a component's styles are serialized as
307
+ `<style data-vm-sheet="styles">` inside its template — plain strings first, then sheets, which is the
308
+ order the browser's cascade applies them in (adopted sheets win over a root's own `<style>`). When
309
+ every style is a sheet the client can adopt, it removes that copy, so the rules never apply twice.
310
+ - **Light DOM:** a component's `@scope (tag) { … }` block is returned in `styles` for the page shell,
311
+ **only for the components this render touched**, and — with a shared `seen` — once across a page of
312
+ islands.
313
+ - **A tag's CSS is established once per process**: whichever render reaches it first sets it. That is
314
+ what stops a per-class sheet being emitted once per instance; the consequence is that CSS varying
315
+ per request is dropped, with a warning — once, naming the component. Put what varies in
316
+ custom properties (see the `@verajs/styles` README).
317
+
318
+ ## The server DOM
319
+
320
+ Importing `@verajs/ssr` installs a DOM on `globalThis`: `document`, `window`, `customElements`,
321
+ `HTMLElement` and the rest, **replacing** any already there.
322
+
323
+ - **Import it first**, before anything that imports `@verajs/renderer`, which builds `TreeWalker`s at
324
+ import time and throws against a bare Node global. Core, `@verajs/styles` and `@verajs/router` are
325
+ order-independent.
326
+ - **Run any other DOM in another process.** jsdom in a test loses its globals the
327
+ moment this module loads, however late, and a component defined afterwards is never upgraded — with
328
+ nothing saying why. This repository's own tests render the server half in a subprocess for exactly
329
+ this reason.
330
+ - **A process that has loaded `@verajs/ssr` is a server.** Wiring vera's renderer there —
331
+ `wire([renderer])` or `wire([renderer({ shadow: 'open' })])` in app code the server and the browser
332
+ share — declines its render insert (the server renders with its own) and keeps only the shadow default,
333
+ so one shared wire call gives both sides the same default root; development says so once per process.
334
+ Import `@verajs/ssr` before that wire call. Code that needs the client renderer in the same process (a
335
+ test that server-renders and then hydrates) installs a client DOM and calls `renderInto` directly —
336
+ `wire([renderer])` there registers no client render insert — or renders the server half in a separate
337
+ process. The client renderer cannot draw into this DOM itself: it holds strings, not a tree. A renderer that is not vera's would displace the server's and is refused at render time; guard
338
+ its wiring (`if (!globalThis.__veraSsrShimmed)`).
339
+
340
+ **It is complete, and checked twice.** Every member a real element, shadow root, document,
341
+ `CSSStyleSheet`, `DOMTokenList` or window exposes in Chromium, Firefox and WebKit is either
342
+ implemented or listed as out of scope with a reason — and every implemented member is compared against
343
+ a real DOM, so one that exists and answers differently fails too. That second check found `tabIndex`
344
+ defaulting to 0, `draggable` defaulting to true, `role` answering `''` where the platform answers
345
+ `null`, `textContent = null` writing the word "null", and a closed shadow root handed straight back. It
346
+ compares a member's *shape*, not its answer to every input, so it is a net rather than a proof — three
347
+ classes of defect were found by going around it deliberately. The window's ~700 interface constructors
348
+ are covered by a rule rather than a list (every interface this DOM implements is exposed, so
349
+ `instanceof` answers for anything it hands you); `tests/dom-surface.mjs` holds the list, with no
350
+ dependency involved.
351
+
352
+ - **Element-specific properties reach the markup.** `input.disabled`, `a.href`, `td.colSpan`,
353
+ `option.selected` — 273 of them across 44 tags, measured from the three engines
354
+ (`scripts/measure-element-reflections.mjs`), each tag getting exactly its own interface, so
355
+ `'disabled' in paragraph` stays `false`. Without this, `button.disabled = true` stored a plain
356
+ property and **served a button that was not disabled** until the bundle landed. A property is in the
357
+ table only when all three engines agree and reading the attribute back gives what was written, which
358
+ excludes ones resolved against a document URL (`form.action`), read from layout (`input.width`) or
359
+ clamped (`meter.value`). `value`, `checked` and `selected` are mirrored to the markup deliberately:
360
+ a browser keeps them off it, but on a server the markup is the whole output.
361
+ - **Events are real and propagate** — capture, target and bubble phases, `once`, `handleEvent`
362
+ objects, `stopPropagation`, `stopImmediatePropagation`, `composedPath()`, a `dispatchEvent` return
363
+ reflecting `preventDefault`, and a shadow boundary crossed only by a `composed` event. The walk is
364
+ over the node tree, so an event does not continue into `document` or `window`.
365
+ - **Where the platform throws, this throws** — an attribute or tag name that cannot be written, a
366
+ second `attachShadow` or `attachInternals`, an invalid custom-element name, and every Node-typed
367
+ argument that is not a node (`appendChild({})`, `removeChild(null)`, `contains({})`), with the
368
+ platform's `TypeError`. `new HTMLElement()`, `new Node()` and `new X()` for a class never defined are
369
+ an `Illegal constructor`, as they are in a browser. Lenience on a server does not make anything work;
370
+ it moves the failure to the client and strips the context.
371
+ - **The Node interfaces are the platform's.** A text node is a `Node`, a `CharacterData` and a `Text`;
372
+ `Node`'s constants are on every node; `append({})` inserts the text `[object Object]`, as the
373
+ `(Node or DOMString)` union converts; and `String(node)` names its interface (`[object Text]`) — for
374
+ text, comments, fragments and shadow roots. An element's name depends on its tag and is not yet
375
+ answered (`[object Node]` here, `[object HTMLDivElement]` in a browser).
376
+ - **A selector this DOM cannot answer honestly throws** rather than answering `null`. It matches type,
377
+ class, id, every attribute operator, `:not()` and all four combinators — descendant, `>`, `+` and
378
+ `~`. Everything else raises, for **two different reasons**: `:hover`, `:checked`, `:visible` and
379
+ `:root` need user state, layout or a document a server does not have, while `:first-child`,
380
+ `:nth-child()`, `:empty`, `:first-of-type`, `:is()` and `:has()` are answerable here and simply are
381
+ not implemented.
382
+ - **Names fold as the platform folds them**: an HTML element lower-cases its tag and attribute names,
383
+ so an `attributes` entry spelled `User-ID` matches an `observedAttributes` entry `user-id`; an
384
+ element from `createElementNS` outside the HTML namespace keeps its case, so an SVG `viewBox`
385
+ survives.
386
+ - `attachShadow({ mode: 'closed' })` gives `element.shadowRoot === null`, as in a browser, and the root
387
+ is serialized anyway — declarative shadow DOM expresses `closed`. `attachInternals()` works, so a
388
+ form-associated custom element runs.
389
+ - The globals a component reaches for exist: `matchMedia` (matching nothing), `getComputedStyle`
390
+ (empty, as a detached element answers), `IntersectionObserver`, `ResizeObserver`,
391
+ `MutationObserver` and `PerformanceObserver` (inert, but constructing one does not throw).
392
+ - **`localStorage`, `sessionStorage`, `indexedDB` and `caches` are deliberately absent.** They are one
393
+ browser's state; a server that invented an empty one would render a logged-out shell the client
394
+ immediately replaces, with nothing failing anywhere. `typeof localStorage === 'undefined'` is the
395
+ guard the ecosystem already writes, and it only works if this does not lie.
396
+
397
+ **Where it deliberately differs:**
398
+
399
+ - **A collection is a plain array**, not a live `NodeList` — `childNodes`, `children`,
400
+ `querySelectorAll`, the `getElementsBy*` family. There is nothing to be live over in a single pass;
401
+ `item()` and `namedItem()` are provided anyway.
402
+ - **A parsed `<template>`'s content is opaque**, and `template.content` is `undefined`. The element is
403
+ modeled — queried, styled, serialized byte for byte — and a query on the host correctly does not
404
+ descend into it; reaching *into* one is what is missing.
405
+ - **A constructed sheet holds its CSS as text**, so `cssRules` is empty and `deleteRule` refuses
406
+ rather than pretends. `checkVisibility()` is always `false` and layout reads as zero, as for a
407
+ detached element in a browser. A `style` value is kept as written (`url("data:…")` keeps its quotes).
408
+ - `insertAdjacentHTML` with `beforebegin` or `afterend` raises a message explaining that a
409
+ server-rendered component has no parent.
410
+ - **A created or parsed `<pre>`, `<listing>` or `<textarea>` whose text begins with a line feed reads back with
411
+ one extra line feed from `innerHTML`/`outerHTML`.** The parser takes one line feed right after those start tags,
412
+ and a browser's own serialization does not account for it — Chromium, Firefox and WebKit serialize the text
413
+ `"\nabc"` as `<pre>\nabc</pre>`, which parses back as `"abc"`. This DOM's serialization is what the server sends,
414
+ so it writes the one the parser will take; templates and `.textContent`/`.value`/`.innerHTML` bindings do the same.
415
+
416
+ **Values read back are the platform's.** A parsed node's text, attribute and comment values are what a browser's
417
+ parser makes of the markup: line breaks normalized (CRLF and CR read as LF; a `&#13;` reference stays a CR),
418
+ `<textarea>` and `<title>` content decoded, and the line feed after `<pre>`/`<listing>`/`<textarea>` taken. The
419
+ markup itself is served byte for byte as it was written.
420
+
421
+ ## What cannot round-trip
422
+
423
+ - **A binding inside a nested `<template>`'s content is ignored, on the server and the client alike.**
424
+ That content is inert markup the renderer never walks, so a value there is never rendered and an
425
+ attribute holding one is dropped whole; a binding on the `<template>` element itself is ordinary.
426
+ Render into the live tree instead.
427
+ - **A `<select>`'s value is served as `<option selected>`** — assigning the property *selects an
428
+ option*, so that is all markup can say, and `.selectedIndex` is served the same way by position. Matching follows the platform (the `value` attribute
429
+ verbatim, otherwise the option's text stripped and collapsed; first match wins), asserted against
430
+ Chromium, Firefox and WebKit in `tests/browser/select-value.test.js`. But a value matching no option cannot be served:
431
+ the client leaves nothing selected, while a parsed `<select>` with no `selected` option shows its
432
+ first, and there is no markup for "none of them". An index out of range, `-1` included, is the same case.
433
+ - **A carriage return survives, as `&#13;`** — the HTML parser collapses a raw CR before tokenizing,
434
+ so escaping it is what keeps a `<textarea>` value or a CSV cell identical on both sides.
435
+ **RAWTEXT is the exception, and it is not fixable**: inside `<style>` and `<script>` a reference is
436
+ not decoded, so there is no spelling of a CR that survives there. CR and LF are interchangeable
437
+ whitespace to CSS and JavaScript, so nothing renders wrongly — the two sides simply hold different
438
+ strings. Asserted in `tests/browser/rawtext-carriage-return.test.js`.
439
+ - **A `<style>` or `<script>` the server cannot place in HTML is served escaped.** Raw text is recognized
440
+ outside `<svg>`, `<math>` and `<noscript>`, inside their HTML integration points (`<svg><foreignObject>`,
441
+ `<math><mi>`…) and after a breakout tag (`<svg><p>`), but the scanner does not track the remaining ways a browser
442
+ re-enters HTML: `<font>` with a `color`, `face` or `size` attribute (it breaks out; here it never does), an end tag
443
+ the parser ignores, an `svg` template rendered outside any `<svg>`, and a template rendered INTO a foreign position
444
+ by its parent — it knows the depth it starts at, not whether that is
445
+ SVG or MathML, so it recognizes no integration point (`html`<svg>${svg`<foreignObject><style>…`}</svg>``). There
446
+ the browser reads HTML raw text, so a `>` in the stylesheet arrives as `&#62;` until hydration replaces it. That is
447
+ the safe direction of a misreading on purpose: the other one writes a value's markup into the page. Put the
448
+ stylesheet in the template that opens the foreign element, or outside it.
449
+ - **`.innerHTML` markup is parsed in place on the server and as a fragment on the client.** The client parses
450
+ the value with the element as its context; the served page is parsed with every real ancestor around it, so a
451
+ few shapes nest differently on first paint — a `<p>` inside a `<p .innerHTML>` (the page closes the outer one),
452
+ an `<a>` inside an `<a>`, table parts outside a table. Hydration re-assigns the value, so the client's DOM is
453
+ right once the script runs; an inline handler in the markup (`onload`, `onerror`) therefore fires twice on an SSR
454
+ page, once from the served HTML and once from the assignment. Inside `<svg>`/`<math>` the server writes the
455
+ value as escaped text, the safe side of the same misreading, until hydration assigns it.
456
+ - **An ordinary element a template leaves open nests differently.** The client parses each template on its own
457
+ and closes what it left open at its end; the server concatenates. Whatever changes how the rest of the page
458
+ PARSES is closed at the template's end on the server too — a comment, `<style>`/`<script>`, `<textarea>` and the
459
+ other text-only elements, `<svg>`, `<math>`, `<noscript>`, `<template>` — so a child can never reach its
460
+ parent's markup. A plain `<b>` or `<div>` left open is not closed, so the parent's next markup nests inside it
461
+ on the server and beside it on the client. Close every element inside the template that opens it.
462
+ - **Beyond that, three things cannot survive a server round trip, and are the only three**: that carriage return
463
+ inside `<style>`/`<script>`, and two characters. **NUL** is dropped in text and becomes U+FFFD in an
464
+ attribute or RAWTEXT, and no spelling round-trips, so it is left alone rather than silently
465
+ rewritten. **A lone surrogate** is not encodable in UTF-8, so the *transport* replaces it. Both are
466
+ covered by `tests/ssr-text-boundary.test.mjs`, alongside twenty-odd cases that do round-trip exactly.
467
+
468
+ ## Known limits
469
+
470
+ - **A parsed node decodes six named references**: `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&apos;` and `&nbsp;`, and
471
+ every numeric one. Any other (`&copy;`, `&mdash;`, a legacy `&amp` with no `;`) reads back as written in that node's
472
+ `textContent` and attributes. The markup is served unchanged, so the page is right; only what a server component
473
+ READS from such markup differs.
474
+
475
+ - `keyed()` and `hold()` are client-renderer constructs; templates that must also server-render use
476
+ plain `.map`.
477
+ - **`slotAssignment: 'manual'` cannot be server-rendered**: declarative shadow DOM has no form for it,
478
+ and `attachShadow` ignores its options when it reuses a declarative root, so the client cannot
479
+ repair it. `mode`, `delegatesFocus`, `clonable` and `serializable` are all serialized.
379
480
  - A function interpolated at a text position renders as nothing here and as its source on the
380
481
  client — put functions in `@event` bindings, where both sides drop them.
381
-
382
- The pre-native strategies (wcc fork, lit-labs renderer, Astro sketch, Reef-era diff renderer)
383
- are retired; strategy 4 is the only one shipped.
482
+ - **What a render creates leaves every store when its render ends.** Its components are reactive DURING the render
483
+ (a write in a setup or a router's first navigation re-renders before the markup is written), and nothing they read
484
+ keeps them alive afterwards. Module-scope state — a store, a `computed` — belongs to the process and stays live; a
485
+ `computed` made inside a render and kept beyond it (stored on a module) stops updating when that render ends. Client
486
+ code in the same process created while an async render is awaiting is treated as part of that render.
487
+ - **No streaming.** `renderToString` returns a string where `@lit-labs/ssr` yields a stream. That buys
488
+ time-to-first-byte in proportion to how long a render takes, and a 100-row table here is PERF_TABLE µs
489
+ — the response is built before a stream would flush its first chunk. Worth revisiting for a page big
490
+ enough that it stops being true.
491
+
492
+ ## Performance
493
+
494
+ `node bench/ssr.mjs` (fastest of 7 rotated rounds; run `cd bench && npm install` first), µs per render
495
+ — a small component, and a 100-row table:
496
+
497
+ | | small | table |
498
+ | --- | --- | --- |
499
+ | **template serialization** — `serializeTemplate` vs `@lit-labs/ssr` | **PERF** | **PERF** |
500
+ | | lit PERF | lit PERF |
501
+ | **whole component** — `renderToString` vs a real `LitElement` | **PERF** | **PERF** |
502
+ | | lit PERF | lit PERF |
503
+
504
+ Vue's compiled SSR is PERF / PERF µs and React PERF / PERF µs, neither of which renders a component.
505
+ The lit element row runs in a separate process: `@lit-labs/ssr` and this package both install DOM
506
+ globals and cannot share one.
384
507
 
385
508
  ## Also exported
386
509
 
387
- `registry` is the `Map` of tag → class this process has seen through `customElements.define`, and
388
- `serializeTemplate` is the sigil-aware template flattener — the two seams an advanced integration
389
- (a custom scanner, a fixture builder) reaches for. Everything an ordinary server needs is
390
- `renderToString` / `renderToStringAsync`; these are listed so their presence is a decision rather
391
- than an accident.
510
+ `registry` — the `Map` of tag → class this process has seen through `customElements.define` — and
511
+ `serializeTemplate`, the sigil-aware template flattener (one template to markup, no component scan),
512
+ are the two seams an advanced integration reaches for: a custom scanner, a fixture builder.
392
513
 
393
514
  ```js
394
- import { renderToString, renderToStringAsync, registry, serializeTemplate } from '@verajs/ssr';
395
-
396
- const { html: markup } = await renderToString(new URL('./components/app.js', import.meta.url));
397
- const page = await renderToStringAsync(entry); // same signature, awaits async lifecycles
398
-
399
- registry.has('app-shell'); // true once the component module has run
400
- const fragment = serializeTemplate(html`<p>${x}</p>`); // one template to markup, no component scan
515
+ import { registry, serializeTemplate } from '@verajs/ssr';
516
+ registry.has('app-shell'); // true once the component's module has run
517
+ const fragment = serializeTemplate(html`<p>${x}</p>`); // '<p>…</p>', every value escaped
401
518
  ```
402
519
 
403
520
  ## For AI assistants — and anyone who wants the whole API on one page