@verajs/renderer 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +729 -226
  2. package/dist/development/vera-renderer-elements.d.ts +39 -0
  3. package/dist/development/vera-renderer-elements.d.ts.map +1 -0
  4. package/dist/development/vera-renderer-elements.js +193 -0
  5. package/dist/development/vera-renderer-elements.js.map +1 -0
  6. package/dist/development/vera-renderer-hydrate-slots.d.ts +94 -0
  7. package/dist/development/vera-renderer-hydrate-slots.d.ts.map +1 -0
  8. package/dist/development/vera-renderer-hydrate-slots.js +325 -0
  9. package/dist/development/vera-renderer-hydrate-slots.js.map +1 -0
  10. package/dist/development/vera-renderer-hydration.d.ts +332 -0
  11. package/dist/development/vera-renderer-hydration.d.ts.map +1 -0
  12. package/dist/development/vera-renderer-hydration.js +864 -0
  13. package/dist/development/vera-renderer-hydration.js.map +1 -0
  14. package/dist/development/vera-renderer-keyed.d.ts +25 -8
  15. package/dist/development/vera-renderer-keyed.d.ts.map +1 -1
  16. package/dist/development/vera-renderer-keyed.js +843 -268
  17. package/dist/development/vera-renderer-keyed.js.map +1 -1
  18. package/dist/development/vera-renderer-multi-window.d.ts +5 -0
  19. package/dist/development/vera-renderer-multi-window.d.ts.map +1 -0
  20. package/dist/development/vera-renderer-multi-window.js +40 -0
  21. package/dist/development/vera-renderer-multi-window.js.map +1 -0
  22. package/dist/development/vera-renderer-namespaces.d.ts +64 -0
  23. package/dist/development/vera-renderer-namespaces.d.ts.map +1 -0
  24. package/dist/development/vera-renderer-namespaces.js +94 -0
  25. package/dist/development/vera-renderer-namespaces.js.map +1 -0
  26. package/dist/development/vera-renderer-native-elements.d.ts +13 -0
  27. package/dist/development/vera-renderer-native-elements.d.ts.map +1 -0
  28. package/dist/development/vera-renderer-native-elements.js +231 -0
  29. package/dist/development/vera-renderer-native-elements.js.map +1 -0
  30. package/dist/development/vera-renderer-portal.d.ts +29 -0
  31. package/dist/development/vera-renderer-portal.d.ts.map +1 -0
  32. package/dist/development/vera-renderer-portal.js +167 -0
  33. package/dist/development/vera-renderer-portal.js.map +1 -0
  34. package/dist/development/vera-renderer-profiler.d.ts +113 -138
  35. package/dist/development/vera-renderer-profiler.d.ts.map +1 -1
  36. package/dist/development/vera-renderer-profiler.js +2428 -2101
  37. package/dist/development/vera-renderer-profiler.js.map +1 -1
  38. package/dist/development/vera-renderer-slots.d.ts +88 -92
  39. package/dist/development/vera-renderer-slots.d.ts.map +1 -1
  40. package/dist/development/vera-renderer-slots.js +1834 -1237
  41. package/dist/development/vera-renderer-slots.js.map +1 -1
  42. package/dist/development/vera-renderer-spread.d.ts +8 -29
  43. package/dist/development/vera-renderer-spread.d.ts.map +1 -1
  44. package/dist/development/vera-renderer-spread.js +542 -461
  45. package/dist/development/vera-renderer-spread.js.map +1 -1
  46. package/dist/development/vera-renderer-tag.d.ts +12 -3
  47. package/dist/development/vera-renderer-tag.d.ts.map +1 -1
  48. package/dist/development/vera-renderer-tag.js +671 -494
  49. package/dist/development/vera-renderer-tag.js.map +1 -1
  50. package/dist/development/vera-renderer-until.d.ts +24 -0
  51. package/dist/development/vera-renderer-until.d.ts.map +1 -0
  52. package/dist/development/vera-renderer-until.js +83 -0
  53. package/dist/development/vera-renderer-until.js.map +1 -0
  54. package/dist/development/vera-renderer.d.ts +77 -96
  55. package/dist/development/vera-renderer.d.ts.map +1 -1
  56. package/dist/development/vera-renderer.js +2401 -2061
  57. package/dist/development/vera-renderer.js.map +1 -1
  58. package/dist/vera-renderer-elements.min.js +2 -0
  59. package/dist/vera-renderer-elements.min.js.map +1 -0
  60. package/dist/vera-renderer-hydrate-slots.min.js +2 -0
  61. package/dist/vera-renderer-hydrate-slots.min.js.map +1 -0
  62. package/dist/vera-renderer-hydration.min.js +3 -0
  63. package/dist/vera-renderer-hydration.min.js.map +1 -0
  64. package/dist/vera-renderer-keyed.min.js +1 -1
  65. package/dist/vera-renderer-keyed.min.js.map +1 -1
  66. package/dist/vera-renderer-multi-window.min.js +2 -0
  67. package/dist/vera-renderer-multi-window.min.js.map +1 -0
  68. package/dist/vera-renderer-namespaces.min.js +2 -0
  69. package/dist/vera-renderer-namespaces.min.js.map +1 -0
  70. package/dist/vera-renderer-native-elements.min.js +2 -0
  71. package/dist/vera-renderer-native-elements.min.js.map +1 -0
  72. package/dist/vera-renderer-portal.min.js +2 -0
  73. package/dist/vera-renderer-portal.min.js.map +1 -0
  74. package/dist/vera-renderer-slots.min.js +1 -1
  75. package/dist/vera-renderer-slots.min.js.map +1 -1
  76. package/dist/vera-renderer-spread.min.js +1 -1
  77. package/dist/vera-renderer-spread.min.js.map +1 -1
  78. package/dist/vera-renderer-tag.min.js +1 -1
  79. package/dist/vera-renderer-tag.min.js.map +1 -1
  80. package/dist/vera-renderer-until.min.js +2 -0
  81. package/dist/vera-renderer-until.min.js.map +1 -0
  82. package/dist/vera-renderer.min.js +1 -1
  83. package/dist/vera-renderer.min.js.map +1 -1
  84. package/package.json +52 -9
  85. package/dist/development/vera-renderer-hydrate.d.ts +0 -118
  86. package/dist/development/vera-renderer-hydrate.d.ts.map +0 -1
  87. package/dist/development/vera-renderer-hydrate.js +0 -3092
  88. package/dist/development/vera-renderer-hydrate.js.map +0 -1
  89. package/dist/vera-renderer-hydrate.min.js +0 -2
  90. package/dist/vera-renderer-hydrate.min.js.map +0 -1
@@ -1,322 +1,897 @@
1
1
  /**
2
- * Keyed list reconciliation, as its own entry.
3
- *
4
- * **This module imports nothing.** Every other renderer entry inlines `./renderer.js` and carries
5
- * its own template cache, so a module that imported one of them would be wrong for the others —
6
- * `hydrate` in particular. Like `spread`, this one talks to whatever renderer is present through a
7
- * mangling-exempt protocol, which is what makes it additive rather than a substitute.
8
- *
9
- * It also does not register. `keyed()` stamps `$r` onto the result it marks, so the algorithm
10
- * travels with the values that need it: importing the marker is the whole installation, and a list
11
- * always names the strategy that understands it. Two strategies therefore cannot disagree — there
12
- * is nothing to disagree about, because the decision is per value rather than per registry.
2
+ * **Where every diagnostic code is explained.** The URL is permanent: a released bundle is immutable, so every version
3
+ * published points here for ever — the domain cannot lapse and `/e/` cannot be reorganized without breaking links in
4
+ * code nobody can edit; the docs site redirects instead. `scripts/sync-diagnostics.mjs` imports this constant, so the
5
+ * pages and the bundles can never disagree about where they are.
13
6
  */
