@webjsdev/core 0.7.49 → 0.7.51

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 (61) hide show
  1. package/dist/webjs-core-browser.js +5 -5
  2. package/dist/webjs-core-browser.js.map +3 -3
  3. package/dist/webjs-core-testing.js +21 -21
  4. package/dist/webjs-core-testing.js.map +3 -3
  5. package/dist/webjs-core.js +7 -7
  6. package/dist/webjs-core.js.map +3 -3
  7. package/index-browser.js +1 -1
  8. package/index.d.ts +1 -1
  9. package/index.js +1 -1
  10. package/package.json +1 -1
  11. package/src/attribute-reader.js +178 -0
  12. package/src/component/lifecycle.js +1481 -0
  13. package/src/component/reactive.js +171 -0
  14. package/src/component/server-element.js +248 -0
  15. package/src/component.d.ts +10 -0
  16. package/src/component.js +2 -1931
  17. package/src/html-entities.js +2179 -0
  18. package/src/render-client/parts.js +2007 -0
  19. package/src/render-client/reconciler.js +388 -0
  20. package/src/render-client/template-compiler.js +525 -0
  21. package/src/render-client.js +1 -2939
  22. package/src/render-server/attrs.js +160 -0
  23. package/src/render-server/dsd.js +445 -0
  24. package/src/render-server/html-scan.js +402 -0
  25. package/src/render-server/slots.js +213 -0
  26. package/src/render-server/stream.js +163 -0
  27. package/src/render-server/template-renderer.js +923 -0
  28. package/src/render-server/text.js +163 -0
  29. package/src/render-server.js +6 -2334
  30. package/src/router-client/anchors.js +44 -0
  31. package/src/router-client/boundaries.js +221 -0
  32. package/src/router-client/constants.js +187 -0
  33. package/src/router-client/diagnostics.js +377 -0
  34. package/src/router-client/dom-differ.js +709 -0
  35. package/src/router-client/dom-parse.js +150 -0
  36. package/src/router-client/events.js +139 -0
  37. package/src/router-client/fetch-apply.js +387 -0
  38. package/src/router-client/form-encoder.js +135 -0
  39. package/src/router-client/frames.js +329 -0
  40. package/src/router-client/head-merge.js +344 -0
  41. package/src/router-client/nav-error.js +105 -0
  42. package/src/router-client/navigator.js +781 -0
  43. package/src/router-client/prefetch.js +824 -0
  44. package/src/router-client/scroll.js +259 -0
  45. package/src/router-client/snapshot-cache.js +97 -0
  46. package/src/router-client/state.js +92 -0
  47. package/src/router-client/stream.js +206 -0
  48. package/src/router-client/swap.js +451 -0
  49. package/src/router-client/upgrade.js +261 -0
  50. package/src/router-client/view-transition.js +223 -0
  51. package/src/router-client.d.ts +10 -1
  52. package/src/router-client.js +75 -5345
  53. package/src/slot/assignment.js +304 -0
  54. package/src/slot/interception.js +558 -0
  55. package/src/slot/polyfills.js +365 -0
  56. package/src/slot/project.js +432 -0
  57. package/src/slot/sensors.js +303 -0
  58. package/src/slot/state.js +245 -0
  59. package/src/slot/symbols.js +85 -0
  60. package/src/slot.js +7 -2199
  61. package/src/webjs-config.d.ts +13 -2
