@verajs/renderer 0.1.5 → 0.2.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 (42) hide show
  1. package/README.md +1063 -27
  2. package/dist/development/vera-renderer-hydrate.d.ts +32 -13
  3. package/dist/development/vera-renderer-hydrate.d.ts.map +1 -1
  4. package/dist/development/vera-renderer-hydrate.js +1959 -269
  5. package/dist/development/vera-renderer-hydrate.js.map +1 -1
  6. package/dist/development/vera-renderer-keyed.d.ts +17 -0
  7. package/dist/development/vera-renderer-keyed.d.ts.map +1 -0
  8. package/dist/development/vera-renderer-keyed.js +322 -0
  9. package/dist/development/vera-renderer-keyed.js.map +1 -0
  10. package/dist/development/vera-renderer-profiler.d.ts +57 -17
  11. package/dist/development/vera-renderer-profiler.d.ts.map +1 -1
  12. package/dist/development/vera-renderer-profiler.js +1592 -244
  13. package/dist/development/vera-renderer-profiler.js.map +1 -1
  14. package/dist/development/vera-renderer-slots.d.ts +103 -0
  15. package/dist/development/vera-renderer-slots.d.ts.map +1 -0
  16. package/dist/development/vera-renderer-slots.js +1387 -0
  17. package/dist/development/vera-renderer-slots.js.map +1 -0
  18. package/dist/development/vera-renderer-spread.d.ts +41 -0
  19. package/dist/development/vera-renderer-spread.d.ts.map +1 -0
  20. package/dist/development/vera-renderer-spread.js +633 -0
  21. package/dist/development/vera-renderer-spread.js.map +1 -0
  22. package/dist/development/vera-renderer-tag.d.ts +61 -0
  23. package/dist/development/vera-renderer-tag.d.ts.map +1 -0
  24. package/dist/development/vera-renderer-tag.js +829 -0
  25. package/dist/development/vera-renderer-tag.js.map +1 -0
  26. package/dist/development/vera-renderer.d.ts +41 -16
  27. package/dist/development/vera-renderer.d.ts.map +1 -1
  28. package/dist/development/vera-renderer.js +1522 -235
  29. package/dist/development/vera-renderer.js.map +1 -1
  30. package/dist/vera-renderer-hydrate.min.js +1 -1
  31. package/dist/vera-renderer-hydrate.min.js.map +1 -1
  32. package/dist/vera-renderer-keyed.min.js +2 -0
  33. package/dist/vera-renderer-keyed.min.js.map +1 -0
  34. package/dist/vera-renderer-slots.min.js +2 -0
  35. package/dist/vera-renderer-slots.min.js.map +1 -0
  36. package/dist/vera-renderer-spread.min.js +2 -0
  37. package/dist/vera-renderer-spread.min.js.map +1 -0
  38. package/dist/vera-renderer-tag.min.js +2 -0
  39. package/dist/vera-renderer-tag.min.js.map +1 -0
  40. package/dist/vera-renderer.min.js +1 -1
  41. package/dist/vera-renderer.min.js.map +1 -1
  42. package/package.json +24 -1
package/README.md CHANGED
@@ -1,40 +1,27 @@
1
1
  # @verajs/renderer
2
2
 
3
- A keyed, template-identity renderer (<!--size:renderer.gzip-->3.55 KB<!--/size:renderer.gzip--> gzip): tagged templates, `.prop`/`?bool`/`@event`
4
- and React-style `onClick` bindings, element refs, `keyed()` lists, `hold()` DOM preservation.
5
- `@verajs/renderer/hydrate` is a drop-in superset whose first render ADOPTS server-rendered DOM —
6
- markerless hydration (no framework comments in server HTML). SSR apps import from `/hydrate`;
7
- everyone else pays zero hydration bytes.
3
+ The DOM renderer for VeraJS — <!--size:renderer.gzip-->4.58 KB<!--/size:renderer.gzip--> gzipped,
4
+ no dependencies, no build step required.
8
5
 
9
- ## Escaping, and the deliberate absence of `unsafeHTML`
6
+ Tagged templates parse once and clone; every render after the first walks only the value slots, so
7
+ updates touch the DOM and nothing else. Lists are keyed by value, not by directive. Server-rendered
8
+ pages hydrate through a separate entry that non-SSR apps never download.
10
9
 
11
- Every interpolated value is escaped at the render boundary. There is no `unsafeHTML` and there will
12
- not be one: shipping a sanctioned opt-out puts an XSS sink in the public API, where it reads as
13
- blessed in tutorials and in review.
14
-
15
- Trusted markup goes through an element ref, so you write the sink yourself:
16
-
17
- ```js
18
- render(html`<div ${(el) => (el.innerHTML = trustedMarkup)}></div>`, host);
10
+ ```sh
11
+ npm i @verajs/core @verajs/renderer
19
12
  ```
20
13
 
21
- Greppable, obviously yours, reviewable as the security decision it is. Sanitize first
22
- (`DOMPurify.sanitize`) unless the markup is genuinely your own, and put it on an element whose
23
- children nothing else binds — the renderer owns the content of elements it renders into.
24
-
25
- `@verajs/renderer/profiler` is a development-only entry that reports how many templates were
26
- committed in place versus torn down and rebuilt, naming the template pairs that churn and where.
27
- `showProfiler()` puts the same information in a live panel in the corner of the page. It costs
28
- production nothing — the instrumentation is removed by the build, not merely unused.
14
+ ## Quick start
29
15
 
30
- Wire once, at your app entry, before any component defines itself:
16
+ `wire([renderer])` is the only wiring. Core's `html` tag already produces the shape this accepts, so
17
+ there is no second call to make.
31
18
 
32
19
  <!-- recipe -->
33
20
  ```js
34
- import { init, createStore, render, setRenderer, html } from '@verajs/core';
35
- import { render as domRender } from '@verajs/renderer';
21
+ import { init, createStore, render, wire, html } from '@verajs/core';
22
+ import { renderer } from '@verajs/renderer';
36
23
 
37
- setRenderer(domRender);
24
+ wire([renderer]);
38
25
 