7
+ const DOCS = 'https://verajs.dev/e/';
14
8
  /**
15
- * The standard head/tail algorithm (as in lit's `repeat` and Vue): skip matching prefixes and
16
- * suffixes, detect the two swap shapes directly, and fall back to key maps for arbitrary moves,
17
- * removals and insertions.
18
- *
19
- * Everything before reconciliation — the mode switch, the empty list, the initial fill — has
20
- * already happened in the renderer and is passed in, so this function only ever runs against a
21
- * non-empty list that is already keyed.
9
+ * **What this copy of the framework has already said** (Brian's ruling, 2026-11-12): the ONE memory behind `warnOnce`, `errorOnce`
10
+ * and `hasWarned`, for DEVELOPMENT-ONLY warnings. It replaced the hand-written once-flags every package kept
11
+ * (`saidLists`, `warnedDrop`, per-element WeakSets, per-key Sets: two naming styles, Brian: no names). **A warning that
12
+ * ships to production keeps its memory at its site** (bytes, measured 2026-11-12: the shared memory costs +80–145 B gz
13
+ * per bundle); development-only warnings use warnOnce. Module state by necessity, since "once" spans every call on the
14
+ * page. One per BUNDLE COPY, exactly the scope each flag had, because this package is inlined into every bundle.
15
+ * A code, or `code key` for a string key, in a Set. An object key (an element, a setup function) in a WeakMap, so its
16
+ * entry goes with the object. Marked pure, so a bundle that never prints once drops both.
22
17
  */
18
+ const printed = /* @__PURE__ */ new Set();
19
+ const printedOn = /* @__PURE__ */ new WeakMap();
20
+ /** Where an object key's (code, value) lives: the value set for that code on that object, made on demand. */
21
+ const valuesOn = (on, code, make) => {
22
+ let codes = printedOn.get(on);
23
+ if (codes === undefined) {
24
+ printedOn.set(on, (codes = new Map()));
25
+ }
26
+ let values = codes.get(code);
27
+ if (values === undefined && make)
28
+ codes.set(code, (values = new Set()));
29
+ return values;
30
+ };
31
+ /** The object and value of an object or pair key. */
32
+ const split = (key) => (Array.isArray(key) ? key : [key, undefined]);
33
+ /** Whether (code, key) is new, recording it if so. */
34
+ const firstTime = (code, key) => {
35
+ if (key === undefined || typeof key === 'string') {
36
+ const entry = key === undefined ? code : `${code} ${key}`;
37
+ if (printed.has(entry))
38
+ return false;
39
+ printed.add(entry);
40
+ return true;
41
+ }
42
+ const [on, sub] = split(key);
43
+ const values = valuesOn(on, code, true);
44
+ if (values.has(sub))
45
+ return false;
46
+ values.add(sub);
47
+ return true;
48
+ };
23
49
  /**
24
- * **Reconciliation for a list whose nodes no longer live where its markers do.**
50
+ * **One shape for every diagnostic the framework prints** — the short line production keeps, the whole sentence
51
+ * development adds — so a package converting its messages writes a table and a call, never its own format.
25
52
  *
26
- * `@verajs/renderer/slots` distributes a light-DOM host's children by MOVING them into the
27
- * component's tree. A keyed list that renders those children therefore ends up split: the items are
28
- * inside the component, the part's own markers stay behind in the host. The two-ended diff below
29
- * positions against those markers and against `end`, so every move it makes asks the host to insert
30
- * before a reference that is somewhere else — `NotFoundError`, in both builds. Shadow DOM never hits
31
- * this because the platform PROJECTS rather than moves: the nodes stay children of the host.
53
+ * production `[vera] hydration: element: found <i> — https://verajs.dev/e/hydration-fallback`
54
+ * development `[vera] hydration: element: found <i> — fell back to a client render: … (hydration-fallback)`
32
55
  *
33
- * The way out is to stop looking for an anchor. Walking the new order in REVERSE, each item is
34
- * placed immediately before its successor **in its own container**, and the last item in each
35
- * container is left exactly where it is. That needs no end marker, no part boundary, and no
36
- * knowledge of slots — and it is what makes a list SPLIT ACROSS SLOTS come out right for free,
37
- * since items in different containers simply have different successors. Native does the same thing
38
- * for the same input: order within each slot follows the logical order.
56
+ * `subject` is the free information — what the code already has at hand, naming the problem area — the same in both
57
+ * builds. `prose` is development only: the package's table entry (`Prose`), called behind `true ` at the call site so
58
+ * the table goes unreferenced in production and rollup drops it whole. Production prints the code inside the link, so
59
+ * the reader is one click from the explanation, which `scripts/sync-diagnostics.mjs` publishes from the same tables.
39
60
  *
40
- * Items created here go into the host, not into a container, because distribution is the observer's
41
- * job and has not run yet. They are skipped by the placement pass for that render and land in slot
42
- * order when it does.
61
+ * **Every production message is coded** (Brian, 2026-11-11; this supersedes "convert where smaller", 2026-10-02):
62
+ * consistency over a few bytes, so no package keeps a hand-written production line beside its table.
43
63
  */
