@verajs/renderer 0.1.2 → 0.1.4

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.
@@ -0,0 +1,1418 @@
1
+ /**
2
+ * @verajs/renderer — a ground-up, keyed, template-identity renderer.
3
+ *
4
+ * Replaces the Reef-derived renderer, which flattened every template to an HTML string and
5
+ * re-parsed it on each change — O(whole template) work for a one-row edit, measured at 85 ms for a
6
+ * two-row swap that lit-html does in 3.5 ms.
7
+ *
8
+ * The architecture here is the one that wins that benchmark:
9
+ *
10
+ * 1. A tagged template literal's `strings` array is frozen and IDENTICAL for every call from the
11
+ * same call site, so it is a cache key for the template's static shape. The shape is parsed
12
+ * ONCE into a `<template>` element with markers where the expressions go.
13
+ * 2. Rendering clones that template and binds "parts" to the marker positions. Every later render
14
+ * of the same shape only compares and commits the dynamic values — static content is never
15
+ * touched again.
16
+ * 3. Arrays reconcile KEYED (see `keyed()`), with head/tail fast paths and map-based moves, so a
17
+ * reorder moves nodes instead of rebuilding them.
18
+ *
19
+ * Built in, where lit-html requires directive imports: keyed list reconciliation (`keyed`),
20
+ * element refs (element-position expressions), toggled-DOM preservation (`hold`), and a
21
+ * whole-range fast clear — one `textContent = ''` where lit removes thousands of nodes one at a
22
+ * time. Like-for-like (lit-html + repeat + ref + cache: 5 021 B gzip), this file is ~28% smaller.
23
+ *
24
+ * What it deliberately does NOT have, which is why it is smaller than lit-html: no directive
25
+ * protocol, no `noChange`/`nothing` sentinels (in a single-expression attribute, `null`/`undefined`
26
+ * REMOVE the attribute; in a child, they clear it), no sanitizer indirection, no async parts, no
27
+ * dev-mode branches.
28
+ *
29
+ * Known limits, deliberate and shared with lit-html's envelope: no bindings inside comments (the
30
+ * value is consumed and ignored), no dynamic tag names, and nested `<template>` elements' contents
31
+ * are not traversed.
32
+ *
33
+ * CONTRACTS THE SPEED PAYS FOR — these are the trade, documented rather than discovered:
34
+ *
35
+ * - **The renderer owns its container below the mount point.** The whole-range fast clear wipes
36
+ * everything in a parent the part fully owns, including nodes user code appended there by hand
37
+ * (lit-html would preserve them). Same contract as mounting Vue or React into a container.
38
+ * - **Do not call `Node.normalize()` on rendered content.** Child anchors are text nodes, and
39
+ * normalize merges adjacent text — lit-html's comment anchors are immune to this; ours are not.
40
+ * - **A plain string renders as text, never as HTML.** The Reef renderer parsed strings as markup;
41
+ * this one has no innerHTML sink at all (an XSS class removed). The deliberate escape hatch for
42
+ * trusted markup is a property binding: `.innerHTML=${trusted}`.
43
+ * - **Hydration is automatic and markerless.** The first render into a container that already has
44
+ * children adopts them as server output of the same template (statics matched byte-for-byte,
45
+ * anchors installed by splitting live text at known value positions), falling back to a clean
46
+ * render on any mismatch. Requires the initial client render to match server state — same
47
+ * contract as React/Vue hydration.
48
+ * - **No directive protocol.** The template language itself is closed to extension — Vera extends
49
+ * at the framework layer (inserts) and through element refs, not inside the renderer's value
50
+ * handling.
51
+ * - Event handlers are invoked with `this` bound to the ELEMENT (lit binds its host).
52
+ *
53
+ * NAMING NOTE: internal class fields and methods are `_`-prefixed because the production build
54
+ * mangles properties matching /^_[a-z]/ (see defaultRollupConfig). That is what lets this file use
55
+ * full descriptive names while still shipping one-letter properties — locals and top-level names
56
+ * are mangled by default anyway, but property names are not. `_$litType$` and `handleEvent`
57
+ * deliberately do not match the pattern: the first is an interop wire format, the second is called
58
+ * by the DOM itself.
59
+ */
60
+ /**
61
+ * Marks a template result with a stable key so list reconciliation moves it instead of rewriting
62
+ * it. Key all items in a list or none — mixing is undefined behaviour, as are duplicate keys.
63
+ *
64
+ * ```js
65
+ * rows.map((r) => keyed(r.id, html`<tr>...</tr>`))
66
+ * ```
67
+ */
68
+ const keyed = (key, result) => {
69
+ result.key = key;
70
+ return result;
71
+ };
72
+ /**
73
+ * Preserves the DOM of templates a child position toggles away from, instead of destroying it —
74
+ * form values, scroll positions and media playback survive the round trip (lit-html calls this
75
+ * `cache`). Stashed DOM is parked in its instance's own fragment and re-adopted on return.
76
+ *
77
+ * ```js
78
+ * html`<div>${hold(editing ? editor() : viewer())}</div>`
79
+ * ```
80
+ */
81
+ const hold = (result) => ({ $h: result });
82
+ /**
83
+ * Unique per module load, so user text can never collide with it. Randomness here cannot break
84
+ * template caching — the marker only ever pairs a scan with its own Template construction.
85
+ */
86
+ const MARKER = '$v' + ((Math.random() * 1e9) >>> 0).toString(36) + '$';
87
+ /** `<?xyz>` parses as a bogus comment whose data is `?xyz`. */
88
+ const MARKER_COMMENT_DATA = '?' + MARKER;
89
+ const doc = document;
90
+ const comment = (data = '') => doc.createComment(data);
91
+ /**
92
+ * One walker for every template construction, re-aimed by assigning `currentNode`. Traversal of a
93
+ * detached fragment cannot escape it — ascent stops at a null parent — and no walk is ever
94
+ * re-entered mid-flight: an inner instantiation only begins after the outer walk has finished
95
+ * collecting its parts.
96
+ */
97
+ const markerWalker = doc.createTreeWalker(doc, 129 /* ELEMENT | COMMENT */);
98
+ /**
99
+ * Second shared walker for indexing and instantiation. Templates ship with NO marker comments —
100
+ * every child slot's anchor is its primed text node — so instances index over elements and texts.
101
+ * Marker comments exist only transiently during template construction, and are created lazily at
102
+ * runtime only if a slot upgrades from text to template/array content. Sharing the walker saves a
103
+ * TreeWalker allocation per instance, which is 10 000 allocations in a 10 000-row create.
104
+ */
105
+ const instanceWalker = doc.createTreeWalker(doc, 5 /* ELEMENT | TEXT */);
106
+ const RAW_TEXT_TAGS = /^(?:script|style|textarea|title)$/i;
107
+ const ATTR_NAME_DELIMITER = /[\s"'>=/]/;
108
+ /** What an expression position turned out to be. */
109
+ const CHILD = 0;
110
+ const ATTRIBUTE = 1;
111
+ const IGNORED = 2; // value consumed, nothing rendered (bindings inside comments, junk positions)
112
+ /** Scanner states. */
113
+ const IN_TEXT = 0;
114
+ const IN_TAG = 1;
115
+ const IN_QUOTED_VALUE = 2; // a static quoted attribute value (no binding seen yet)
116
+ const IN_COMMENT = 3;
117
+ const IN_RAW_TEXT = 4; // inside <script>/<style>/<textarea>/<title>
118
+ const IN_BOUND_VALUE = 5; // collecting a bound attribute's statics
119
+ /**
120
+ * One pass over the template strings, producing parseable HTML with markers plus an ordered spec
121
+ * list. Runs once per template shape, so clarity beats micro-optimisation here.
122
+ *
123
+ * A small state machine rather than tail regexes, because `>` inside quoted attribute values and
124
+ * inside comments must not terminate a tag, and raw-text elements swallow markup.
125
+ */
126
+ const scan = (strings) => {
127
+ const specs = [];
128
+ let markup = '';
129
+ let state = IN_TEXT;
130
+ let quote = '';
131
+ let quoteStart = 0; // markup index of the opening quote while IN_QUOTED_VALUE
132
+ let rawTag = ''; // which raw-text element we are inside
133
+ let tagNameStart = 0; // markup index where the current tag's name begins
134
+ let isClosing = false;
135
+ let attrName = '';
136
+ let statics = [];
137
+ let pending = ''; // the static chunk currently being collected IN_BOUND_VALUE
138
+ /** Backscan an attribute name that ends at `end` (exclusive); '' when malformed. */
139
+ const attrNameBefore = (end) => {
140
+ let at = end;
141
+ while (at > 0 && !ATTR_NAME_DELIMITER.test(markup[at - 1]))
142
+ at--;
143
+ return markup.slice(at, end);
144
+ };
145
+ for (let i = 0; i < strings.length; i++) {
146
+ const segment = strings[i];
147
+ let pos = 0;
148
+ while (pos < segment.length) {
149
+ const ch = segment[pos];
150
+ if (state === IN_BOUND_VALUE) {
151
+ if (ch === quote ||
152
+ (quote === '' && (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r' || ch === '>' || ch === '/'))) {
153
+ /**
154
+ * The bound attribute closes. Emit a marker attribute whose VALUE carries the statics
155
+ * joined by the marker — reading them back from the parsed attribute means entities
156
+ * arrive decoded, exactly as a static attribute would.
157
+ */
158
+ statics.push(pending);
159
+ const quoteChar = quote || '"';
160
+ markup += ` ${specs.length}${MARKER}=${quoteChar}${statics.join(MARKER)}${quoteChar}`;
161
+ specs.push({ _type: ATTRIBUTE, _name: attrName });
162
+ state = IN_TAG;
163
+ if (quote !== '')
164
+ pos++; // consume the closing quote; unquoted terminators reprocess IN_TAG
165
+ continue;
166
+ }
167
+ pending += ch;
168
+ pos++;
169
+ }
170
+ else if (state === IN_TEXT) {
171
+ if (ch === '<') {
172
+ if (segment.startsWith('!--', pos + 1)) {
173
+ state = IN_COMMENT;
174
+ markup += '<!--';
175
+ pos += 4;
176
+ continue;
177
+ }
178
+ isClosing = segment[pos + 1] === '/';
179
+ tagNameStart = markup.length + (isClosing ? 2 : 1);
180
+ state = IN_TAG;
181
+ }
182
+ markup += ch;
183
+ pos++;
184
+ }
185
+ else if (state === IN_TAG) {
186
+ if (ch === '"' || ch === "'") {
187
+ quote = ch;
188
+ quoteStart = markup.length;
189
+ state = IN_QUOTED_VALUE;
190
+ }
191
+ else if (ch === '>') {
192
+ const tagName = markup.slice(tagNameStart).match(/^[a-zA-Z][^\s/>]*/)?.[0] ?? '';
193
+ if (!isClosing && RAW_TEXT_TAGS.test(tagName) && !markup.endsWith('/')) {
194
+ rawTag = tagName.toLowerCase();
195
+ state = IN_RAW_TEXT;
196
+ }
197
+ else {
198
+ state = IN_TEXT;
199
+ }
200
+ }
201
+ markup += ch;
202
+ pos++;
203
+ }
204
+ else if (state === IN_QUOTED_VALUE) {
205
+ if (ch === quote)
206
+ state = IN_TAG;
207
+ markup += ch;
208
+ pos++;
209
+ }
210
+ else if (state === IN_COMMENT) {
211
+ if (ch === '-' && segment.startsWith('->', pos + 1)) {
212
+ markup += '-->';
213
+ pos += 3;
214
+ state = IN_TEXT;
215
+ continue;
216
+ }
217
+ markup += ch;
218
+ pos++;
219
+ }
220
+ else {
221
+ // IN_RAW_TEXT
222
+ if (ch === '<' &&
223
+ segment.slice(pos + 1, pos + 2 + rawTag.length).toLowerCase() === '/' + rawTag &&
224
+ (pos + 2 + rawTag.length >= segment.length || /[\s/>]/.test(segment[pos + 2 + rawTag.length]))) {
225
+ isClosing = true;
226
+ tagNameStart = markup.length + 2;
227
+ state = IN_TAG;
228
+ }
229
+ markup += ch;
230
+ pos++;
231
+ }
232
+ }
233
+ // ── expression boundary ──────────────────────────────────────────────────
234
+ if (i === strings.length - 1)
235
+ break;
236
+ if (state === IN_TEXT) {
237
+ markup += `<?${MARKER}>`;
238
+ specs.push({ _type: CHILD });
239
+ }
240
+ else if (state === IN_RAW_TEXT) {
241
+ markup += MARKER; // a text marker; comments cannot be parsed inside raw-text elements
242
+ specs.push({ _type: CHILD });
243
+ }
244
+ else if (state === IN_COMMENT) {
245
+ specs.push({ _type: IGNORED }); // binding inside a comment: consumed, ignored
246
+ }
247
+ else if (state === IN_BOUND_VALUE) {
248
+ statics.push(pending); // this attribute spans another expression
249
+ pending = '';
250
+ }
251
+ else if (state === IN_QUOTED_VALUE) {
252
+ // expression inside a quoted attribute value -> becomes a bound attribute
253
+ const name = markup[quoteStart - 1] === '=' ? attrNameBefore(quoteStart - 1) : '';
254
+ if (name) {
255
+ attrName = name;
256
+ statics = [markup.slice(quoteStart + 1)]; // the static prefix already inside the quotes
257
+ pending = '';
258
+ markup = markup.slice(0, quoteStart - 1 - name.length); // cut `name="` back out
259
+ state = IN_BOUND_VALUE;
260
+ }
261
+ else {
262
+ specs.push({ _type: IGNORED });
263
+ }
264
+ }
265
+ else {
266
+ // IN_TAG: `name=${x}` unquoted, or an element-position expression
267
+ const name = markup.endsWith('=') ? attrNameBefore(markup.length - 1) : '';
268
+ if (name) {
269
+ attrName = name;
270
+ statics = [''];
271
+ pending = '';
272
+ quote = '';
273
+ markup = markup.slice(0, markup.length - 1 - name.length);
274
+ state = IN_BOUND_VALUE;
275
+ }
276
+ else {
277
+ /**
278
+ * Element-position expression — an element REF, not a no-op. Marked exactly like a bound
279
+ * attribute ('&' cannot begin a real attribute binding), so no new machinery exists for it.
280
+ */
281
+ markup += ` ${specs.length}${MARKER}="${MARKER}"`;
282
+ specs.push({ _type: ATTRIBUTE, _name: '&' });
283
+ }
284
+ }
285
+ }
286
+ return { markup, specs };
287
+ };
288
+ const templateCache = new WeakMap();
289
+ class Template {
290
+ _element;
291
+ _parts = [];
292
+ constructor(result) {
293
+ const type = result._$litType$ ?? 1;
294
+ const { markup, specs } = scan(result.strings);
295
+ this._element = doc.createElement('template');
296
+ /** svg/mathml fragments only parse inside their root; wrap, then unwrap below. */
297
+ this._element.innerHTML = type === 2 ? `<svg>${markup}</svg>` : type === 3 ? `<math>${markup}</math>` : markup;
298
+ const content = this._element.content;
299
+ if (type !== 1) {
300
+ const wrapper = content.firstChild;
301
+ while (wrapper.firstChild)
302
+ content.insertBefore(wrapper.firstChild, wrapper);
303
+ content.removeChild(wrapper);
304
+ }
305
+ /**
306
+ * Pass 1 — DISCOVER over ELEMENT | COMMENT: pair scan specs with parsed nodes in document
307
+ * order (which is expression order), and swap every marker comment for a primed empty text
308
+ * node. The shipped template then contains no comments at all: each clone is three nodes
309
+ * lighter per typical row, and the primed text doubles as both anchor and first-commit target.
310
+ */
311
+ markerWalker.currentNode = content;
312
+ let specIndex = 0;
313
+ let node;
314
+ const parts = this._parts;
315
+ const consumeIgnored = () => {
316
+ while (specIndex < specs.length && specs[specIndex]._type === IGNORED) {
317
+ parts.push({ _type: IGNORED, _index: -1 });
318
+ specIndex++;
319
+ }
320
+ };
321
+ consumeIgnored();
322
+ while (specIndex < specs.length && (node = markerWalker.nextNode()) !== null) {
323
+ if (node.nodeType === 1) {
324
+ const element = node;
325
+ if (element.hasAttributes()) {
326
+ for (const attributeName of element.getAttributeNames()) {
327
+ if (attributeName.endsWith(MARKER)) {
328
+ /**
329
+ * The marker attribute's value carries the statics; the REAL (case-preserved) name
330
+ * comes from the spec — the HTML parser lowercases attribute names, which would
331
+ * corrupt `.someProp`.
332
+ */
333
+ const spec = specs[specIndex++];
334
+ parts.push({
335
+ _type: ATTRIBUTE,
336
+ _index: -1,
337
+ _name: spec._name,
338
+ _statics: element.getAttribute(attributeName).split(MARKER),
339
+ _node: element,
340
+ });
341
+ element.removeAttribute(attributeName);
342
+ consumeIgnored();
343
+ }
344
+ }
345
+ }
346
+ if (RAW_TEXT_TAGS.test(element.tagName) && element.textContent.includes(MARKER)) {
347
+ /**
348
+ * Comments cannot be PARSED inside raw-text elements, but they are legal DOM once
349
+ * created — so the scan left text markers, and here they become real marker comments.
350
+ * The walker visits them next and they pair as ordinary child parts.
351
+ */
352
+ const pieces = element.textContent.split(MARKER);
353
+ element.textContent = '';
354
+ for (let p = 0; p < pieces.length - 1; p++) {
355
+ if (pieces[p])
356
+ element.append(pieces[p]);
357
+ element.append(comment(MARKER_COMMENT_DATA));
358
+ }
359
+ if (pieces[pieces.length - 1])
360
+ element.append(pieces[pieces.length - 1]);
361
+ }
362
+ }
363
+ else if (node.data === MARKER_COMMENT_DATA) {
364
+ specIndex++;
365
+ const primedText = doc.createTextNode('');
366
+ node.parentNode.insertBefore(primedText, node);
367
+ /** Re-aim the walker before removing the node it stands on. */
368
+ markerWalker.currentNode = primedText;
369
+ node.remove();
370
+ parts.push({ _type: CHILD, _index: -1, _node: primedText });
371
+ consumeIgnored();
372
+ }
373
+ }
374
+ /** Pass 2 — INDEX over ELEMENT | TEXT, the mask instances walk with. */
375
+ instanceWalker.currentNode = content;
376
+ let nodeIndex = -1;
377
+ let partIndex = 0;
378
+ while (partIndex < parts.length && parts[partIndex]._type === IGNORED)
379
+ partIndex++;
380
+ while (partIndex < parts.length && (node = instanceWalker.nextNode()) !== null) {
381
+ nodeIndex++;
382
+ while (partIndex < parts.length && parts[partIndex]._node === node) {
383
+ parts[partIndex]._index = nodeIndex;
384
+ partIndex++;
385
+ while (partIndex < parts.length && parts[partIndex]._type === IGNORED)
386
+ partIndex++;
387
+ }
388
+ }
389
+ for (const part of parts)
390
+ part._node = undefined;
391
+ }
392
+ }
393
+ const getTemplate = (result) => {
394
+ let template = templateCache.get(result.strings);
395
+ if (template === undefined)
396
+ templateCache.set(result.strings, (template = new Template(result)));
397
+ return template;
398
+ };
399
+ const IGNORED_PART = { _commit: (_values, index) => index + 1 };
400
+ /** Never equal to any user value, so the first commit always runs. */
401
+ const UNSET = {};
402
+ /** Removal target: nodes moved here are dropped when it is emptied. */
403
+ const SCRATCH = doc.createDocumentFragment();
404
+ /** A fresh markered part: two comments inserted before `ref` in `parent`. */
405
+ const createMarkeredPart = (parent, ref) => {
406
+ const start = comment();
407
+ const end = comment();
408
+ parent.insertBefore(start, ref);
409
+ parent.insertBefore(end, ref);
410
+ return new ChildPart(start, end);
411
+ };
412
+ const toText = (value) => (value == null ? '' : String(value));
413
+ /** Binding kinds, resolved once from the attribute name's first character. */
414
+ const ATTR = 0; // plain attribute
415
+ const PROPERTY = 1; // .name
416
+ const BOOLEAN = 2; // ?name
417
+ const EVENT = 3; // @name
418
+ const REF = 4; // element-position expression
419
+ class AttrPart {
420
+ _element;
421
+ _name;
422
+ _statics;
423
+ _slots; // how many expression values this binding consumes
424
+ _kind;
425
+ _isFullValue; // exactly one expression with no static text around it
426
+ _committed = UNSET;
427
+ _handler = null;
428
+ constructor(element, name, statics) {
429
+ const first = name[0];
430
+ let kind = first === '.' ? PROPERTY : first === '?' ? BOOLEAN : first === '@' ? EVENT : first === '&' ? REF : ATTR;
431
+ let realName = kind ? name.slice(1) : name;
432
+ /** React muscle-memory, buildless: `onClick=${fn}` ≡ `@click=${fn}`. Strictly `on` + a
433
+ * capital — all-lowercase `onclick` stays a plain attribute (legal inline-handler HTML). */
434
+ if (kind === ATTR && first === 'o' && name.charCodeAt(1) === 110 && name.charCodeAt(2) > 64 && name.charCodeAt(2) < 91) {
435
+ kind = EVENT;
436
+ realName = name.slice(2).toLowerCase();
437
+ }
438
+ this._kind = kind;
439
+ this._name = realName;
440
+ this._element = element;
441
+ this._statics = statics;
442
+ this._slots = statics.length - 1;
443
+ this._isFullValue = this._slots === 1 && statics[0] === '' && statics[1] === '';
444
+ }
445
+ /** Stable listener registered once; swapping the handler never touches the DOM. */
446
+ handleEvent(event) {
447
+ if (this._handler)
448
+ this._handler.call(this._element, event);
449
+ }
450
+ _commit(values, index) {
451
+ const kind = this._kind;
452
+ let value;
453
+ if (this._isFullValue || kind >= EVENT) {
454
+ value = values[index]; // raw and uncoerced — events and refs receive the actual value
455
+ }
456
+ else {
457
+ const statics = this._statics;
458
+ let joined = statics[0];
459
+ for (let i = 0; i < this._slots; i++)
460
+ joined += toText(values[index + i]) + statics[i + 1];
461
+ value = joined;
462
+ }
463
+ if (value !== this._committed) {
464
+ /** On the very first commit the attribute does not exist, so a null needs no DOM call. */
465
+ const isFirst = this._committed === UNSET;
466
+ this._committed = value;
467
+ if (kind === ATTR) {
468
+ if (value == null) {
469
+ if (!isFirst)
470
+ this._element.removeAttribute(this._name);
471
+ }
472
+ else
473
+ this._element.setAttribute(this._name, value);
474
+ }
475
+ else if (kind === PROPERTY) {
476
+ const target = this._element;
477
+ const name = this._name;
478
+ target[name] = value;
479
+ /**
480
+ * Detection only, and deliberately not repair.
481
+ *
482
+ * A property set on a custom element that has not upgraded yet lands as an own property on
483
+ * the instance. When the definition arrives — lazily imported, code-split, or a module that
484
+ * simply had not run — `customElements.define` upgrades synchronously and the class's field
485
+ * initializers execute. At target ES2022 a field declaration is a `[[Define]]`, so
486
+ * `item?: T` emits `item;` and overwrites the bound value with `undefined`. Nothing throws;
487
+ * it reads as broken reactivity.
488
+ *
489
+ * Repairing it was tried and removed. Re-applying when the slot came back `undefined`
490
+ * covered `item?: T` but not `item = someDefault`, which overwrites with the default and
491
+ * never looks clobbered — so the repair was silently partial, and made the bug intermittent
492
+ * across two spellings of the same mistake. It also cost 74 B in every app while leaving
493
+ * `declare` mandatory anyway, because a property assigned imperatively is unrecoverable:
494
+ * the renderer never saw it, and by the time `init()` runs the value is already gone.
495
+ *
496
+ * So this is `true`-only and production pays nothing — no check, no message, no
497
+ * `whenDefined` subscription. Lit reached the same place from the other direction and
498
+ * throws (`lit.dev/msg/class-field-shadowing`); a warning suffices here because Vera has no
499
+ * prototype accessors to shadow permanently — the damage is one lost value, not a property
500
+ * that never updates again.
501
+ */
502
+ if (true) {
503
+ const tag = this._element.localName;
504
+ if (tag.indexOf('-') > 0 && !customElements.get(tag)) {
505
+ customElements.whenDefined(tag).then(() => {
506
+ /**
507
+ * States what was observed rather than diagnosing it. A class field is the usual
508
+ * cause by a wide margin, but a component that assigns the property itself during
509
+ * upgrade produces the same observation, and that is a legitimate — if confusing —
510
+ * thing to do, since the renderer's dirty check will not re-apply the bound value on
511
+ * the next render either.
512
+ */
513
+ if (target[name] !== value)
514
+ console.warn(`@verajs/renderer: the value bound by \`.${name}=\${…}\` on <${tag}> was replaced ` +
515
+ `while the element upgraded. A class field is the usual cause: at ES2022 ` +
516
+ `\`${name}?: …\` emits \`${name};\`, which runs during upgrade and overwrites ` +
517
+ `whatever was set beforehand — write it \`declare ${name}?: …\` instead, which ` +
518
+ `emits nothing. A plain field also wipes properties assigned imperatively, ` +
519
+ `which cannot be detected at all. Ignore this if the component replaced the ` +
520
+ `value on purpose.`);
521
+ });
522
+ }
523
+ }
524
+ }
525
+ else if (kind === BOOLEAN) {
526
+ if (!isFirst || value)
527
+ this._element.toggleAttribute(this._name, !!value);
528
+ }
529
+ else if (kind === EVENT) {
530
+ if (this._handler === null && value != null)
531
+ this._element.addEventListener(this._name, this);
532
+ this._handler = value ?? null;
533
+ }
534
+ else if (value != null) {
535
+ /**
536
+ * Element ref: `<input ${myRef} />`. A function is called with the element; an object gets
537
+ * the element assigned to `.value` — which makes core's own `ref()` double as an element
538
+ * ref, reactively. Runs once per distinct value, not once per render.
539
+ */
540
+ if (typeof value === 'function')
541
+ value(this._element);
542
+ else if (typeof value === 'object')
543
+ value.value = this._element;
544
+ // any other value type at element position is consumed and ignored
545
+ }
546
+ }
547
+ return index + this._slots;
548
+ }
549
+ }
550
+ class Instance {
551
+ _parts = [];
552
+ _fragment;
553
+ constructor(template) {
554
+ /** cloneNode over importNode: same document, and it measures slightly cheaper. */
555
+ this._fragment = template._element.content.cloneNode(true);
556
+ const templateParts = template._parts;
557
+ /** Shared walker, ELEMENT | TEXT — child anchors are the primed text nodes themselves. */
558
+ instanceWalker.currentNode = this._fragment;
559
+ let nodeIndex = -1;
560
+ let node = null;
561
+ for (let i = 0; i < templateParts.length; i++) {
562
+ const templatePart = templateParts[i];
563
+ if (templatePart._type === IGNORED) {
564
+ this._parts.push(IGNORED_PART);
565
+ continue;
566
+ }
567
+ while (nodeIndex < templatePart._index) {
568
+ node = instanceWalker.nextNode();
569
+ nodeIndex++;
570
+ }
571
+ this._parts.push(templatePart._type === CHILD
572
+ ? new TextPart(node)
573
+ : new AttrPart(node, templatePart._name, templatePart._statics));
574
+ }
575
+ }
576
+ _update(values) {
577
+ let valueIndex = 0;
578
+ const parts = this._parts;
579
+ for (let i = 0; i < parts.length; i++)
580
+ valueIndex = parts[i]._commit(values, valueIndex);
581
+ }
582
+ }
583
+ /** A single property read — this runs once per list item per render, so it must be minimal. */
584
+ const isTemplateResult = (value) => value.strings !== undefined;
585
+ /**
586
+ * The common case of a child expression is plain text, and the template primes every child slot
587
+ * with a text node — so the steady state is compare-and-assign on `.data`. This part carries only
588
+ * that, upgrading itself to a full ChildPart the first time it sees null, a template, or an array.
589
+ */
590
+ class TextPart {
591
+ _text;
592
+ _value = '';
593
+ _upgraded = null;
594
+ constructor(text) {
595
+ this._text = text;
596
+ }
597
+ _commit(values, index) {
598
+ const value = values[index];
599
+ if (this._upgraded !== null) {
600
+ this._upgraded._set(value);
601
+ return index + 1;
602
+ }
603
+ if (value == null || typeof value === 'object') {
604
+ /**
605
+ * Upgrade in place: marker comments come into existence only now, anchored around the text
606
+ * node, and the full part inherits the committed text state and delegates forever.
607
+ *
608
+ * BOTH markers are ours. Borrowing `this._text.nextSibling` as the end instead would hand
609
+ * this part a boundary owned by the NEXT part — and the next part removes that very node
610
+ * when it upgrades and clears its own text. The stale reference then makes `_clear()` walk
611
+ * past the end of the child list. Owning both anchors also makes `_end === null` mean
612
+ * exactly one thing: the root part, which really does own its container.
613
+ */
614
+ const start = comment();
615
+ const end = comment();
616
+ const parent = this._text.parentNode;
617
+ parent.insertBefore(start, this._text);
618
+ parent.insertBefore(end, this._text.nextSibling);
619
+ const part = new ChildPart(start, end);
620
+ part._mode = TEXT;
621
+ part._text = this._text;
622
+ part._value = this._value;
623
+ this._upgraded = part;
624
+ part._set(value);
625
+ return index + 1;
626
+ }
627
+ if (value !== this._value) {
628
+ this._value = value;
629
+ this._text.data = value;
630
+ }
631
+ return index + 1;
632
+ }
633
+ }
634
+ /** What a ChildPart currently contains. */
635
+ const EMPTY = 0;
636
+ const TEXT = 1;
637
+ const TEMPLATE = 2;
638
+ const LIST = 3;
639
+ /**
640
+ * Development-only profiling hook, armed by `@verajs/renderer/profiler`. Null until something
641
+ * arms it, so an unprofiled development render pays one null check per template commit.
642
+ *
643
+ * Every reference sits behind `true`, which `defineDev()` folds to `false` before terser runs —
644
+ * so the declaration, the constants and every call site are removed from the production bundle.
645
+ * Verified by byte comparison, not assumed.
646
+ */
647
+ const PROFILE_UPDATE = 0; // same template identity — values committed in place
648
+ const PROFILE_CREATE = 1; // first template into an empty part
649
+ const PROFILE_REBUILD = 2; // template identity CHANGED — subtree torn down and rebuilt
650
+ const PROFILE_FRAME_START = 3;
651
+ const PROFILE_FRAME_END = 4;
652
+ let _profileHook = null;
653
+ /** @internal */
654
+ const _setProfileHook = (fn) => {
655
+ _profileHook = fn;
656
+ };
657
+ class ChildPart {
658
+ _start;
659
+ /** Exclusive end of this part's range; null means "to the end of the parent". */
660
+ _end;
661
+ _mode = EMPTY;
662
+ _value;
663
+ _text = null;
664
+ _instance = null;
665
+ /** The committed template's strings identity — the same-template fast path in `_set`. */
666
+ _shape = null;
667
+ _items = null;
668
+ _keyedList = false;
669
+ /** Held instances by template identity; survives clears so state outlives interim content. */
670
+ _held = null;
671
+ constructor(start, end) {
672
+ this._start = start;
673
+ this._end = end;
674
+ }
675
+ _commit(values, index) {
676
+ this._set(values[index]);
677
+ return index + 1;
678
+ }
679
+ _insert(node) {
680
+ this._start.parentNode.insertBefore(node, this._end);
681
+ }
682
+ _clear() {
683
+ const parent = this._start.parentNode;
684
+ const end = this._end;
685
+ /**
686
+ * When this part owns its parent's entire contents, one `textContent = ''` replaces removing
687
+ * every node individually. For a 1 000-row table body that is the difference between ~22 ms
688
+ * (lit-html's per-node teardown) and ~5 ms.
689
+ *
690
+ * A part owns the whole parent when nothing precedes its start AND nothing follows its end —
691
+ * `_end === null` (a root part, which runs to the end by definition) or `_end` is the last
692
+ * child. The second case is the common one and used to miss this path entirely: every list
693
+ * written as `<tbody>${rows}</tbody>` sits inside a template, and since 0.1.2 a nested part
694
+ * always owns an end marker, so `_end === null` alone never held for it.
695
+ *
696
+ * Re-appending both anchors in order restores the part's boundary exactly as it was.
697
+ */
698
+ if (this._start.previousSibling === null && (end === null || end.nextSibling === null)) {
699
+ parent.textContent = '';
700
+ parent.appendChild(this._start);
701
+ if (end !== null)
702
+ parent.appendChild(end);
703
+ }
704
+ else {
705
+ let node = this._start.nextSibling;
706
+ /**
707
+ * `node !== null` is a backstop, not an expected exit. Reaching the end of the child list
708
+ * without meeting `_end` means something detached this part's boundary; stopping leaves
709
+ * nodes behind, which beats throwing out of the middle of a render pass.
710
+ */
711
+ while (node !== null && node !== this._end) {
712
+ const next = node.nextSibling;
713
+ parent.removeChild(node);
714
+ node = next;
715
+ }
716
+ }
717
+ this._mode = EMPTY;
718
+ this._text = null;
719
+ this._instance = null;
720
+ this._items = null;
721
+ this._shape = null;
722
+ }
723
+ _set(value) {
724
+ if (value == null) {
725
+ if (this._mode !== EMPTY)
726
+ this._clear();
727
+ return;
728
+ }
729
+ if (typeof value !== 'object') {
730
+ if (this._mode === TEXT) {
731
+ if (this._value !== value) {
732
+ this._value = value;
733
+ this._text.data = value; // the DOM coerces numbers etc.
734
+ }
735
+ }
736
+ else {
737
+ if (this._mode !== EMPTY)
738
+ this._clear();
739
+ this._text = doc.createTextNode(value);
740
+ this._insert(this._text);
741
+ this._value = value;
742
+ this._mode = TEXT;
743
+ }
744
+ return;
745
+ }
746
+ const heldResult = value.$h;
747
+ if (heldResult !== undefined) {
748
+ this._commitHeld(heldResult);
749
+ return;
750
+ }
751
+ if (isTemplateResult(value)) {
752
+ /**
753
+ * Same-shape fast path on `strings` identity alone — no template-cache lookup. This is the
754
+ * hottest line in a keyed list update: for every row whose shape did not change (all of
755
+ * them, in practice), commit costs one identity compare before touching the values.
756
+ */
757
+ if (this._shape === value.strings) {
758
+ if (true && _profileHook)
759
+ _profileHook(PROFILE_UPDATE, this, value.strings);
760
+ this._instance._update(value.values);
761
+ return;
762
+ }
763
+ /**
764
+ * Reaching here with a template already committed means the identity changed, so the
765
+ * subtree below is about to be destroyed and rebuilt rather than updated. That is what
766
+ * `?hidden=${…}` over a swapped subtree exists to avoid, and it is otherwise invisible.
767
+ */
768
+ if (true && _profileHook) {
769
+ _profileHook(this._mode === TEMPLATE ? PROFILE_REBUILD : PROFILE_CREATE, this, value.strings);
770
+ }
771
+ const template = getTemplate(value);
772
+ if (this._mode !== EMPTY)
773
+ this._clear();
774
+ const instance = new Instance(template);
775
+ instance._update(value.values);
776
+ this._insert(instance._fragment);
777
+ this._instance = instance;
778
+ this._shape = value.strings;
779
+ this._mode = TEMPLATE;
780
+ return;
781
+ }
782
+ if (Array.isArray(value)) {
783
+ this._commitList(value);
784
+ return;
785
+ }
786
+ if (typeof value[Symbol.iterator] === 'function') {
787
+ this._commitList([...value]);
788
+ return;
789
+ }
790
+ // any other object: render as text
791
+ this._set(String(value));
792
+ }
793
+ /** Commits a template while stashing whatever it replaces — see the `hold()` export. */
794
+ _commitHeld(result) {
795
+ if (this._mode === TEMPLATE && this._shape === result.strings) {
796
+ this._instance._update(result.values);
797
+ return;
798
+ }
799
+ const held = (this._held ??= new Map());
800
+ if (this._mode === TEMPLATE) {
801
+ /** Park the live nodes back in their instance's own (empty) fragment. */
802
+ const fragment = this._instance._fragment;
803
+ let node = this._start.nextSibling;
804
+ while (node !== this._end) {
805
+ const next = node.nextSibling;
806
+ fragment.appendChild(node);
807
+ node = next;
808
+ }
809
+ held.set(this._shape, this._instance);
810
+ }
811
+ else if (this._mode !== EMPTY) {
812
+ this._clear();
813
+ }
814
+ const instance = held.get(result.strings) ?? new Instance(getTemplate(result));
815
+ instance._update(result.values);
816
+ this._insert(instance._fragment);
817
+ this._instance = instance;
818
+ this._shape = result.strings;
819
+ this._mode = TEMPLATE;
820
+ }
821
+ /**
822
+ * Creates one list item. A single-root template instance becomes an element-mode item with no
823
+ * markers at all; anything else gets its own start/end marker pair so moves can never dangle.
824
+ */
825
+ _createItem(value, parent, ref) {
826
+ if (value !== null && typeof value === 'object' && value.strings !== undefined) {
827
+ const result = value;
828
+ const template = getTemplate(result);
829
+ const instance = new Instance(template);
830
+ instance._update(result.values);
831
+ const rootNode = instance._fragment.firstChild;
832
+ if (rootNode !== null && rootNode.nodeType === 1 && rootNode.nextSibling === null) {
833
+ parent.insertBefore(rootNode, ref);
834
+ return {
835
+ _key: result.key,
836
+ _element: rootNode,
837
+ _instance: instance,
838
+ _shape: result.strings,
839
+ _part: null,
840
+ };
841
+ }
842
+ /** Multi-root template: markered part, content already instantiated. */
843
+ const part = createMarkeredPart(parent, ref);
844
+ part._instance = instance;
845
+ part._shape = result.strings;
846
+ part._mode = TEMPLATE;
847
+ part._start.parentNode.insertBefore(instance._fragment, part._end);
848
+ return { _key: result.key, _element: null, _instance: null, _shape: null, _part: part };
849
+ }
850
+ const part = createMarkeredPart(parent, ref);
851
+ part._set(value);
852
+ return { _key: value?.key, _element: null, _instance: null, _shape: null, _part: part };
853
+ }
854
+ /** Commits a new value into an existing item, demoting element mode if the shape changed. */
855
+ _updateItem(item, value) {
856
+ if (item._element !== null) {
857
+ if (value !== null && typeof value === 'object' && value.strings === item._shape) {
858
+ item._instance._update(value.values);
859
+ return;
860
+ }
861
+ /** Shape changed: swap the bare element for a markered part in its place. */
862
+ const part = createMarkeredPart(item._element.parentNode, item._element);
863
+ item._element.remove();
864
+ item._element = null;
865
+ item._instance = null;
866
+ item._shape = null;
867
+ (item._part = part)._set(value);
868
+ return;
869
+ }
870
+ item._part._set(value);
871
+ }
872
+ /** The item's first node — its move/removal handle and the insertion reference before it. */
873
+ _firstNode(item) {
874
+ return item._element ?? item._part._start;
875
+ }
876
+ _moveItem(item, ref, parent = this._start.parentNode) {
877
+ if (item._element !== null) {
878
+ parent.insertBefore(item._element, ref);
879
+ return;
880
+ }
881
+ let node = item._part._start;
882
+ const stop = item._part._end.nextSibling;
883
+ while (node !== stop) {
884
+ const next = node.nextSibling;
885
+ parent.insertBefore(node, ref);
886
+ node = next;
887
+ }
888
+ }
889
+ /** Removal is a move into a scratch fragment that is immediately emptied. */
890
+ _dropItem(item) {
891
+ this._moveItem(item, null, SCRATCH);
892
+ SCRATCH.textContent = '';
893
+ }
894
+ _commitList(newValues) {
895
+ if (this._mode !== LIST) {
896
+ if (this._mode !== EMPTY)
897
+ this._clear();
898
+ this._items = [];
899
+ this._keyedList = false;
900
+ this._mode = LIST;
901
+ }
902
+ const count = newValues.length;
903
+ if (count === 0) {
904
+ if (this._items.length) {
905
+ this._clear();
906
+ this._items = [];
907
+ this._mode = LIST;
908
+ }
909
+ return;
910
+ }
911
+ const isKeyed = newValues[0] != null && newValues[0].key !== undefined;
912
+ if (isKeyed !== this._keyedList && this._items.length) {
913
+ this._clear();
914
+ this._items = [];
915
+ this._mode = LIST;
916
+ }
917
+ this._keyedList = isKeyed;
918
+ const items = this._items;
919
+ const parent = this._start.parentNode;
920
+ if (items.length === 0) {
921
+ /** Initial fill builds off-document and lands in one insert. */
922
+ const fragment = doc.createDocumentFragment();
923
+ for (let i = 0; i < count; i++)
924
+ items.push(this._createItem(newValues[i], fragment, null));
925
+ this._insert(fragment);
926
+ return;
927
+ }
928
+ if (!isKeyed) {
929
+ // index mode: update in place, grow at the end, shrink from the end
930
+ const shared = items.length < count ? items.length : count;
931
+ for (let i = 0; i < shared; i++)
932
+ this._updateItem(items[i], newValues[i]);
933
+ if (count > items.length) {
934
+ const fragment = doc.createDocumentFragment();
935
+ for (let i = items.length; i < count; i++)
936
+ items.push(this._createItem(newValues[i], fragment, null));
937
+ this._insert(fragment);
938
+ }
939
+ else if (count < items.length) {
940
+ const last = items[items.length - 1];
941
+ let node = this._firstNode(items[count]);
942
+ const stop = last._element !== null ? last._element.nextSibling : last._part._end.nextSibling;
943
+ while (node !== stop) {
944
+ const next = node.nextSibling;
945
+ parent.removeChild(node);
946
+ node = next;
947
+ }
948
+ items.length = count;
949
+ }
950
+ return;
951
+ }
952
+ /**
953
+ * Zero-allocation fast path for the dominant case: same length, same key order — a pure
954
+ * in-place update (a selection change, a field edit). No key array, no output array, no null
955
+ * checks. Falls through to the full algorithm on the first mismatch; the items already updated
956
+ * re-verify there as cheap no-op compares.
957
+ */
958
+ if (items.length === count) {
959
+ let i = 0;
960
+ while (i < count && items[i]._key === newValues[i].key) {
961
+ this._updateItem(items[i], newValues[i]);
962
+ i++;
963
+ }
964
+ if (i === count)
965
+ return;
966
+ }
967
+ /**
968
+ * Keyed reconciliation — the standard head/tail algorithm (as in lit's `repeat` and Vue):
969
+ * skip matching prefixes and suffixes, detect the two swap shapes directly, and fall back to
970
+ * key maps for arbitrary moves, removals and insertions.
971
+ */
972
+ const oldItems = items;
973
+ const newKeys = new Array(count);
974
+ for (let i = 0; i < count; i++)
975
+ newKeys[i] = newValues[i].key;
976
+ const newItems = new Array(count);
977
+ let oldHead = 0;
978
+ let oldTail = oldItems.length - 1;
979
+ let newHead = 0;
980
+ let newTail = count - 1;
981
+ let newKeyToIndex;
982
+ let oldKeyToIndex;
983
+ const refAt = (i) => i < count && newItems[i] !== undefined ? this._firstNode(newItems[i]) : this._end;
984
+ while (oldHead <= oldTail && newHead <= newTail) {
985
+ if (oldItems[oldHead] === null)
986
+ oldHead++;
987
+ else if (oldItems[oldTail] === null)
988
+ oldTail--;
989
+ else if (oldItems[oldHead]._key === newKeys[newHead]) {
990
+ this._updateItem((newItems[newHead] = oldItems[oldHead]), newValues[newHead]);
991
+ oldHead++;
992
+ newHead++;
993
+ }
994
+ else if (oldItems[oldTail]._key === newKeys[newTail]) {
995
+ this._updateItem((newItems[newTail] = oldItems[oldTail]), newValues[newTail]);
996
+ oldTail--;
997
+ newTail--;
998
+ }
999
+ else if (oldItems[oldHead]._key === newKeys[newTail]) {
1000
+ const item = oldItems[oldHead];
1001
+ this._moveItem(item, refAt(newTail + 1));
1002
+ this._updateItem(item, newValues[newTail]);
1003
+ newItems[newTail] = item;
1004
+ oldHead++;
1005
+ newTail--;
1006
+ }
1007
+ else if (oldItems[oldTail]._key === newKeys[newHead]) {
1008
+ const item = oldItems[oldTail];
1009
+ this._moveItem(item, this._firstNode(oldItems[oldHead]));
1010
+ this._updateItem(item, newValues[newHead]);
1011
+ newItems[newHead] = item;
1012
+ oldTail--;
1013
+ newHead++;
1014
+ }
1015
+ else {
1016
+ if (newKeyToIndex === undefined) {
1017
+ newKeyToIndex = new Map();
1018
+ for (let i = newHead; i <= newTail; i++)
1019
+ newKeyToIndex.set(newKeys[i], i);
1020
+ oldKeyToIndex = new Map();
1021
+ for (let i = oldHead; i <= oldTail; i++) {
1022
+ if (oldItems[i] !== null)
1023
+ oldKeyToIndex.set(oldItems[i]._key, i);
1024
+ }
1025
+ }
1026
+ if (!newKeyToIndex.has(oldItems[oldHead]._key)) {
1027
+ this._dropItem(oldItems[oldHead]);
1028
+ oldHead++;
1029
+ }
1030
+ else if (!newKeyToIndex.has(oldItems[oldTail]._key)) {
1031
+ this._dropItem(oldItems[oldTail]);
1032
+ oldTail--;
1033
+ }
1034
+ else {
1035
+ const oldIndex = oldKeyToIndex.get(newKeys[newHead]);
1036
+ if (oldIndex === undefined) {
1037
+ newItems[newHead] = this._createItem(newValues[newHead], parent, this._firstNode(oldItems[oldHead]));
1038
+ }
1039
+ else {
1040
+ const item = oldItems[oldIndex];
1041
+ this._moveItem(item, this._firstNode(oldItems[oldHead]));
1042
+ this._updateItem(item, newValues[newHead]);
1043
+ newItems[newHead] = item;
1044
+ oldItems[oldIndex] = null;
1045
+ }
1046
+ newHead++;
1047
+ }
1048
+ }
1049
+ }
1050
+ while (newHead <= newTail) {
1051
+ newItems[newHead] = this._createItem(newValues[newHead], parent, refAt(newTail + 1));
1052
+ newHead++;
1053
+ }
1054
+ while (oldHead <= oldTail) {
1055
+ const item = oldItems[oldHead++];
1056
+ if (item !== null)
1057
+ this._dropItem(item);
1058
+ }
1059
+ this._items = newItems;
1060
+ }
1061
+ }
1062
+ const rootParts = new WeakMap();
1063
+ /**
1064
+ * Renders a template result into a container. Slots into Vera via `setRenderer(render)`; core's
1065
+ * built-in `html` tag already produces the accepted shape, so no `setHtml` call is required —
1066
+ * though lit-html's `html` also works, its results being structurally identical.
1067
+ *
1068
+ * HYDRATION lives in `@verajs/renderer/hydrate` — a drop-in superset entry whose `render` adopts
1069
+ * existing server-rendered children on first render. SSR apps import from there instead of here;
1070
+ * this entry carries zero hydration code.
1071
+ */
1072
+ const render = (result, container) => {
1073
+ if (true && _profileHook)
1074
+ _profileHook(PROFILE_FRAME_START, container, null);
1075
+ let part = rootParts.get(container);
1076
+ if (part === undefined) {
1077
+ const marker = comment();
1078
+ container.appendChild(marker);
1079
+ rootParts.set(container, (part = new ChildPart(marker, null)));
1080
+ }
1081
+ part._set(result);
1082
+ if (true && _profileHook)
1083
+ _profileHook(PROFILE_FRAME_END, container, null);
1084
+ };
1085
+
1086
+ const CSS = `
1087
+ :host { all: initial; }
1088
+ .panel {
1089
+ position: fixed; z-index: 2147483647;
1090
+ font: 11px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1091
+ color: #e6edf3; background: #0d1117ee; border: 1px solid #30363d; border-radius: 6px;
1092
+ box-shadow: 0 8px 24px #0008; width: 340px; max-width: calc(100vw - 24px);
1093
+ backdrop-filter: blur(6px);
1094
+ }
1095
+ .bar { display: flex; align-items: center; gap: 8px; padding: 6px 8px; cursor: default; }
1096
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: #3fb950; flex: none; }
1097
+ .dot.idle { background: #6e7681; }
1098
+ .title { font-weight: 600; letter-spacing: .02em; flex: 1; }
1099
+ button {
1100
+ font: inherit; color: #e6edf3; background: #21262d; border: 1px solid #30363d;
1101
+ border-radius: 4px; padding: 1px 7px; cursor: pointer;
1102
+ }
1103
+ button:hover { background: #30363d; }
1104
+ .body { padding: 0 8px 8px; }
1105
+ .stats { display: grid; grid-template-columns: 1fr auto; gap: 0 10px; margin-bottom: 6px; }
1106
+ .stats b { font-weight: 600; }
1107
+ .warn { color: #f0883e; }
1108
+ .good { color: #3fb950; }
1109
+ .churn { border-top: 1px solid #30363d; padding-top: 6px; }
1110
+ .churn h4 { margin: 0 0 4px; font-size: 11px; font-weight: 600; color: #f0883e; }
1111
+ .row { margin-bottom: 5px; }
1112
+ .where { color: #8b949e; }
1113
+ .tpl { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1114
+ .from { color: #ff7b72; }
1115
+ .to { color: #7ee787; }
1116
+ .hint { color: #8b949e; border-top: 1px solid #30363d; padding-top: 5px; margin-top: 2px; }
1117
+ .empty { color: #8b949e; }
1118
+ .collapsed .body { display: none; }
1119
+ `;
1120
+ const CORNERS = {
1121
+ 'top-left': 'top:12px;left:12px;',
1122
+ 'top-right': 'top:12px;right:12px;',
1123
+ 'bottom-left': 'bottom:12px;left:12px;',
1124
+ 'bottom-right': 'bottom:12px;right:12px;',
1125
+ };
1126
+ /**
1127
+ * Mounts the panel and returns a function that removes it. Requires a DOM, so it is a no-op
1128
+ * (returning a no-op) anywhere without one.
1129
+ */
1130
+ const mountOverlay = (read, isActive, control, options = {}) => {
1131
+ if (typeof document === 'undefined' || document.body === null)
1132
+ return () => { };
1133
+ const { corner = 'bottom-right', interval = 400, rows = 4 } = options;
1134
+ const host = document.createElement('div');
1135
+ /**
1136
+ * Open, not closed. Style isolation is the same either way; closed only blocks script access,
1137
+ * which for a development tool costs more than it buys — you want to inspect this in devtools,
1138
+ * and it is what makes the panel testable.
1139
+ */
1140
+ const root = host.attachShadow({ mode: 'open' });
1141
+ const style = document.createElement('style');
1142
+ style.textContent = CSS;
1143
+ const panel = document.createElement('div');
1144
+ panel.className = 'panel';
1145
+ panel.setAttribute('style', CORNERS[corner] ?? CORNERS['bottom-right']);
1146
+ panel.innerHTML =
1147
+ '<div class="bar">' +
1148
+ '<span class="dot"></span><span class="title">renderer profiler</span>' +
1149
+ '<button data-act="toggle">stop</button>' +
1150
+ '<button data-act="reset">reset</button>' +
1151
+ '<button data-act="fold">–</button>' +
1152
+ '</div>' +
1153
+ '<div class="body"><div class="stats"></div><div class="churn"></div></div>';
1154
+ root.append(style, panel);
1155
+ document.body.appendChild(host);
1156
+ const dot = panel.querySelector('.dot');
1157
+ const stats = panel.querySelector('.stats');
1158
+ const churn = panel.querySelector('.churn');
1159
+ const toggle = panel.querySelector('[data-act="toggle"]');
1160
+ const fold = panel.querySelector('[data-act="fold"]');
1161
+ const escape = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1162
+ const paint = () => {
1163
+ const report = read();
1164
+ const running = isActive();
1165
+ dot.className = running ? 'dot' : 'dot idle';
1166
+ toggle.textContent = running ? 'stop' : 'start';
1167
+ const commits = report.updates + report.creates + report.rebuilds;
1168
+ const share = commits === 0 ? 0 : Math.round((report.rebuilds / commits) * 100);
1169
+ stats.innerHTML =
1170
+ `<span>frames</span><b>${report.frames}</b>` +
1171
+ `<span>time in render</span><b>${report.ms.toFixed(1)}ms</b>` +
1172
+ `<span>slowest frame</span><b>${report.slowestFrameMs.toFixed(1)}ms</b>` +
1173
+ `<span>updated in place</span><b class="good">${report.updates}</b>` +
1174
+ `<span>created</span><b>${report.creates}</b>` +
1175
+ `<span>rebuilt</span><b class="${report.rebuilds > 0 ? 'warn' : ''}">` +
1176
+ `${report.rebuilds}${commits > 0 ? ` (${share}%)` : ''}</b>`;
1177
+ if (report.churn.length === 0) {
1178
+ churn.innerHTML =
1179
+ commits === 0
1180
+ ? '<div class="empty">No renders recorded yet.</div>'
1181
+ : '<div class="empty good">No template churn — every commit updated in place.</div>';
1182
+ return;
1183
+ }
1184
+ const shown = report.churn.slice(0, rows);
1185
+ const hidden = report.churn.length - shown.length;
1186
+ churn.innerHTML =
1187
+ '<h4>Torn down, not updated</h4>' +
1188
+ shown
1189
+ .map((entry) => `<div class="row"><div class="where">${entry.count}× at ${escape(entry.where)}</div>` +
1190
+ `<div class="tpl from">${escape(entry.from)}</div>` +
1191
+ `<div class="tpl to">→ ${escape(entry.to)}</div></div>`)
1192
+ .join('') +
1193
+ (hidden > 0 ? `<div class="where">+${hidden} more</div>` : '') +
1194
+ '<div class="hint">Prefer one stable template with <b>?hidden=${…}</b> over swapping subtrees.</div>';
1195
+ };
1196
+ panel.addEventListener('click', (event) => {
1197
+ const act = event.target?.dataset?.act;
1198
+ if (act === 'toggle') {
1199
+ if (isActive())
1200
+ control.stop();
1201
+ else
1202
+ control.start();
1203
+ }
1204
+ else if (act === 'reset')
1205
+ control.start();
1206
+ else if (act === 'fold') {
1207
+ const folded = panel.classList.toggle('collapsed');
1208
+ fold.textContent = folded ? '+' : '–';
1209
+ }
1210
+ paint();
1211
+ });
1212
+ paint();
1213
+ const timer = setInterval(paint, interval);
1214
+ return () => {
1215
+ clearInterval(timer);
1216
+ host.remove();
1217
+ };
1218
+ };
1219
+
1220
+ /**
1221
+ * `@verajs/renderer/profiler` — a development-only render profiler.
1222
+ *
1223
+ * **What it is for.** The renderer commits a template by identity: if `strings` is the same array
1224
+ * as last time, values are written in place; if it is a different array, the subtree is destroyed
1225
+ * and rebuilt. Writing `${cond ? html`<a/>` : html`<b/>`}` swaps identity on every toggle, so what
1226
+ * looks like an update is a teardown — which is why the house guidance is a stable shape with
1227
+ * `?hidden=${…}`. Nothing surfaces that today. This does: it counts in-place updates against
1228
+ * rebuilds and names the template pairs that churn.
1229
+ *
1230
+ * **How to use it.** This entry re-exports the renderer's whole public API, so point your importmap
1231
+ * (or bundler alias) at it instead of `@verajs/renderer` and nothing else changes:
1232
+ *
1233
+ * ```js
1234
+ * import { render, startProfiling, stopProfiling, formatReport } from '@verajs/renderer/profiler';
1235
+ * startProfiling();
1236
+ * // …drive the app…
1237
+ * console.log(formatReport(stopProfiling()));
1238
+ * ```
1239
+ *
1240
+ * **Development only, by construction.** The instrumentation in `renderer.ts` sits behind
1241
+ * `true`, which the build folds to `false` before terser runs — so a production renderer carries
1242
+ * no hook, no call sites and no cost, and this entry is not built for production at all. Profiling
1243
+ * minified, property-mangled output would not be meaningful anyway.
1244
+ *
1245
+ * Like `./hydrate.ts`, this bundle contains its own copy of the renderer. Import the app's renderer
1246
+ * *through* this entry; importing both side by side gives you two renderer modules with two
1247
+ * template caches, and the profiler would observe an instance nothing renders into.
1248
+ */
1249
+ let active = false;
1250
+ let frames = 0;
1251
+ let updates = 0;
1252
+ let creates = 0;
1253
+ let rebuilds = 0;
1254
+ let totalMs = 0;
1255
+ let slowestMs = 0;
1256
+ let depth = 0;
1257
+ let frameStart = 0;
1258
+ let churn = new Map();
1259
+ /** Stable ids for template identities, so grouping a rebuild costs two lookups and a concat. */
1260
+ let nextId = 1;
1261
+ const ids = new WeakMap();
1262
+ const idOf = (strings) => {
1263
+ let id = ids.get(strings);
1264
+ if (id === undefined)
1265
+ ids.set(strings, (id = nextId++));
1266
+ return id;
1267
+ };
1268
+ /** Readable one-line form of a template, cached — a rebuild loop would otherwise rebuild it too. */
1269
+ const described = new WeakMap();
1270
+ const describe = (strings) => {
1271
+ let text = described.get(strings);
1272
+ if (text === undefined) {
1273
+ text = strings.join('${…}').replace(/\s+/g, ' ').trim();
1274
+ if (text.length > 72)
1275
+ text = text.slice(0, 71) + '…';
1276
+ described.set(strings, text);
1277
+ }
1278
+ return text;
1279
+ };
1280
+ /**
1281
+ * `parentElement` is null across a shadow boundary, which is exactly where components live — so
1282
+ * step to the host rather than reporting `(detached)` for every shadow root.
1283
+ */
1284
+ const up = (node) => {
1285
+ const parent = node.parentElement;
1286
+ if (parent !== null)
1287
+ return parent;
1288
+ const root = node.getRootNode();
1289
+ return root !== node && root.host !== undefined ? root.host : null;
1290
+ };
1291
+ /** Three levels of ancestry is enough to locate a slot without printing a whole path. */
1292
+ const label = (node) => {
1293
+ const path = [];
1294
+ let el = node === null ? null : node.nodeType === 1 ? node : up(node);
1295
+ for (let i = 0; i < 3 && el !== null; i++) {
1296
+ let part = el.localName;
1297
+ if (el.id)
1298
+ part += '#' + el.id;
1299
+ else {
1300
+ const cls = el.getAttribute('class');
1301
+ if (cls)
1302
+ part += '.' + cls.trim().split(/\s+/)[0];
1303
+ }
1304
+ path.unshift(part);
1305
+ el = up(el);
1306
+ }
1307
+ return path.length === 0 ? '(detached)' : path.join(' > ');
1308
+ };
1309
+ const hook = (kind, subject, shape) => {
1310
+ if (kind === PROFILE_UPDATE) {
1311
+ updates++;
1312
+ return;
1313
+ }
1314
+ if (kind === PROFILE_FRAME_START) {
1315
+ if (depth++ === 0)
1316
+ frameStart = performance.now();
1317
+ return;
1318
+ }
1319
+ if (kind === PROFILE_FRAME_END) {
1320
+ if (--depth === 0) {
1321
+ const elapsed = performance.now() - frameStart;
1322
+ totalMs += elapsed;
1323
+ if (elapsed > slowestMs)
1324
+ slowestMs = elapsed;
1325
+ frames++;
1326
+ }
1327
+ return;
1328
+ }
1329
+ if (kind === PROFILE_CREATE) {
1330
+ creates++;
1331
+ return;
1332
+ }
1333
+ if (kind !== PROFILE_REBUILD)
1334
+ return;
1335
+ rebuilds++;
1336
+ const part = subject;
1337
+ const from = part._shape;
1338
+ if (from === null || shape === null)
1339
+ return;
1340
+ const key = idOf(from) + '>' + idOf(shape);
1341
+ let record = churn.get(key);
1342
+ if (record === undefined) {
1343
+ churn.set(key, (record = { from: describe(from), to: describe(shape), count: 0, where: label(part._start) }));
1344
+ }
1345
+ record.count++;
1346
+ };
1347
+ const reset = () => {
1348
+ frames = updates = creates = rebuilds = depth = 0;
1349
+ totalMs = slowestMs = frameStart = 0;
1350
+ churn = new Map();
1351
+ };
1352
+ /** Begin collecting. Calling this while already profiling restarts the collection. */
1353
+ const startProfiling = () => {
1354
+ reset();
1355
+ active = true;
1356
+ _setProfileHook(hook);
1357
+ };
1358
+ /** What has been measured so far, without ending the session. Drives the live overlay. */
1359
+ const getReport = () => ({
1360
+ frames,
1361
+ ms: totalMs,
1362
+ slowestFrameMs: slowestMs,
1363
+ updates,
1364
+ creates,
1365
+ rebuilds,
1366
+ churn: [...churn.values()].sort((a, b) => b.count - a.count),
1367
+ });
1368
+ /** Stop collecting and return what was measured. Safe to call when not profiling. */
1369
+ const stopProfiling = () => {
1370
+ _setProfileHook(null);
1371
+ active = false;
1372
+ return getReport();
1373
+ };
1374
+ const isProfiling = () => active;
1375
+ /** Profile one synchronous stretch of work. */
1376
+ const profile = (fn) => {
1377
+ startProfiling();
1378
+ try {
1379
+ return { result: fn(), report: stopProfiling() };
1380
+ }
1381
+ catch (error) {
1382
+ stopProfiling();
1383
+ throw error;
1384
+ }
1385
+ };
1386
+ /**
1387
+ * Mounts a live panel in the corner of the page and starts profiling. Returns a function that
1388
+ * removes it and stops. Plain DOM in a closed shadow root — it never renders itself through the
1389
+ * renderer, which would fold its own commits into the numbers it reports.
1390
+ */
1391
+ const showProfiler = (options) => {
1392
+ startProfiling();
1393
+ const unmount = mountOverlay(getReport, isProfiling, { start: startProfiling, stop: stopProfiling }, options);
1394
+ return () => {
1395
+ unmount();
1396
+ stopProfiling();
1397
+ };
1398
+ };
1399
+ /** Human-readable summary. The overlay renders the same data; this is for a console or a log. */
1400
+ const formatReport = (report) => {
1401
+ const committed = report.updates + report.creates + report.rebuilds;
1402
+ const share = committed === 0 ? 0 : Math.round((report.rebuilds / committed) * 100);
1403
+ const lines = [
1404
+ `${report.frames} frame(s), ${report.ms.toFixed(1)}ms total, slowest ${report.slowestFrameMs.toFixed(1)}ms`,
1405
+ `${report.updates} updated in place, ${report.creates} created, ${report.rebuilds} rebuilt (${share}% of commits)`,
1406
+ ];
1407
+ if (report.churn.length > 0) {
1408
+ lines.push('', 'Template identity churn — these were torn down, not updated:');
1409
+ for (const entry of report.churn) {
1410
+ lines.push(` ${entry.count}x at ${entry.where}`, ` ${entry.from}`, ` -> ${entry.to}`);
1411
+ }
1412
+ lines.push('', 'Prefer one stable template with ?hidden=${…} over swapping subtrees.');
1413
+ }
1414
+ return lines.join('\n');
1415
+ };
1416
+
1417
+ export { formatReport, getReport, hold, isProfiling, keyed, profile, render, showProfiler, startProfiling, stopProfiling };
1418
+ //# sourceMappingURL=vera-renderer-profiler.js.map