39
26
  customElements.define(
40
27
  'click-counter',
@@ -50,5 +37,1054 @@ customElements.define(
50
37
  document.body.append(document.createElement('click-counter'));
51
38
  ```
52
39
 
53
- Without `setRenderer`, core has no renderer at all: `render()` warns once in development and puts
40
+ Without it, core has no renderer at all: `render()` warns once in development and puts
54
41
  nothing on the page. `@event`, `.prop` and `?bool` bindings are the first things to go missing.
42
+
43
+ ### `renderInto(result, container)`
44
+
45
+ The same write, called directly — no reactivity, no lifecycle, no custom element. `wire([renderer])`
46
+ registers exactly this function, so a component's `render()` ends up here; calling it yourself is how
47
+ you draw into a plain node, which is the incremental-adoption path and the way to test a template
48
+ without spinning up an element.
49
+
50
+ ```js
51
+ import { renderInto } from '@verajs/renderer';
52
+ import { html } from '@verajs/core';
53
+
54
+ renderInto(html`<p>${count}</p>`, document.querySelector('#app'));
55
+ ```
56
+
57
+ It **owns its own range and nothing else**: the first call anchors a root part at a marker it
58
+ appends, later calls with the same container reuse that part and walk only the value slots, and
59
+ whatever was already in the container stays. It is not reactive — call it again to update, or use a
60
+ component and let a store do it.
61
+
62
+ It was named `render` until 0.2.0, which collided with core's `render` — a different function, with
63
+ a different arity, that declares a *reactive* template and commits a component's setup. Both are
64
+ public and both are documented, so a reader who knew one misread the other.
65
+
66
+ ## Bindings
67
+
68
+ | Written | Means |
69
+ | --- | --- |
70
+ | `<p>${value}</p>` | child content — see [Values](#values) |
71
+ | `<p title=${value}>` | attribute. `null`/`undefined` **remove** it |
72
+ | `<p class="a ${b} ${c}">` | attribute built from several expressions and the static text between them |
73
+ | `<x-item .item=${value}>` | property assignment, uncoerced — objects, arrays, functions |
74
+ | `<p ?hidden=${value}>` | boolean attribute, present when truthy |
75
+ | `<input !checked=${value}>` | property written from the **live DOM** rather than from what the binding last wrote — see below |
76
+ | `<button @click=${fn}>` | event listener. An object with a `handleEvent` method works too — `addEventListener` takes both |
77
+ | `<button onClick=${fn}>` | the same thing, React-style. Strictly `on` + a capital — a template-written `onclick` stays a plain attribute (yours, greppable); **spread refuses it** (see the spread section's security note) |
78
+ | `<input ${fn}>` | element ref: a function is called with the element |
79
+ | `<input ${obj}>` | element ref: an object gets the element assigned to `.value`, so core's `ref()` works here |
80
+ | `<input ${spread(props)}>` | names resolved at runtime — see [`/spread`](#verajsrendererspread) |
81
+
82
+ A ref runs once per **distinct value**, not once per render.
83
+
84
+ **A ref is released when its subtree is rendered away, and not when its component is removed from
85
+ the document.** Toggling `${show ? html`<i ${box}>` : 'gone'}` sets `box.value` back to `null` (and
86
+ calls a function ref with `null`); removing the whole component leaves `box.value` pointing at the
87
+ element, now detached. That is deliberate rather than an oversight: here a disconnect is not a
88
+ destruction — moving a node between parents fires one, and the component re-renders on reconnect —
89
+ so releasing would blank every ref for the frame it takes a move to complete. Guard with
90
+ `box.value?.isConnected` if you need to know, and note that a ref created inside the component (the
91
+ way every example writes it) becomes garbage along with it either way.
92
+
93
+ An event handler is called with the element as `this`, and the listener is registered once — swapping
94
+ the handler across renders never touches the DOM, so there is no add/remove churn and no way to end
95
+ up with two. `undefined`, `null` and `false` all mean *no handler*, so `@click=${enabled && onClick}`
96
+ binds conditionally without a ternary. Anything else that cannot listen — a string, a number, an
97
+ object with no `handleEvent` — is inert, and **development names it at the binding**: a listener is
98
+ only ever called when a user clicks, so left unchecked the mistake surfaces at a point where nothing
99
+ on the stack says where the value came from.
100
+
101
+ ### `!name` — a live property
102
+
103
+ Every other binding skips a write when the value matches what it last wrote. That is what keeps a
104
+ field someone has typed into, and it is exactly wrong for a control whose DOM state changes as a
105
+ **side effect of interacting with a sibling**:
106
+
107
+ ```js
108
+ html`<input type="radio" name="pick" !checked=${state.picked === 'one'} />
109
+ <input type="radio" name="pick" !checked=${state.picked === 'two'} />`
110
+ ```
111
+
112
+ Clicking the second radio unchecks the first *in the DOM*, with no event on it. With `.checked` the
113
+ first binding still says `true`, still matches what it committed, and never writes again — the model
114
+ and the page diverge and no amount of re-rendering reconciles them. A `<select>`'s options are the
115
+ same shape.
116
+
117
+ It is deliberately narrow, and it is a **property** binding only:
118
+
119
+ - **Not for text inputs.** Bind those with `.value` and let a person's typing stand. `!value` exists
120
+ and is authoritative, which is precisely why it is not the default.
121
+ - **Not offered for attributes or booleans.** Nothing changes those behind the renderer's back, so
122
+ there is nothing to re-read.
123
+ - **It yields during hydration.** A click that happened before the bundle landed had no handler to
124
+ report it, so adoption records the value without writing; live semantics resume on the first
125
+ state-driven render.
126
+
127
+ `spread({ '!checked': … })` means the same thing, and `@verajs/ssr` serializes it exactly as
128
+ `.checked` — a server has nothing to re-read.
129
+
130
+ Bindings inside comments are not supported — the value is consumed and ignored. A **dynamic tag
131
+ name** is a binding a template cannot express either, and has its own entry:
132
+ [`/tag`](#verajsrenderertag).
133
+
134
+ ## Values
135
+
136
+ What a child position does with each kind of value. These match lit-html exactly, `null` and
137
+ `undefined` included.
138
+
139
+ | Value | Renders |
140
+ | --- | --- |
141
+ | string, number, `true`, `false`, `0` | as text — `${cond && 'x'}` puts the word `false` on the page |
142
+ | `null`, `undefined` | nothing |
143
+ | a template result | the template, updated in place while its shape holds |
144
+ | an array or iterable | each entry in order; key them with `keyed()` |
145
+ | a DOM node or fragment | itself, moved into place |
146
+ | anything else | `String(value)` |
147
+
148
+ Strings render as **text**, always. There is no path by which an interpolated value becomes markup
149
+ — see [Trusted HTML](#trusted-html-and-why-there-is-no-unsafehtml).
150
+
151
+ A DOM node renders as itself, which is how a template holds something another library owns:
152
+
153
+ ```js
154
+ const chart = document.createElement('canvas');
155
+ new Chart(chart, config);
156
+
157
+ renderInto(html`<figure>${chart}<figcaption>${title}</figcaption></figure>`, host);
158
+ ```
159
+
160
+ ## Lists — `keyed()`
161
+
162
+ ```js
163
+ import { renderInto } from '@verajs/renderer';
164
+ import { keyed } from '@verajs/renderer/keyed';
165
+
166
+ renderInto(html`<ul>${rows.map((row) => keyed(row.id, html`<li>${row.label}</li>`))}</ul>`, host);
167
+ ```
168
+
169
+ `keyed(key, result)` tags a result with its identity, so a reorder **moves** the existing elements
170
+ instead of rebuilding them — focus, scroll position, form state and running animations all survive.
171
+ It is its own entry because most apps never reorder a list, and the algorithm that makes reordering
172
+ cheap is <!--size:keyed.gzip-->923 B<!--/size:keyed.gzip--> gzipped they would otherwise carry. Importing `keyed` is the whole installation:
173
+ nothing registers, and there is no `wire()` call — the marker stamps each result with the strategy
174
+ that understands it, so a list always names its own reconciler and two strategies cannot disagree
175
+ about one. Lit splits `repeat` out for the same reason; the difference is that this one arrives on
176
+ the values rather than through a directive protocol.
177
+
178
+ **Keep it on the same version as `@verajs/renderer`.** It reaches the renderer through a handful of
179
+ two-character members that are exempt from property mangling, and nothing checks that both sides
180
+ agree about them — a `keyed` bundle paired with a different renderer release fails at runtime rather
181
+ than at install. Both ship from this package and bump together, so a single version range covers it;
182
+ the trap is pinning one and floating the other. `@verajs/renderer/spread` carries the same rule for
183
+ the same reason.
184
+
185
+ **It is additive, not a substitute.** Unlike `/hydrate` and `/profiler`, this entry imports nothing
186
+ at all — it reaches whatever renderer is present through a handful of mangling-exempt members — so
187
+ it is safe alongside any of them, `/hydrate` included.
188
+
189
+ **A list is keyed because `keyed()` marked it, not because its results have a `key` property.**
190
+ Setting `.key` by hand no longer makes a list keyed — the marker is what carries the algorithm, so
191
+ it is what the renderer looks for, on the client and when adopting server markup alike.
192
+
193
+ **Key every item in a list, or none of them.** A list is keyed when its first item is, and an
194
+ unkeyed item in a keyed list has no identity to match on.
195
+
196
+ An unkeyed list is not wrong — it updates each position in place, which is exactly right for a list
197
+ whose order never changes.
198
+
199
+ ## Preserving DOM — `hold()`
200
+
201
+ ```js
202
+ renderInto(html`<div>${hold(editing ? editor(state) : viewer(state))}</div>`, host);
203
+ ```
204
+
205
+ `hold(result)` parks the DOM it replaces instead of destroying it, keyed by template identity, and
206
+ brings it back when that template returns. lit calls this `cache`. What survives is everything no
207
+ attribute records: what the user typed, a checkbox or radio the user set, a `<select>`'s chosen
208
+ option, a `<details>` left open, a media element's playback position — and the nodes themselves, so
209
+ the element that had focus is the same element when it comes back.
210
+
211
+ **A scroll offset does not survive, and cannot.** Every engine resets `scrollTop` to zero the moment
212
+ an element leaves the document — measured on Chromium, Firefox and WebKit, which report `0` while
213
+ parked, `0` on return, and `0` even for a node moved directly between two attached parents. Nothing an
214
+ applier does with the nodes can hold it, and lit's `cache()` cannot either. If a scroll position
215
+ matters, read it before the toggle and restore it after.
216
+
217
+ Anything that is not a template passes straight through — there is nothing to park for a string, a list, `null` or `false` — so `hold(editing && editor())` is safe to write.
218
+
219
+ It only re-adopts a template it has seen at **that same call site** — two `hold()` calls in
220
+ different templates are two different templates, and neither adopts the other's DOM. The other
221
+ direction is also safe, and reads less obviously from "call site": every keyed **row** of a list
222
+ shares one call site, and each still holds its own state — the cache rides the row's own part, so
223
+ two rows toggling through the same `hold` never adopt each other's parked DOM, including through a
224
+ reorder while one is parked. Measured, and pinned in the combination matrix.
225
+
226
+ **It keeps every shape it has parked, for as long as the part lives.** That is the point — a tab
227
+ strip of twelve panels holds twelve, and each comes back exactly as it was left — but it is a cache
228
+ with no eviction, so `hold` over an unbounded set of templates retains an unbounded amount of DOM.
229
+ Verified: fifty distinct shapes cycled through one `hold` and the first still re-adopted its own
230
+ nodes. lit's `cache()` behaves the same way, and for the same reason — evicting would silently throw
231
+ away the state the applier exists to preserve, which is worse than holding it. Use `hold` for a
232
+ set you can name, and let an unbounded one rebuild.
233
+
234
+ ## Write stable shapes
235
+
236
+ Rendering the same elements every pass and toggling `hidden` is faster than swapping one subtree for
237
+ another. Template identity holds, so values update in place rather than the subtree being torn down
238
+ and rebuilt. Both forms are correct; this one is cheaper.
239
+
240
+ ```js
241
+ // fragile — two sibling parts, each swapping between a template and ''
242
+ html`<section>
243
+ ${items.length === 0 ? html`<p>empty</p>` : html`<ul>${rows}</ul>`}
244
+ ${busy ? html`<p>loading</p>` : ''}
245
+ </section>`;
246
+
247
+ // preferred — one shape, visibility toggled
248
+ html`<section>
249
+ <p ?hidden=${items.length > 0}>empty</p>
250
+ <ul ?hidden=${items.length === 0}>${rows}</ul>
251
+ <p ?hidden=${!busy}>loading</p>
252
+ </section>`;
253
+ ```
254
+
255
+ [`/profiler`](#verajsrendererprofiler) exists to make the difference visible: it counts templates
256
+ committed in place against templates that replaced a different template.
257
+
258
+ ## Entries
259
+
260
+ | Import | What it adds | Ships in production |
261
+ | --- | --- | --- |
262
+ | `@verajs/renderer` | the renderer | yes |
263
+ | `@verajs/renderer/hydrate` | a superset whose first render adopts server-rendered DOM | yes |
264
+ | `@verajs/renderer/keyed` | `keyed(key, result)` — keyed list reconciliation | yes |
265
+ | `@verajs/renderer/spread` | `spread(props)` — binding names resolved at runtime | yes |
266
+ | `@verajs/renderer/tag` | `` tag`h1` `` — an element whose tag name is decided at runtime | yes |
267
+ | `@verajs/renderer/slots` | `slots` (wire it) + `slotted(host, name?)` — light-DOM `<slot>` distribution | yes |
268
+ | `@verajs/renderer/profiler` | a superset that measures template churn | no — development only |
269
+
270
+ `/hydrate` and `/profiler` each re-export the whole public API, so they are drop-in replacements for
271
+ the base import. **Never mix two of them in one app** — that loads two renderers with two template
272
+ caches.
273
+
274
+ **Which means an app can have one of them, not both — so a hydrating app cannot be profiled.** They
275
+ each bundle their own renderer with its own instrumentation hook, so profiling while rendering
276
+ through `/hydrate` observes an instance nothing renders into: measured, three renders reported zero
277
+ frames while the page updated correctly. `formatReport` says so when it observed nothing, because a
278
+ zero report is otherwise indistinguishable from an app with nothing to optimise.
279
+
280
+ ## `@verajs/renderer/slots` — light-DOM slots
281
+
282
+ Native `<slot>` needs a shadow root. This entry teaches the renderer to distribute a light-DOM
283
+ component's own children into the `<slot name="…">` positions of its template, so **one component
284
+ works in both modes** — users write `<div slot="title">` exactly as they would against shadow DOM.
285
+
286
+ **Wire it at your app entry, before anything renders.** A template resolves this once, at
287
+ construction, and is interned per call site for the life of the page — so wiring `slots` after a
288
+ component has already rendered does not reach that component, and it keeps showing its fallback
289
+ content while the children the host was given sit beside it as stray markup. Development names it
290
+ when it happens, but the rule is cheaper than the diagnostic: wire it in the same call as the
291
+ renderer, `wire([renderer, slots])`.
292
+
293
+ Given this markup:
294
+
295
+ ```html
296
+ <my-card>
297
+ <h2 slot="header">Hello</h2>
298
+ Body text goes to the default slot.
299
+ </my-card>
300
+ ```
301
+
302
+ <!-- recipe -->
303
+ ```js
304
+ import { init, render, wire, html } from '@verajs/core';
305
+ import { renderer } from '@verajs/renderer';
306
+ import { slots, slotted } from '@verajs/renderer/slots';
307
+
308
+ wire([renderer, slots]);
309
+
310
+ customElements.define(
311
+ 'my-card',
312
+ class extends HTMLElement {
313
+ connectedCallback() {
314
+ init(this); // LIGHT DOM — no shadow options
315
+ render(
316
+ () => html`<article>
317
+ <header><slot name="header" @slotchange=${(e) => this.onHeader(e.target)}>Untitled</slot></header>
318
+ <main><slot>Nothing here yet.</slot></main>
319
+ </article>`
320
+ );
321
+ }
322
+ /** Written exactly as it would be against a shadow root, and it runs in both. */
323
+ onHeader(slot) {
324
+ console.log('header is now:', slot.assignedElements().map((el) => el.textContent));
325
+ }
326
+ }
327
+ );
328
+
329
+ const card = document.createElement('my-card');
330
+ card.innerHTML = '<h2 slot="header">Hello</h2>Body text goes to the default slot.';
331
+ document.body.append(card);
332
+
333
+ await new Promise((resolve) => requestAnimationFrame(resolve));
334
+ console.log(card.querySelector('header').textContent); // "Hello"
335
+ console.log(card.querySelector('main').textContent); // "Body text goes to the default slot."
336
+ console.log(slotted(card, 'header').length); // 1
337
+ ```
338
+
339
+ `slots` is the insert descriptor you wire; that is all a consumer touches.
340
+
341
+ > **Wire the renderer as a MODULE — `wire([renderer, slots])` — not as a bare function.** Both
342
+ > spellings register a renderer, and only the module form runs the descriptor's `connect()`, which
343
+ > is how the renderer receives the app's insert registry and therefore how it finds this seam at
344
+ > all. `wire({ on: 'render', fn: renderInto, priority: 50 })` leaves that registry unset, so every
345
+ > `<slot>` renders its fallback and nothing says why. (That spelling is documented for wiring a
346
+ > DIFFERENT renderer — lit-html — where there is no seam to find.) The assignment follows
347
+ the platform's own rules — elements to the slot their `slot` attribute names, text to the default
348
+ slot, fallback shown only while a slot is unassigned and restored when it empties, direct children
349
+ only. Live: appending, removing, or re-slotting children redistributes automatically, with one documented
350
+ divergence — see **Late children** below. Re-renders leave slotted nodes in place, identity intact, so focus and input values
351
+ survive; SSR emits already-distributed markup and hydration adopts it.
352
+
353
+ **A `<slot>` inside another slot's fallback works**, and takes over at the moment that fallback
354
+ becomes visible — the same thing the platform does, verified by layout on three engines. Slots are
355
+ handed over in document order, so a slot's nested slots are taken over first, while they still have
356
+ a parent to anchor into.
357
+
358
+ **`::slotted()` is shadow-only and deliberately not translated.** In light DOM the slotted content
359
+ is in the same tree, so an ordinary descendant selector reaches it — and reaches deeper than
360
+ `::slotted()` can, which only ever matched top-level assigned nodes. Measured on three engines, the
361
+ two are exactly complementary: neither spelling reaches across. A component that renders both ways
362
+ writes both, `::slotted(img), [part="body"] img`, exactly as `:host, :scope` was needed before
363
+ `:host` became translatable.
364
+
365
+ The asymmetry with `:host` is the reason one is translated and this is not. `:host` styles the
366
+ component ITSELF and nothing else can supply it, so a component from npm that uses it is visibly
367
+ broken in light mode. `::slotted()` styles the USER'S content, which in light DOM the page author
368
+ can already reach — so the failure is a missing default rather than a broken component, and making
369
+ it work would mean writing framework attributes into the user's own markup.
370
+
371
+ ### Late children
372
+
373
+ **A node added AFTER the first render joins its slot with full native semantics** — bare text and
374
+ attribute-less elements included, in document order, exactly as a shadow root would assign them.
375
+ The renderer stamps everything it emits at a light host's top level with a hidden, non-enumerable
376
+ property, so an unstamped node there is knowably the user's; `slot=""`/`slot="name"` still route,
377
+ they are simply no longer required.
378
+
379
+ This used to be the feature's one documented divergence, and the rule existed because a light
380
+ host's children after the first render are also the component's own rendered output, with nothing
381
+ in the DOM to tell them apart. Ownership is written down now rather than inferred from position,
382
+ so the ambiguity — and the rule — are gone. Two things remain worth knowing: whitespace appended
383
+ to a light host suppresses the default fallback, which is parity (a shadow root does the same), and
384
+ re-slotting a node (`slot="a"` → `"b"`) rejoins in light-tree order rather than arrival order.
385
+ Every position you can reach orders exactly as the platform does — what light has fewer of is
386
+ positions you can name, since a distributed child is no longer a direct child of the host.
387
+
388
+ **Cloning a RENDERED light component does not work, and cannot.** `cloneNode(true)` copies a
389
+ light host's children — which after a render are the component's own output with the user's slotted
390
+ nodes already distributed into it. The clone then captures all of that as its slot content, so its
391
+ rendered tree ends up nested inside its own default slot. A shadow component clones cleanly for the
392
+ opposite reason: `cloneNode` does not copy a shadow root, so the clone re-renders and its light
393
+ children are still just its light children.
394
+
395
+ Nothing can detect this — the ambiguity is the same one behind the late-children rule above, and
396
+ the original user content was consumed at the first render, so there is nothing to recover. **To
397
+ duplicate a component, clone the SOURCE markup and let the copy render itself**, rather than cloning
398
+ a live instance. This matters most to anything that duplicates components as an operation: an editor
399
+ canvas, a repeater, a drag-to-copy.
400
+
401
+ **`slotted(host, name?)`** is the component-internal accessor — what the user assigned to a slot,
402
+ answered identically in shadow mode (native assignment) and light mode (the capture map). Omit
403
+ `name` for the default slot. Component authors reach for this; app users do not.
404
+
405
+ ### The `<slot>` element is still the component's handle on the slot
406
+
407
+ A slot is not only a position, and a component that keeps up with what it was given binds to the
408
+ element itself. All of that means here what it means in a shadow root:
409
+
410
+ ```js
411
+ render(() => html`<header>
412
+ <slot name=${section} &ref=${(el) => (this.slot = el)}
413
+ @slotchange=${(e) => wire(e.target.assignedElements())}>Nothing yet</slot>
414
+ </header>`);
415
+ ```
416
+
417
+ - **`@slotchange`** fires on first assignment and on every change after it — and only then, so a
418
+ child added without a `slot` attribute fires nothing. The sequence and each event's
419
+ `assignedNodes()` are asserted against real shadow DOM, which is the oracle for this. It fires
420
+ for a slot whose rendering is currently displaced too (assignment is independent of rendering),
421
+ exactly as native does for a slot that is not on screen.
422
+ - **`node.assignedSlot` answers `null` — ask the slot, not the node.** The reverse lookup is a
423
+ platform accessor tied to real shadow assignment, and overriding it on YOUR nodes is an intrusion
424
+ this module refuses. The forward reads carry the same fact: `slot.assignedNodes().includes(node)`
425
+ through a `&ref`, or `slotted(host, name)` from outside.
426
+ - **Bind `slotchange` directly — it does not bubble to the host.** In a shadow root one listener on
427
+ the root hears every slot by bubbling; here the slot handles are deliberately out of the document,
428
+ so there is no tree for the event to climb and `host.addEventListener('slotchange', …)` hears
429
+ silence. Use `@slotchange` on each slot, which also hands you the right `event.target`. (The same
430
+ boundary as `querySelector('slot')`: fewer places to listen, not fewer events.)
431
+ - **`assignedNodes(options)` / `assignedElements(options)`** answer from the live assignment,
432
+ through `event.target` or a `&ref`. With nothing assigned, `{ flatten: true }` gives the fallback
433
+ actually on screen — slottables only, so a comment you wrote into fallback content is not in it,
434
+ and a nested slot flattens through to whatever it is showing, both as the platform does.
435
+ - **Use `child.before(node)` / `child.after(node)`, never `host.insertBefore(node, child)`.** A light
436
+ host's children are physically moved into the slot they are assigned to, so a child you appended
437
+ and kept a reference to is no longer a *direct* child of the host — and `insertBefore` throws
438
+ `NotFoundError` when its reference node is not a child of the node it is called on. In a shadow
439
+ root the same line works, because there nothing moves. `before()`/`after()` route through the
440
+ node's own current parent, so they are correct in both modes, and the content lands in the order
441
+ you asked for. This is the sharpest difference between the two modes and the easiest to hit.
442
+ - **A displaced node is *disconnected* here; native slotting never disconnects it.** Shadow
443
+ distribution is virtual — a slottable no slot names stays in the light tree, connected, merely
444
+ unrendered. Light slots park it physically, so a custom element inside displaced content runs its
445
+ `disconnectedCallback` (and a Vera component's effect cleanups) on the way out, and
446
+ `connectedCallback` again when its slot returns — with its element identity, stores and typed-in
447
+ state intact, and reactivity re-established by the re-init. Component authors already handle this
448
+ pair for any `appendChild` move; the difference is only *when* it happens: a component that
449
+ pauses a video on disconnect pauses while displaced here and keeps playing in a shadow root.
450
+ The slot element is deliberately not in your DOM (see below), so it is unreachable by selector and
451
+ reports `isConnected === false`. It is a live API object, not a position in the tree.
452
+ - **`name` can be a binding.** `<slot name=${section}>` routes by the name it actually has, and
453
+ re-routes if it changes between renders.
454
+
455
+ ### Keeping the `<slot>` in the tree — a strategy you can own
456
+
457
+ Every boundary above has one cause: the shipped strategy removes the `<slot>` element so your
458
+ markup stays exactly what you wrote. The seam it registers through is public, single-registrant,
459
+ and takes whole strategies — so if you would rather have the *shadow tree's own structure* (the
460
+ slot element present, selectable, `:first-child`-countable, made layout-invisible by the same
461
+ `display: contents` the UA stylesheet gives real slots), you can wire a strategy that keeps it.
462
+ This one is complete enough to run — and it runs, in CI, as written:
463
+
464
+ <!-- recipe -->
465
+ ```js
466
+ import { init, render, wire, html } from '@verajs/core';
467
+ import { renderer } from '@verajs/renderer';
468
+
469
+ /** Distribution that KEEPS the <slot>: content moves INSIDE it, fallback shows when it is empty. */
470
+ const slotsInTree = {
471
+ name: 'my-app/slots-in-tree',
472
+ on: 'slot',
473
+ priority: 50,
474
+ fn(slot, root, name) {
475
+ if (root.nodeType !== 1) return null; // a shadow root keeps native slotting
476
+ const host = root;
477
+ const fallback = [...slot.childNodes];
478
+ const isMine = (n) =>
479
+ n.nodeType === 1 ? (n.getAttribute('slot') ?? '') === name
480
+ : name === '' && n.nodeType === 3 && n.data.trim() !== '';
481
+ let shown = -1;
482
+ const fill = () => {
483
+ for (const n of [...host.childNodes]) if (isMine(n)) slot.append(n);
484
+ const assigned = [...slot.childNodes].filter((n) => !fallback.includes(n));
485
+ for (const n of fallback) (assigned.length ? n.remove() : slot.append(n));
486
+ observer.takeRecords(); // our own moves are not the user's
487
+ if (assigned.length !== shown) {
488
+ shown = assigned.length;
489
+ slot.dispatchEvent(new Event('slotchange', { bubbles: true })); // real ancestors — it CLIMBS
490
+ }
491
+ };
492
+ const observer = new MutationObserver(fill);
493
+ fill();
494
+ observer.observe(host, { childList: true, subtree: true });
495
+ return { _$park$: () => { observer.disconnect(); for (const n of [...slot.childNodes]) if (!fallback.includes(n)) host.append(n); } };
496
+ },
497
+ };
498
+
499
+ wire([renderer, slotsInTree]);
500
+ document.head.insertAdjacentHTML('beforeend', '<style>slot{display:contents}</style>');
501
+
502
+ customElements.define('tree-card', class extends HTMLElement {
503
+ connectedCallback() {
504
+ init(this);
505
+ render(() => html`<article><slot name="header">Untitled</slot></article>`);
506
+ }
507
+ });
508
+
509
+ const card = document.createElement('tree-card');
510
+ card.innerHTML = '<h2 slot="header">Hello</h2>';
511
+ document.body.append(card);
512
+ await new Promise((resolve) => requestAnimationFrame(resolve));
513
+
514
+ /** Every documented boundary of the shipped strategy, working: */
515
+ let heard = 0;
516
+ card.addEventListener('slotchange', () => heard++); // a HOST-level listener — bubbling exists here
517
+ if (!card.querySelector('slot')) throw new Error('querySelector finds the slot');
518
+ if (card.querySelector('h2').parentElement.localName !== 'slot') throw new Error('reverse lookup');
519
+ card.querySelector('h2').remove();
520
+ await new Promise((resolve) => setTimeout(resolve, 0));
521
+ if (card.querySelector('article').textContent !== 'Untitled') throw new Error('fallback returns');
522
+ if (heard !== 1) throw new Error('slotchange bubbled to the host');
523
+ ```
524
+
525
+ The trade is the one the platform itself makes: this is the shadow tree's structure, so the
526
+ `<slot>` now appears in your host's serialized markup (as it appears in a `shadowRoot`'s), your
527
+ component CSS can select it — and structural selectors written against the template see it as the
528
+ child it is, because selectors follow the tree, not layout. Wire it *instead of* `slots` — the
529
+ seam is single-registrant, and wiring both says so in development, by name.
530
+
531
+ What this recipe deliberately does not do is the audited module's territory: light-tree ordering
532
+ under re-slots and prepends, duplicate-name handover, nested slots in fallbacks, dynamic
533
+ `name=${…}`, SSR and hydration. It is a starting point you own, not a drop-in peer — the measured
534
+ design for a full sibling lives with the maintainers.
535
+
536
+ **The one thing a light-DOM slot cannot carry is presentation** — `class`, `style`, `id` and other
537
+ plain attributes. A light host has no second tree, so the slot element is not rendered and there is
538
+ nothing for them to apply to, while in a shadow root they do apply. Put them on a real element
539
+ around the slot. Development builds say so, naming the attribute, rather than leaving it to be
540
+ found.
541
+
542
+ Additive like `keyed`/`spread`: it imports no renderer and reaches the one present through the wired
543
+ seam, so it is safe beside any renderer entry on a CDN page. The entry is
544
+ **<!--size:slots.gzip-->3.35 KB<!--/size:slots.gzip-->** gzipped and only apps importing it pay;
545
+ `@verajs/renderer` itself carries just the seam that records where a template's slots are. It is
546
+ also Node-safe — it imports nothing and touches no global document — so a universal app can wire it
547
+ on both sides.
548
+
549
+ ## `@verajs/renderer/hydrate`
550
+
551
+ <!-- recipe -->
552
+ ```js
553
+ import { renderer } from '@verajs/renderer/hydrate'; // instead of '@verajs/renderer'
554
+ ```
555
+
556
+ Same name, same `wire([renderer])`, different entry — this one's `renderer` binds the adopting
557
+ render below, so swapping the import (or the importmap target) really is the only change.
558
+
559
+ The first render into a container that already has children **adopts** them as server output of the
560
+ same template: node identity is preserved, listeners attach, and updates mutate the adopted nodes.
561
+ Hydration here is **markerless** — server HTML carries no framework comments, and the client repairs
562
+ its own anchors into the adopted DOM.
563
+
564
+ Any disagreement with the server markup clears the container (keeping `<style data-vm-sheet="styles">` tags)
565
+ and renders fresh, so correctness never depends on the server output being right. A DOM node at a
566
+ child position is the one thing the server cannot have rendered; it is inserted without giving up
567
+ adoption of everything around it.
568
+
569
+ **A fallback warns in development, naming the first place the two renders disagreed** — *"expected
570
+ `<p>` and found `<div>`"*, *"`<ul>` contains `<li>`, which the template does not describe"*. The page
571
+ is correct either way, which is the point of the fallback and also why it needs saying: that
572
+ container's markup was just thrown away, and with nothing observable to notice, the only symptom is
573
+ a first paint that is slower than the one you paid a server render for. An attribute that disagrees
574
+ is simply re-set during adoption and is not a fallback at all.
575
+
576
+ **A fallback costs one container, not the page.** Adoption is decided per container, so components
577
+ hydrating into their own roots are independent: one that disagrees rebuilds and warns, and every
578
+ other one keeps the server's nodes. Measured in `tests/hydrate-mismatch.test.mjs` — three containers,
579
+ one mismatch, one warning, two adoptions. Worth stating because the warning used to imply otherwise
580
+ and sent the reader hunting for a page-wide cause.
581
+
582
+ **Comments are outside the comparison, in both directions** — a comment in your template is not
583
+ required in the server markup, and one in the server markup that your template does not have is not
584
+ a disagreement. A comment renders nothing, so neither direction changes what a reader sees; matching
585
+ on them would only cost every commented template its adoption.
586
+
587
+ On a CDN page, point the import map's `@verajs/renderer` at `vera-renderer-hydrate.min.js` and
588
+ nothing else changes. Apps that never hydrate download none of this.
589
+
590
+ ### Importing this in Node
591
+
592
+ **`@verajs/renderer` needs a DOM to be imported at all**, not merely to render. It captures
593
+ `document` at module scope and builds two shared `TreeWalker`s there, which is what saves an
594
+ allocation per instance — so `import '@verajs/renderer'` on a server throws
595
+ `ReferenceError: document is not defined` before any of your code runs. The same is true of
596
+ `/hydrate` and `/profiler`, and of `@verajs/jsx/standalone`, which contains a renderer.
597
+
598
+ This is worth stating because [`@verajs/router`](../router#node-and-ssr) documents the opposite
599
+ about itself, and the asymmetry is easy to read the wrong way. The rest of the family is Node-safe:
600
+ `@verajs/core`, `@verajs/inserts`, `@verajs/store` and `/collections`, `@verajs/router`,
601
+ `@verajs/styles`, `@verajs/autoloader`, `@verajs/jsx` (the transform), `@verajs/ssr` — **and
602
+ `@verajs/renderer/keyed`, `/spread` and `/tag`**, which hold no DOM of their own even though their
603
+ parent entry does.
604
+
605
+ In a universal app, hand the renderer in rather than importing it in shared code — which is what
606
+ `examples/kitchen-sink/wiring.js` does, taking it as a parameter so the server can pass `null`.
607
+ `tests/node-import-safety.test.mjs` holds both halves of that list.
608
+
609
+ ## `@verajs/renderer/spread`
610
+
611
+ Spread a props object onto an element, with names resolved at runtime.
612
+
613
+ <!-- recipe -->
614
+ ```js
615
+ import { init, createStore, render, wire, html } from '@verajs/core';
616
+ import { renderer } from '@verajs/renderer';
617
+ import { spread } from '@verajs/renderer/spread';
618
+
619
+ wire([renderer]);
620
+
621
+ customElements.define(
622
+ 'x-field',
623
+ class extends HTMLElement {
624
+ connectedCallback() {
625
+ init(this, { mode: 'open' });
626
+ const state = createStore({ disabled: false });
627
+ const props = {
628
+ id: 'email', // attribute
629
+ placeholder: 'you@example.com', // "
630
+ '.value': '', // property
631
+ '?disabled': state.disabled, // boolean attribute
632
+ onInput: (e) => console.log(e.target.value), // event — @input works too
633
+ };
634
+ render(() => html`<input ${spread(props)} />`);
635
+ }
636
+ }
637
+ );
638
+
639
+ document.body.append(document.createElement('x-field'));
640
+ ```
641
+
642
+ Keys carry the same sigils as written bindings, so a spread key and a written binding mean the same
643
+ thing — `.value`, `?disabled`, `@click`, `onClick`, and `&ref` for an element ref.
644
+
645
+ **A key that cannot be written into markup is skipped**, with a warning in development. That is any
646
+ name holding whitespace, a quote, `<`, `>`, `/`, `=`, a backtick or a control character. Engines are
647
+ more permissive than markup — measured across Chromium, Firefox and WebKit, `setAttribute` accepts
648
+ `"`, `'` and `<` — but a name that binds in the browser and cannot survive server rendering is worse
649
+ than one that works nowhere, so both sides apply the same rule. Skipped rather than thrown: the keys
650
+ are runtime data, and one bad name in a props bag should not cost the render.
651
+
652
+ Several spreads on one element are supported — each element position owns its own keys, so
653
+ `<div ${spread(a)} ${spread(b)}>` works and neither releases the other's bindings.
654
+
655
+ Keys are strings carrying sigils, so TypeScript cannot check them against the element's attributes.
656
+ That is a genuine step down from written bindings, and the trade for names that are not known until
657
+ runtime.
658
+
659
+ ### `props()` — a typed bag of property bindings
660
+
661
+ For the common case where every key is a **property**, `props()` removes both the sigils and the
662
+ typing gap:
663
+
664
+ ```js
665
+ import { props } from '@verajs/renderer/spread';
666
+
667
+ html`<calendar-day ${props({ date, events })}></calendar-day>`
668
+ ```
669
+
670
+ ```jsx
671
+ <calendar-day {...props({ date, events })}></calendar-day>
672
+ <calendar-day date={date} events={events} /> // JSX only: bare props ARE props on a component tag
673
+ ```
674
+
675
+ One function, both surfaces — JSX compiles `{...x}` to `spread(x)`, and `spread()` recognises an
676
+ already-branded result, so the two spellings are literally the same call. In JSX the bag is
677
+ optional altogether: on a dash-named tag a bare prop compiles to the `.name` binding directly
678
+ (`@verajs/jsx`'s README has the two attribute carve-outs), so `props()` is the template's
679
+ spelling and the bag for names not known until runtime. It exists because an
680
+ attribute is always a string: an array, a `Date` or a store can only reach a custom element as a
681
+ property — and while vera's JSX accepts the sigil spelling `.date={d}`, TSX's type-checker refuses
682
+ it (TS1003), so the bag is the typed path.
683
+
684
+ Three rules, each earned:
685
+
686
+ - **Keys are property names, never sigils** — `props({ date })` binds `.date`. Events and boolean
687
+ attributes keep their own spellings (`@click`/`onClick`, `?disabled`); this bag is properties
688
+ only, by definition.
689
+ - **Prefer keys spelled conditionally over bags that change shape**:
690
+ `props({ date: loaded ? date : null })` — key present from the first render — over
691
+ `props(loaded ? { date } : {})`. Both work (a key that appears later on a component is adopted
692
+ live, and one that disappears restores what the element held), but a stable shape means values
693
+ update in place, the same reason templates prefer `?hidden` over swapped subtrees.
694
+ - **A type argument makes the bag checked**: `props<CalendarDay>({ dat })` is a compile error
695
+ naming the misspelling — the checking that sigil-keyed spread genuinely cannot have.
696
+
697
+ ### How a component receives them
698
+
699
+ Nothing to declare on the other side — no `static properties`, no props argument. A component that
700
+ calls `init()` finds every bound property on `this`, **reactively**: reading `this.date` in a
701
+ render tracks it, the parent's next commit re-renders, and a store or `ref()` passed through stays
702
+ live because it arrives by identity. The full reception contract — including what happens when the
703
+ component's module loads *after* the parent rendered — is documented with `init()` in
704
+ `@verajs/core`'s README; this package's half is the delivery:
705
+
706
+ - **A property is not an attribute.** `date="…"` is an attribute — always a string, visible in
707
+ markup. `.date=${…}`/`props({ date })` is a property — any value, by identity, invisible to
708
+ `getAttribute`. Components receive **properties**; attributes are for CSS hooks and static
709
+ markup.
710
+ - **Delivery survives lazy definition.** A property bound before the element's module runs would
711
+ otherwise be destroyed by the class's field initializers at upgrade (at ES2022,
712
+ `item?: T` emits a real `item;` that runs during upgrade). The renderer records what nothing
713
+ received yet, and `init()` re-applies it — so a bound value outranks a class default, in both
714
+ field spellings. Elements that never call `init()` keep the development warning and the
715
+ `declare` advice instead.
716
+ - **Platform and foreign elements are untouched.** A property with an accessor anywhere —
717
+ `.title`, a Lit-style element, anything that already receives it — is delivered plainly and
718
+ never recorded.
719
+ - **SSR delivers, never serializes.** Under `@verajs/ssr`, a property bound on a rendered
720
+ component tag reaches that child's server render by identity — the markup never carries it, and
721
+ an unregistered tag passes through for the client to handle.
722
+
723
+ ### Removing a key
724
+
725
+ A key that disappears between renders **restores what the element held before the binding existed**.
726
+
727
+ ```js
728
+ renderInto(html`<input type="text" ${spread({ type: 'number' })} />`, host); // type="number"
729
+ renderInto(html`<input type="text" ${spread({})} />`, host); // type="text" again
730
+ ```
731
+
732
+ Not removed — *restored*. The usual framing, "what value means absent", has no answer for a
733
+ property: `delete` cannot remove a prototype accessor, and assigning `undefined` puts the literal
734
+ string `"undefined"` into a form field. Asked as "undo what this binding did" it is well defined for
735
+ every kind, because it reads the element's own pristine state — `""` for `input.value`, `undefined`
736
+ for a custom element's property.
737
+
738
+ **On a hydrated page it restores the server's value**, because that is genuinely what was there
739
+ before the binding: the server rendered this same spread, and a spread key *replaces* a static
740
+ attribute in server markup exactly as it overwrites one on the client. The original is gone by
741
+ construction, so bind `null` when you mean removal:
742
+
743
+ ```js
744
+ renderInto(html`<input ${spread({ id: null })} />`, host); // removes, on either path
745
+ ```
746
+
747
+ One residue worth knowing: `.value`, `.checked` and `.selected` are mirrored to attributes
748
+ server-side so hydration can read them back, and releasing the property does not clear that
749
+ attribute. The property is correct either way; the attribute lingers as the field's *default* value.
750
+
751
+ A released event binding stops dispatching; the listener itself stays registered, which is how
752
+ written `@event` bindings behave too.
753
+
754
+ ### What it costs, and why it is a separate entry
755
+
756
+ `@verajs/renderer` grows **5 B** gzipped for the protocol this uses, whether or not you import it —
757
+ measured 2026-08-27 by deleting the `_$apply$` branch and rebuilding, as a **difference** rather than
758
+ a pair of totals — the totals move with every change to this package and the difference does not,
759
+ which is the mistake this line already made once. `llms.txt` and this file disagreed about the figure
760
+ for a while, at 16 B and 8 B respectively, and both were wrong. Nothing regenerates it, so it is
761
+ dated; re-measure the same way if it matters.
762
+ The entry itself is **<!--size:spread.gzip-->1.60 KB<!--/size:spread.gzip-->** gzipped, and only apps
763
+ that import it pay for that.
764
+
765
+ Runtime is at parity with writing the bindings out: both do one comparison per binding per render,
766
+ and the spread does one part-dispatch where five written bindings do five.
767
+
768
+ Template renderers bake attribute names into the template at parse time. That is what makes them
769
+ small and fast, and it is why neither this renderer nor lit-html has spread built in —
770
+ [lit's spread PR](https://github.com/lit/lit/pull/1960) has been an open draft since 2021.
771
+
772
+ The renderer itself holds only a protocol: a value at element position carrying `_$apply$` applies
773
+ itself. Everything else lives in this entry, which imports nothing — not even from the renderer — so
774
+ it loads alongside any renderer that honours the protocol, including your own.
775
+
776
+ ## `@verajs/renderer/profiler`
777
+
778
+ <!-- recipe -->
779
+ ```js
780
+ import { renderInto, profile, formatReport } from '@verajs/renderer/profiler';
781
+
782
+ /** `profile` awaits an async driver — driving an app means awaiting frames, and the render
783
+ scheduler is `requestAnimationFrame`, so nothing commits inside one synchronous turn. */
784
+ const { report } = await profile(async () => { /* click around, await frames */ });
785
+ console.log(formatReport(report));
786
+ // 39 updated in place, 2 created, 19 rebuilt (32% of commits)
787
+ // Template identity churn — these were torn down, not updated:
788
+ // 10x at body > main#app > ul.todo-list
789
+ // <li class="done"><s>${…}</s></li>
790
+ // -> <li><label><input type="checkbox">${…}</label></li>
791
+ ```
792
+
793
+ `showProfiler()` puts the same numbers in a live panel in the corner of the page and returns a
794
+ function that removes it. The panel is plain DOM in a shadow root — it never renders itself through
795
+ the renderer, so it does not appear in its own measurements.
796
+
797
+ **Calling it again replaces the panel rather than adding one**, and a second call's `options` take
798
+ effect. That matters because the natural way to use this is a console — `showProfiler()`, look,
799
+ `showProfiler()` again — where the first return value is already gone: two panels would sit on top of
800
+ each other in the same corner, and the second one's teardown would stop profiling for the first,
801
+ which kept repainting a frozen report.
802
+
803
+ Full API: `startProfiling()`, `stopProfiling()`, `getReport()`, `isProfiling()`, `profile(fn)`,
804
+ `formatReport(report)`, `showProfiler(options?)`. The first four are `profile()` unrolled, for a
805
+ session that does not fit one callback — a long-running tab, a REPL:
806
+
807
+ ```js
808
+ import { startProfiling, stopProfiling, getReport, isProfiling, formatReport } from '@verajs/renderer/profiler';
809
+
810
+ startProfiling();
811
+ // … interact with the app for as long as you like …
812
+ if (isProfiling()) console.log(formatReport(getReport())); // read mid-flight without stopping
813
+ stopProfiling(); // freezes the report
814
+ ```
815
+
816
+ This costs production nothing, and there is nothing to strip: the instrumentation sits behind a
817
+ `__DEV__` constant the build folds to `false`, so `vera-renderer.min.js` is byte-identical whether
818
+ or not this entry exists.
819
+
820
+ ## Trusted HTML, and why there is no `unsafeHTML`
821
+
822
+ Every interpolated value is escaped at the render boundary. There is no `unsafeHTML` and there will
823
+ not be one: shipping a sanctioned opt-out puts an XSS sink in the public API, where it reads as
824
+ blessed in tutorials and in review.
825
+
826
+ Trusted markup goes through a property binding, so you write the sink yourself:
827
+
828
+ ```js
829
+ renderInto(html`<div .innerHTML=${trustedMarkup}></div>`, host);
830
+ ```
831
+
832
+ Greppable, obviously yours, reviewable as the security decision it is. Sanitize first
833
+ (`DOMPurify.sanitize`) unless the markup is genuinely your own, and put it on an element whose
834
+ children nothing else binds — the renderer owns the content of elements it renders into.
835
+
836
+ **Security: spread refuses the injection sinks.** The `.innerHTML` posture above rests on the
837
+ template spelling being greppable, obviously yours, and reviewable — three properties a spread key
838
+ does not have, because spread names arrive at runtime inside a props object that is often built
839
+ from data. So `spread()` refuses `.innerHTML`/`!outerHTML` property keys, the `srcdoc` attribute,
840
+ and any inline-handler attribute name (`onclick` and friends, any casing — `on` + Capital with a
841
+ function remains the documented event spelling and still works), on the client AND in the SSR
842
+ serializer alike. Development builds name each refused key and the sanctioned template spelling.
843
+ If you genuinely need one of these dynamically, write the binding in the template where a reviewer
844
+ can see it.
845
+
846
+ ## `@verajs/renderer/tag`
847
+
848
+ An element whose **tag name** is decided at runtime — a heading whose level comes from data, a
849
+ component that renders `<a>` or `<button>`.
850
+
851
+ ```js
852
+ import { html, tag } from '@verajs/renderer/tag';
853
+
854
+ const HEADING = { 1: tag`h1`, 2: tag`h2`, 3: tag`h3` };
855
+
856
+ const H = HEADING[state.level];
857
+ renderInto(html`<${H} class="title">${state.text}</${H}>`, host);
858
+ ```
859
+
860
+ A template renderer bakes tag names into its statics — that is what template identity *is*, and
861
+ what every fast path here depends on. So a runtime tag cannot be a binding: it is spliced into the
862
+ statics before the renderer sees the template. Downstream nothing changes. The renderer,
863
+ `@verajs/ssr` and hydration all receive an ordinary template and are unaware this entry exists.
864
+
865
+ Note the `html` import: in a template containing a tag, use the one from here rather than core's.
866
+
867
+ ### In JSX
868
+
869
+ **A tag is also a component.** A capitalized JSX tag compiles to `H({…})`, and a tag *is* that
870
+ function, so the same value works in both notations with no compiler change and no new syntax —
871
+ `<{expr}>` is not valid JSX or TSX, and inventing it would break `tsc`, Prettier and every editor.
872
+
873
+ ```jsx
874
+ const H = HEADING[state.level];
875
+ return <H className="title" hidden={state.muted}>{state.text}</H>;
876
+ ```
877
+
878
+ React's names are mapped here exactly as the compiler maps them on a written element, so `<H
879
+ className="t" hidden={false}>` and `<h1 className="t" hidden={false}>` mean the same thing. That is
880
+ a correctness matter, not an ergonomic one: passed through raw, `hidden={false}` becomes the
881
+ attribute `hidden="false"` and any value at all applies it.
882
+
883
+ `ref` is mapped too — `<H ref={r}>` binds exactly as `<h1 ref={r}>` does. `key` never reaches the
884
+ component: `@verajs/jsx` consumes it into `keyed(…)` for both spellings, and a hand-written
885
+ `H({ key })` drops it and says so in development, because a key marks a template for reconciliation
886
+ and this call *returns* one rather than being one.
887
+
888
+ **`dangerouslySetInnerHTML` is the one React name a tag cannot honour, and that is a security
889
+ property rather than a gap.** A tag reaches its element through `/spread`, whose names are only
890
+ known at runtime — which is exactly what makes that sink unreviewable — so `/spread` refuses
891
+ `.innerHTML` outright. Write the element directly, with the value sanitized first:
892
+
893
+ ```js
894
+ renderInto(html`<${H} .innerHTML=${trusted}>`, host);
895
+ ```
896
+
897
+ `tests/jsx-component-equivalence.test.mjs` drives every one of these both ways, compiled and
898
+ rendered, and compares the DOM — because the name-level pin that preceded it passed for the entire
899
+ life of three defects.
900
+
901
+ ### What to know
902
+
903
+ - **A string can never become a tag.** Only another tag may be interpolated, so the set of tags an
904
+ app can produce is fixed by its source. That is what keeps a tag out of reach of a request — the
905
+ same reasoning as there being no `unsafeHTML` — and it is what bounds the cache below.
906
+ - **Each tag is its own template.** Switching tags rebuilds the subtree, which is correct: the
907
+ element genuinely changed. Within a tag it updates in place like anything else.
908
+ - **The cache is per call site.** Spliced statics hang off the call site's own `strings` array, so
909
+ two template literals in the source are two entries however identical they look. Right for real
910
+ code, where a template lives at one place in a render function — and the thing that catches people
911
+ writing tests for it.
912
+ - HTML only. There is no `svg`/`mathml` equivalent yet.
913
+
914
+ <!--size:tag.gzip-->2.20 KB<!--/size:tag.gzip--> gzipped, which includes `/spread` — the factory
915
+ needs it to apply props whose names it cannot know. Additive, like `/spread` and unlike the other
916
+ entries: it inlines no renderer internals, so it is safe alongside any of them.
917
+
918
+ This entry also exports `jsxName` and `BOOLEAN_ATTRIBUTES`, **which are not API for applications.**
919
+ They are the table this entry uses to map React's names, and `@verajs/jsx` carries its own copy
920
+ deliberately — the two are build-time and runtime, and a shared package would be a dependency where
921
+ a test does the job. `tests/jsx-name-mapping.test.mjs` asserts the two agree on every key, and it can
922
+ only do that against the built artifact, which is why they are exported at all. Read them if you are
923
+ writing something that has to agree with both; do not build on them:
924
+
925
+ ```js
926
+ import { jsxName, BOOLEAN_ATTRIBUTES } from '@verajs/renderer/tag';
927
+
928
+ jsxName('className'); // 'class' — the runtime half of the React-name mapping
929
+ BOOLEAN_ATTRIBUTES.has('disabled'); // true — the names the tag entry toggles rather than assigns
930
+ ```
931
+
932
+ ## Extending it — `_$apply$` and `_$child$`
933
+
934
+ The renderer holds no directive system. It holds a **protocol**, at the two positions worth
935
+ extending, and everything built on it is an ordinary package the renderer knows nothing about —
936
+ `@verajs/renderer/spread` is the proof, at 5 B of protocol in this bundle and its own weight only
937
+ for apps that import it.
938
+
939
+ | position | brand | called as |
940
+ | --- | --- | --- |
941
+ | element — `<div ${value}>` | `_$apply$` | `value._$apply$(element, part)` |
942
+ | child — `<div>${value}</div>` | `_$child$` | `value._$child$(part, previous)` |
943
+
944
+ A child-position value carrying `_$child$` applies itself. It is handed the part and whatever it
945
+ returned last time **at that part**, and calls `part._$commit$(value)` to render content. That is
946
+ the whole surface: `until()` is nine lines against it.
947
+
948
+ ```js
949
+ /** Hoisted — the applier's identity is its own continuity key. */
950
+ function applyUntil(part, previous) {
951
+ if (previous && previous.promise === this.promise) return previous;
952
+ if (previous) previous.live = false;
953
+ const state = { promise: this.promise, live: true };
954
+ part._$commit$(this.placeholder);
955
+ this.promise.then((value) => { if (state.live) part._$commit$(value); });
956
+ return state;
957
+ }
958
+ const until = (promise, placeholder) => ({ _$child$: applyUntil, promise, placeholder });
959
+
960
+ renderInto(html`<p>${until(fetchUser(), html`<em>loading…</em>`)}</p>`, host);
961
+ ```
962
+
963
+ Three rules, each of which is a real trap:
964
+
965
+ - **Hoist the applier.** Written as an object-literal method it is a new function per call, so the
966
+ part can never recognise it and `previous` is always `undefined`. Its identity is what keeps two
967
+ appliers at one part from reading each other's state.
968
+ - **Continuity lives in the return value**, not in an applier instance. That is what makes this a
969
+ protocol rather than a framework — no base class, no `directive()` factory, no lifecycle.
970
+ - **Teardown is opt-in, on the applier.** `applyThing._$detach$ = (previous) => …` is called with
971
+ whatever the applier last returned, when the subtree holding it is removed — replaced, dropped
972
+ from a keyed list, or shrunk out of an unkeyed one. Declaring it is what arms the walk; an applier
973
+ that does not declare it costs nothing, and neither does an app with no such applier anywhere.
974
+
975
+ It **notifies, it does not defer**. The nodes are already going. To hold content on screen while it
976
+ animates out, do not remove it: an applier owns what it commits, so it can simply not commit the
977
+ removal until it is ready — see *Deferring a removal* below.
978
+ - **Why declaring `_$detach$` is what arms it:** `_clear` bulk-removes DOM — when the part owns
979
+ its parent, one `parent.textContent = ''`, which is what makes clearing a 1 000-row table ~5 ms
980
+ against lit-html's ~22 ms. Notifying nested appliers means walking the part tree on removal,
981
+ which is exactly the per-node work that fast path exists to skip — so the walk runs only once
982
+ something, anywhere, has declared teardown, and an app with none pays nothing.
983
+
984
+ ### Deferring a removal
985
+
986
+ An applier owns the content it commits, so an exit animation needs nothing from the renderer — it
987
+ just does not commit the removal until the animation has finished:
988
+
989
+ ```js
990
+ function applyTransition(part, previous) {
991
+ const next = this.value;
992
+ const state = previous ?? { shown: undefined, timer: null };
993
+ if (next != null) { part._$commit$(next); state.shown = next; return state; }
994
+ if (state.shown != null && state.timer === null)
995
+ state.timer = setTimeout(() => { state.timer = null; part._$commit$(null); }, 300);
996
+ return state;
997
+ }
998
+ const transition = (value) => ({ _$child$: applyTransition, value });
999
+ ```
1000
+
1001
+ This works for a child position and for a whole list committed as one value. It does **not** work for
1002
+ one row inside a keyed list: that row's removal is decided by the reconciler, and nothing inside it
1003
+ is asked.
1004
+
1005
+ Both names survive minification by construction: the renderer mangles `/^_[a-z]/`, and `_$…$` does
1006
+ not match it. `tests/minification-contracts.test.mjs` holds that.
1007
+
1008
+ The check costs the hot path nothing: it sits after the template branch, and a template — the
1009
+ common object at a child position — returns before ever reading it, so only arrays, nodes and
1010
+ appliers pay a property read. Measured with no runtime difference distinguishable from noise.
1011
+
1012
+ The whole protocol is **116 B gzipped** — the check, the two fields holding an applier's state and
1013
+ whose it is, the save/restore in `_$commit$` that stops an applier's own rendering from destroying
1014
+ its continuity, and the `_$detach$` call. It was 94 B before teardown existed.
1015
+
1016
+ ## Animating things in and out
1017
+
1018
+ There is no transition component, and none is needed — but the shapes are worth knowing, because
1019
+ one of the obvious ones does not work in every engine.
1020
+
1021
+ **Fading on `?hidden`.** The framework's own advice is to prefer a stable shape with `?hidden=${…}`
1022
+ over swapping subtrees, and that is also what makes an exit transition possible: the element is
1023
+ still there to animate.
1024
+
1025
+ ```css
1026
+ .fade { opacity: 1; transition: opacity 200ms; }
1027
+ .fade[hidden] { display: block; opacity: 0; pointer-events: none; }
1028
+ ```
1029
+
1030
+ The `display: block` is load-bearing — it overrides the user agent's `[hidden] { display: none }`,
1031
+ which would otherwise remove the element from rendering instantly with nothing to fade.
1032
+
1033
+ **Do not reach for `transition-behavior: allow-discrete` on `display` for this.** Measured
1034
+ 2026-08-24 across all three engines, transitioning `display` with `allow-discrete`: Chromium and
1035
+ WebKit fade correctly, **Firefox jumps straight to `display: none`** and no transition runs. All
1036
+ three report `CSS.supports('transition-behavior', 'allow-discrete')` as `true`, so the feature test
1037
+ does not tell you. The opacity-only shape above behaves identically in all three.
1038
+
1039
+ **Animating a removal**, where the element really does leave the render, is the browser's job:
1040
+
1041
+ ```js
1042
+ const flushSync = (fn) => {
1043
+ const previous = setRenderScheduler((run) => run());
1044
+ try { fn(); } finally { setRenderScheduler(previous); }
1045
+ };
1046
+
1047
+ document.startViewTransition(() => flushSync(() => { state.rows = next; }));
1048
+ ```
1049
+
1050
+ The View Transitions API snapshots the DOM around the callback and cross-fades, so a row that
1051
+ disappears fades out and the rows below animate up. `startViewTransition` is present in Chromium,
1052
+ Firefox and WebKit. Two things it needs: the state change must happen **inside** the callback —
1053
+ which is what `flushSync` is for, since a render deferred to the next frame lands after the snapshot
1054
+ — and each row needs its own `view-transition-name`, or the whole page cross-fades as one image.
1055
+
1056
+ **Or keep it in state.** Mark the row `leaving`, animate, then drop it. Vue's `<Transition>` is
1057
+ sugar over exactly this, and it is the only one of the three that gives you a completion callback.
1058
+
1059
+ ## Absent on purpose
1060
+
1061
+ Directives other renderers ship, and what replaces them here.
1062
+
1063
+ | Elsewhere | Here |
1064
+ | --- | --- |
1065
+ | `repeat()` | `keyed()` |
1066
+ | `cache()` | `hold()` |
1067
+ | `ref()` | an element-position expression, `<input ${myRef}>` |
1068
+ | `ifDefined()` | built in — `null`/`undefined` remove an attribute |
1069
+ | `classMap()` / `styleMap()` | build the string: `class="base ${extra}"` |
1070
+ | `guard()` | reactivity already skips unchanged work |
1071
+ | `until()`, `asyncReplace()` | render a loading state and re-render from an effect — or nine lines against [`_$child$`](#extending-it--_apply-and-_child) |
1072
+ | `unsafeHTML()` | `.innerHTML=${trusted}`, above |
1073
+ | `literal()` / `static-html` | [`/tag`](#verajsrenderertag) — and a tag doubles as a JSX component |
1074
+ | `live()` | [`!name`](#name--a-live-property) — a sigil, for the case that needs it |
1075
+
1076
+ ## Types
1077
+
1078
+ `TemplateResult` is exported for annotating what a template function returns. The rest of the
1079
+ surface is inferred.
1080
+
1081
+ ## For AI assistants — and anyone who wants the whole API on one page
1082
+
1083
+ The repository root's [`llms.txt`](../../llms.txt) is the complete, hand-maintained API
1084
+ reference for every package, written to be pasted into a model's context window: full export
1085
+ tables, the buildless CDN and JSX recipes, semantics that differ from other frameworks, and the
1086
+ mistakes that come up most. Its recipes are executed by the test suite, so they stay honest.
1087
+
1088
+ ## License
1089
+
1090
+ MIT