44
- const reconcileRelocated = (part, newValues, items, parent, end) => {
45
- const count = newValues.length;
46
- const byKey = new Map();
47
- for (const item of items)
48
- if (item !== null)
49
- byKey.set(item.$k, item);
50
- const newItems = new Array(count);
51
- for (let i = 0; i < count; i++) {
52
- const existing = byKey.get(newValues[i].key);
53
- if (existing !== undefined) {
54
- part.$u(existing, newValues[i]);
55
- newItems[i] = existing;
56
- byKey.delete(newValues[i].key);
57
- }
58
- }
59
- /** Whatever kept no key is gone. `$d` moves into a scratch fragment, so its parent is irrelevant. */
60
- for (const dropped of byKey.values())
61
- part.$d(dropped);
64
+ /*
65
+ * The parameter names are deliberately unlike anything a caller holds: terser will not inline a function whose
66
+ * parameter shadows a name at the call site (measured 2026-10-02 — directives passes its own `code`, and a parameter
67
+ * called `code` left `((e,t,n)=>`…`)(0,t,n)` in its bundle, +8 B; renamed, the call folds to the bare template).
68
+ */
69
+ /**
70
+ * **A misused API, named by its function** — the thrown-error twin of `diagnostic()`: `untrack: expected a function …
71
+ * (untrack-not-function)`, function-first because a stack already names the source and the sweep reads that shape. The
72
+ * prose comes from a package's table, behind `true `, so a development-only guard costs production nothing.
73
+ */
74
+ const misuse = (forName, withCode, andProse) => true && andProse
75
+ ? `${forName}: ${andProse[0]}${andProse[1] ? ` ${andProse[1]}` : ''} (${withCode})`
76
+ : `${forName}: ${DOCS}${withCode}`;
77
+ const diagnostic = (inArea, bySubject, withCode, andProse) =>
78
+ /** `true ` HERE as well as at the call: production folds this to the one-line form, branch and all. */
79
+ true && andProse
80
+ ? `[vera] ${inArea}: ${bySubject} — ${andProse[0]}${andProse[1] ? ` ${andProse[1]}` : ''} (${withCode})`
81
+ : `[vera] ${inArea}: ${bySubject} — ${DOCS}${withCode}`;
82
+ /**
83
+ * The printer behind both, on one level. `andDetail` is `diagnostic()`'s prose, or a function returning it where building
84
+ * the sentence costs something: it is called only the first time. `...andMore` rides beside the line behind '%s' (an
85
+ * element, a thrown error), never inside it, so text from outside cannot forge a line. The console method is read at the
86
+ * call, so a test that replaces `console.warn` sees it.
87
+ */
88
+ const sayOnce = (level) => (inArea, bySubject, withCode, andDetail, forKey, ...andMore) => {
89
+ if (!firstTime(withCode, forKey))
90
+ return;
91
+ const line = diagnostic(inArea, bySubject, withCode, typeof andDetail === 'function' ? andDetail() : andDetail);
92
+ if (andMore.length)
93
+ console[level]('%s', line, ...andMore);
94
+ else
95
+ console[level](line);
96
+ };
97
+ /**
98
+ * **A diagnostic said once per page** (per key, where one is given: a string, or an object such as the element it is
99
+ * about): `diagnostic()`'s arguments, then the key, then what rides beside the line. Coded in production exactly as
100
+ * `diagnostic()` is, because it IS `diagnostic()`. `errorOnce` is its twin on `console.error`, for a refusal a page should
101
+ * not miss.
102
+ */
103
+ const warnOnce = /* @__PURE__ */ sayOnce('warn');
104
+
105
+ const PROSE = {
106
+ 'keyed-duplicate-key': (key) => [
107
+ `the key ${key} is used by more than one item in this list. A key identifies one item, so which of them keeps the existing DOM is not defined — the list still renders, but nothing about which node ends up where can be relied on.`,
108
+ 'Give every item a key of its own — an id, not an index or a value two items share.',
109
+ ],
110
+ 'selector-not-wired': () => [
111
+ 'createSelector needs the keyed module wired, and it was not.',
112
+ 'Wire it once at your entry — `wire([renderer, lists])` — before a component creates a selector.',
113
+ ],
114
+ 'keyed-not-template': (received) => [
115
+ `expected a template as the second argument and received ${received}.`,
116
+ 'It marks a template with a key — `keyed(row.id, html`<li>…</li>`)`.',
117
+ ],
118
+ };
119
+
120
+ const reconcile = (part, values, items, parent, end) => {
121
+ const count = values.length;
122
+ /** A `null` item is unkeyed, as the renderer's `$c` already treats it — never a throw on the second render. */
123
+ const key = (i) => values[i]?.key;
124
+ let start = 0;
125
+ let oldEnd = items.length - 1;
126
+ let newEnd = count - 1;
62
127
  /**
63
- * **One reverse pass that both places and creates**, so an item's successor is already final when
64
- * it is needed — and it is needed twice. Placing reads it as the reference; CREATING reads the
65
- * container it lives in, which is the only way a new item can land among its logical neighbours.
66
- *
67
- * Creating in the host instead would be simpler and is wrong: the observer distributes it later
68
- * and appends it, so an insertion in the middle of a list arrives at the end. Creating it in the
69
- * successor's container puts it where native would — and if it names a DIFFERENT slot than its
70
- * neighbour, it is in the host's subtree with a `slot` attribute, which is exactly what the
71
- * observer is watching for, so that case corrects itself.
72
- *
73
- * `$m` short-circuits an item already in position, which is what keeps this from re-attaching a
74
- * whole list; re-attaching is not free, it blurs focus and restarts transitions.
128
+ * The unchanged run at each end, matched without allocating. When what remains between them is only
129
+ * removals (a row deleted) or only insertions (rows appended, prepended, inserted), it is settled here;
130
+ * a same-order update is the case where nothing remains at all.
75
131
  */
76
- const successorIn = new Map();
77
- for (let i = count - 1; i >= 0; i--) {
78
- const item = newItems[i];
79
- if (item === undefined)
80
- continue; // created below, in forward order, once neighbours are final
81
- const container = part.$f(item).parentNode;
82
- if (container === null)
83
- continue;
84
- const successor = successorIn.get(container);
85
- if (successor !== undefined)
86
- part.$m(item, successor, container);
87
- successorIn.set(container, part.$f(item));
132
+ /** A row whose value is the result committed last time (a list row that did not re-render) is not even asked. */
133
+ while (start <= oldEnd && start <= newEnd && items[start].$k === key(start)) {
134
+ const value = values[start];
135
+ if (value === undefined || value !== items[start].$j)
136
+ items[start] = part.$u(items[start], value);
137
+ start++;
88
138
  }
89
- /**
90
- * **Creations run FORWARD, after every surviving item is in its final place.** Two reasons.
91
- * A new item belongs beside its logical successor, and the successor's position is only final
92
- * once the reverse pass above has run. And consecutive new rows must land in logical order:
93
- * created back-to-front they arrive in the host reversed, the observer captures them in
94
- * arrival order, and the list renders permuted.
95
- *
96
- * Created under the HOST, before `end` — the part's own boundary. Created straight into the
97
- * component's tree they would read as the component's own output and never be captured;
98
- * appended to the host's tail they would sit in the component's region, which is the same
99
- * mistake. Between the part's markers they are unambiguously the host's content, which the
100
- * observer captures with native semantics. A new item whose logical successor lives inside
101
- * the component is then moved beside it — a move, which the observer already reads correctly.
102
- */
103
- for (let i = 0; i < count; i++) {
104
- if (newItems[i] !== undefined)
105
- continue;
106
- const created = part.$c(newValues[i], parent, end);
107
- const following = i + 1 < count ? newItems[i + 1] : undefined;
108
- if (following !== undefined) {
109
- const first = part.$f(following);
110
- if (first.parentNode !== null && first.parentNode !== parent)
111
- part.$m(created, first, first.parentNode);
112
- }
113
- newItems[i] = created;
139
+ while (start <= oldEnd && start <= newEnd && items[oldEnd].$k === key(newEnd)) {
140
+ const value = values[newEnd];
141
+ if (value === undefined || value !== items[oldEnd].$j)
142
+ items[oldEnd] = part.$u(items[oldEnd], value);
143
+ oldEnd--;
144
+ newEnd--;
114
145
  }
115
- return newItems;
116
- };
117
- const reconcile = (part, newValues, items, parent, end) => {
118
- const count = newValues.length;
119
146
  /**
120
- * Zero-allocation fast path for the dominant case: same length, same key order — a pure in-place
121
- * update (a selection change, a field edit). No key array, no output array, no null checks. Falls
122
- * through to the full algorithm on the first mismatch; the items already updated re-verify there
123
- * as cheap no-op compares.
147
+ * A repeated key, said where it can have arisen: only when the new list has items between the end scans (inserted
148
+ * or moved) — a same-order update and a pure removal cannot create one, and never pay for the check. It behaves
149
+ * correctly in the common case and arbitrarily in the rest — the shape of bug that survives a test suite.
150
+ * Development only; the keys are gathered only here.
124
151
  */
125
- if (items.length === count) {
126
- let i = 0;
127
- while (i < count && items[i].$k === newValues[i].key) {
128
- part.$u(items[i], newValues[i]);
129
- i++;
152
+ if (true && start <= newEnd) {
153
+ const seen = new Set();
154
+ for (let i = 0; i < count; i++) {
155
+ const k = key(i);
156
+ if (seen.has(k)) {
157
+ /** Once per (list, key): the same duplicate on every reconcile is noise; a NEW duplicate key is news. */
158
+ warnOnce('keyed', 'a keyed list', 'keyed-duplicate-key', true && (() => PROSE['keyed-duplicate-key'](String(k))), [part, k]);
159
+ break;
160
+ }
161
+ seen.add(k);
130
162
  }
131
- if (i === count)
132
- return items;
163
+ }
164
+ if (start > newEnd) {
165
+ for (let i = start; i <= oldEnd; i++)
166
+ part.$d(items[i]);
167
+ items.splice(start, oldEnd - start + 1);
168
+ return items;
169
+ }
170
+ /** Joined with `concat`, never spread into `splice`: an engine caps a call's arguments (JavaScriptCore at 65 536). */
171
+ const ref = start < items.length ? part.$f(items[start]) : end;
172
+ const added = [];
173
+ if (start > oldEnd) {
174
+ for (let i = start; i <= newEnd; i++)
175
+ added.push(part.$c(values[i], parent, ref));
176
+ return items.slice(0, start).concat(added, items.slice(start));
133
177
  }
134
178
  /**
135
- * **Has anything moved this list's nodes out from under its markers?**
136
- *
137
- * Only `@verajs/renderer/slots` does today, but the question is asked of the DOM rather than of
138
- * that module — keyed imports nothing, and a list does not need to know what moved its nodes to
139
- * know that they moved.
140
- *
141
- * Placed after the no-change fast path, so the dominant case (same keys, same order) never
142
- * reaches it. What remains is one `parentNode` read per item against a diff that already does far
143
- * more per item, and it breaks on the first mismatch, so the case it exists for costs exactly one.
144
- */
145
- for (let i = 0; i < items.length; i++)
146
- if (part.$f(items[i]).parentNode !== parent)
147
- return reconcileRelocated(part, newValues, items, parent, end);
148
- const oldItems = items;
149
- const newKeys = new Array(count);
150
- for (let i = 0; i < count; i++)
151
- newKeys[i] = newValues[i].key;
152
- /**
153
- * Said once, where it is nearly free: the general algorithm already walks every key, and a list
154
- * whose keys never move never reaches here at all. A duplicate key is a mistake that behaves
155
- * *correctly* in the common case and arbitrarily in the rest, which is the shape of bug that
156
- * survives a test suite.
179
+ * A genuine reorder: two-ended from where the scans stopped, with a key map of the old middle built only
180
+ * when both ends miss. An old item the new list no longer holds stays until the final sweep removes it.
157
181
  */
158
- if (true && new Set(newKeys).size !== count) {
159
- const seen = new Set();
160
- const repeated = newKeys.filter((key) => (seen.has(key) ? true : (seen.add(key), false)));
161
- console.warn(`[vera] keyed: the key ${String(repeated[0])} is used by more than one item in this list. ` +
162
- `A key identifies one item, so which of them keeps the existing DOM is not defined — ` +
163
- `the list still renders, but nothing about which node ends up where can be relied on.`);
164
- }
165
- const newItems = new Array(count);
166
- let oldHead = 0;
167
- let oldTail = oldItems.length - 1;
168
- let newHead = 0;
169
- let newTail = count - 1;
170
- let newKeyToIndex;
171
- let oldKeyToIndex;
172
- const refAt = (i) => i < count && newItems[i] !== undefined ? part.$f(newItems[i]) : end;
173
- while (oldHead <= oldTail && newHead <= newTail) {
174
- if (oldItems[oldHead] === null)
182
+ const old = items;
183
+ const next = items.slice(0, start).concat(new Array(newEnd - start + 1), items.slice(oldEnd + 1));
184
+ const before = (i) => (i < count ? part.$f(next[i]) : end);
185
+ let map;
186
+ /** The new middle's keys, built with `map`: what tells a removed old end from a moved one. */
187
+ let fresh;
188
+ let oldHead = start;
189
+ let newHead = start;
190
+ while (oldHead <= oldEnd && newHead <= newEnd) {
191
+ const head = old[oldHead];
192
+ const tail = old[oldEnd];
193
+ if (head === null)
175
194
  oldHead++;
176
- else if (oldItems[oldTail] === null)
177
- oldTail--;
178
- else if (oldItems[oldHead].$k === newKeys[newHead]) {
179
- part.$u((newItems[newHead] = oldItems[oldHead]), newValues[newHead]);
195
+ else if (tail === null)
196
+ oldEnd--;
197
+ else if (head.$k === key(newHead)) {
198
+ next[newHead] = part.$u(head, values[newHead]);
180
199
  oldHead++;
181
200
  newHead++;
182
201
  }
183
- else if (oldItems[oldTail].$k === newKeys[newTail]) {
184
- part.$u((newItems[newTail] = oldItems[oldTail]), newValues[newTail]);
185
- oldTail--;
186
- newTail--;
202
+ else if (tail.$k === key(newEnd)) {
203
+ next[newEnd] = part.$u(tail, values[newEnd]);
204
+ oldEnd--;
205
+ newEnd--;
187
206
  }
188
- else if (oldItems[oldHead].$k === newKeys[newTail]) {
189
- const item = oldItems[oldHead];
190
- part.$m(item, refAt(newTail + 1), parent);
191
- part.$u(item, newValues[newTail]);
192
- newItems[newTail] = item;
207
+ else if (head.$k === key(newEnd)) {
208
+ part.$m(head, before(newEnd + 1), parent);
209
+ next[newEnd] = part.$u(head, values[newEnd]);
193
210
  oldHead++;
194
- newTail--;
211
+ newEnd--;
195
212
  }
196
- else if (oldItems[oldTail].$k === newKeys[newHead]) {
197
- const item = oldItems[oldTail];
198
- part.$m(item, part.$f(oldItems[oldHead]), parent);
199
- part.$u(item, newValues[newHead]);
200
- newItems[newHead] = item;
201
- oldTail--;
213
+ else if (tail.$k === key(newHead)) {
214
+ part.$m(tail, part.$f(head), parent);
215
+ next[newHead] = part.$u(tail, values[newHead]);
216
+ oldEnd--;
202
217
  newHead++;
203
218
  }
204
219
  else {
205
- if (newKeyToIndex === undefined) {
206
- newKeyToIndex = new Map();
207
- for (let i = newHead; i <= newTail; i++)
208
- newKeyToIndex.set(newKeys[i], i);
209
- oldKeyToIndex = new Map();
210
- for (let i = oldHead; i <= oldTail; i++) {
211
- if (oldItems[i] !== null)
212
- oldKeyToIndex.set(oldItems[i].$k, i);
213
- }
220
+ if (map === undefined) {
221
+ map = new Map();
222
+ for (let i = oldHead; i <= oldEnd; i++)
223
+ if (old[i] !== null)
224
+ map.set(old[i].$k, i);
225
+ fresh = new Set();
226
+ for (let i = newHead; i <= newEnd; i++)
227
+ fresh.add(key(i));
214
228
  }
215
- if (!newKeyToIndex.has(oldItems[oldHead].$k)) {
216
- part.$d(oldItems[oldHead]);
217
- oldHead++;
229
+ /**
230
+ * **An old end the new list no longer holds is REMOVED, not worked around** (2026-10-20): a push and a middle
231
+ * splice in one flush left no unchanged run at either end, and the walk moved every row past the removed one —
232
+ * 999 `insertBefore` on 1000 rows, where 2 DOM operations are right (`auto-moves.mjs`).
233
+ */
234
+ if (!fresh.has(head.$k)) {
235
+ part.$d(head);
236
+ old[oldHead++] = null;
237
+ continue;
218
238
  }
219
- else if (!newKeyToIndex.has(oldItems[oldTail].$k)) {
220
- part.$d(oldItems[oldTail]);
221
- oldTail--;
239
+ if (!fresh.has(tail.$k)) {
240
+ part.$d(tail);
241
+ old[oldEnd--] = null;
242
+ continue;
222
243
  }
244
+ /**
245
+ * A slot the map points at may already be spoken for when a key repeats: nulled by an earlier reuse,
246
+ * or consumed by the two-ended branches (which move pointers without nulling). Either is treated as
247
+ * "not found" and gets a fresh item — duplicate keys are undefined behavior, but undefined must still
248
+ * mean a list, never a throw or a row rendered twice.
249
+ */
250
+ const at = map.get(key(newHead));
251
+ const reusable = at === undefined || at < oldHead || at > oldEnd ? null : old[at];
252
+ if (reusable === null)
253
+ next[newHead] = part.$c(values[newHead], parent, part.$f(head));
223
254
  else {
224
- const oldIndex = oldKeyToIndex.get(newKeys[newHead]);
225
- /**
226
- * **`oldItems[oldIndex]` can be null, and reading it crashed the render.** The map holds one
227
- * index per key, so a list where a key appears twice finds, for the second one, the slot the
228
- * first already consumed and nulled. `part.$m(null, …)` then read `_element` of null and took
229
- * the whole render down with a `TypeError` naming the renderer's internals rather than
230
- * anything the caller wrote.
231
- *
232
- * Duplicate keys are documented as undefined behaviour and stay that way — which of the two
233
- * keeps the existing node is not specified. Undefined must still mean *a list*, though, not
234
- * an exception from three frames inside a private algorithm: the shapes that crash are
235
- * particular (a duplicate **and** a reorder **and** a new key, found by fuzzing over a
236
- * four-key alphabet), so this passes in development and takes the page down later.
237
- *
238
- * Two ways a slot can already be spoken for, and both have to be checked. The map nulls what
239
- * it consumes, so `oldItems[oldIndex] === null` catches one. The other is invisible: the map
240
- * is built once, and the head/tail branches above consume items by *moving the pointers*
241
- * without nulling anything — so an index that was live when the map was built can now sit
242
- * outside `[oldHead, oldTail]`. With unique keys that is unreachable, because a key is looked
243
- * up at most once; with a repeated key it hands the same item to two positions, and the list
244
- * then renders one item short of what it holds. Checking only for null fixed the crash and
245
- * left that, which is the worse of the two — nothing throws and the page is quietly wrong.
246
- *
247
- * Treating either as "not found" gives the second occurrence a fresh item, which is what the
248
- * branch below already does for a key that never existed.
249
- */
250
- const reusable = oldIndex === undefined || oldIndex < oldHead || oldIndex > oldTail
251
- ? null
252
- : oldItems[oldIndex];
253
- if (reusable === null) {
254
- newItems[newHead] = part.$c(newValues[newHead], parent, part.$f(oldItems[oldHead]));
255
- }
256
- else {
257
- const item = reusable;
258
- part.$m(item, part.$f(oldItems[oldHead]), parent);
259
- part.$u(item, newValues[newHead]);
260
- newItems[newHead] = item;
261
- oldItems[oldIndex] = null;
262
- }
263
- newHead++;
255
+ part.$m(reusable, part.$f(head), parent);
256
+ next[newHead] = part.$u(reusable, values[newHead]);
257
+ old[at] = null;
264
258
  }
265
- }
266
- }
267
- /**
268
- * The trailing fill inserts every remaining item before the same reference — `refAt(newTail + 1)`
269
- * cannot move while the loop runs, because the loop itself only fills slots *below* it. Built
270
- * into a fragment and landed with one `insertBefore`, an append of 1 000 rows costs one live-DOM
271
- * insertion instead of 1 000 — the same batching the renderer's index-mode grow path has always
272
- * had, which this path silently lacked. A single item skips the fragment: one insert either way.
273
- */
274
- if (newHead < newTail) {
275
- const ref = refAt(newTail + 1);
276
- const fragment = parent.ownerDocument.createDocumentFragment();
277
- while (newHead <= newTail) {
278
- newItems[newHead] = part.$c(newValues[newHead], fragment, null);
279
259
  newHead++;
280
260
  }
281
- parent.insertBefore(fragment, ref);
282
- }
283
- else if (newHead === newTail) {
284
- newItems[newHead] = part.$c(newValues[newHead], parent, refAt(newTail + 1));
285
- newHead++;
286
- }
287
- while (oldHead <= oldTail) {
288
- const item = oldItems[oldHead++];
289
- if (item !== null)
290
- part.$d(item);
291
261
  }
292
- return newItems;
262
+ const fill = before(newEnd + 1);
263
+ for (; newHead <= newEnd; newHead++)
264
+ next[newHead] = part.$c(values[newHead], parent, fill);
265
+ for (; oldHead <= oldEnd; oldHead++)
266
+ if (old[oldHead] !== null)
267
+ part.$d(old[oldHead]);
268
+ return next;
293
269
  };
294
270
  /**
295
- * Marks a template result with a stable key so list reconciliation moves it instead of rewriting
296
- * it. Key all items in a list or none — mixing is undefined behaviour, as are duplicate keys.
297
- *
298
- * **Undefined means the list is arbitrary, not that the render fails.** With a repeated key, which
299
- * item keeps the existing node is unspecified; the render still completes and the DOM still holds
300
- * what the list holds. Development warns, once per render.
271
+ * Marks a template result with a stable key, so list reconciliation moves it instead of rewriting it.
272
+ * Key all items in a list or none. A repeated key is undefined behavior: which item keeps the existing
273
+ * node is unspecified, but the render completes and the DOM holds what the list holds.
301
274
  *
302
275
  * ```js
303
276
  * import { keyed } from '@verajs/renderer/keyed';
304
- * rows.map((r) => keyed(r.id, html`<tr>...</tr>`))
277
+ * rows.map((r) => keyed(r.id, html`<tr>…</tr>`))
305
278
  * ```
306
279
  */
307
280
  const keyed = (key, result) => {
308
281
  /**
309
- * Two arguments, and the second is the one that goes missing — `keyed(row.id)` instead of
310
- * `keyed(row.id, html\`…\`)`. It failed with `Cannot set properties of undefined (setting 'key')`,
311
- * which names this function's internals and not the call.
282
+ * The second argument is the one that goes missing — `keyed(row.id)`. It failed with `Cannot set properties of
283
+ * undefined (setting 'key')`, which names this function's internals and not the call.
312
284
  */
313
285
  if (true && (result === null || typeof result !== 'object'))
314
- throw new TypeError(`keyed: expected a template as the second argument and received ${String(result)}. ` +
315
- `It marks a template with a key — \`keyed(row.id, html\`<li>…</li>\`)\`.`);
286
+ throw new TypeError(misuse('keyed', 'keyed-not-template', true && PROSE['keyed-not-template'](String(result))));
316
287
  result.key = key;
317
288
  result.$r = reconcile;
318
289
  return result;
319
290
  };
291
+ /** Core's queued-hook factory (`$q`) and retire (`$z`), handed over by `lists` when it is wired: a row's subscriber. */
292
+ let hook;
293
+ /** Core's bare row hook (`$qb`), its direct retire (`$zh`) and the hook → owner read (`$ow`): one object fewer and no closure per row. */
294
+ let bareHook;
295
+ let retireHook;
296
+ let ownerOf;
297
+ /** Core's run ownership (`$own`). */
298
+ let own;
299
+ /** Core's settle (`$so`): a row that owns lists settles them where its run ends, or disposes them as it drops. */
300
+ let settle;
301
+ /**
302
+ * **How many live lists a ROW owns** (a `.map` inside a row's render), page-wide: while it is 0 — every page without
303
+ * nested lists — a row's run and its drop pay one module read for ownership, and no lookup (what (e′) paid per row).
304
+ */
305
+ let nested = 0;
306
+ /** Every row's callback, ONE function: core calls it as a method of the row's hook, which leads back to the row. */
307
+ function rowCb(signal, init) {
308
+ rowRun.call(ownerOf(this), signal, init);
309
+ }
310
+ /** Core's retire (`$z`): what releases a row's subscriptions. */
311
+ let retire;
312
+ /** Core's raw walk of a store array (`$w`), when core is wired; otherwise the list walks itself. */
313
+ let walk;
314
+ /** Core's raw read of a store array WITHOUT subscribing (`$wr`): what the list compares its unchanged ends on. */
315
+ let rawOf;
316
+ /** The render counter: a row stamped with this render's `t` was met in it; one not met is swept (`eachValue`). */
317
+ let tick = 0;
318
+ /**
319
+ * A row's template result, ready for the list part: its `key` (what reconcile matches on), `$r` (the keyed strategy, so
320
+ * the part reconciles by key) and `_$same$` (opts the result into the identity skip: the renderer may do nothing when
321
+ * the SAME result object comes back, which a list row returns when it did not re-render).
322
+ */
323
+ const stamp = (rec) => {
324
+ const r = rec.row(rec.item);
325
+ /** An automatic `.map` row may return a string or a number (`.map((t) => t.name).join(', ')`): nothing to stamp. */
326
+ if (r === null || typeof r !== 'object')
327
+ return r;
328
+ r.key = rec.key;
329
+ r.$r = reconcile;
330
+ r._$same$ = 1;
331
+ return r;
332
+ };
333
+ /**
334
+ * **A row: its record AND its hook's OWNER, one object; the hook is core's BARE row hook (`$qb`: never in the owner's hook list, retired directly), held in `h`, run through the one shared `rowCb`.** (An earlier version made the row
335
+ * its own hook, a subclass of core's hook class across the bundle boundary: one object per row instead of two. It bought
336
+ * nothing — a Chrome profile of create10k showed the two identical, and two races put it 4–6% SLOWER at Chrome 10k
337
+ * creation — and the cross-bundle subclass cost two mangling bugs; REVERTED, Brian 2026-10-20.) As the owner it carries
338
+ * what core's hooks read of an owner: `_$g$` its generation (bumped by `drop`, which retires the hook), `_$x$` /
339
+ * `localName`, `_$h$` the hook list core keeps on it (declared, so its first write is no shape change), `isConnected` (core
340
+ * skips a disconnected owner's writes; the row is connected while its rendered node is) and `ownerDocument` (the
341
+ * scheduler uses the element's own window). As the record: `part` its list part, `list` its automatic list, `key`,
342
+ * `item` / `row` what it renders from, `result` its last template result, `inst` the instance that result was committed
343
+ * into, `seen` the render that last met it.
344
+ */
345
+ class Row {
346
+ constructor(p, k, item, row, t, list, src) {
347
+ this._$g$ = 1;
348
+ this._$x$ = false;
349
+ this._$h$ = undefined;
350
+ this.localName = 'each-row';
351
+ this.h = undefined;
352
+ this.part = p;
353
+ this.list = list;
354
+ this.result = null;
355
+ this.inst = undefined;
356
+ this.key = k;
357
+ this.item = item;
358
+ this.src = src;
359
+ this.row = row;
360
+ this.seen = t;
361
+ }
362
+ get isConnected() {
363
+ const node = this.inst?.$R;
364
+ return node === undefined || node.isConnected;
365
+ }
366
+ get ownerDocument() {
367
+ return this.inst?.$R?.ownerDocument ?? document;
368
+ }
369
+ }
370
+ /**
371
+ * The row's run: a write the row's render read wakes exactly this row. It re-stamps and commits its new result into its
372
+ * OWN instance in place (`part.$u`); if the instance had to be replaced (the row's shape changed), the list part's item
373
+ * array is patched to point at the new one.
374
+ */
375
+ function rowRun(_signal, init) {
376
+ const list = this.list;
377
+ /** An automatic list the parent's latest run no longer reached: its rows go with it. */
378
+ if (!init && list !== undefined && list.mapped !== list.parent.$runs)
379
+ return orphan(list);
380
+ const r = stamp(this);
381
+ this.result = r;
382
+ /** The row's render returned: a nested list it hid this time goes now (core's ownership, settled here — (e″)). */
383
+ if (nested !== 0)
384
+ settle(this.h);
385
+ /**
386
+ * A run its LIST asked for (`init`: created, or re-run in the list's walk) only records its result — the list hands it
387
+ * to the renderer. Only a write the row heard commits or wakes anything: a walk-time run that woke the parent made the
388
+ * parent re-run its rows, which woke it again (a loop, measured 2026-10-20).
389
+ */
390
+ if (init)
391
+ return;
392
+ /**
393
+ * An automatic list's row commits in place only while the page shows what the parent's LATEST run mapped (`committed`);
394
+ * otherwise the map's result was used as a value (summed, joined, chained), so the parent re-renders with it.
395
+ */
396
+ if (list !== undefined && list.committed !== list.parent.$runs)
397
+ return list.parent.$n();
398
+ if (this.inst !== undefined) {
399
+ const part = this.part;
400
+ const out = part.$u(this.inst, r);
401
+ if (out !== this.inst) {
402
+ const items = part.$i;
403
+ items[items.indexOf(this.inst)] = out;
404
+ this.inst = out;
405
+ }
406
+ }
407
+ }
408
+ const makeRow = (part, k, item, row, list, src) => {
409
+ const rec = new Row(part, k, item, row, tick, list, src);
410
+ rec.h = bareHook(rec, rowCb);
411
+ /** `init`: a hook's first run is immediate (a queued hook's write-time run would only enqueue it). */
412
+ rec.h.$n(undefined, true);
413
+ return rec;
414
+ };
415
+ /** A row that left the list: its generation moves on (it goes inert) and core retires it (a self-owned hook: directly). */
416
+ const drop = (rec) => {
417
+ rec._$g$++;
418
+ retireHook(rec.h);
419
+ if (nested !== 0)
420
+ settle(rec.h, true);
421
+ /** A row owns exactly one hook today; if anything ever registers another on it, the full retire still runs. */
422
+ if (rec._$h$ !== undefined)
423
+ retire(rec);
424
+ };
425
+ /**
426
+ * **Automatic `.map`** (Brian 2026-10-20: every `.map` on a store array inside a render is
427
+ * a keyed list, with no rule and nothing to learn). Core's array handler hands `state.todos.map(fn)` here when it runs in
428
+ * a render (`$M`). The result is a REAL array of the row results — `.map(i => i.name).join(', ')` still works — and each
429
+ * `fn(item)` runs once, under its ROW's hook, so the parent never subscribes to row fields: a write to
430
+ * one item re-renders that row. A LIST (below) owns the rows and, as its own hook, the array's shape (`ITEMS`): a push
431
+ * or a splice re-runs the list, not the parent.
432
+ *
433
+ * **The stale-value rule, decided by WHICH hook ran** (signals-readiness constraint 4: no change information is read):
434
+ * the parent's run called `.map` → every row re-runs with the new `fn` (fresh parent values, exactly as a plain map); the
435
+ * list's own hook ran alone → only the shape changed, so unchanged rows are skipped.
436
+ *
437
+ * **Keys:** an item's own `id`, else the item itself — what lets a refetch (`state.todos = await …`) keep the rows of
438
+ * unchanged ids, and their DOM. A repeated `id` turns the list to identity keys for good (development warns,
439
+ * `keyed-duplicate-key`); the same object twice gets a fresh row per occurrence. **A plain map instead** when `fn`
440
+ * declares an index (`(t, i) => …`: a row would show a stale position after a reorder) or the array holds primitives.
441
+ *
442
+ * **Lists are matched to calls by ORDER within the parent's run**, as hooks are: the parent's k-th `.map` is the k-th
443
+ * list. A list the parent's latest run did not reach is an orphan; its next wake retires it with its rows.
444
+ */
445
+ class List {
446
+ constructor(parent, owner) {
447
+ this._$g$ = 1;
448
+ this._$x$ = false;
449
+ this._$h$ = undefined;
450
+ this.localName = 'each-list';
451
+ this.h = undefined;
452
+ this.parent = parent;
453
+ this.owner = owner;
454
+ this.fn = undefined;
455
+ this.items = [];
456
+ this.cache = new Map();
457
+ this.recs = [];
458
+ this.values = [];
459
+ this.part = undefined;
460
+ this.mapped = 0;
461
+ this.committed = -1;
462
+ this.all = true;
463
+ this.ident = false;
464
+ this.dead = false;
465
+ this.raw = undefined;
466
+ this.$r = -1;
467
+ this.$h = undefined;
468
+ }
469
+ /** Disposed by core when the parent's run ends without claiming it, or the parent hook retires. */
470
+ $d() {
471
+ orphan(this);
472
+ }
473
+ /** Connected while the component that mapped it is. */
474
+ get isConnected() {
475
+ return this.owner.isConnected !== false;
476
+ }
477
+ get ownerDocument() {
478
+ return this.owner.ownerDocument ?? document;
479
+ }
480
+ }
481
+ /** The mark on a map's result: the list that made it. A Symbol private to this module copy. */
482
+ const AUTO = Symbol();
483
+ /**
484
+ * The marked array this module is committing right now, so the renderer's own list path takes THAT array — and only
485
+ * it: a row built during the commit carries its own nested list, which must still reach `commitList` (a plain flag
486
+ * turned every nested list away, so every inner write re-ran its outer row — measured 2026-10-20).
487
+ */
488
+ let committing;
489
+ /**
490
+ * **Only a map whose rows are TEMPLATES becomes a list** (option C, Brian 2026-10-20 — measured first without the rule:
491
+ * a `map → reduce` over 10k items in a render cost +29% Chrome / +30% Firefox on its first render and twice the heap,
492
+ * 5.63 vs 2.85 MB, for rows nothing renders). A call site's first item decides, ONCE: its row run untracked; a result
493
+ * that is not an object marks the call site `PLAIN` for good, and it maps natively from then on.
494
+ */
495
+ const PLAIN = 0;
496
+ const listsOf = new WeakMap();
497
+ /** Core's `untracked` (`$t`): the deciding run of a call site's first item subscribes nothing. */
498
+ let untracked;
499
+ /** A list the parent no longer reaches: its rows and its own hook retire. */
500
+ const orphan = (list) => {
501
+ /**
502
+ * ONCE: a second orphan would count a row-owned list out of `nested` twice, and a count driven to 0 while nested
503
+ * lists live turns their settling off — the leak (e″) closes, silently. Unreachable today (an orphaned list's hooks and
504
+ * rows move generation, so nothing queued runs them again), kept as the invariant.
505
+ */
506
+ if (list.dead)
507
+ return;
508
+ list.dead = true;
509
+ if (ownerOf(list.parent) instanceof Row)
510
+ nested--;
511
+ for (let i = 0; i < list.recs.length; i++)
512
+ drop(list.recs[i]);
513
+ list.recs = [];
514
+ list.cache.clear();
515
+ /**
516
+ * A disposed list may stay RECORDED (in the per-array history), so it lets go of everything else: its last
517
+ * results (a hidden 10k list's 10 000 template results), its render's callback, its array and its part (Brian 2026-10-20:
518
+ * "is there any risk with references getting held with the tables?").
519
+ */
520
+ list.values = [];
521
+ list.fn = undefined;
522
+ list.items = [];
523
+ list.part = undefined;
524
+ list._$g$++;
525
+ retire(list);
526
+ };
527
+ /** The list's result committed into `part` by the renderer's own list path; then each row learns its instance and part. */
528
+ const commitList = (list, part) => {
529
+ const outer = committing;
530
+ committing = list.values;
531
+ try {
532
+ part.$p(list.values);
533
+ }
534
+ finally {
535
+ committing = outer;
536
+ }
537
+ /**
538
+ * Marked committed only once the commit SUCCEEDED: a commit that threw left the list "committed" with its
539
+ * rows' instances stale, and the next row write patched an instance the part no longer held (`items[-1]`). Unmarked,
540
+ * a row write wakes the parent instead, which re-renders and commits again.
541
+ */
542
+ list.part = part;
543
+ list.committed = list.parent.$runs;
544
+ const its = part.$i;
545
+ const recs = list.recs;
546
+ if (its !== undefined)
547
+ for (let i = 0; i < recs.length; i++) {
548
+ recs[i].inst = its[i];
549
+ recs[i].part = part;
550
+ }
551
+ };
552
+ /**
553
+ * The row last met as raw slot `value` is met again unchanged: the same raw object AND the same key (`id` written in
554
+ * place re-keys the row, as a full walk would; a row keyed by identity has `key === src`).
555
+ */
556
+ const same = (rec, value) => rec.src === value && (rec.key === value || (value !== null && typeof value === 'object' && value.id === rec.key));
557
+ /** The list's run: walk the array (subscribing the list to its shape), reuse / create / sweep rows, mark the result. */
558
+ function listRun() {
559
+ const all = this.all;
560
+ this.all = false;
561
+ if (!all && this.mapped !== this.parent.$runs)
562
+ return orphan(this);
563
+ const t = ++tick;
564
+ const fn = this.fn;
565
+ const cache = this.cache;
566
+ const prev = this.recs;
567
+ const n = this.items.length;
568
+ const recs = new Array(n);
569
+ const values = new Array(n);
570
+ let i = 0;
571
+ let restart = false;
572
+ /**
573
+ * **The unchanged ends, settled on RAW slots before any key is resolved** (the reconcile's two-ends idea, one level
574
+ * up). A swap or a splice changes a few slots and re-ran this whole walk — a Map lookup, an `hasOwn`, a proxy read per
575
+ * row, 63% of a Chrome swap (2026-10-23). Off when every row must re-run (`all`), and off unless core can hand the raw
576
+ * slots (`rawOf`: a plain store array) — the fallback below reads through the proxy, whose per-index reads are links.
577
+ * Every row kept here is stamped `seen` BEFORE the middle runs, so a middle item repeating its key is still a duplicate.
578
+ */
579
+ let front = 0;
580
+ let back = 0;
581
+ const raw = all ? undefined : rawOf?.(this.items);
582
+ if (raw !== undefined) {
583
+ const m = prev.length;
584
+ const lim = n < m ? n : m;
585
+ while (front < lim && same(prev[front], raw[front]))
586
+ front++;
587
+ while (back < lim - front && same(prev[m - 1 - back], raw[n - 1 - back]))
588
+ back++;
589
+ for (let j = 0; j < front; j++) {
590
+ const rec = prev[j];
591
+ rec.seen = t;
592
+ recs[j] = rec;
593
+ values[j] = rec.result;
594
+ }
595
+ for (let j = 1; j <= back; j++) {
596
+ const rec = prev[m - j];
597
+ rec.seen = t;
598
+ recs[n - j] = rec;
599
+ values[n - j] = rec.result;
600
+ }
601
+ i = front;
602
+ }
603
+ const visit = (source, item) => {
604
+ if (restart)
605
+ return;
606
+ /** The row last run at this position, met again as the same raw slot: no key to resolve (a swap's untouched middle). */
607
+ const at = raw === undefined ? undefined : prev[i];
608
+ let rec;
609
+ let k;
610
+ if (at !== undefined && at.seen !== t && same(at, source)) {
611
+ rec = at;
612
+ k = at.key;
613
+ }
614
+ else {
615
+ k = this.ident || !Object.hasOwn(source, 'id') ? source : source.id;
616
+ rec = cache.get(k);
617
+ }
618
+ if (rec !== undefined && rec.seen === t) {
619
+ if (!this.ident) {
620
+ /** A repeated id: identity keys from now on, and this run again from the start. Said once per list. */
621
+ if (true )
622
+ warnOnce('keyed', 'an automatic .map list', 'keyed-duplicate-key', true && (() => PROSE['keyed-duplicate-key'](String(k))), this);
623
+ this.ident = true;
624
+ restart = true;
625
+ return;
626
+ }
627
+ /** The same object twice under identity keys: a row of its own, never cached. */
628
+ rec = makeRow(undefined, {}, item, fn, this, source);
629
+ }
630
+ else if (rec === undefined) {
631
+ rec = makeRow(undefined, k, item, fn, this, source);
632
+ cache.set(k, rec);
633
+ }
634
+ else if (all || rec.item !== item) {
635
+ /** Through the row's OWN hook: what it reads subscribes the row, never the list or the parent. */
636
+ rec.item = item;
637
+ rec.row = fn;
638
+ rec.h.$n(undefined, true);
639
+ }
640
+ rec.seen = t;
641
+ rec.src = source;
642
+ recs[i] = rec;
643
+ values[i++] = rec.result;
644
+ };
645
+ if (!walk(this.items, visit, front, n - back))
646
+ for (let j = 0; j < n; j++) {
647
+ const item = this.items[j];
648
+ visit(item, item);
649
+ }
650
+ if (restart) {
651
+ /** Identity keys now: every row is made again by a full walk, then this run's commit decision still applies. */
652
+ for (const rec of cache.values())
653
+ drop(rec);
654
+ cache.clear();
655
+ this.recs = [];
656
+ this.all = true;
657
+ listRun.call(this);
658
+ if (all)
659
+ return;
660
+ if (this.committed === this.parent.$runs && this.part !== undefined)
661
+ commitList(this, this.part);
662
+ else
663
+ this.parent.$n();
664
+ return;
665
+ }
666
+ /** Last run's rows this run did not meet: swept (each drops its own subscriptions). The kept ends were all met. */
667
+ for (let j = front; j < prev.length - back; j++) {
668
+ const rec = prev[j];
669
+ if (rec.seen !== t) {
670
+ if (cache.get(rec.key) === rec)
671
+ cache.delete(rec.key);
672
+ drop(rec);
673
+ }
674
+ }
675
+ this.recs = recs;
676
+ values[AUTO] = this;
677
+ this.values = values;
678
+ if (all)
679
+ return;
680
+ /** The shape changed alone: commit where the page shows the parent's latest result, or re-render the parent. */
681
+ if (this.committed === this.parent.$runs && this.part !== undefined)
682
+ commitList(this, this.part);
683
+ else
684
+ this.parent.$n();
685
+ }
686
+ /** Core's `$M`: `state.todos.map(fn)` inside a render. `raw` is the array behind `proxy`; `method` the native `map`. */
687
+ const automap = (proxy, raw, fn, parent, owner, method) => {
688
+ let state = listsOf.get(parent);
689
+ if (state === undefined)
690
+ listsOf.set(parent, (state = { v: parent.$runs, n: 0, lists: [], occ: new Map(), byRaw: new WeakMap() }));
691
+ else if (state.v !== parent.$runs) {
692
+ state.v = parent.$runs;
693
+ state.n = 0;
694
+ state.occ.clear();
695
+ }
696
+ /**
697
+ * EVERY `.map` call in a render takes its place in the order, whatever path it takes (one rule). An index or
698
+ * non-function callback needs no memory — its arity is known at every call — so it takes the place WITHOUT writing
699
+ * PLAIN: writing it could overwrite a live list unretired, and turn a list that slid onto this place into a plain map.
700
+ */
701
+ if (typeof fn !== 'function' || fn.length > 1) {
702
+ state.n++;
703
+ return method.call(proxy, fn);
704
+ }
705
+ /**
706
+ * **A list is found by (ARRAY, its occurrence in this run) first** (2026-10-20): a conditional `.map` before
707
+ * another no longer slides the later one onto its list — a hidden map shifts only other maps over the SAME array. A new
708
+ * array (a refetch) falls back to the list at this call's place in order, but only one whose own array is not mapped in
709
+ * this run, so it never takes another site's list. A PLAIN decision is found only by its exact array (a refetched plain
710
+ * site decides again: one untracked call).
711
+ */
712
+ const k = state.occ.get(raw) ?? 0;
713
+ state.occ.set(raw, k + 1);
714
+ const slots = state.byRaw.get(raw);
715
+ let list = slots?.[k];
716
+ /** Dead, or already claimed by another call this run (a list serves ONE call per run): not this call's. */
717
+ if (list !== undefined && list !== PLAIN && (list.dead || list.mapped === parent.$runs))
718
+ list = undefined;
719
+ /**
720
+ * The order fallback is for a REFETCH only — a brand-new array, with no history of its own. An array that has history is
721
+ * a RETURNING one (a list shown again): falling back would hand it another array's list, and that array's own call would
722
+ * then share it (measured: auto-cond, both lists rendered from one).
723
+ */
724
+ if (list === undefined && slots === undefined) {
725
+ const at = state.lists[state.n];
726
+ if (at !== undefined && at !== PLAIN && !at.dead && at.mapped !== parent.$runs && !state.occ.has(at.raw))
727
+ list = at;
728
+ }
729
+ const st = state;
730
+ const put = (v) => {
731
+ st.lists[st.n] = v;
732
+ let mine = st.byRaw.get(raw);
733
+ if (mine === undefined)
734
+ st.byRaw.set(raw, (mine = []));
735
+ mine[k] = v;
736
+ if (v !== PLAIN)
737
+ v.raw = raw;
738
+ };
739
+ if (list === PLAIN) {
740
+ state.n++;
741
+ return method.call(proxy, fn);
742
+ }
743
+ /**
744
+ * **A call site with a live list ALWAYS runs it — an empty array included** (2026-10-20): the empty case took the plain
745
+ * path, so clearing a list never swept its rows — 10 000 rows stayed alive and subscribed after `state.rows = []`
746
+ * (Chrome: 12.22 MB retained after a clear vs the earlier idiom's 4.50, `perrow.mjs`), each create ran beside the last one's
747
+ * rows (twice the live heap: Firefox's extra major GC), and the empty call did not count its place in the parent's
748
+ * order, so a later `.map` slid into this one's list. With no list yet, an empty or primitive array maps natively, and
749
+ * still takes its place (an empty one stays undecided; a primitive one is PLAIN for good).
750
+ */
751
+ if (list === undefined || list.dead) {
752
+ if (raw.length === 0) {
753
+ state.n++;
754
+ return method.call(proxy, fn);
755
+ }
756
+ if (raw[0] === null || typeof raw[0] !== 'object') {
757
+ put(PLAIN);
758
+ state.n++;
759
+ return method.call(proxy, fn);
760
+ }
761
+ }
762
+ if (list === undefined) {
763
+ const first = untracked(() => fn(proxy[0]));
764
+ /**
765
+ * A list only when the first row is a TEMPLATE result — the renderer's OWN definition, `strings !== undefined`
766
+ * (`isTemplateResult`, renderer.ts; a DELIBERATE twin, since this module imports nothing at runtime: change both
767
+ * together), so a hand-built `{ strings, values }` the renderer accepts is a list here too —
768
+ * not any object: a computational map returning plain objects (`items.map((i) => ({ ...i, label }))`, a directives
769
+ * query) became a tracked list and broke `directives-query` (2026-10-20).
770
+ */
771
+ if (first === null || typeof first !== 'object' || first.strings === undefined) {
772
+ put(PLAIN);
773
+ state.n++;
774
+ return method.call(proxy, fn);
775
+ }
776
+ }
777
+ if (list === undefined || list.dead) {
778
+ const made = new List(parent, owner);
779
+ made.h = hook(made, () => listRun.call(made));
780
+ if (ownerOf(parent) instanceof Row)
781
+ nested++;
782
+ list = made;
783
+ }
784
+ put(list);
785
+ state.n++;
786
+ /**
787
+ * **Owned by the parent's run** (core's `$own`): when a parent run ENDS without claiming this list — its
788
+ * render hid it, or no longer reaches it — core disposes it (`$d`, an orphan's retirement) at once, `.map` call or not.
789
+ */
790
+ own(parent, list);
791
+ list.fn = fn;
792
+ list.items = proxy;
793
+ list.mapped = parent.$runs;
794
+ list.all = true;
795
+ list.h.$n(undefined, true);
796
+ return list.values;
797
+ };
798
+ const eachValue = (part, value, adopted) => {
799
+ if (value === null || typeof value !== 'object')
800
+ return false;
801
+ /** An automatic `.map` result: committed by its list, which then knows the part its rows live in. */
802
+ if (Array.isArray(value)) {
803
+ const list = value[AUTO];
804
+ if (list === undefined || value === committing)
805
+ return false;
806
+ /**
807
+ * **Hydrating: the list ADOPTS the server's rows** (2026-10-22). The base adopted one instance per row FROM THESE
808
+ * ROWS' OWN results — same count, same templates, same keys, by construction — so the list only takes ownership
809
+ * (`ADOPTED`, 2) and the base's queued commits patch any stale value in place, as for every adopted instance. It used
810
+ * to claim, which rebuilt every row. Any other shape (no adopted items, a count that differs) builds, as before.
811
+ */
812
+ const items = adopted?.$i;
813
+ if (items !== undefined && items.length === list.recs.length) {
814
+ list.part = part;
815
+ list.committed = list.parent.$runs;
816
+ for (let i = 0; i < items.length; i++) {
817
+ list.recs[i].inst = items[i];
818
+ list.recs[i].part = part;
819
+ }
820
+ return 2;
821
+ }
822
+ commitList(list, part);
823
+ return true;
824
+ }
825
+ return false;
826
+ };
827
+ /**
828
+ * **`createSelector(source)` → `isSelected(key)`** (2026-10-20): selection that wakes
829
+ * exactly the rows whose answer changed. `isSelected(key)` subscribes the running hook to ONE cell per key (core's store
830
+ * kit, `$k`, on a private target), and a hook watching `source` wakes only the previous and the new key's cells when it
831
+ * changes — so a select re-renders 2 rows, not every row that compared against `state.selected`.
832
+ *
833
+ * ```js
834
+ * const isSelected = createSelector(() => state.selected);
835
+ * state.rows.map((r) => html`<tr class=${isSelected(r.id) ? 'selected' : ''}>…</tr>`)
836
+ * ```
837
+ *
838
+ * Made in a component's setup, it is that component's (its watcher retires with it); with no component being set up it
839
+ * THROWS, as every hook does. Its watcher runs inside the write (an immediate hook), so the woken rows render in the same flush.
840
+ * Its keys are bounded: cells no row reads any more are pruned on an amortized budget (below).
841
+ */
842
+ let kit;
843
+ let makeHook;
844
+ const createSelector = (source) => {
845
+ if (kit === undefined || makeHook === undefined)
846
+ throw new Error(misuse('createSelector', 'selector-not-wired', true && PROSE['selector-not-wired']()));
847
+ const target = {};
848
+ const k = kit;
849
+ let current = target;
850
+ const run = makeHook({
851
+ callback: () => {
852
+ const next = source();
853
+ if (next === current)
854
+ return;
855
+ const prev = current;
856
+ current = next;
857
+ if (prev !== target)
858
+ k.trigger(target, prev, false, true);
859
+ k.trigger(target, next, true, false);
860
+ },
861
+ priority: 0,
862
+ });
863
+ run?.(undefined, true);
864
+ /**
865
+ * **Keys are bounded by core**: every big key map is swept as it grows (createProxy's `sweepIfDue`) — the cells no
866
+ * row reads any more go, so a list whose ids only increase (a feed, a log) keeps only about twice its live keys. (This
867
+ * selector had its own budgeted prune until core generalized it, 2026-10-23.)
868
+ */
869
+ return (key) => {
870
+ k.track(target, key);
871
+ return current === key;
872
+ };
873
+ };
874
+ /**
875
+ * Wire it: `wire([renderer, lists])`. A CONNECTOR (a function `wire` hands the registry): core's registry carries the
876
+ * hook machinery (`$q`, `$z`) and the raw walk (`$w`); automatic `.map` results are recognized on the renderer's `'value'` insert.
877
+ */
878
+ const lists = (registry, w) => {
879
+ hook = registry.$q;
880
+ bareHook = registry.$qb;
881
+ retireHook = registry.$zh;
882
+ ownerOf = registry.$ow;
883
+ own = registry.$own;
884
+ settle = registry.$so;
885
+ /** Core's array handler asks `$M` for a store array's `.map` inside a render: automatic lists. */
886
+ registry.$M = automap;
887
+ retire = registry.$z;
888
+ untracked = registry.$t;
889
+ kit = registry.$k;
890
+ makeHook = registry.$s?.[2];
891
+ walk = registry.$w;
892
+ rawOf = registry.$wr;
893
+ w({ on: 'value', fn: eachValue, priority: 50 });
894
+ };
320
895
 
321
- export { keyed };
896
+ export { createSelector, keyed, lists };
322
897
  //# sourceMappingURL=vera-renderer-keyed.js.map