@@ -0,0 +1,2007 @@
1
+ import { isTemplate, MARKER } from '../html.js';
2
+ import {
3
+ assertNotFunctionActionAttr, assertNotFunctionReflectedActionProp, isBoundFormAction,
4
+ } from '../form-action.js';
5
+ import { isRepeat } from '../repeat.js';
6
+ import {
7
+ isUnsafeHTML, isLive, isKeyed, isGuard, isTemplateContent, isRef, isCache, isUntil, isAsyncAppend, isAsyncReplace, isWatch
8
+ } from '../directives.js';
9
+ import { Signal } from '../signal.js';
10
+ import {
11
+ SLOT_FALLBACK_FRAG, SLOT_STATE, SLOT_OWNER, applySlotAssignments, withRendererWrites,
12
+ } from '../slot.js';
13
+ import { compile, templateCache } from './template-compiler.js';
14
+
15
+ /**
16
+ * The container the in-progress `render()` is committing into, or null
17
+ * outside one. Every part created or applied during that render belongs to
18
+ * THIS container's component, which is what an out-of-band commit needs to
19
+ * know to reach the right error boundary. A structural parent walk cannot
20
+ * work it out: `html`<child-el>${watch(sig)}</child-el>`` puts the part in the
21
+ * PARENT's template but inside the child's tag, so the walk meets the child
22
+ * first. Same reason `SLOT_OWNER` exists.
23
+ * @type {any}
24
+ */
25
+ export let currentRenderRoot = null;
26
+
27
+ export function setCurrentRenderRoot(root) {
28
+ currentRenderRoot = root;
29
+ }
30
+
31
+ /**
32
+ * Open the renderer-write window on a light-DOM host while `fn` commits into
33
+ * it, so the host's patched slot-interception methods delegate to native and
34
+ * a renderer commit is never mistaken for authored content. A no-op (just runs
35
+ * `fn`) when `node` is not a slot host, so nested and non-host commits pay
36
+ * nothing. Covers the ASYNC commit paths (async directives, streaming) that
37
+ * run outside a synchronous render() call.
38
+ */
39
+ export function commitInto(node, fn) {
40
+ const host = node && /** @type {any} */ (node)[SLOT_STATE] ? node : null;
41
+ if (!host) return fn();
42
+ return withRendererWrites(host, fn);
43
+ }
44
+
45
+ /**
46
+ * Client-side renderer with **fine-grained** updates.
47
+ *
48
+ * Each TemplateResult is compiled once (keyed by the tagged-template's
49
+ * `strings` array identity, so reuse is free across renders) into:
50
+ * - a `<template>` element with static HTML + marker comments/attributes
51
+ * at each dynamic hole
52
+ * - a list of `Part` descriptors (kind + DOM location + attr/event name)
53
+ *
54
+ * On first render the template is cloned into the container and each Part
55
+ * is bound to the freshly-created node. Subsequent renders compare the new
56
+ * values to the last-applied values and only touch parts that changed.
57
+ * Text-position holes containing nested TemplateResults reuse the existing
58
+ * child instance when the inner `strings` match; they only rebuild when the
59
+ * template shape changes.
60
+ *
61
+ * Consequences worth knowing:
62
+ * - Input focus, cursor position, selection, and scroll inside components
63
+ * survive re-renders triggered by property assignments, signal changes,
64
+ * or `requestUpdate()`.
65
+ * - Event listeners are attached once and retargeted when the handler
66
+ * reference changes (swap-in-place via a dispatch closure, so `addEventListener`
67
+ * isn't churned every render).
68
+ * - A plain `.map()` array reconciles POSITIONALLY (non-keyed), matching
69
+ * lit-html: each index updates its item instance in place when the
70
+ * template shape is unchanged, so DOM node identity (and the focus,
71
+ * selection, scroll, and in-progress native drag it carries) survives an
72
+ * item-level update. See `reconcileArray`. Keyed reordering still needs
73
+ * the `repeat()` directive.
74
+ */
75
+
76
+ /**
77
+ * One `method` / `enctype` hole on a candidate bound form. `statics` / `group`
78
+ * are carried for a mixed attribute, whose value is the concatenation of its
79
+ * static pieces and every one of its holes.
80
+ *
81
+ * @typedef {{ i: number, kind: string, statics?: string[], group?: number[] }} FormAttrPart
82
+ */
83
+
84
+ /**
85
+ * What one `<form action=${...}>` in a template needs at reconcile time (#1155).
86
+ * Every field is a property of the TEMPLATE, computed once per template literal
87
+ * call site, so it cannot drift out of step with the live DOM.
88
+ *
89
+ * @typedef {{
90
+ * actionIdxs: number[],
91
+ * duplicateAction: boolean,
92
+ * staticAction: boolean,
93
+ * authoredName: boolean,
94
+ * authoredValue: boolean,
95
+ * authoredForm: boolean,
96
+ * nameParts: {i: number, kind: string}[],
97
+ * valueParts: {i: number, kind: string}[],
98
+ * propAttrs: string[],
99
+ * staticMethod: string | null,
100
+ * staticEnctype: string | null,
101
+ * methodParts: FormAttrPart[],
102
+ * enctypeParts: FormAttrPart[],
103
+ * }} FormActionRecord
104
+ */
105
+
106
+ /**
107
+ * The element carrying the error boundary for a render root. A ShadowRoot has
108
+ * no boundary of its own; its `.host` is the component.
109
+ * @param {any} root
110
+ * @returns {any}
111
+ */
112
+ export function boundaryOwnerOf(root) {
113
+ if (!root) return null;
114
+ if (root.nodeType === 11 && root.host) return root.host;
115
+ return root;
116
+ }
117
+
118
+ /**
119
+ * Run an OUT-OF-BAND commit (a `watch` notify microtask, an `until`
120
+ * resolution) with the part's owner installed as the current render root.
121
+ *
122
+ * Without this the commit runs with no owner in scope, so any `watch` /
123
+ * `until` nested INSIDE the template it commits is installed unstamped and
124
+ * its own later throw escapes to the window. A directive nested in that
125
+ * template belongs to the same component as the part committing it, which is
126
+ * exactly the owner already recorded here.
127
+ *
128
+ * @param {Extract<BoundPart, {kind:'child'}>} part
129
+ * @param {() => void} fn
130
+ */
131
+ export function commitOutOfBand(part, fn) {
132
+ const owner = /** @type any */ (part).__commitOwner;
133
+ const prev = currentRenderRoot;
134
+ if (owner) currentRenderRoot = owner;
135
+ try {
136
+ fn();
137
+ } finally {
138
+ currentRenderRoot = prev;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * @param {PartDescriptor} p
144
+ * @param {DocumentFragment | Element} root
145
+ * @returns {BoundPart}
146
+ */
147
+ export function bindPart(p, root) {
148
+ if (p.kind === 'noop') return /** @type any */ ({ kind: 'noop', mixedAnchor: /** @type any */ (p).mixedAnchor });
149
+ let node = /** @type Node */ (root);
150
+ for (const i of p.path) node = node.childNodes[i];
151
+ if (p.kind === 'child') {
152
+ return { kind: 'child', marker: /** @type Comment */ (node) };
153
+ }
154
+ const el = /** @type Element */ (node);
155
+ if (p.kind === 'event') {
156
+ /** @type {BoundPart} */
157
+ const part = {
158
+ kind: 'event',
159
+ el,
160
+ name: p.name || '',
161
+ handler: null,
162
+ // The dispatcher is the registered listener; handler swaps behind it.
163
+ dispatcher(ev) { part.handler?.(ev); },
164
+ };
165
+ el.addEventListener(part.name, part.dispatcher);
166
+ return part;
167
+ }
168
+ if (p.kind === 'attr') return { kind: 'attr', el, name: p.name || '' };
169
+ if (p.kind === 'attr-mixed') return { kind: 'attr-mixed', el, name: p.name || '', statics: p.statics || [], group: p.group || [] };
170
+ if (p.kind === 'prop') return { kind: 'prop', el, name: p.name || '' };
171
+ if (p.kind === 'bool') return { kind: 'bool', el, name: p.name || '' };
172
+ if (p.kind === 'element') return { kind: 'element', el };
173
+ if (p.kind === 'slot') {
174
+ const slotEl = /** @type {HTMLSlotElement} */ (el);
175
+ // Defer fallback-strip and SLOT_FALLBACK_FRAG installation to apply
176
+ // time so we know whether the slot is light or shadow at the point
177
+ // where the decision matters. At bind time the cloned slot still
178
+ // holds its fallback content from the template clone; we just
179
+ // record the slot ref.
180
+ return { kind: 'slot', slotEl, applied: false };
181
+ }
182
+ throw new Error(`unknown part kind ${/** @type any */(p).kind}`);
183
+ }
184
+
185
+ /**
186
+ * @param {BoundPart} part
187
+ * @param {unknown} value
188
+ * @param {unknown} _prev
189
+ */
190
+ export function applyPart(part, value, _prev, allValues, reconcileFormActionsCb) {
191
+ // Unwrap live() to dirty-check against the live DOM value, not the
192
+ // last rendered value. Essential for <input> two-way binding.
193
+ if (isLive(value)) {
194
+ const liveVal = /** @type any */ (value).value;
195
+ if (part.kind === 'prop' && /** @type any */ (part.el)[part.name] === liveVal) return;
196
+ if (part.kind === 'attr' && part.el.getAttribute(part.name) === String(liveVal)) return;
197
+ if (part.kind === 'bool' && part.el.hasAttribute(part.name) === !!liveVal) return;
198
+ value = liveVal;
199
+ }
200
+
201
+ switch (part.kind) {
202
+ case 'child':
203
+ applyChild(part, value, reconcileFormActionsCb);
204
+ break;
205
+ case 'attr': {
206
+ if (value == null || value === false) part.el.removeAttribute(part.name);
207
+ else if (isBoundFormAction(value, part.name, part.el.localName)) {
208
+ // #1155: the ONE supported form-action binding, applied to the live
209
+ // form exactly as SSR wrote it. A component that ships re-renders its
210
+ // whole template on hydration, so without this the SSR'd hidden field
211
+ // would be replaced by an `action` attribute holding a stringified
212
+ // function, and the form would post to a garbage url.
213
+ //
214
+ // Nothing happens here. The whole decision (identity, the submit
215
+ // attributes, the hidden field) is made at the end of the pass by
216
+ // `reconcileFormAction`, because it depends on holes that have not
217
+ // committed yet when this one does.
218
+ } else {
219
+ // #1154: refuse to stringify a function into action=/formaction=
220
+ // (mirrors the SSR guard, so a client re-render cannot write a
221
+ // server action's source into the live DOM).
222
+ assertNotFunctionActionAttr(value, part.name, part.el.localName);
223
+ part.el.setAttribute(part.name, String(value));
224
+ }
225
+ break;
226
+ }
227
+ case 'prop':
228
+ // `.action=${fn}` is a leak too, not just the attribute form, but only
229
+ // where the property is a REFLECTED IDL attribute: assigning a function
230
+ // to `form.action` (or `.formAction` on a button/input) stringifies it
231
+ // into that element's own content attribute in a real browser. On any
232
+ // other native tag it is a plain expando that reflects nothing, and on a
233
+ // custom element it is an author-defined property, so a function is
234
+ // legitimate in both. The helper owns that distinction.
235
+ //
236
+ // Not covered here, because it is not a commit: a custom element's prop
237
+ // declared `reflect: true` reflects from its own setter. That path used
238
+ // to write String(value) and leak the source. #1169 made it remove the
239
+ // attribute instead (an array carrying one included, via the same
240
+ // `carriesFunction` predicate this file's guard uses), so it is guarded
241
+ // at the setter rather than here. One carve-out stays the author's call:
242
+ // a prop supplying its own `converter.toAttribute` runs that converter
243
+ // first and is left alone, so it still writes whatever the author
244
+ // returns for a function.
245
+ assertNotFunctionReflectedActionProp(value, part.name, part.el.localName);
246
+ /** @type any */ (part.el)[part.name] = value;
247
+ break;
248
+ case 'bool':
249
+ // #1154: never leaked (a boolean binding stringifies nothing), but
250
+ // `?action=${fn}` is meaningless in every case, and refusing it keeps
251
+ // this renderer agreeing with both SSR machines.
252
+ assertNotFunctionActionAttr(value, part.name, part.el.localName);
253
+ if (value) part.el.setAttribute(part.name, '');
254
+ else part.el.removeAttribute(part.name);
255
+ break;
256
+ case 'event':
257
+ // NOT guarded, deliberately. An event binding never stringifies its
258
+ // value, and a function is the legitimate thing to pass one, so
259
+ // `<my-el @action=${handler}>` has to keep working.
260
+ part.handler = typeof value === 'function' ? /** @type any */ (value) : null;
261
+ break;
262
+ case 'element':
263
+ applyElement(part, value);
264
+ break;
265
+ case 'attr-mixed': {
266
+ // Reconstruct the attribute from static pieces + all dynamic values.
267
+ const mp = /** @type {{ statics: string[], group: number[] }} */ (/** @type any */ (part));
268
+ let val = mp.statics[0];
269
+ for (let j = 0; j < mp.group.length; j++) {
270
+ const piece = allValues ? allValues[mp.group[j]] : value;
271
+ // #1154: same function guard for each piece of a mixed attribute.
272
+ assertNotFunctionActionAttr(piece, part.name, part.el.localName);
273
+ val += String(piece ?? '');
274
+ val += mp.statics[j + 1] || '';
275
+ }
276
+ part.el.setAttribute(part.name, val);
277
+ break;
278
+ }
279
+ case 'slot': {
280
+ // Slot parts have no template-hole value to apply. The "apply" is
281
+ // a one-shot trigger that runs after the template fragment has
282
+ // been inserted into the host's render root. At this point the
283
+ // slot's parent chain reveals whether it lives inside a shadow
284
+ // root (browser native projection) or in light DOM (framework
285
+ // projection). For shadow-DOM slots we leave the cloned fallback
286
+ // in place. For light-DOM slots we move the fallback into a
287
+ // per-slot holding fragment owned by slot.js (via the
288
+ // SLOT_FALLBACK_FRAG symbol) so the slot can receive projected
289
+ // children, and we kick off projection.
290
+ //
291
+ // For NESTED templates (a slot inside `${cond ? html`<slot/>` : ''}`),
292
+ // the slot's parent chain at first apply may still lead through
293
+ // an unattached fragment. findSlotHost returns null then; we
294
+ // retry on the next microtask, by which point the outer's
295
+ // replaceChildren has placed the entire tree into the host.
296
+ if (part.applied) break;
297
+ const slotEl = part.slotEl;
298
+ const finalize = () => {
299
+ const host = findSlotHost(slotEl);
300
+ if (!host) {
301
+ part.applied = true;
302
+ return;
303
+ }
304
+ // A FORWARDED slot's owner is known immediately (the SLOT_OWNER
305
+ // stamp) but the child component has not yet PLACED the slot into
306
+ // the owner's subtree, so the owner's apply cannot find it yet.
307
+ // Re-defer until the child places it (host.contains becomes true);
308
+ // the child WILL place it, or the owner disconnects and the retries
309
+ // stop. A normal own slot is already inside its host, so this passes
310
+ // on the first call with no extra deferral.
311
+ if (!host.contains(slotEl)) {
312
+ if (host.isConnected) queueMicrotask(finalize);
313
+ else part.applied = true;
314
+ return;
315
+ }
316
+ part.applied = true;
317
+ // Shadow DOM: native projection. Leave fallback in place.
318
+ if (isInShadowRootEl(slotEl)) return;
319
+ // Light DOM: harvest the cloned fallback into a holding
320
+ // fragment, then place the host's slot record (#1015). The
321
+ // application is deferred one microtask so the documented
322
+ // lifecycle timing holds: firstUpdated() sees the <slot>
323
+ // element itself, the populated content lands right after.
324
+ const frag = document.createDocumentFragment();
325
+ while (slotEl.firstChild) frag.appendChild(slotEl.firstChild);
326
+ /** @type {any} */ (slotEl)[SLOT_FALLBACK_FRAG] = frag;
327
+ queueMicrotask(() => applySlotAssignments(host));
328
+ };
329
+ const directHost = findSlotHost(slotEl);
330
+ if (directHost && directHost.contains(slotEl)) {
331
+ finalize();
332
+ } else {
333
+ queueMicrotask(finalize);
334
+ }
335
+ break;
336
+ }
337
+ case 'noop':
338
+ // intentionally empty: used for holes inside HTML comments
339
+ break;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Walk a slot element's parent chain looking for a WebComponent host
345
+ * (an element that has slot state initialised). Used by the slot-part's
346
+ * apply and teardown steps to coordinate with slot.js.
347
+ *
348
+ * @param {HTMLSlotElement} slotEl
349
+ * @returns {Element | null}
350
+ */
351
+ export function findSlotHost(slotEl) {
352
+ // Template-owner stamp wins (a forwarded slot's true host), else the
353
+ // nearest SLOT_STATE ancestor structurally.
354
+ const owner = /** @type any */ (slotEl)[SLOT_OWNER];
355
+ if (owner && owner.isConnected) return owner;
356
+ let p = slotEl.parentElement;
357
+ while (p) {
358
+ if (/** @type any */ (p)[SLOT_STATE]) return p;
359
+ p = p.parentElement;
360
+ }
361
+ return null;
362
+ }
363
+
364
+ /**
365
+ * True when an element is inside a shadow root (so native browser slot
366
+ * projection applies). Mirrors slot.js's helper; duplicated here to
367
+ * avoid the round trip through the slot.js public surface for this
368
+ * hot path.
369
+ * @param {Element} el
370
+ * @returns {boolean}
371
+ */
372
+ export function isInShadowRootEl(el) {
373
+ let n = /** @type {Node} */ (el);
374
+ for (let depth = 0; depth < 128; depth++) {
375
+ const parent = n.parentNode;
376
+ if (!parent) return false;
377
+ if (parent === n) return false;
378
+ // A real ShadowRoot is a DocumentFragment (nodeType 11) exposing its
379
+ // owner as `.host`. Checking `.host` truthiness ALONE misfires on
380
+ // ordinary elements: HTMLAnchorElement/HTMLAreaElement expose a
381
+ // URL-derived `.host` ('example.com'), so a slot nested inside an
382
+ // <a> card was misread as shadow DOM and its light-DOM application
383
+ // silently skipped (surfaced by #1015's removal of the redundant
384
+ // observer repair paths that used to mask it).
385
+ if (parent.nodeType === 11 && /** @type any */ (parent).host) return true;
386
+ n = parent;
387
+ }
388
+ return false;
389
+ }
390
+
391
+ /**
392
+ * Child (text-position) part. Replace the marker's surrounding nodes with the
393
+ * new value's rendered form. Nested TemplateResults get an instance with its
394
+ * own parts; we reuse on `strings` identity.
395
+ *
396
+ * @param {Extract<BoundPart, {kind:'child'}>} part
397
+ * @param {unknown} value
398
+ */
399
+ /**
400
+ * Apply a value at an element-position part (`<tag ${expr}>`). The
401
+ * sole supported directive here is `ref(refOrCallback)` and
402
+ * `createRef()`. Other values are ignored so a stray non-ref hole
403
+ * doesn't crash. Tracks the prior target so a change from one ref to
404
+ * another correctly unsets the old target before binding the new one.
405
+ *
406
+ * @param {Extract<BoundPart, {kind:'element'}>} part
407
+ * @param {unknown} value
408
+ */
409
+ export function applyElement(part, value) {
410
+ // Matches lit-html's RefDirective.update():
411
+ // 1. If the ref target changed since last render, unbind the prior one.
412
+ // 2. If the ref target OR the element identity changed, bind the new
413
+ // (ref, element) pair. If both are stable, skip entirely.
414
+ // For callback refs, an unset-before-bind cycle runs whenever the
415
+ // same callback is now pointing at a different element.
416
+ const partAny = /** @type any */ (part);
417
+ const nextTarget = isRef(value) ? /** @type any */ (value).target : undefined;
418
+ const prevTarget = partAny.__refTarget;
419
+ const refChanged = nextTarget !== prevTarget;
420
+
421
+ if (refChanged && prevTarget) {
422
+ if (typeof prevTarget === 'function') {
423
+ try { prevTarget(undefined); } catch {}
424
+ } else if (typeof prevTarget === 'object') {
425
+ prevTarget.value = undefined;
426
+ }
427
+ }
428
+
429
+ if (refChanged || partAny.__refElement !== part.el) {
430
+ partAny.__refTarget = nextTarget;
431
+ if (nextTarget) {
432
+ if (typeof nextTarget === 'function') {
433
+ // Same callback now pointing at a different element: deliver
434
+ // an `undefined` cleanup for the prior element first.
435
+ if (!refChanged && partAny.__refElement !== undefined) {
436
+ try { nextTarget(undefined); } catch {}
437
+ }
438
+ try { nextTarget(part.el); } catch {}
439
+ } else if (typeof nextTarget === 'object') {
440
+ nextTarget.value = part.el;
441
+ }
442
+ }
443
+ partAny.__refElement = part.el;
444
+ // Keep the legacy `lastTarget` field in sync for clearInstance /
445
+ // disposeInstance which read it for template-disposal cleanup.
446
+ part.lastTarget = nextTarget;
447
+ }
448
+ }
449
+
450
+ export function applyChild(part, value, reconcileFormActionsCb) {
451
+ // Drop directive state from prior renders when the new value is for a
452
+ // different directive (or no directive at all). Keeps __untilState
453
+ // from leaking across replacements, __guardDeps from causing a stale
454
+ // short-circuit, etc. Done once per outermost applyChild call; the
455
+ // directive handlers recurse via applyChildInner (no re-clear) so
456
+ // their own state survives the recursion.
457
+ clearStaleDirectiveState(part, value);
458
+ return applyChildInner(part, value, reconcileFormActionsCb);
459
+ }
460
+
461
+ /**
462
+ * Internal dispatch. Used both by `applyChild` (which first clears
463
+ * stale per-part directive state) and by directive handlers that
464
+ * recurse with a different value at the same part. Recursing via
465
+ * `applyChild` would clear the directive state that was just set,
466
+ * because the inner value almost always isn't itself a directive.
467
+ *
468
+ * @param {Extract<BoundPart, {kind:'child'}>} part
469
+ * @param {unknown} value
470
+ */
471
+ export function applyChildInner(part, value, reconcileFormActionsCb) {
472
+ // Open the renderer-write window around this commit. Most calls are
473
+ // synchronous inside render() (the window is already open, this nests
474
+ // harmlessly), but the async directive paths (until, watch, asyncAppend /
475
+ // asyncReplace, streaming) re-enter here from a promise / microtask OUTSIDE
476
+ // any render() window, so this is where those commits into a light host are
477
+ // marked as renderer writes rather than authored content.
478
+ return commitInto(part.marker && part.marker.parentNode, () =>
479
+ applyChildInnerRaw(part, value, reconcileFormActionsCb),
480
+ );
481
+ }
482
+
483
+ /**
484
+ * @param {Extract<BoundPart, {kind:'child'}>} part
485
+ * @param {unknown} value
486
+ */
487
+ export function applyChildInnerRaw(part, value, reconcileFormActionsCb) {
488
+ const marker = part.marker;
489
+
490
+ // unsafeHTML directive: inject raw HTML string as DOM nodes.
491
+ if (isUnsafeHTML(value)) {
492
+ teardownChild(part);
493
+ const htmlStr = String(/** @type any */ (value).value ?? '');
494
+ const template = document.createElement('template');
495
+ template.innerHTML = htmlStr;
496
+ const nodes = [...template.content.childNodes];
497
+ const frag = document.createDocumentFragment();
498
+ for (const n of nodes) frag.appendChild(n);
499
+ marker.parentNode?.insertBefore(frag, marker);
500
+ part.child = nodes;
501
+ return;
502
+ }
503
+
504
+ // keyed directive: when key changes, tear down and remount fresh DOM.
505
+ // When the key matches, recurse so the standard template-reconciliation
506
+ // path can update the existing DOM in place.
507
+ if (isKeyed(value)) {
508
+ const v = /** @type any */ (value);
509
+ const prevKey = /** @type any */ (part).__keyedKey;
510
+ if (prevKey !== undefined && !Object.is(prevKey, v.key)) {
511
+ teardownChild(part);
512
+ }
513
+ /** @type any */ (part).__keyedKey = v.key;
514
+ applyChildInner(part, v.value, reconcileFormActionsCb);
515
+ return;
516
+ }
517
+
518
+ // guard directive: skip re-evaluation when the deps array is shallow-
519
+ // equal to the prior call. Stored deps live on the part so they
520
+ // persist across renders that reuse the same template (and thus the
521
+ // same part).
522
+ if (isGuard(value)) {
523
+ const v = /** @type any */ (value);
524
+ const prevDeps = /** @type any */ (part).__guardDeps;
525
+ const nextDeps = v.deps;
526
+ // Accept any value for deps. When deps is an array, compare shallowly.
527
+ // When it's a primitive (number, string, undefined), compare with
528
+ // Object.is. Mirrors lit-html's tolerance for non-array deps so user
529
+ // code like `guard(this.id, () => ...)` works without crashing.
530
+ if (prevDeps !== undefined) {
531
+ const equal = Array.isArray(prevDeps) && Array.isArray(nextDeps)
532
+ ? shallowEqualArray(prevDeps, nextDeps)
533
+ : Object.is(prevDeps, nextDeps);
534
+ if (equal) return;
535
+ }
536
+ // Snapshot the deps BEFORE running `fn` (so a fn that mutates the array
537
+ // it was handed cannot rewrite what we record), but RECORD them only
538
+ // after the commit succeeds. Recording first meant a throw part-way
539
+ // through the commit left the region torn down with the NEW deps already
540
+ // stored, so every later render with the same deps hit the `equal`
541
+ // short-circuit above and skipped the region forever. Renders are always
542
+ // microtask-scheduled (`_scheduleUpdate`), so `fn()` cannot re-enter this
543
+ // part synchronously and see the stale deps.
544
+ const depsSnapshot = Array.isArray(nextDeps) ? nextDeps.slice() : nextDeps;
545
+ applyChildInner(part, v.fn(), reconcileFormActionsCb);
546
+ /** @type any */ (part).__guardDeps = depsSnapshot;
547
+ return;
548
+ }
549
+
550
+ // templateContent directive: clone the content of a <template> element.
551
+ if (isTemplateContent(value)) {
552
+ teardownChild(part);
553
+ const tpl = /** @type any */ (value).template;
554
+ if (tpl && tpl.content) {
555
+ const frag = tpl.content.cloneNode(true);
556
+ const nodes = [...frag.childNodes];
557
+ marker.parentNode?.insertBefore(frag, marker);
558
+ part.child = nodes;
559
+ }
560
+ return;
561
+ }
562
+
563
+ // ref directive in a child position: no DOM produced. Element-position
564
+ // refs are bound via element parts; a stray ref() in a child position
565
+ // is a no-op for compatibility.
566
+ if (isRef(value)) {
567
+ return;
568
+ }
569
+
570
+ // cache directive: real DOM retention. When the inner value changes
571
+ // to a different template shape, detach (rather than destroy) the
572
+ // current DOM and stash it keyed by its template strings. When a
573
+ // previously-cached shape returns, re-attach it before the marker
574
+ // and reconcile values. Preserves input state, scroll, focus across
575
+ // toggles between sub-templates (e.g. tab interfaces).
576
+ if (isCache(value)) {
577
+ return applyCache(part, /** @type any */ (value).value, reconcileFormActionsCb);
578
+ }
579
+
580
+ // until directive: render the highest-priority resolved value among
581
+ // the candidates. Synchronous values are rendered immediately; Promises
582
+ // are awaited in the background and applied if no higher-priority
583
+ // candidate has resolved yet. When the marker is torn down, in-flight
584
+ // priorities are cleared so late resolves cannot overwrite later DOM.
585
+ if (isUntil(value)) {
586
+ return applyUntil(part, /** @type any */ (value).args, reconcileFormActionsCb);
587
+ }
588
+
589
+ // watch directive: bind a part to a signal. Reads the signal at
590
+ // render time and subscribes the part to changes. When the signal
591
+ // fires, only this part updates; the host component's render() does
592
+ // not re-run. The signal read inside the watcher's observe is
593
+ // tracked against the part's private Watcher, NOT the host's render
594
+ // watcher (so the host doesn't subscribe to a full re-render too).
595
+ if (isWatch(value)) {
596
+ return applyWatch(part, /** @type any */ (value).signal, reconcileFormActionsCb);
597
+ }
598
+
599
+ // asyncAppend / asyncReplace: subscribe to the AsyncIterable. Each
600
+ // yielded value is mapped (optional) and appended (asyncAppend) or
601
+ // replaces (asyncReplace) the prior content. Teardown aborts the
602
+ // iteration so leaked iterators do not keep references to detached
603
+ // DOM.
604
+ if (isAsyncAppend(value)) {
605
+ return applyAsyncAppend(part, /** @type any */ (value), reconcileFormActionsCb);
606
+ }
607
+ if (isAsyncReplace(value)) {
608
+ return applyAsyncReplace(part, /** @type any */ (value), reconcileFormActionsCb);
609
+ }
610
+
611
+ // Repeat directive: keyed reconciliation. Keep previous state when both
612
+ // old and new are repeats; otherwise tear down and rebuild.
613
+ if (isRepeat(value)) {
614
+ if (part.child && /** @type any */ (part.child).kind === 'repeat') {
615
+ reconcileRepeat(part, value, reconcileFormActionsCb);
616
+ return;
617
+ }
618
+ teardownChild(part);
619
+ const state = { kind: 'repeat', map: new Map() };
620
+ part.child = state;
621
+ applyRepeatFresh(marker, state, value, reconcileFormActionsCb);
622
+ return;
623
+ }
624
+
625
+ // Plain array (a `.map()` / list interpolation): positional, non-keyed
626
+ // reconciliation. Update each position's instance IN PLACE when its
627
+ // template shape is unchanged, so DOM node identity survives an item
628
+ // update (focus, selection, scroll, and an in-progress native drag all
629
+ // survive). Mirrors lit-html's non-keyed array child part. Without this,
630
+ // flipping one item's binding rebuilt the WHOLE list and detached every
631
+ // node, which cancels a native drag mid-gesture. Use `repeat()` for keyed
632
+ // reordering.
633
+ if (Array.isArray(value)) {
634
+ if (part.child && /** @type any */ (part.child).kind === 'array') {
635
+ reconcileArray(part, value, reconcileFormActionsCb);
636
+ return;
637
+ }
638
+ teardownChild(part);
639
+ const arrState = { kind: 'array', items: [] };
640
+ part.child = arrState;
641
+ applyArrayFresh(marker, /** @type any */ (arrState), value, reconcileFormActionsCb);
642
+ return;
643
+ }
644
+
645
+ // Remove previously rendered nodes between marker and its next sibling we own.
646
+ if (part.child) {
647
+ const c = /** @type any */ (part.child);
648
+ if (c.kind === 'repeat') {
649
+ teardownRepeat(c);
650
+ part.child = undefined;
651
+ } else if (c.kind === 'array') {
652
+ teardownArray(/** @type any */ (c));
653
+ part.child = undefined;
654
+ } else if (c.kind === 'async-stream') {
655
+ teardownAsyncStream(c);
656
+ part.child = undefined;
657
+ } else if ('strings' in /** @type any */ (part.child)) {
658
+ // Previous was a TemplateInstance.
659
+ const inst = /** @type TemplateInstance */ (part.child);
660
+ if (isTemplate(value) && inst.strings === /** @type any */ (value).strings) {
661
+ updateInstance(inst, /** @type any */ (value).values, reconcileFormActionsCb);
662
+ return;
663
+ }
664
+ removeBetween(inst.startNode, inst.endNode);
665
+ part.child = undefined;
666
+ } else {
667
+ // Previous was ChildNode[]: remove each node we inserted.
668
+ for (const n of /** @type ChildNode[] */ (part.child)) {
669
+ if (n.parentNode) n.parentNode.removeChild(n);
670
+ }
671
+ part.child = undefined;
672
+ }
673
+ }
674
+
675
+ if (value == null || value === false || value === true) return;
676
+
677
+ if (isTemplate(value)) {
678
+ const tr = /** @type any */ (value);
679
+ const { templateEl, parts, formActions } = compile(tr);
680
+ const frag = /** @type DocumentFragment */ (templateEl.content.cloneNode(true));
681
+ const startNode = document.createComment(`${MARKER}s`);
682
+ const endNode = document.createComment(`${MARKER}e`);
683
+ const bound = parts.map((p) => bindPart(p, frag));
684
+ const lastValues = [];
685
+ for (let i = 0; i < tr.values.length; i++) {
686
+ applyPart(bound[i], tr.values[i], undefined, tr.values, reconcileFormActionsCb);
687
+ lastValues.push(tr.values[i]);
688
+ }
689
+ if (reconcileFormActionsCb) reconcileFormActionsCb(formActions, bound, tr.values);
690
+ const nodes = [startNode, ...frag.childNodes, endNode];
691
+ marker.parentNode?.insertBefore(nodesToFrag(nodes), marker);
692
+ // Slot parts in this nested template need their one-shot apply just
693
+ // like createInstance does for top-level templates. The slot is now
694
+ // in the live tree (insertBefore above) so its parent walk can
695
+ // reach the host. Without this loop, conditional / nested templates
696
+ // with <slot> inside never trigger projection.
697
+ for (const p of bound) {
698
+ if (p.kind === 'slot') applyPart(p, undefined, undefined, [], reconcileFormActionsCb);
699
+ }
700
+ part.child = { strings: tr.strings, bound, lastValues, startNode, endNode };
701
+ return;
702
+ }
703
+
704
+ const node = document.createTextNode(String(value));
705
+ marker.parentNode?.insertBefore(node, marker);
706
+ part.child = [node];
707
+ }
708
+
709
+ export function updateInstance(inst, values, reconcileFormActionsCb) {
710
+ for (let i = 0; i < values.length; i++) {
711
+ const next = values[i];
712
+ if (Object.is(next, inst.lastValues[i])) continue;
713
+ const bp = inst.bound[i];
714
+ // A hole that belongs to a mixed attribute (`class="a ${x} b ${y}"`) is a
715
+ // `noop` pointing at the attribute's anchor part; re-apply the anchor so the
716
+ // whole attribute is rebuilt from every hole's current value, not just the
717
+ // anchor hole's. Without this, a change confined to a non-anchor hole is
718
+ // dropped (the attribute goes stale).
719
+ const anchor = /** @type any */ (bp).mixedAnchor;
720
+ try {
721
+ if (bp.kind === 'noop' && anchor != null) {
722
+ applyPart(inst.bound[anchor], values[anchor], inst.lastValues[anchor], values, reconcileFormActionsCb);
723
+ } else {
724
+ applyPart(bp, next, inst.lastValues[i], values, reconcileFormActionsCb);
725
+ }
726
+ } catch (err) {
727
+ // A commit that throws leaves `lastValues` for THIS hole un-advanced,
728
+ // still holding the value from before the throw. That is almost always
729
+ // the value the recovering render supplies, so the `Object.is` skip at
730
+ // the top of this loop would skip the hole FOREVER. Harmless for an
731
+ // attribute (its commit stringifies before touching the DOM, so nothing
732
+ // changed), and permanently destructive for a child position, whose
733
+ // commit tears the old content down BEFORE the step that throws: the
734
+ // region is left empty and never re-rendered.
735
+ //
736
+ // Poison the entry with a sentinel no author value can ever be, so the
737
+ // next render always re-applies this hole. The value is deliberately
738
+ // NOT advanced to `next` either, since `next` was never committed.
739
+ inst.lastValues[i] = COMMIT_FAILED;
740
+ if (bp.kind === 'noop' && anchor != null) inst.lastValues[anchor] = COMMIT_FAILED;
741
+ throw err;
742
+ }
743
+ inst.lastValues[i] = next;
744
+ }
745
+ // Unconditional, and NOT inside the loop above: a form's correctness depends
746
+ // on holes other than its own, and the `Object.is` skip means the action hole
747
+ // may not have been re-applied at all this pass.
748
+ if (reconcileFormActionsCb) reconcileFormActionsCb(templateCache.get(inst.strings)?.formActions ?? null, inst.bound, values);
749
+ }
750
+
751
+ /**
752
+ * Sentinel parked in `lastValues` for a hole whose commit threw, so the next
753
+ * render cannot mistake the un-advanced entry for "already applied". Never
754
+ * equal (by `Object.is`) to anything an author can pass through a template.
755
+ */
756
+ const COMMIT_FAILED = Symbol('webjs.commitFailed');
757
+
758
+ /**
759
+ * Remove a template instance's whole range, its bookend markers INCLUDED.
760
+ *
761
+ * Every caller discards the instance right after: the map entry or slot that
762
+ * held it is dropped, and a replacement, where there is one, is built with
763
+ * markers of its own. So this is a REMOVE, never lit's clear-and-reuse. A
764
+ * caller that wants to keep the bookends and render into them again needs its
765
+ * OWN function, because the two want opposite answers for the end marker.
766
+ *
767
+ * `parent` is read BEFORE the walk because the walk removes `start` on its
768
+ * first iteration, which nulls `start.parentNode`. Reading it afterwards
769
+ * compared the end marker's live parent against `null`, so the guard could
770
+ * never fire and every teardown left one `wjm-e` comment in the document,
771
+ * unbounded for the life of the region.
772
+ *
773
+ * The `end.parentNode === parent` comparison is a refusal, not a formality. A
774
+ * marker moved under a different parent is not this region's to remove, and
775
+ * `parent.removeChild(end)` on it throws NotFoundError from inside a teardown
776
+ * that has to stay total.
777
+ *
778
+ * The walk assumes the range is INTACT: it steps `nextSibling` from `start`
779
+ * and stops on `end`, so a range whose end no longer follows its start runs
780
+ * off the child list and takes the part's own marker with it. That is not
781
+ * something this function defends against, before or after the parent capture,
782
+ * and the consequence is spelled out where it bites, on `reconcileRepeat`'s
783
+ * catch below. The guard is the narrower promise: whatever the walk did, a
784
+ * marker that is somewhere else is left alone.
785
+ *
786
+ * @param {Node} start @param {Node} end
787
+ */
788
+ export function removeBetween(start, end) {
789
+ const parent = start.parentNode;
790
+ if (!parent) return;
791
+ let n = start;
792
+ while (n && n !== end) {
793
+ const next = n.nextSibling;
794
+ n.parentNode?.removeChild(n);
795
+ n = next;
796
+ }
797
+ if (end.parentNode === parent) parent.removeChild(end);
798
+ }
799
+
800
+ /* ================================================================
801
+ * Keyed list (repeat) support
802
+ * ================================================================ */
803
+
804
+ /** @param {ChildNode[]} nodes */
805
+ export function nodesToFrag(nodes) {
806
+ const frag = document.createDocumentFragment();
807
+ for (const n of nodes) frag.appendChild(n);
808
+ return frag;
809
+ }
810
+
811
+ /**
812
+ * Build a TemplateInstance whose nodes (including bookends) live in a
813
+ * document fragment that the caller will insert wherever it wants.
814
+ * @param {import('../html.js').TemplateResult} tr
815
+ * @returns {{ inst: TemplateInstance, frag: DocumentFragment }}
816
+ */
817
+ export function buildDetached(tr, reconcileFormActionsCb) {
818
+ const { templateEl, parts, formActions } = compile(tr);
819
+ const frag = /** @type DocumentFragment */ (templateEl.content.cloneNode(true));
820
+ const startNode = document.createComment(`${MARKER}s`);
821
+ const endNode = document.createComment(`${MARKER}e`);
822
+ const bound = parts.map((p) => bindPart(p, frag));
823
+ const lastValues = [];
824
+ for (let i = 0; i < tr.values.length; i++) {
825
+ applyPart(bound[i], tr.values[i], undefined, tr.values, reconcileFormActionsCb);
826
+ lastValues.push(tr.values[i]);
827
+ }
828
+ if (reconcileFormActionsCb) reconcileFormActionsCb(formActions, bound, tr.values);
829
+ // Slot parts need their one-shot apply exactly like createInstance and the
830
+ // nested-template path. The fragment is still detached here, so the
831
+ // slot-part's own deferred finalize (a one-microtask retry when the parent
832
+ // walk cannot reach a host yet) carries it: every caller inserts the
833
+ // returned fragment synchronously in the same task, so the retry lands in
834
+ // the live tree. Without this loop a <slot> inside a repeat() / array item
835
+ // never finalizes and its content is never placeable.
836
+ for (const p of bound) {
837
+ if (p.kind === 'slot') applyPart(p, undefined, undefined, [], reconcileFormActionsCb);
838
+ }
839
+ const outFrag = document.createDocumentFragment();
840
+ outFrag.appendChild(startNode);
841
+ while (frag.firstChild) outFrag.appendChild(frag.firstChild);
842
+ outFrag.appendChild(endNode);
843
+ return {
844
+ inst: { strings: tr.strings, bound, lastValues, startNode, endNode },
845
+ frag: outFrag,
846
+ };
847
+ }
848
+
849
+ /** @param {TemplateInstance} inst */
850
+ export function disposeInstance(inst) {
851
+ for (const p of inst.bound) {
852
+ if (p.kind === 'event') p.el.removeEventListener(p.name, p.dispatcher);
853
+ if (p.kind === 'element') {
854
+ // Unbind any active ref so the user observes the element being
855
+ // removed (callback receives undefined / Ref.value cleared).
856
+ // Mirrors lit-html's cleanup-on-disconnect for element parts.
857
+ //
858
+ // BOTH branches swallow, and lit is not the reason: lit's ref directive
859
+ // guards neither, so a throw there propagates. The reason is that a
860
+ // teardown has to be TOTAL. `lastTarget` is cleared only AFTER these
861
+ // writes, so a throw leaves the part still pointing at the ref and
862
+ // every later teardown of the same instance throws at the same line
863
+ // forever. It also aborts the rest of this loop, so the remaining
864
+ // parts keep their listeners and their refs bound. A teardown has no
865
+ // retry either (a commit has the COMMIT_FAILED sentinel and a next
866
+ // render; this does not), so there is nothing a propagated error could
867
+ // usefully repair.
868
+ //
869
+ // The object branch is the one this adds. The callback branch was
870
+ // already guarded here AND on the commit path (`applyElement` wraps
871
+ // every `nextTarget(...)` / `prevTarget(undefined)` call), so a
872
+ // throwing ref CALLBACK has always been swallowed everywhere. What was
873
+ // inconsistent is the object ref, guarded on neither. This makes the
874
+ // two agree on TEARDOWN, which is where the totality argument bites.
875
+ // It does NOT touch the commit path, so `applyElement`'s object-ref
876
+ // writes still propagate to the component boundary, which has a route
877
+ // for the error and a next render to repair it.
878
+ const prev = /** @type any */ (p).lastTarget;
879
+ if (prev) {
880
+ if (typeof prev === 'function') {
881
+ try { prev(undefined); } catch {}
882
+ } else if (typeof prev === 'object') {
883
+ try { prev.value = undefined; } catch {}
884
+ }
885
+ /** @type any */ (p).lastTarget = undefined;
886
+ /** @type any */ (p).__lastEl = undefined;
887
+ }
888
+ }
889
+ }
890
+ }
891
+
892
+ /**
893
+ * Initial fresh render of a repeat directive. Inserts all items' nodes
894
+ * immediately before the part's marker comment.
895
+ *
896
+ * @param {Comment} marker
897
+ * @param {{ kind: 'repeat', map: Map<any, TemplateInstance> }} state
898
+ * @param {any} value
899
+ */
900
+ function applyRepeatFresh(marker, state, value, reconcileFormActionsCb) {
901
+ const { items, keyFn, templateFn } = value;
902
+ const parent = marker.parentNode;
903
+ if (!parent) return;
904
+ const bulk = document.createDocumentFragment();
905
+ for (let i = 0; i < items.length; i++) {
906
+ const key = keyFn(items[i], i);
907
+ const tr = templateFn(items[i], i);
908
+ if (!isTemplate(tr)) continue;
909
+ const { inst, frag } = buildDetached(/** @type any */ (tr), reconcileFormActionsCb);
910
+ state.map.set(key, inst);
911
+ bulk.appendChild(frag);
912
+ }
913
+ parent.insertBefore(bulk, marker);
914
+ }
915
+
916
+ /**
917
+ * Keyed reconciliation. For each key in the new list:
918
+ * - hit: update the existing instance in place (if template shape matches),
919
+ * then move its nodes into position
920
+ * - miss: build a new instance and insert
921
+ * Finally drop instances whose keys aren't in the new list.
922
+ *
923
+ * @param {Extract<BoundPart, {kind:'child'}>} part
924
+ * @param {any} value
925
+ */
926
+ function reconcileRepeat(part, value, reconcileFormActionsCb) {
927
+ const marker = part.marker;
928
+ const parent = marker.parentNode;
929
+ if (!parent) return;
930
+ const state = /** @type {{ kind: 'repeat', map: Map<any, TemplateInstance> }} */ (part.child);
931
+ const { items, keyFn, templateFn } = value;
932
+ const newMap = new Map();
933
+
934
+ try {
935
+ // Walk the new list and position each item's nodes immediately before the marker.
936
+ for (let i = 0; i < items.length; i++) {
937
+ const key = keyFn(items[i], i);
938
+ const tr = templateFn(items[i], i);
939
+ if (!isTemplate(tr)) continue;
940
+ const existing = state.map.get(key);
941
+ if (existing && existing.strings === /** @type any */ (tr).strings) {
942
+ updateInstance(existing, /** @type any */ (tr).values, reconcileFormActionsCb);
943
+ // Move nodes before marker preserving element identity.
944
+ moveRange(existing.startNode, existing.endNode, parent, marker);
945
+ newMap.set(key, existing);
946
+ state.map.delete(key);
947
+ } else {
948
+ if (existing) {
949
+ // Unmapped BEFORE the row is touched, for the reason spelled out
950
+ // in the leftover loop below: a key kept across a refused removal
951
+ // points at a half-removed row, and reusing that row later walks
952
+ // the removal off the end of the region. Same ordering, same
953
+ // trade, and the two have to agree or the invariant the catch
954
+ // relies on holds on one branch and not the other.
955
+ state.map.delete(key);
956
+ disposeInstance(existing);
957
+ removeBetween(existing.startNode, existing.endNode);
958
+ }
959
+ const { inst, frag } = buildDetached(/** @type any */ (tr), reconcileFormActionsCb);
960
+ parent.insertBefore(frag, marker);
961
+ newMap.set(key, inst);
962
+ }
963
+ }
964
+
965
+ // Remove any keys that remain in the old map. The key leaves the map
966
+ // BEFORE its row is touched and the removal is in a `finally`, so at any
967
+ // throw point `state.map` holds exactly the leftovers this pass has not
968
+ // reached, and a row whose dispose threw still leaves the document.
969
+ // Iterating a snapshot keeps the delete obviously safe rather than
970
+ // relying on the reader knowing that deleting during a Map iteration is
971
+ // legal.
972
+ for (const [k, inst] of [...state.map]) {
973
+ state.map.delete(k);
974
+ try {
975
+ disposeInstance(inst);
976
+ } finally {
977
+ removeBetween(inst.startNode, inst.endNode);
978
+ }
979
+ }
980
+ state.map = newMap;
981
+ } catch (err) {
982
+ // The walk moves DOM and drains `state.map` incrementally while the
983
+ // replacement map is accumulated locally, so a throw part-way through
984
+ // leaves NEITHER map describing what is on screen: the already-processed
985
+ // keys sit only in `newMap`, which is about to be discarded, while their
986
+ // nodes stay in the document tracked by nothing. The next (perfectly
987
+ // valid) render then rebuilds those keys from scratch and the orphaned
988
+ // originals are never removed, so the list shows duplicated rows forever
989
+ // with nothing logged after the first throw.
990
+ //
991
+ // Re-unite every instance still in the document under `state.map` (the
992
+ // two maps are disjoint: a key lands in `newMap` only after being deleted
993
+ // from `state.map`), so the map describes the DOM again and nothing is
994
+ // orphaned. That is the whole repair. The next render is then an ORDINARY
995
+ // reconcile against a truthful map, which repositions every row and
996
+ // re-applies whatever the throw skipped.
997
+ //
998
+ // That claim covers the REMOVAL loop as well as the walk, and only
999
+ // because the loop was written to earn it. It drops each key before
1000
+ // touching that row and removes the nodes in a `finally`, so a throw
1001
+ // mid-removal cannot merge `newMap` over a `state.map` still holding
1002
+ // disposed, detached rows. That was the failure: the row the app DELETED
1003
+ // stayed on screen, the survivors reordered, and a later render that
1004
+ // re-added that key reinserted the detached instance. The invariant, at
1005
+ // any throw point on either branch: every instance this pass has not
1006
+ // destructively touched is described by exactly one of the two maps,
1007
+ // `newMap` for the processed new keys and `state.map` for the leftovers
1008
+ // not reached yet, which is what makes the merge below correct. The
1009
+ // exception is the row named in the residual just below, whose removal
1010
+ // refused part-way; that one is in neither map, by choice.
1011
+ //
1012
+ // The residual is a throw from `removeBetween` ITSELF, which only calls
1013
+ // `removeChild` on nodes the renderer owns, so it takes a throwing DOM to
1014
+ // reach. That row is already unmapped, so its remaining nodes stay in the
1015
+ // document tracked by nothing and a later re-add of that key builds a
1016
+ // second row beside them. Unmapping AFTER the removal instead would keep
1017
+ // that key, and it is measurably worse rather than better: the row is
1018
+ // half removed, its start marker gone and its end marker still in place,
1019
+ // so the re-add hits the reuse branch and `moveRange` re-attaches the
1020
+ // lone start marker AFTER the end marker. The next removal of that key
1021
+ // then walks forward from a start that never reaches its end, taking the
1022
+ // repeat part's own marker and every following sibling with it, and the
1023
+ // region is dead for good. One untracked row beats a destroyed list.
1024
+ //
1025
+ // Deliberately NOT a teardown-and-rebuild of the region. Rebuilding is
1026
+ // the obvious defensive move and it is measurably worse: it discards node
1027
+ // identity for every row, which is the exact cost keyed reconciliation
1028
+ // exists to avoid (see the plain-array note below, a rebuild cancels an
1029
+ // in-progress native drag). It is also unnecessary, because this map is
1030
+ // restored to the truth rather than left describing a DOM that moved, so
1031
+ // there is nothing to guess and no partial DOM move to unwind.
1032
+ //
1033
+ // That is only half of it, and the other half does NOT live here: the row
1034
+ // whose own commit threw is repaired by the COMMIT_FAILED sentinel in
1035
+ // `updateInstance`, not by anything below. Without it the failed hole
1036
+ // compares EQUAL on the next render (its `lastValues` entry never
1037
+ // advanced past the throw, so it still holds the value that render
1038
+ // supplies) and is skipped forever, which for a child position means the
1039
+ // row stays permanently blank. Do not remove the sentinel on the theory
1040
+ // that a half-updated instance heals itself; it does not.
1041
+ for (const [k, inst] of newMap) state.map.set(k, inst);
1042
+ throw err;
1043
+ }
1044
+ }
1045
+
1046
+ /** @param {{ kind: 'repeat', map: Map<any, TemplateInstance> }} state */
1047
+ function teardownRepeat(state) {
1048
+ // Same delete-as-you-go shape as the leftover loop in `reconcileRepeat`,
1049
+ // for the same reason: a throw part-way must not leave already-removed
1050
+ // instances in the map. The trailing `clear()` stays as a no-op safety net.
1051
+ for (const [k, inst] of [...state.map]) {
1052
+ state.map.delete(k);
1053
+ try {
1054
+ disposeInstance(inst);
1055
+ } finally {
1056
+ removeBetween(inst.startNode, inst.endNode);
1057
+ }
1058
+ }
1059
+ state.map.clear();
1060
+ }
1061
+
1062
+ /* ================================================================
1063
+ * Plain array (.map) support: positional, non-keyed reconciliation
1064
+ * ================================================================ */
1065
+
1066
+ /**
1067
+ * One rendered slot of a plain array. A `tpl` carries a detached template
1068
+ * instance (bookended by its own markers), a `text` carries a single text
1069
+ * node, and an `empty` slot (a nullish / boolean element) renders nothing
1070
+ * but still holds the position so index-based reconciliation stays aligned.
1071
+ * @typedef {{ type: 'tpl', inst: TemplateInstance } | { type: 'text', node: Text } | { type: 'empty' }} ArrayItem
1072
+ */
1073
+
1074
+ /** @param {ArrayItem} item @returns {ChildNode | null} */
1075
+ function arrayItemFirstNode(item) {
1076
+ if (item.type === 'tpl') return item.inst.startNode;
1077
+ if (item.type === 'text') return item.node;
1078
+ return null;
1079
+ }
1080
+
1081
+ /** @param {ArrayItem} item */
1082
+ function removeArrayItem(item) {
1083
+ if (item.type === 'tpl') {
1084
+ disposeInstance(item.inst);
1085
+ removeBetween(item.inst.startNode, item.inst.endNode);
1086
+ } else if (item.type === 'text') {
1087
+ item.node.parentNode?.removeChild(item.node);
1088
+ }
1089
+ }
1090
+
1091
+ /**
1092
+ * Build the slot for one array element, plus the fragment to insert (null
1093
+ * for an empty slot). A TemplateResult becomes a detached instance, a
1094
+ * primitive becomes a text node, and nullish / boolean renders nothing.
1095
+ * @param {unknown} v
1096
+ * @returns {{ item: ArrayItem, frag: Node | null }}
1097
+ */
1098
+ function buildArrayItem(v, reconcileFormActionsCb) {
1099
+ if (isTemplate(v)) {
1100
+ const { inst, frag } = buildDetached(/** @type any */ (v), reconcileFormActionsCb);
1101
+ return { item: { type: 'tpl', inst }, frag };
1102
+ }
1103
+ if (v != null && v !== false && v !== true) {
1104
+ const node = document.createTextNode(String(v));
1105
+ return { item: { type: 'text', node }, frag: node };
1106
+ }
1107
+ return { item: { type: 'empty' }, frag: null };
1108
+ }
1109
+
1110
+ /**
1111
+ * Initial render of a plain array: insert every slot's nodes before the marker.
1112
+ * @param {Comment} marker
1113
+ * @param {{ kind: 'array', items: ArrayItem[] }} state
1114
+ * @param {unknown[]} value
1115
+ */
1116
+ function applyArrayFresh(marker, state, value, reconcileFormActionsCb) {
1117
+ const parent = marker.parentNode;
1118
+ if (!parent) return;
1119
+ const bulk = document.createDocumentFragment();
1120
+ /** @type {ArrayItem[]} */
1121
+ const items = [];
1122
+ for (const v of value) {
1123
+ const { item, frag } = buildArrayItem(v, reconcileFormActionsCb);
1124
+ if (frag) bulk.appendChild(frag);
1125
+ items.push(item);
1126
+ }
1127
+ parent.insertBefore(bulk, marker);
1128
+ state.items = items;
1129
+ }
1130
+
1131
+ /**
1132
+ * Positional (non-keyed) reconciliation. For each index, update the slot
1133
+ * in place when its shape is unchanged (preserving DOM node identity),
1134
+ * otherwise replace it; grow or shrink at the tail. There is no key
1135
+ * matching, so a reorder reduces to a series of in-place value updates;
1136
+ * reach for `repeat()` when element identity must follow a moved key.
1137
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1138
+ * @param {unknown[]} value
1139
+ */
1140
+ function reconcileArray(part, value, reconcileFormActionsCb) {
1141
+ const marker = part.marker;
1142
+ const parent = marker.parentNode;
1143
+ if (!parent) return;
1144
+ const state = /** @type {{ kind: 'array', items: ArrayItem[] }} */ (part.child);
1145
+ const old = state.items;
1146
+ /** @type {ArrayItem[]} */
1147
+ const next = [];
1148
+ // How many slots of `old` are fully processed. Tracked rather than inferred
1149
+ // from `next.length`, because the shrink loop below advances through `old`
1150
+ // while `next` stops growing, so the two part company there. The catch is
1151
+ // the only reader.
1152
+ let consumed = 0;
1153
+
1154
+ try {
1155
+ for (let i = 0; i < value.length; i++) {
1156
+ const v = value[i];
1157
+ const o = old[i];
1158
+ if (isTemplate(v)) {
1159
+ const tr = /** @type any */ (v);
1160
+ if (o && o.type === 'tpl' && o.inst.strings === tr.strings) {
1161
+ updateInstance(o.inst, tr.values, reconcileFormActionsCb);
1162
+ next.push(o);
1163
+ consumed = i + 1;
1164
+ continue;
1165
+ }
1166
+ } else if (v != null && v !== false && v !== true) {
1167
+ if (o && o.type === 'text') {
1168
+ const str = String(v);
1169
+ if (o.node.data !== str) o.node.data = str;
1170
+ next.push(o);
1171
+ consumed = i + 1;
1172
+ continue;
1173
+ }
1174
+ } else {
1175
+ // Empty slot: drop any prior nodes that occupied this position.
1176
+ // Deliberately NOT reordered like the branch below. That reorder
1177
+ // exists to keep a slot that was already BUILT and INSERTED tracked,
1178
+ // and this branch builds and inserts nothing, so pushing first would
1179
+ // only mean a throw from the removal leaves a phantom empty slot at
1180
+ // this index AND `old[i]` spliced in at the next one, shifting every
1181
+ // later slot by one in a POSITIONAL reconciler. Removing first, a
1182
+ // throw here leaves `old[i]` describing its own position, which is
1183
+ // still exactly where its nodes are.
1184
+ if (o) removeArrayItem(o);
1185
+ next.push({ type: 'empty' });
1186
+ consumed = i + 1;
1187
+ continue;
1188
+ }
1189
+ // Shape changed, or the array grew past the old length. Build fresh,
1190
+ // insert at this position (before the current / next still-attached
1191
+ // old node, else the marker), then drop the old slot it replaced.
1192
+ // The push sits BEFORE the removal, which is a pure reordering on the
1193
+ // success path and means a slot that has already been built and
1194
+ // inserted is never untracked at any throw point.
1195
+ const { item, frag } = buildArrayItem(v, reconcileFormActionsCb);
1196
+ if (frag) parent.insertBefore(frag, nextArrayAnchor(old, i, marker));
1197
+ next.push(item);
1198
+ if (o) removeArrayItem(o);
1199
+ consumed = i + 1;
1200
+ }
1201
+
1202
+ // Shrink: remove slots beyond the new length.
1203
+ for (let i = value.length; i < old.length; i++) {
1204
+ removeArrayItem(old[i]);
1205
+ consumed = i + 1;
1206
+ }
1207
+ state.items = next;
1208
+ } catch (err) {
1209
+ // `state.items` is committed only after the whole walk, so a throw part
1210
+ // way through discards `next` entirely: the map of slots keeps describing
1211
+ // positions whose nodes were already removed, while the freshly built and
1212
+ // inserted ones are in the document tracked by nothing. Nothing is logged
1213
+ // after the first throw, and the orphan outlives even a render of an EMPTY
1214
+ // array, because the only code that could remove it walks `state.items`.
1215
+ //
1216
+ // Splice the untouched tail of `old` onto what `next` accumulated, so the
1217
+ // bookkeeping describes the DOM again. The invariant that holds at any
1218
+ // throw point: every live node is described by exactly one slot, the
1219
+ // slots below `next.length` being the rebuilt or reused ones and the rest
1220
+ // the part of `old` this pass never reached. Index alignment survives
1221
+ // because this reconciler is POSITIONAL, so a slot's index IS its
1222
+ // identity, which is also why the boundary has to come from `consumed`
1223
+ // rather than `next.length`: during the shrink loop those differ, and
1224
+ // splicing from `next.length` would re-describe slots already removed.
1225
+ // A later render that grew the array would then match a live value
1226
+ // against a DETACHED slot with the same `strings`, update it in place,
1227
+ // and that row would silently never appear.
1228
+ //
1229
+ // Deliberately NOT a teardown-and-rebuild of the region, for the reason
1230
+ // recorded on `reconcileRepeat`'s catch above: it discards node identity
1231
+ // for every row, which cancels an in-progress native drag and drops focus
1232
+ // and scroll.
1233
+ //
1234
+ // The residual is a throw from the removal step itself, which takes a
1235
+ // throwing DOM to reach (the teardown it calls is total, so only
1236
+ // `removeBetween` is left, and that calls `removeChild` solely on nodes
1237
+ // the renderer owns). State it rather than deny it: `removeBetween`
1238
+ // takes the start marker first and then early-returns for good once that
1239
+ // marker is gone, so a row whose removal refused part-way can never be
1240
+ // removed afterwards. Its remaining nodes stay in the document, and an
1241
+ // EMPTY render will not clear them. Tracked or not, they are there for
1242
+ // the life of the region, the same residual `reconcileRepeat`'s catch
1243
+ // names. What this repair buys is that there is only ONE such row and
1244
+ // every other slot still reconciles, where before the whole pass was
1245
+ // discarded.
1246
+ state.items = next.concat(old.slice(consumed));
1247
+ throw err;
1248
+ }
1249
+ }
1250
+
1251
+ /**
1252
+ * The node a freshly-built slot at index `i` inserts before: the first
1253
+ * node of the current or next still-attached old slot, else the part
1254
+ * marker (a tail append).
1255
+ * @param {ArrayItem[]} old @param {number} i @param {Comment} marker
1256
+ * @returns {ChildNode}
1257
+ */
1258
+ function nextArrayAnchor(old, i, marker) {
1259
+ for (let j = i; j < old.length; j++) {
1260
+ const f = arrayItemFirstNode(old[j]);
1261
+ if (f && f.parentNode) return f;
1262
+ }
1263
+ return marker;
1264
+ }
1265
+
1266
+ /** @param {{ kind: 'array', items: ArrayItem[] }} state */
1267
+ function teardownArray(state) {
1268
+ for (const it of state.items) removeArrayItem(it);
1269
+ state.items = [];
1270
+ }
1271
+
1272
+ /**
1273
+ * Collect [start .. end] (inclusive) and insert immediately before `anchor`.
1274
+ * Browsers treat insertBefore of an already-connected node as a move and
1275
+ * preserve element identity + focus.
1276
+ *
1277
+ * @param {Node} start
1278
+ * @param {Node} end
1279
+ * @param {Node} parent
1280
+ * @param {Node} anchor
1281
+ */
1282
+ export function moveRange(start, end, parent, anchor) {
1283
+ // No-op if the range is already immediately before the anchor.
1284
+ if (end.nextSibling === anchor && start.parentNode === parent) return;
1285
+ const frag = document.createDocumentFragment();
1286
+ let n = start;
1287
+ while (n) {
1288
+ const next = n.nextSibling;
1289
+ frag.appendChild(n);
1290
+ if (n === end) break;
1291
+ n = next;
1292
+ }
1293
+ parent.insertBefore(frag, anchor);
1294
+ }
1295
+
1296
+ /**
1297
+ * Shallow array equality (Object.is on each element). Used by the
1298
+ * `guard` directive to skip re-evaluation when deps are unchanged.
1299
+ * @param {readonly unknown[]} a
1300
+ * @param {readonly unknown[]} b
1301
+ */
1302
+ function shallowEqualArray(a, b) {
1303
+ if (a === b) return true;
1304
+ if (!a || !b || a.length !== b.length) return false;
1305
+ for (let i = 0; i < a.length; i++) {
1306
+ if (!Object.is(a[i], b[i])) return false;
1307
+ }
1308
+ return true;
1309
+ }
1310
+
1311
+ /** @param {Extract<BoundPart, {kind:'child'}>} part */
1312
+ export function teardownChild(part) {
1313
+ // Always abort any in-flight directive state on the part, even if
1314
+ // `part.child` itself is something else (e.g. an `until` directive
1315
+ // installed __untilState but applyChild's recursion overwrote
1316
+ // part.child to the rendered fallback shape).
1317
+ const partAny = /** @type any */ (part);
1318
+ if (partAny.__untilState) {
1319
+ partAny.__untilState.aborted = true;
1320
+ partAny.__untilState = undefined;
1321
+ }
1322
+ if (partAny.__watchSub) {
1323
+ teardownWatch(partAny);
1324
+ }
1325
+
1326
+ if (!part.child) return;
1327
+ const c = /** @type any */ (part.child);
1328
+ if (c.kind === 'repeat') {
1329
+ teardownRepeat(c);
1330
+ } else if (c.kind === 'array') {
1331
+ teardownArray(c);
1332
+ } else if (c.kind === 'async-stream') {
1333
+ teardownAsyncStream(c);
1334
+ } else if ('strings' in c) {
1335
+ const inst = /** @type TemplateInstance */ (part.child);
1336
+ disposeInstance(inst);
1337
+ removeBetween(inst.startNode, inst.endNode);
1338
+ } else {
1339
+ for (const n of /** @type ChildNode[] */ (part.child)) {
1340
+ if (n.parentNode) n.parentNode.removeChild(n);
1341
+ }
1342
+ }
1343
+ part.child = undefined;
1344
+ }
1345
+
1346
+ /**
1347
+ * Clear per-part directive state slots that don't apply to the value
1348
+ * currently being rendered. Prevents stale `__guardDeps` from short-
1349
+ * circuiting a render when the directive at this position is no longer
1350
+ * a guard, stale `__cacheMap` from accumulating across non-cache
1351
+ * renders, and stale `__untilState` from letting a prior Promise
1352
+ * resolution overwrite newer DOM.
1353
+ *
1354
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1355
+ * @param {unknown} value
1356
+ */
1357
+ export function clearStaleDirectiveState(part, value) {
1358
+ const partAny = /** @type any */ (part);
1359
+ if (partAny.__untilState && !isUntil(value)) {
1360
+ partAny.__untilState.aborted = true;
1361
+ partAny.__untilState = undefined;
1362
+ }
1363
+ if (partAny.__guardDeps !== undefined && !isGuard(value)) {
1364
+ partAny.__guardDeps = undefined;
1365
+ }
1366
+ if (partAny.__cacheMap && !isCache(value)) {
1367
+ partAny.__cacheMap = undefined;
1368
+ }
1369
+ if (partAny.__keyedKey !== undefined && !isKeyed(value)) {
1370
+ partAny.__keyedKey = undefined;
1371
+ }
1372
+ if (partAny.__watchSub && !isWatch(value)) {
1373
+ teardownWatch(partAny);
1374
+ }
1375
+ }
1376
+
1377
+ /* ================================================================
1378
+ * Cache directive: detach + retain prior template instances so that
1379
+ * toggling between sub-templates preserves their DOM state.
1380
+ * ================================================================ */
1381
+
1382
+ /**
1383
+ * Apply the `cache` directive at a child position. The cache is stored
1384
+ * on the part as `__cacheMap: Map<strings, { inst, holderFrag }>`.
1385
+ *
1386
+ * When the new inner value is a template whose `strings` already lives
1387
+ * in the cache map, re-attach the stashed nodes before the marker and
1388
+ * reconcile values against the new template. When the new inner is a
1389
+ * template whose strings aren't cached, stash the currently-attached
1390
+ * instance (if any) into the cache map before rendering the new one.
1391
+ *
1392
+ * Non-template inner values fall through to the generic applyChild path
1393
+ * (after first stashing any currently-attached cached instance).
1394
+ *
1395
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1396
+ * @param {unknown} inner
1397
+ */
1398
+ function applyCache(part, inner, reconcileFormActionsCb) {
1399
+ const marker = part.marker;
1400
+ const partAny = /** @type any */ (part);
1401
+ /** @type {Map<TemplateStringsArray, { inst: TemplateInstance, holder: DocumentFragment }>} */
1402
+ let cacheMap = partAny.__cacheMap;
1403
+ if (!cacheMap) {
1404
+ cacheMap = new Map();
1405
+ partAny.__cacheMap = cacheMap;
1406
+ }
1407
+
1408
+ const currentChild = /** @type any */ (part.child);
1409
+ const currentIsInstance = currentChild && 'strings' in currentChild;
1410
+
1411
+ // If the currently-attached child IS a template instance, decide
1412
+ // whether to update-in-place, stash for later, or destroy.
1413
+ if (currentIsInstance) {
1414
+ const currentInst = /** @type TemplateInstance */ (currentChild);
1415
+ // Same template structure: reconcile values, no detach/re-attach.
1416
+ if (isTemplate(inner) && currentInst.strings === /** @type any */ (inner).strings) {
1417
+ updateInstance(currentInst, /** @type any */ (inner).values, reconcileFormActionsCb);
1418
+ return;
1419
+ }
1420
+ // Different shape: detach the current instance into a holder fragment
1421
+ // and store it in the cache map. We keep the existing instance, slot
1422
+ // markers, and rendered nodes; only the parent changes. moveRange's
1423
+ // null anchor means "append to parent".
1424
+ const holder = document.createDocumentFragment();
1425
+ moveRange(currentInst.startNode, currentInst.endNode, holder, null);
1426
+ cacheMap.set(currentInst.strings, { inst: currentInst, holder });
1427
+ part.child = undefined;
1428
+ }
1429
+ // Now part.child is either undefined or some non-instance shape (rare;
1430
+ // happens when prior render had a string / array / etc.). For non-
1431
+ // instance shapes, fall through to the generic teardown via applyChild.
1432
+
1433
+ // If the new inner is a template AND we've cached an instance for its
1434
+ // strings, re-attach it.
1435
+ if (isTemplate(inner)) {
1436
+ const tr = /** @type any */ (inner);
1437
+ const cached = cacheMap.get(tr.strings);
1438
+ if (cached) {
1439
+ cacheMap.delete(tr.strings);
1440
+ // Tear down any non-instance child currently attached (a string /
1441
+ // array of text nodes from a prior cache(non-template) render).
1442
+ // Without this the prior nodes remain in the DOM alongside the
1443
+ // re-attached cached template.
1444
+ if (part.child) {
1445
+ teardownChild(part);
1446
+ }
1447
+ // Move the cached nodes back before the marker.
1448
+ moveRange(cached.inst.startNode, cached.inst.endNode, /** @type Node */ (marker.parentNode), marker);
1449
+ // Reconcile values so any state changes since detachment apply.
1450
+ updateInstance(cached.inst, tr.values, reconcileFormActionsCb);
1451
+ part.child = cached.inst;
1452
+ // A re-attached instance may carry ALREADY-APPLIED slot parts, whose
1453
+ // finalize will never fire again, while the host's record moved on
1454
+ // during the stash (content for these slots was parked when an apply
1455
+ // ran with the slot unreachable). Re-run the apply for each owning
1456
+ // host so parked content is pulled back out. The collection walks the
1457
+ // re-attached DOM RANGE (not the instance tree): slot parts live on
1458
+ // whatever template level contains the <slot> (nested holes, repeat /
1459
+ // array items, streamed chunks), so a structural DOM walk is the only
1460
+ // shape that covers every composition uniformly. moveRange already
1461
+ // ran, so the range is live and each slot's parent walk reaches its
1462
+ // host.
1463
+ const hosts = new Set();
1464
+ for (
1465
+ let n = cached.inst.startNode.nextSibling;
1466
+ n && n !== cached.inst.endNode;
1467
+ n = n.nextSibling
1468
+ ) {
1469
+ if (n.nodeType !== 1) continue;
1470
+ const el = /** @type {Element} */ (n);
1471
+ if (el.matches('slot[data-webjs-light]')) {
1472
+ const h = findSlotHost(el);
1473
+ if (h) hosts.add(h);
1474
+ }
1475
+ for (const s of el.querySelectorAll('slot[data-webjs-light]')) {
1476
+ const h = findSlotHost(s);
1477
+ if (h) hosts.add(h);
1478
+ }
1479
+ }
1480
+ for (const h of hosts) applySlotAssignments(h);
1481
+ return;
1482
+ }
1483
+ }
1484
+
1485
+ // No cached instance available. Render the new inner value via the
1486
+ // standard applyChild path. The currentIsInstance branch already
1487
+ // handled detaching the prior instance; if part.child still holds a
1488
+ // non-instance shape, applyChild will tear it down generically.
1489
+ applyChildInner(part, inner, reconcileFormActionsCb);
1490
+ }
1491
+
1492
+ /**
1493
+ * Apply the `until` directive at a child position.
1494
+ *
1495
+ * Priority is left-to-right: args[0] has the highest priority. The
1496
+ * highest-priority synchronous candidate (if any) renders immediately.
1497
+ * Strictly-higher-priority Promises are awaited in the background; when
1498
+ * one resolves AND no higher-priority Promise has already resolved, its
1499
+ * result becomes the rendered value.
1500
+ *
1501
+ * The directive's state lives on `part.__untilState` (a stable slot
1502
+ * that survives `applyChild`'s overwrites of `part.child`). When a new
1503
+ * render replaces the directive, the prior state's `aborted` flag flips
1504
+ * to `true` so any in-flight Promise resolutions short-circuit instead
1505
+ * of overwriting newer DOM.
1506
+ *
1507
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1508
+ * @param {readonly unknown[]} args
1509
+ */
1510
+ function applyUntil(part, args, reconcileFormActionsCb) {
1511
+ // Carry forward the prior render's `highestResolved` ONLY when the
1512
+ // args list is unchanged. When any argument identity changes, prior
1513
+ // priorities no longer apply (a Promise that won at index 0 may now
1514
+ // sit at a different index, or have been replaced entirely); the
1515
+ // state must reset to Infinity so the new args' Promises can compete.
1516
+ //
1517
+ // For TemplateResult args, compare by `strings` array identity rather
1518
+ // than the wrapper object identity. `html\`loading...\`` evaluates to
1519
+ // a fresh TemplateResult on every call but the strings array is
1520
+ // interned per call site, so the conceptual value is unchanged.
1521
+ const partAny = /** @type any */ (part);
1522
+ // Same as applyWatch: the promise handlers below commit with no render on
1523
+ // the stack, so the owning component is recorded here while it is knowable.
1524
+ if (currentRenderRoot) partAny.__commitOwner = boundaryOwnerOf(currentRenderRoot);
1525
+ const prevState = partAny.__untilState;
1526
+ const prevArgs = partAny.__untilArgs;
1527
+ const argEq = (a, b) => {
1528
+ if (Object.is(a, b)) return true;
1529
+ if (isTemplate(a) && isTemplate(b)
1530
+ && /** @type any */ (a).strings === /** @type any */ (b).strings) return true;
1531
+ return false;
1532
+ };
1533
+ const argsEqual = prevArgs && prevArgs.length === args.length
1534
+ && prevArgs.every((a, i) => argEq(a, args[i]));
1535
+ const carriedHighest = argsEqual && prevState ? prevState.highestResolved : Infinity;
1536
+ if (prevState) prevState.aborted = true;
1537
+ partAny.__untilArgs = args.slice();
1538
+
1539
+ /** @type {{aborted:boolean, highestResolved:number}} */
1540
+ const state = { aborted: false, highestResolved: carriedHighest };
1541
+ partAny.__untilState = state;
1542
+
1543
+ // Highest-priority synchronous candidate. If found, render it now
1544
+ // and cap further Promise subscription to strictly-higher priorities.
1545
+ let firstSyncIdx = -1;
1546
+ let firstSyncVal = undefined;
1547
+ for (let i = 0; i < args.length; i++) {
1548
+ const a = args[i];
1549
+ if (!a || typeof (/** @type any */ (a).then) !== 'function') {
1550
+ firstSyncIdx = i;
1551
+ firstSyncVal = a;
1552
+ break;
1553
+ }
1554
+ }
1555
+
1556
+ if (firstSyncIdx !== -1 && firstSyncIdx <= state.highestResolved) {
1557
+ // The sync candidate beats any previously-rendered Promise value
1558
+ // (when firstSyncIdx < state.highestResolved) OR re-renders the
1559
+ // sync fallback at the same priority slot (when ===), in case its
1560
+ // value changed between renders.
1561
+ applyChildInner(part, firstSyncVal, reconcileFormActionsCb);
1562
+ state.highestResolved = firstSyncIdx;
1563
+ } else if (firstSyncIdx === -1 && !partAny.__untilEverRendered) {
1564
+ // First-ever render of this part with all-Promise args: render
1565
+ // empty as the initial fallback while Promises settle.
1566
+ applyChildInner(part, '', reconcileFormActionsCb);
1567
+ }
1568
+ // Else: either there is no sync candidate but the part has rendered
1569
+ // before (preserve existing DOM until a Promise resolves), OR the
1570
+ // sync candidate is lower-priority than what's already rendered.
1571
+ // Either way: leave the existing DOM in place. This prevents the
1572
+ // "all-Promises wipes prior content" flash on re-renders.
1573
+ partAny.__untilEverRendered = true;
1574
+
1575
+ // Subscribe to Promises with priority strictly less than what's
1576
+ // currently rendered. (Lower index = higher priority in lit's model.)
1577
+ // Each subscription wraps in Promise.resolve() so synchronous
1578
+ // thenables get a microtask boundary, matching lit's contract that
1579
+ // all Promise/thenable resolutions are deferred.
1580
+ const cap = firstSyncIdx === -1
1581
+ ? Math.min(args.length, state.highestResolved)
1582
+ : Math.min(firstSyncIdx, state.highestResolved);
1583
+ for (let i = 0; i < cap; i++) {
1584
+ const a = args[i];
1585
+ if (!a || typeof (/** @type any */ (a).then) !== 'function') continue;
1586
+
1587
+ Promise.resolve(/** @type Promise<unknown> */ (a)).then(
1588
+ (resolved) => {
1589
+ if (state.aborted) return;
1590
+ if (i >= state.highestResolved) return;
1591
+ // Commit FIRST, record the new priority only once it succeeded.
1592
+ // Advancing `highestResolved` up front meant a commit throw left the
1593
+ // region torn down while the state claimed index `i` had won, so
1594
+ // every later resolution at a lower priority was refused and the
1595
+ // region stayed empty. Committing first also keeps the throw inside
1596
+ // the try, where it can reach the component boundary.
1597
+ try {
1598
+ commitOutOfBand(part, () => applyChildInner(part, resolved, reconcileFormActionsCb));
1599
+ } catch (err) {
1600
+ reportOutOfBandCommitError(part, err);
1601
+ return;
1602
+ }
1603
+ state.highestResolved = i;
1604
+ },
1605
+ // Swallow rejection. A rejected Promise is treated as "no value";
1606
+ // the existing render stays in place.
1607
+ () => {},
1608
+ );
1609
+ }
1610
+ }
1611
+
1612
+ /**
1613
+ * Route a throw from an OUT-OF-BAND commit to the owning component's
1614
+ * render-error boundary.
1615
+ *
1616
+ * `watch`'s notify microtask and `until`'s Promise resolution commit from
1617
+ * outside `component.js`'s update cycle, so none of the boundaries that wrap
1618
+ * every other render path are on the stack. Left alone, a commit throw there
1619
+ * escapes as a window-level `error` / unhandled rejection instead of the
1620
+ * per-component `renderError()` the sync and async render paths both route
1621
+ * to, which breaks per-component error isolation for exactly these two
1622
+ * directives.
1623
+ *
1624
+ * Reads the owner stamped on the part when the directive was installed. See
1625
+ * the note in the body for why this is not a walk up the parent chain.
1626
+ *
1627
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1628
+ * @param {unknown} error
1629
+ */
1630
+ export function reportOutOfBandCommitError(part, error) {
1631
+ let err;
1632
+ try {
1633
+ err = error instanceof Error ? error : new Error(String(error));
1634
+ } catch {
1635
+ // The thrown value's own `toString` threw. That is the exact class of
1636
+ // value that makes a commit throw in the first place, so it is reachable
1637
+ // here; do not let stringifying it mask the original failure.
1638
+ err = new Error('render error (unstringifiable thrown value)');
1639
+ }
1640
+ // The owner stamped when the directive was installed, which is the
1641
+ // component whose TEMPLATE holds this part. Never walk the parent chain
1642
+ // for this: `_handleRenderError` lives on WebComponent's prototype, so
1643
+ // every upgraded element on the way up carries one, and the FIRST one a
1644
+ // structural walk meets is the innermost element the part happens to sit
1645
+ // inside, not the template that owns it. Routing there is not merely the
1646
+ // wrong log line: a light-DOM component's renderError() commits into the
1647
+ // component itself, which would replace the very children holding this
1648
+ // part's markers and silently kill every later update through it.
1649
+ const owner = /** @type any */ (part).__commitOwner;
1650
+ if (owner && typeof owner._handleRenderError === 'function') {
1651
+ owner._handleRenderError(err);
1652
+ return;
1653
+ }
1654
+ // No component boundary owns this part (a bare `render()` into a plain
1655
+ // container). Nothing can contain the error, so surface it rather than
1656
+ // swallow it.
1657
+ throw err;
1658
+ }
1659
+
1660
+ /**
1661
+ * Bind a child part to a signal. Reads the signal once and writes its
1662
+ * value into the part. Installs a per-part `Signal.subtle.Watcher`
1663
+ * that, on signal change, re-reads and re-applies the value WITHOUT
1664
+ * re-running the host component's render(). When the part is torn
1665
+ * down (teardownChild) the watcher is disposed.
1666
+ *
1667
+ * The signal read happens inside the watcher's `observe()`, so the
1668
+ * dependency edge connects the signal to THIS watcher. The host's
1669
+ * own render watcher is outside the active stack here, so the host
1670
+ * does not also subscribe to the signal (which would double-fire as
1671
+ * both a full re-render and a watch update).
1672
+ *
1673
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1674
+ * @param {{ get: () => unknown, __isSignal: true }} sig
1675
+ */
1676
+ function applyWatch(part, sig, reconcileFormActionsCb) {
1677
+ const partAny = /** @type any */ (part);
1678
+ // Record the owning component while we are still inside its render(), the
1679
+ // only moment it is knowable. The notify microtask below commits with no
1680
+ // render on the stack and no way to derive it. Keep a prior stamp if this
1681
+ // somehow runs outside a render, rather than clearing a good owner.
1682
+ if (currentRenderRoot) partAny.__commitOwner = boundaryOwnerOf(currentRenderRoot);
1683
+ // Same signal as last render: refresh dep tracking via observe (the
1684
+ // spec-aligned Watcher fires once per arm, so re-observing re-arms).
1685
+ if (partAny.__watchSig === sig && partAny.__watchSub) {
1686
+ let value;
1687
+ partAny.__watchSub.observe(() => { value = sig.get(); });
1688
+ applyChildInner(part, value, reconcileFormActionsCb);
1689
+ return;
1690
+ }
1691
+ // Signal changed (or first render). Tear down any prior watcher.
1692
+ if (partAny.__watchSub) {
1693
+ partAny.__watchSub.dispose();
1694
+ partAny.__watchSub = undefined;
1695
+ }
1696
+ partAny.__watchSig = sig;
1697
+ // Notify defers to a microtask because the spec forbids signal reads
1698
+ // inside the notify itself. The microtask re-observes (re-arms + re-
1699
+ // records the dep) and applies the new value to the part.
1700
+ const watcher = new Signal.subtle.Watcher(() => {
1701
+ queueMicrotask(() => {
1702
+ if (partAny.__watchSub !== watcher) return;
1703
+ let v;
1704
+ // Nothing above this microtask catches: it runs outside the host's
1705
+ // update cycle, so a commit throw here would surface at the window
1706
+ // instead of the component's renderError(). Route it explicitly.
1707
+ try {
1708
+ watcher.observe(() => { v = sig.get(); });
1709
+ commitOutOfBand(part, () => applyChildInner(part, v, reconcileFormActionsCb));
1710
+ } catch (err) {
1711
+ reportOutOfBandCommitError(part, err);
1712
+ }
1713
+ });
1714
+ });
1715
+ partAny.__watchSub = watcher;
1716
+ let initial;
1717
+ watcher.observe(() => { initial = sig.get(); });
1718
+ applyChildInner(part, initial, reconcileFormActionsCb);
1719
+ }
1720
+
1721
+ /**
1722
+ * Dispose a `watch` directive's per-part watcher. Called from
1723
+ * `teardownChild` and from `clearStaleDirectiveState` when the value
1724
+ * at the part is no longer a watch.
1725
+ * @param {any} partAny
1726
+ */
1727
+ function teardownWatch(partAny) {
1728
+ if (partAny.__watchSub) {
1729
+ partAny.__watchSub.dispose();
1730
+ partAny.__watchSub = undefined;
1731
+ partAny.__watchSig = undefined;
1732
+ }
1733
+ }
1734
+
1735
+ /* ================================================================
1736
+ * asyncAppend / asyncReplace: stream from AsyncIterable.
1737
+ * ================================================================ */
1738
+
1739
+ /**
1740
+ * Apply `asyncAppend(iterable, mapper?)` at a child position.
1741
+ *
1742
+ * Iterates the AsyncIterable in the background. Each yielded value is
1743
+ * mapped (optional) and rendered as a node group, appended before the
1744
+ * marker. The state is stored on `part.child` so `teardownChild` can
1745
+ * abort the iteration when the part is reset.
1746
+ *
1747
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1748
+ * @param {{ iterable: AsyncIterable<unknown>, mapper?: (v: unknown, i: number) => unknown }} dir
1749
+ */
1750
+ function applyAsyncAppend(part, dir, reconcileFormActionsCb) {
1751
+ const partAny = /** @type any */ (part);
1752
+ // Record the owning component while we are still inside its render(), the
1753
+ // only moment it is knowable, exactly as `applyWatch` / `applyUntil` do.
1754
+ // Chunks commit from an async loop with no render on the stack, so without
1755
+ // this both the chunk's own commit throw and any directive nested inside a
1756
+ // chunk have no owner to route to. Stamped ABOVE the short-circuit so a
1757
+ // re-render that returns early still refreshes the owner, and guarded so a
1758
+ // re-install outside a render keeps a previously good one.
1759
+ if (currentRenderRoot) partAny.__commitOwner = boundaryOwnerOf(currentRenderRoot);
1760
+ // Same-iterable short-circuit: if the prior render's iterable identity
1761
+ // matches, the existing iterator is still consuming it. Re-subscribing
1762
+ // would start a fresh iterator that misses already-yielded values.
1763
+ // Matches lit-html's behavior.
1764
+ const currentChild = /** @type any */ (part.child);
1765
+ if (currentChild && currentChild.kind === 'async-stream'
1766
+ && currentChild.mode === 'append'
1767
+ && currentChild.iterable === dir.iterable) {
1768
+ return;
1769
+ }
1770
+
1771
+ teardownChild(part);
1772
+
1773
+ const iterator = /** @type AsyncIterator<unknown> */ (
1774
+ dir.iterable[Symbol.asyncIterator]()
1775
+ );
1776
+ /** @type {AsyncStreamState} */
1777
+ const state = {
1778
+ kind: 'async-stream',
1779
+ mode: 'append',
1780
+ aborted: false,
1781
+ iterable: dir.iterable,
1782
+ iterator,
1783
+ /** @type {ChildNode[]} */ nodes: [],
1784
+ };
1785
+ part.child = state;
1786
+
1787
+ consumeAsyncStream(state, part, dir, reconcileFormActionsCb);
1788
+ }
1789
+
1790
+ /**
1791
+ * Apply `asyncReplace(iterable, mapper?)` at a child position. Same as
1792
+ * `applyAsyncAppend` but each new value replaces the previous content.
1793
+ *
1794
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1795
+ * @param {{ iterable: AsyncIterable<unknown>, mapper?: (v: unknown, i: number) => unknown }} dir
1796
+ */
1797
+ function applyAsyncReplace(part, dir, reconcileFormActionsCb) {
1798
+ const partAny = /** @type any */ (part);
1799
+ // Owner stamp: see comment in applyAsyncAppend. Above the short-circuit.
1800
+ if (currentRenderRoot) partAny.__commitOwner = boundaryOwnerOf(currentRenderRoot);
1801
+ // Same-iterable short-circuit: see comment in applyAsyncAppend.
1802
+ const currentChild = /** @type any */ (part.child);
1803
+ if (currentChild && currentChild.kind === 'async-stream'
1804
+ && currentChild.mode === 'replace'
1805
+ && currentChild.iterable === dir.iterable) {
1806
+ return;
1807
+ }
1808
+
1809
+ teardownChild(part);
1810
+
1811
+ const iterator = /** @type AsyncIterator<unknown> */ (
1812
+ dir.iterable[Symbol.asyncIterator]()
1813
+ );
1814
+ /** @type {AsyncStreamState} */
1815
+ const state = {
1816
+ kind: 'async-stream',
1817
+ mode: 'replace',
1818
+ aborted: false,
1819
+ iterable: dir.iterable,
1820
+ iterator,
1821
+ /** @type {ChildNode[]} */ nodes: [],
1822
+ };
1823
+ part.child = state;
1824
+
1825
+ consumeAsyncStream(state, part, dir, reconcileFormActionsCb);
1826
+ }
1827
+
1828
+ /**
1829
+ * @typedef {{
1830
+ * kind: 'async-stream',
1831
+ * mode: 'append' | 'replace',
1832
+ * aborted: boolean,
1833
+ * iterable: AsyncIterable<unknown>,
1834
+ * iterator: AsyncIterator<unknown>,
1835
+ * nodes: ChildNode[],
1836
+ * }} AsyncStreamState
1837
+ */
1838
+ /**
1839
+ * Consume an AsyncIterable for `asyncAppend` / `asyncReplace`. Drives
1840
+ * the iterator with an explicit `.next()` loop (rather than `for await`)
1841
+ * so that `teardownAsyncStream` can call `iterator.return()` to break
1842
+ * a generator parked on an `await`. The `aborted` flag is also checked
1843
+ * after every `next()` resolve to short-circuit if abortion happened
1844
+ * while the iterator was suspended.
1845
+ *
1846
+ * Each pass carries TWO try spans, and which failure lands in which is the
1847
+ * load-bearing part. SPAN A is the author's own code, the iterable AND the
1848
+ * `mapper` it was given, and a throw from either is logged to the console and
1849
+ * ends the stream, on the long-standing reasoning that an author's iterable
1850
+ * should handle its own errors. SPAN B is the chunk COMMIT, which is a render
1851
+ * failure of the component whose template holds the binding, so it routes to
1852
+ * that component's `renderError()` and stops the stream.
1853
+ *
1854
+ * Scope note: only a throw from the COMMIT can stop the stream from here. A
1855
+ * directive nested INSIDE a committed chunk (a `watch` whose signal changes
1856
+ * later) throws from its own handler, outside this loop entirely, so it
1857
+ * reaches the boundary but this loop knows nothing about it and keeps
1858
+ * pulling. That is the same for any directive nested anywhere else. lit is no authority
1859
+ * either way here (it has no per-component boundary, and both failures become
1860
+ * unhandled rejections at the window), so this follows the
1861
+ * per-component error isolation WebJs has instead.
1862
+ *
1863
+ * @param {AsyncStreamState} state
1864
+ * @param {Extract<BoundPart, {kind:'child'}>} part
1865
+ * @param {{ iterable: AsyncIterable<unknown>, mapper?: (v: unknown, i: number) => unknown }} dir
1866
+ */
1867
+ async function consumeAsyncStream(state, part, dir, reconcileFormActionsCb) {
1868
+ const marker = part.marker;
1869
+ let i = 0;
1870
+ while (!state.aborted) {
1871
+ /** @type {IteratorResult<unknown>} */
1872
+ let result;
1873
+ /** @type {unknown} */
1874
+ let mapped;
1875
+ // SPAN A, the author's iterable. A throw here is the author's generator
1876
+ // failing, not a render, so it keeps the long-standing console.error and
1877
+ // ends the stream. It is a separate span from the commit below on purpose
1878
+ // rather than a flag the one catch inspects, because the distinction is
1879
+ // the whole point: `reportOutOfBandCommitError` RETHROWS for a part with
1880
+ // no owner, and a single enclosing try would hand that rethrow straight
1881
+ // back to this swallow, which is the escape this split exists to stop.
1882
+ try {
1883
+ result = await state.iterator.next();
1884
+ if (state.aborted) break;
1885
+ if (result.done) break;
1886
+ mapped = dir.mapper ? dir.mapper(result.value, i) : result.value;
1887
+ } catch (err) {
1888
+ // Note this ENDS the stream, and always has: the catch used to sit
1889
+ // outside the loop, so there has never been a resume path here.
1890
+ if (typeof console !== 'undefined') console.error('[webjs] asyncStream error:', err);
1891
+ return;
1892
+ }
1893
+
1894
+ // SPAN B, the chunk commit. This is a render of the component whose
1895
+ // TEMPLATE holds the binding, so a throw is that component's render
1896
+ // failure and routes to its `renderError()`, the same as `watch` and
1897
+ // `until` already do from their own out-of-band commits. `renderToNodes`
1898
+ // is INSIDE the wrap because that is where a nested directive is
1899
+ // installed and reads `currentRenderRoot`; without it, a `watch()` inside
1900
+ // a chunk is stamped with no owner and its later throw escapes.
1901
+ // `commitInto` is a different concern (the renderer-write window for a
1902
+ // light slot host), so the two nest rather than replace each other.
1903
+ try {
1904
+ commitOutOfBand(part, () => {
1905
+ const newNodes = renderToNodes(mapped, reconcileFormActionsCb);
1906
+
1907
+ // This chunk commit runs in an async loop OUTSIDE any render() window,
1908
+ // so open the renderer-write window explicitly: without it, committing a
1909
+ // stream chunk into a light slot host would hit the patched insertBefore /
1910
+ // removeChild and fold the renderer's own output into `authored`.
1911
+ commitInto(marker.parentNode, () => {
1912
+ if (state.mode === 'replace') {
1913
+ for (const n of state.nodes) {
1914
+ if (n.parentNode) n.parentNode.removeChild(n);
1915
+ }
1916
+ state.nodes = [];
1917
+ }
1918
+
1919
+ const frag = document.createDocumentFragment();
1920
+ for (const n of newNodes) frag.appendChild(n);
1921
+ marker.parentNode?.insertBefore(frag, marker);
1922
+ state.nodes.push(...newNodes);
1923
+ });
1924
+ });
1925
+ } catch (err) {
1926
+ // Stop the stream. The boundary is about to render an error state, and
1927
+ // appending later chunks into a region it may have replaced is not a
1928
+ // recovery. The rendered nodes are left alone: blanking the region is a
1929
+ // separate decision, and `teardownAsyncStream` is for the part being
1930
+ // reset, not for this.
1931
+ state.aborted = true;
1932
+ try { state.iterator.return?.()?.catch?.(() => {}); } catch {}
1933
+ // Rethrows when nothing can receive the error, which for a bare
1934
+ // `render()` into a plain container is an owner that carries no
1935
+ // `_handleRenderError` (the stamp records the container itself, so the
1936
+ // owner is present, just not a component). Surfacing beats swallowing
1937
+ // there, and it matches `watch` and `until`, which rethrow from their
1938
+ // own out-of-band handlers for the same reason. The exact shape differs
1939
+ // by site rather than being one thing: this rejects the loop's
1940
+ // promise, `until` rejects from its `.then`, and `watch` throws inside
1941
+ // a `queueMicrotask`, which is an uncaught error rather than a
1942
+ // rejection.
1943
+ reportOutOfBandCommitError(part, err);
1944
+ return;
1945
+ }
1946
+
1947
+ i++;
1948
+ }
1949
+ }
1950
+
1951
+ /**
1952
+ * Render a single value into a flat list of DOM nodes for insertion via
1953
+ * insertBefore. Handles strings, numbers, TemplateResult, and arrays.
1954
+ * @param {unknown} value
1955
+ * @returns {ChildNode[]}
1956
+ */
1957
+ function renderToNodes(value, reconcileFormActionsCb) {
1958
+ if (value == null || value === false || value === true) return [];
1959
+ if (isTemplate(value)) {
1960
+ const tr = /** @type any */ (value);
1961
+ const { templateEl, parts, formActions } = compile(tr);
1962
+ const frag = /** @type DocumentFragment */ (templateEl.content.cloneNode(true));
1963
+ const bound = parts.map((p) => bindPart(p, frag));
1964
+ for (let i = 0; i < tr.values.length; i++) {
1965
+ applyPart(bound[i], tr.values[i], undefined, tr.values, reconcileFormActionsCb);
1966
+ }
1967
+ if (reconcileFormActionsCb) reconcileFormActionsCb(formActions, bound, tr.values);
1968
+ // Slot parts need their one-shot apply here too (same contract as
1969
+ // createInstance / nested templates / buildDetached): the caller
1970
+ // (consumeAsyncStream) inserts these nodes synchronously in the same
1971
+ // task, so the slot-part's one-microtask finalize retry lands in the
1972
+ // live tree. Without this, a <slot> inside streamed chunk content never
1973
+ // finalizes and its name suppresses parking forever.
1974
+ for (const p of bound) {
1975
+ if (p.kind === 'slot') applyPart(p, undefined, undefined, [], reconcileFormActionsCb);
1976
+ }
1977
+ return [...frag.childNodes];
1978
+ }
1979
+ if (Array.isArray(value)) {
1980
+ const nodes = [];
1981
+ for (const v of value) nodes.push(...renderToNodes(v, reconcileFormActionsCb));
1982
+ return nodes;
1983
+ }
1984
+ return [document.createTextNode(String(value))];
1985
+ }
1986
+
1987
+ /**
1988
+ * Abort an async-stream directive. Sets `aborted = true` (so the next
1989
+ * `await iterator.next()` resolution short-circuits), removes all nodes
1990
+ * rendered so far, and explicitly calls `iterator.return()` so a
1991
+ * generator parked on `await` can unwind via its `finally` blocks
1992
+ * instead of leaking.
1993
+ * @param {AsyncStreamState} state
1994
+ */
1995
+ function teardownAsyncStream(state) {
1996
+ state.aborted = true;
1997
+ for (const n of state.nodes) {
1998
+ if (n.parentNode) n.parentNode.removeChild(n);
1999
+ }
2000
+ state.nodes = [];
2001
+ // Best-effort iterator cleanup. `.return()` is optional on AsyncIterators;
2002
+ // generators built via `async function*` provide it and run their
2003
+ // `finally` blocks. Swallow any rejection so teardown can't throw.
2004
+ try {
2005
+ state.iterator.return?.()?.catch?.(() => {});
2006
+ } catch { /* ignore */ }
2007
+ }