streetui 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.cjs +1 -1
- package/dist/bin.cjs.map +1 -1
- package/dist/bin.js +1 -1
- package/dist/bin.js.map +1 -1
- package/dist/create-bin.cjs +1 -1
- package/dist/create-bin.cjs.map +1 -1
- package/dist/create-bin.js +1 -1
- package/dist/create-bin.js.map +1 -1
- package/dist/{hydration-diagnostics-CEhFie5X.d.cts → hydration-diagnostics-C8sAQkJR.d.cts} +1 -1
- package/dist/{hydration-diagnostics-CEhFie5X.d.ts → hydration-diagnostics-C8sAQkJR.d.ts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{renderer-interface-CYJIOjj5.d.ts → renderer-interface--uOV_DNy.d.ts} +1 -1
- package/dist/{renderer-interface-DhgAgwa9.d.cts → renderer-interface-BXICy39g.d.cts} +1 -1
- package/dist/{server-wz5X8SA9.d.ts → server-DjtNMn_3.d.ts} +1 -1
- package/dist/{server-Lwm5W3o9.d.cts → server-pBuPd74Z.d.cts} +1 -1
- package/dist/server.cjs +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +2 -2
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../renderer/src/render-context.ts","../../core/src/lifecycle.ts","../../renderer/src/node-instance.ts","../../renderer/src/attributes.ts","../../renderer/src/events.ts","../../dom/src/server-node.ts","../../dom/src/server-adapter.ts","../../dom/src/focus.ts","../../renderer/src/tag-map.ts","../../renderer/src/patch.ts","../../renderer/src/reconciliation.ts","../../renderer/src/transition.ts","../../renderer/src/head.ts","../../renderer/src/mount.ts","../../renderer/src/dehydrate.ts","../../compiler/src/analysis/analyze.ts","../../compiler/src/analysis/inspect.ts","../../renderer/src/static-ssr-plan.ts","../../renderer/src/ssr.ts","../src/version.ts"],"sourcesContent":["/**\n * RenderContext — shared state for a single mount operation.\n *\n * Passed through the render pipeline so every sub-function has access\n * to the DOM adapter, graph, and instance map without prop-drilling.\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { NodeInstance } from './node-instance.js';\nimport type { HydrationDiagnosticSink } from './hydration-diagnostics.js';\nimport type { HeadManager } from './head.js';\n\nexport interface RenderContext {\n readonly dom: DOMAdapter;\n readonly graph: ApplicationGraph;\n /** Maps GraphNode.id → its live NodeInstance */\n readonly instances: Map<string, NodeInstance>;\n /** The root container element. */\n readonly container: Element;\n /**\n * Optional dev-only sink that observes hydration mismatch repairs. When\n * absent (the default) the hydration path does no extra work — this is how\n * DevTools/diagnostics stay off the production runtime path.\n */\n readonly hydrationDiagnostics?: HydrationDiagnosticSink;\n /**\n * Optional SSR-only static-subtree plan (v1.7). Maps a maximal\n * static-subtree root GraphNode.id → its precomputed, verbatim HTML string.\n * Present only on the server render path when a plan has been built; on the\n * browser mount path it is always `undefined`, so the client hot path is\n * unaffected (a single `=== undefined` check short-circuits). When a mounted\n * node's id is in this map, the renderer emits the precomputed HTML via\n * `dom.createRawHTML` instead of recursively constructing the subtree.\n */\n readonly staticHTML?: ReadonlyMap<string, string>;\n /**\n * Lazily-created coordinator for `head()` metadata nodes (2.0 §1). Created on\n * first `wireHeadBehavior` call on the browser (never on the server, where\n * `dom.head()` is null and `renderHead` emits the metadata instead). Mutable\n * because it is attached on demand; a render with no `head()` nodes never\n * allocates one.\n */\n head?: HeadManager;\n}\n\nexport function createRenderContext(\n dom: DOMAdapter,\n graph: ApplicationGraph,\n container: Element,\n hydrationDiagnostics?: HydrationDiagnosticSink,\n staticHTML?: ReadonlyMap<string, string>,\n): RenderContext {\n return {\n dom,\n graph,\n instances: new Map(),\n container,\n ...(hydrationDiagnostics !== undefined ? { hydrationDiagnostics } : {}),\n ...(staticHTML !== undefined ? { staticHTML } : {}),\n };\n}\n","/**\n * Application and component lifecycle primitives.\n *\n * Lifecycle phases:\n * created → mounted → active ⇄ updating → unmounting → destroyed\n */\n\nexport type LifecyclePhase =\n | 'created'\n | 'mounted'\n | 'active'\n | 'updating'\n | 'unmounting'\n | 'destroyed';\n\nexport type LifecycleHook = () => void | Promise<void>;\n\nexport class Lifecycle {\n private _phase: LifecyclePhase = 'created';\n private readonly _hooks: Map<LifecyclePhase, LifecycleHook[]> = new Map();\n\n get phase(): LifecyclePhase {\n return this._phase;\n }\n\n get isMounted(): boolean {\n return this._phase === 'mounted' || this._phase === 'active' || this._phase === 'updating';\n }\n\n get isDestroyed(): boolean {\n return this._phase === 'destroyed';\n }\n\n on(phase: LifecyclePhase, hook: LifecycleHook): () => void {\n const hooks = this._hooks.get(phase) ?? [];\n hooks.push(hook);\n this._hooks.set(phase, hooks);\n return () => {\n const current = this._hooks.get(phase);\n if (current !== undefined) {\n const idx = current.indexOf(hook);\n if (idx !== -1) current.splice(idx, 1);\n }\n };\n }\n\n async transition(to: LifecyclePhase): Promise<void> {\n this._phase = to;\n const hooks = this._hooks.get(to) ?? [];\n for (const hook of hooks) {\n await hook();\n }\n }\n\n onMount(hook: LifecycleHook): () => void {\n return this.on('mounted', hook);\n }\n\n onUnmount(hook: LifecycleHook): () => void {\n return this.on('unmounting', hook);\n }\n\n onDestroy(hook: LifecycleHook): () => void {\n return this.on('destroyed', hook);\n }\n}\n\n/** A simple cleanup registry — collect teardown functions and run them all at once. */\nexport class CleanupRegistry {\n private readonly _fns: Array<() => void> = [];\n\n add(fn: () => void): void {\n this._fns.push(fn);\n }\n\n run(): void {\n for (const fn of this._fns) {\n try {\n fn();\n } catch {\n // Best-effort cleanup; don't let one failure block others\n }\n }\n this._fns.length = 0;\n }\n}\n","/**\n * NodeInstance — the renderer's live counterpart to a GraphNode.\n *\n * Tracks the actual DOM node(s), all signal subscriptions that drive\n * targeted DOM updates, and DOM event listener teardowns.\n */\n\nimport { CleanupRegistry } from '@streetui/core';\nimport type { GraphNode } from '@streetui/graph';\nimport type { ReadonlySignal } from '@streetui/state';\n\nexport class NodeInstance {\n readonly graphNode: GraphNode;\n /** The primary DOM node for this instance (element or text node). */\n domNode: Node;\n readonly children: NodeInstance[] = [];\n readonly cleanup: CleanupRegistry = new CleanupRegistry();\n\n constructor(graphNode: GraphNode, domNode: Node) {\n this.graphNode = graphNode;\n this.domNode = domNode;\n }\n\n addChild(child: NodeInstance): void {\n this.children.push(child);\n }\n\n /** Subscribe to a signal; auto-cleanup on unmount. */\n trackSignal<T>(sig: ReadonlySignal<T>, handler: (v: T) => void): void {\n const unsub = sig.subscribe(handler);\n this.cleanup.add(unsub);\n }\n\n /** Register a raw cleanup fn (DOM event removal, etc.). */\n trackCleanup(fn: () => void): void {\n this.cleanup.add(fn);\n }\n\n dispose(): void {\n for (const child of this.children) {\n child.dispose();\n }\n this.cleanup.run();\n }\n}\n","/**\n * Attribute and property application helpers.\n *\n * Decides whether a prop should be set as a DOM attribute or a JS property,\n * handling special cases (boolean attrs, event-like props, style, class).\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\n\n// Properties that must be set as JS object properties, not HTML attributes\nconst DOM_PROPERTIES = new Set([\n 'value', 'checked', 'selected', 'indeterminate',\n 'innerHTML', 'textContent', 'innerText',\n 'scrollTop', 'scrollLeft',\n]);\n\n// Boolean attributes — present means true, absent means false\nconst BOOLEAN_ATTRS = new Set([\n 'disabled', 'readonly', 'required', 'checked', 'selected',\n 'multiple', 'autofocus', 'autoplay', 'controls', 'default',\n 'defer', 'formnovalidate', 'hidden', 'ismap', 'loop',\n 'novalidate', 'open', 'reversed', 'scoped', 'seamless',\n]);\n\nexport function applyProp(\n dom: DOMAdapter,\n element: Element,\n name: string,\n value: unknown,\n): void {\n // Skip internal renderer metadata\n if (name.startsWith('_')) return;\n // Skip event handlers (handled separately)\n if (name.startsWith('on')) return;\n\n if (DOM_PROPERTIES.has(name)) {\n dom.setProperty(element, name, value);\n return;\n }\n\n if (BOOLEAN_ATTRS.has(name)) {\n if (value === true || value === '' || value === name) {\n dom.setAttribute(element, name, '');\n } else {\n dom.removeAttribute(element, name);\n }\n return;\n }\n\n if (name === 'class' || name === 'className') {\n dom.setAttribute(element, 'class', String(value ?? ''));\n return;\n }\n\n if (name === 'style' && typeof value === 'object' && value !== null) {\n const el = element as HTMLElement;\n const styles = value as Record<string, string>;\n for (const [k, v] of Object.entries(styles)) {\n el.style.setProperty(k, v);\n }\n return;\n }\n\n if (value === null || value === undefined || value === false) {\n dom.removeAttribute(element, name);\n return;\n }\n\n dom.setAttribute(element, name, String(value));\n}\n\nexport function patchProp(\n dom: DOMAdapter,\n element: Element,\n name: string,\n oldValue: unknown,\n newValue: unknown,\n): void {\n if (Object.is(oldValue, newValue)) return;\n applyProp(dom, element, name, newValue);\n}\n","/**\n * Event wiring for the renderer.\n *\n * Given a GraphNode with event descriptors, this wires DOM listeners\n * that call the handlers stored in the graph's handler registry.\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { NodeInstance } from './node-instance.js';\n\nexport function wireEvents(\n dom: DOMAdapter,\n graph: ApplicationGraph,\n node: GraphNode,\n element: Element,\n instance: NodeInstance,\n): void {\n // Fast exit for event-free nodes — avoids allocating a for-of iterator over\n // an empty array on every node during a large mount/hydrate.\n if (node.events.length === 0) return;\n for (const eventDesc of node.events) {\n const handler = graph.getHandler(eventDesc.handlerKey);\n if (handler === undefined) continue;\n\n const domListener: EventListener = (domEvent: Event) => {\n // For input events, pass the current value as first arg\n if (eventDesc.type === 'input' || eventDesc.type === 'change') {\n const input = domEvent.target as HTMLInputElement;\n (handler as (v: string) => void)(input.value);\n } else if (eventDesc.type === 'submit') {\n domEvent.preventDefault();\n (handler as (e: Event) => void)(domEvent);\n } else {\n (handler as () => void)();\n }\n };\n\n dom.addEventListener(element, eventDesc.type, domListener);\n instance.trackCleanup(() => {\n dom.removeEventListener(element, eventDesc.type, domListener);\n });\n }\n}\n","/**\n * Server-side DOM node model.\n *\n * A tiny, dependency-free tree of plain objects that mirrors just enough of the\n * browser DOM for StreetUI's renderer to build a tree on the server and\n * serialize it to an HTML string. There is NO browser global here — these are\n * ordinary classes usable in any JavaScript environment (Node, workers, tests).\n *\n * The renderer never touches these types directly; it goes through the\n * `DOMAdapter` interface, and `ServerDOMAdapter` translates adapter calls into\n * operations on this model.\n */\n\nexport type ServerNodeKind = 'element' | 'text' | 'comment' | 'fragment' | 'raw';\n\nexport interface ServerNode {\n readonly kind: ServerNodeKind;\n parent: ServerParent | null;\n}\n\nexport type ServerParent = ServerElement | ServerFragment;\n\n/** A minimal inline-style holder mirroring `element.style.setProperty`. */\nexport class ServerStyle {\n readonly declarations = new Map<string, string>();\n setProperty(name: string, value: string): void {\n this.declarations.set(name, value);\n }\n get isEmpty(): boolean {\n return this.declarations.size === 0;\n }\n toCss(): string {\n return [...this.declarations.entries()].map(([k, v]) => `${k}: ${v}`).join('; ');\n }\n}\n\nexport class ServerText implements ServerNode {\n readonly kind = 'text' as const;\n parent: ServerParent | null = null;\n data: string;\n constructor(data: string) {\n this.data = data;\n }\n}\n\nexport class ServerComment implements ServerNode {\n readonly kind = 'comment' as const;\n parent: ServerParent | null = null;\n data: string;\n constructor(data: string) {\n this.data = data;\n }\n}\n\nexport class ServerFragment implements ServerNode {\n readonly kind = 'fragment' as const;\n parent: ServerParent | null = null;\n readonly children: ServerNode[] = [];\n}\n\n/**\n * A pre-serialized, verbatim HTML fragment (v1.7 static SSR plan).\n *\n * Emitted for provably-static subtrees whose HTML the compiler-derived static\n * SSR plan already computed once. Serializing this node copies its stored\n * string directly — it allocates no ServerElement/ServerText, no attribute Map\n * and no children array for the collapsed subtree. The stored `html` is\n * produced by the exact same mount + serialize pipeline as the runtime path, so\n * the output is byte-identical (the v1.7 byte-identity gate proves this).\n *\n * This node is SSR-only: it is created solely via `ServerDOMAdapter.createRawHTML`\n * on the server render path and never appears in a browser build.\n */\nexport class ServerRawHTML implements ServerNode {\n readonly kind = 'raw' as const;\n parent: ServerParent | null = null;\n readonly html: string;\n constructor(html: string) {\n this.html = html;\n }\n}\n\nexport class ServerElement implements ServerNode {\n readonly kind = 'element' as const;\n parent: ServerParent | null = null;\n readonly tagName: string;\n readonly attributes = new Map<string, string>();\n readonly children: ServerNode[] = [];\n\n // Lazily-allocated stores. On the 10k-row SSR corpus ~0% of elements carry JS\n // properties or inline styles (measured, §5: 1 of 80,029 elements uses\n // `properties`, 0 use `style`), so eagerly allocating a `properties` Map plus\n // a `ServerStyle` (which itself holds a Map) per element wasted ~240k\n // allocations per /users render — all in the dominant mount phase. These are\n // created on first WRITE via the `properties`/`style` getters; the serializer\n // reads the raw `_properties`/`_style` fields so a READ never forces an\n // allocation. Output is byte-identical: an unset store previously serialized\n // to nothing (empty `properties.has(...)` / `style.isEmpty`), and a null store\n // is skipped the same way.\n _properties: Map<string, unknown> | null = null;\n _style: ServerStyle | null = null;\n\n constructor(tagName: string) {\n this.tagName = tagName.toLowerCase();\n }\n\n /** JS properties set via `setProperty` (e.g. input `value`, `checked`). Allocated on first access. */\n get properties(): Map<string, unknown> {\n return (this._properties ??= new Map());\n }\n\n /** Inline-style holder mirroring `element.style`. Allocated on first access. */\n get style(): ServerStyle {\n return (this._style ??= new ServerStyle());\n }\n}\n\n// ── HTML serialization ─────────────────────────────────────────────────────────\n\n/**\n * HTML \"void\" elements — self-closing, never given a closing tag or children.\n */\nconst VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr',\n]);\n\n/**\n * Element properties that should be reflected into the serialized HTML so the\n * hydrated DOM carries the same initial state. `value`/`checked` matter for\n * form controls whose live state is a JS property, not an attribute.\n */\nconst SERIALIZED_PROPERTIES: Record<string, 'attr' | 'boolean'> = {\n value: 'attr',\n checked: 'boolean',\n selected: 'boolean',\n};\n\n/**\n * Precomputed `[name, kind]` pairs of SERIALIZED_PROPERTIES. Hoisted to module\n * scope so `serializeAttributes` does not allocate a fresh entries array for\n * every element serialized (measured hot: ~80k elements on the 10k-row route).\n */\nconst SERIALIZED_PROPERTY_ENTRIES: ReadonlyArray<readonly [string, 'attr' | 'boolean']> =\n Object.entries(SERIALIZED_PROPERTIES) as Array<[string, 'attr' | 'boolean']>;\n\n// Fast-path escaping. The chained `.replace(/…/g, …)` form makes 3–4 full\n// passes and allocates an intermediate string per pass even when nothing needs\n// escaping. These variants scan once and, in the overwhelmingly common case of\n// no special character, return the input unchanged (zero allocation). Output is\n// byte-identical to the chained form (verified over the real SSR corpus).\nconst TEXT_SPECIAL = /[&<>]/;\nconst ATTR_SPECIAL = /[&<>\"]/;\n\n/** Escape text node content. */\nexport function escapeHtmlText(value: string): string {\n if (!TEXT_SPECIAL.test(value)) return value;\n let out = '';\n let last = 0;\n for (let i = 0; i < value.length; i++) {\n let esc: string;\n switch (value.charCodeAt(i)) {\n case 38: esc = '&'; break; // &\n case 60: esc = '<'; break; // <\n case 62: esc = '>'; break; // >\n default: continue;\n }\n out += value.slice(last, i) + esc;\n last = i + 1;\n }\n return out + value.slice(last);\n}\n\n/** Escape a double-quoted attribute value. */\nexport function escapeHtmlAttr(value: string): string {\n if (!ATTR_SPECIAL.test(value)) return value;\n let out = '';\n let last = 0;\n for (let i = 0; i < value.length; i++) {\n let esc: string;\n switch (value.charCodeAt(i)) {\n case 38: esc = '&'; break; // &\n case 60: esc = '<'; break; // <\n case 62: esc = '>'; break; // >\n case 34: esc = '"'; break; // \"\n default: continue;\n }\n out += value.slice(last, i) + esc;\n last = i + 1;\n }\n return out + value.slice(last);\n}\n\nfunction serializeAttributes(el: ServerElement): string {\n const parts: string[] = [];\n\n for (const [name, value] of el.attributes) {\n if (value === '') {\n parts.push(` ${name}`);\n } else {\n parts.push(` ${name}=\"${escapeHtmlAttr(value)}\"`);\n }\n }\n\n // Read the raw backing field (may be null): most elements have no JS\n // properties, so skipping the whole loop avoids touching a store that was\n // never allocated (§5).\n const props = el._properties;\n if (props !== null) {\n for (const [name, kind] of SERIALIZED_PROPERTY_ENTRIES) {\n if (!props.has(name)) continue;\n if (el.attributes.has(name)) continue; // an explicit attribute already won\n const raw = props.get(name);\n if (kind === 'boolean') {\n if (raw === true) parts.push(` ${name}`);\n } else {\n if (raw !== undefined && raw !== null) {\n parts.push(` ${name}=\"${escapeHtmlAttr(String(raw))}\"`);\n }\n }\n }\n }\n\n const style = el._style;\n if (style !== null && !style.isEmpty && !el.attributes.has('style')) {\n parts.push(` style=\"${escapeHtmlAttr(style.toCss())}\"`);\n }\n\n return parts.join('');\n}\n\n/** Serialize a single server node (element/text/comment/fragment/raw) to HTML. */\nexport function serializeServerNode(node: ServerNode): string {\n switch (node.kind) {\n case 'text':\n return escapeHtmlText((node as ServerText).data);\n case 'comment':\n return `<!--${(node as ServerComment).data}-->`;\n case 'fragment':\n return serializeChildren(node as ServerFragment);\n case 'raw':\n // Verbatim: the string was produced by this same serializer for a static\n // subtree, so it is already correctly escaped. Copy it as-is (§8).\n return (node as ServerRawHTML).html;\n case 'element': {\n const el = node as ServerElement;\n const tag = el.tagName;\n const attrs = serializeAttributes(el);\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrs}>`;\n }\n return `<${tag}${attrs}>${serializeChildren(el)}</${tag}>`;\n }\n }\n}\n\n/** Serialize the children of an element or fragment (its \"inner HTML\"). */\nexport function serializeChildren(node: ServerElement | ServerFragment): string {\n let out = '';\n for (const child of node.children) {\n out += serializeServerNode(child);\n }\n return out;\n}\n","/**\n * Server implementation of `DOMAdapter`.\n *\n * Builds a lightweight in-memory tree (see `server-node.ts`) instead of touching\n * a real browser DOM, then lets the caller serialize it to an HTML string. It is\n * completely free of browser globals, so the exact same renderer that runs in\n * the browser can produce HTML on the server.\n *\n * The `DOMAdapter` interface is typed against the lib DOM types (`Element`,\n * `Node`, `Text`, …). Our server nodes structurally stand in for those at\n * runtime, so the boundary uses `as unknown as` casts in one place. Everything\n * inside operates on the real server-node model.\n */\n\nimport type { DOMAdapter } from './adapter.js';\nimport {\n ServerElement,\n ServerText,\n ServerComment,\n ServerFragment,\n ServerRawHTML,\n serializeChildren,\n serializeServerNode,\n type ServerNode,\n type ServerParent,\n} from './server-node.js';\n\nfunction asServer(node: unknown): ServerNode {\n return node as unknown as ServerNode;\n}\nfunction asParent(node: unknown): ServerParent {\n return node as unknown as ServerParent;\n}\n\nexport class ServerDOMAdapter implements DOMAdapter {\n createElement(tag: string, _ns?: string): Element {\n return new ServerElement(tag) as unknown as Element;\n }\n\n createTextNode(data: string): Text {\n return new ServerText(data) as unknown as Text;\n }\n\n createComment(data: string): Comment {\n return new ServerComment(data) as unknown as Comment;\n }\n\n createFragment(): DocumentFragment {\n return new ServerFragment() as unknown as DocumentFragment;\n }\n\n /**\n * Create a verbatim pre-serialized HTML node (v1.7 static SSR plan, §6).\n * Server-only: the browser adapter does not implement this, and the renderer\n * fast path only invokes it when a static SSR plan is present (SSR). The\n * stored HTML was produced by this same serializer, so it is emitted as-is.\n */\n createRawHTML(html: string): Node {\n return new ServerRawHTML(html) as unknown as Node;\n }\n\n appendChild(parent: Node, child: Node): void {\n const p = asParent(parent);\n const c = asServer(child);\n this._detach(c);\n c.parent = p;\n p.children.push(c);\n }\n\n insertBefore(parent: Node, child: Node, reference: Node | null): void {\n const p = asParent(parent);\n const c = asServer(child);\n this._detach(c);\n c.parent = p;\n if (reference === null) {\n p.children.push(c);\n return;\n }\n const ref = asServer(reference);\n const idx = p.children.indexOf(ref);\n if (idx === -1) p.children.push(c);\n else p.children.splice(idx, 0, c);\n }\n\n removeChild(parent: Node, child: Node): void {\n const p = asParent(parent);\n const c = asServer(child);\n const idx = p.children.indexOf(c);\n if (idx !== -1) {\n p.children.splice(idx, 1);\n c.parent = null;\n }\n }\n\n replaceChild(parent: Node, newChild: Node, oldChild: Node): void {\n const p = asParent(parent);\n const nc = asServer(newChild);\n const oc = asServer(oldChild);\n const idx = p.children.indexOf(oc);\n if (idx === -1) return;\n this._detach(nc);\n nc.parent = p;\n p.children.splice(idx, 1, nc);\n oc.parent = null;\n }\n\n private _detach(node: ServerNode): void {\n if (node.parent !== null) {\n const siblings = node.parent.children;\n const idx = siblings.indexOf(node);\n if (idx !== -1) siblings.splice(idx, 1);\n node.parent = null;\n }\n }\n\n setAttribute(element: Element, name: string, value: string): void {\n (element as unknown as ServerElement).attributes.set(name, value);\n }\n\n removeAttribute(element: Element, name: string): void {\n (element as unknown as ServerElement).attributes.delete(name);\n }\n\n getAttribute(element: Element, name: string): string | null {\n return (element as unknown as ServerElement).attributes.get(name) ?? null;\n }\n\n setProperty(element: Element, name: string, value: unknown): void {\n (element as unknown as ServerElement).properties.set(name, value);\n }\n\n setTextContent(node: Node, text: string): void {\n const n = asServer(node);\n if (n.kind === 'element' || n.kind === 'fragment') {\n const el = n as ServerElement | ServerFragment;\n el.children.length = 0;\n const t = new ServerText(text);\n t.parent = el;\n el.children.push(t);\n } else if (n.kind === 'text') {\n (n as ServerText).data = text;\n }\n }\n\n getTextContent(node: Node): string | null {\n const n = asServer(node);\n if (n.kind === 'text') return (n as ServerText).data;\n if (n.kind === 'element' || n.kind === 'fragment') {\n let out = '';\n for (const c of (n as ServerElement | ServerFragment).children) {\n out += this.getTextContent(c as unknown as Node) ?? '';\n }\n return out;\n }\n return null;\n }\n\n // Server nodes never dispatch events — listeners are a no-op on the server.\n addEventListener(): void {\n /* no-op on the server */\n }\n removeEventListener(): void {\n /* no-op on the server */\n }\n\n querySelector(): Element | null {\n return null;\n }\n querySelectorAll(): NodeListOf<Element> {\n return [] as unknown as NodeListOf<Element>;\n }\n getElementById(): Element | null {\n return null;\n }\n\n focus(): void {\n // No focus concept on the server — intentional no-op (SSR-safe).\n }\n\n body(): Element | null {\n // No document on the server — portals degrade to inline rendering.\n return null;\n }\n\n head(): Element | null {\n // No document on the server — head metadata is emitted as a string by\n // `renderHead()` instead of being applied to a live document.head.\n return null;\n }\n\n activeElement(): Element | null {\n return null;\n }\n\n contains(_ancestor: Element, _node: Node): boolean {\n return false;\n }\n\n matches(_element: Element, _selector: string): boolean {\n return false;\n }\n\n isElement(node: Node): node is Element {\n return asServer(node).kind === 'element';\n }\n\n isTextNode(node: Node): node is Text {\n return asServer(node).kind === 'text';\n }\n\n tagName(element: Element): string {\n return (element as unknown as ServerElement).tagName;\n }\n\n parentNode(node: Node): Node | null {\n return (asServer(node).parent as unknown as Node | null) ?? null;\n }\n\n nextSibling(node: Node): Node | null {\n const n = asServer(node);\n const parent = n.parent;\n if (parent === null) return null;\n const idx = parent.children.indexOf(n);\n if (idx === -1 || idx + 1 >= parent.children.length) return null;\n return parent.children[idx + 1] as unknown as Node;\n }\n\n firstChild(node: Node): Node | null {\n const n = asServer(node);\n if (n.kind === 'element' || n.kind === 'fragment') {\n const el = n as ServerElement | ServerFragment;\n return (el.children[0] as unknown as Node) ?? null;\n }\n return null;\n }\n\n childNodes(node: Node): Node[] {\n const n = asServer(node);\n if (n.kind === 'element' || n.kind === 'fragment') {\n return (n as ServerElement | ServerFragment).children as unknown as Node[];\n }\n return [];\n }\n\n // ── Server-only ────────────────────────────────────────────────────────────\n\n /** Serialize a node's children (\"inner HTML\") to an HTML string. */\n serializeInner(node: Node): string {\n const n = asServer(node);\n if (n.kind === 'element' || n.kind === 'fragment') {\n return serializeChildren(n as ServerElement | ServerFragment);\n }\n return '';\n }\n\n /** Serialize a node (including itself) to an HTML string. */\n serializeOuter(node: Node): string {\n return serializeServerNode(asServer(node));\n }\n}\n\n// `/* @__PURE__ */`: this singleton is a convenience export only (no internal\n// runtime path references it). Marking construction pure lets bundlers drop it —\n// and with it the whole server serializer chain (serializeServerNode/escape/\n// VOID_ELEMENTS) — out of client bundles that never import SSR. Without this,\n// the un-annotated `new` is treated as a side effect and retained everywhere.\nexport const serverDOMAdapter = /* @__PURE__ */ new ServerDOMAdapter();\n","/**\n * Focus helpers built on the {@link DOMAdapter} abstraction.\n *\n * These are the minimal, genuinely-useful focus operations an app needs:\n * focus a specific element (e.g. the first field when a route or modal opens)\n * or focus the first focusable element inside a container (e.g. move focus\n * into a dialog). Both go through the adapter, so they are no-ops on the server\n * (`ServerDOMAdapter.querySelector` returns null / `focus` does nothing) and\n * therefore safe to call from universal code.\n */\n\nimport type { DOMAdapter } from './adapter.js';\n\n/** Default selector for natively focusable / tabbable elements. */\nexport const FOCUSABLE_SELECTOR =\n 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex=\"-1\"])';\n\n/**\n * Focus the element with the given id, scoped to `root`.\n * Returns true if an element was found and focused.\n */\nexport function focusById(dom: DOMAdapter, root: Element | Document, id: string): boolean {\n const el = dom.querySelector(root, `[id=\"${id}\"]`);\n if (el === null) return false;\n dom.focus(el);\n return true;\n}\n\n/**\n * Focus the first focusable element inside `container`.\n * Returns true if a focusable element was found and focused.\n */\nexport function focusFirst(\n dom: DOMAdapter,\n container: Element | Document,\n selector: string = FOCUSABLE_SELECTOR,\n): boolean {\n const el = dom.querySelector(container, selector);\n if (el === null) return false;\n dom.focus(el);\n return true;\n}\n\n/**\n * Ordered list of focusable/tabbable descendants of `container`.\n * Re-checks each candidate against the selector so elements disabled after the\n * initial query (e.g. a button toggled to `disabled`) are excluded.\n */\nexport function getFocusable(\n dom: DOMAdapter,\n container: Element,\n selector: string = FOCUSABLE_SELECTOR,\n): Element[] {\n return Array.from(dom.querySelectorAll(container, selector)).filter((el) =>\n dom.matches(el, selector),\n );\n}\n\n/**\n * Capture the currently-focused element so it can be restored later (e.g. when\n * a dialog closes). Returns null on the server or when nothing is focused.\n */\nexport function saveFocus(dom: DOMAdapter): Element | null {\n return dom.activeElement();\n}\n\n/** Restore focus to a previously {@link saveFocus}-d element. No-op if null. */\nexport function restoreFocus(dom: DOMAdapter, saved: Element | null): void {\n if (saved !== null) dom.focus(saved);\n}\n\n/**\n * Move focus into `container` on open: the element with id `initialFocusId` if\n * given and present, otherwise the first focusable element. Server-safe no-op.\n */\nexport function focusInitial(\n dom: DOMAdapter,\n container: Element,\n initialFocusId?: string,\n): void {\n if (initialFocusId !== undefined && focusById(dom, container, initialFocusId)) return;\n focusFirst(dom, container);\n}\n\n/**\n * Trap Tab / Shift+Tab focus within `container` (wrap-around at both ends).\n * Attaches a keydown listener to the container and returns a cleanup function\n * that detaches it. Server-safe: `addEventListener` is a no-op, and the returned\n * cleanup is still callable.\n */\nexport function trapFocus(dom: DOMAdapter, container: Element): () => void {\n const onKeydown = ((event: KeyboardEvent): void => {\n if (event.key !== 'Tab') return;\n const items = getFocusable(dom, container);\n if (items.length === 0) {\n event.preventDefault();\n return;\n }\n const first = items[0]!;\n const last = items[items.length - 1]!;\n const active = dom.activeElement();\n if (active === null || !dom.contains(container, active)) {\n event.preventDefault();\n dom.focus(first);\n } else if (event.shiftKey && active === first) {\n event.preventDefault();\n dom.focus(last);\n } else if (!event.shiftKey && active === last) {\n event.preventDefault();\n dom.focus(first);\n }\n }) as EventListener;\n dom.addEventListener(container, 'keydown', onKeydown);\n return () => dom.removeEventListener(container, 'keydown', onKeydown);\n}\n\n/**\n * Modal containment: if focus moves to an element outside `container`, redirect\n * it back inside. Listens on the document body (focusin bubbles there) and\n * returns a cleanup function. Server-safe no-op (body() is null).\n *\n * Nested modals (§16): every active containment pushes its container onto a\n * module-level stack, and a handler only redirects while ITS container is the\n * top of the stack — i.e. the most recently opened modal. This is the framework's\n * minimal \"focus owner\" concept: because overlay panels are relocated to\n * body-level portals (siblings, not descendants), two overlapping `containFocus`\n * handlers would otherwise fight over every `focusin`. The stack makes exactly\n * one owner authoritative at a time; cleanup pops it so the previous modal\n * resumes ownership. State is internal and torn down on cleanup — nothing is\n * retained on the graph (§18).\n */\nconst containmentStack: Element[] = [];\n\nexport function containFocus(dom: DOMAdapter, container: Element): () => void {\n const body = dom.body();\n if (body === null) return () => {};\n containmentStack.push(container);\n const onFocusIn = ((event: FocusEvent): void => {\n // Only the topmost owner enforces containment (nested-modal correctness).\n if (containmentStack[containmentStack.length - 1] !== container) return;\n const target = event.target as Node | null;\n if (target !== null && !dom.contains(container, target)) {\n focusFirst(dom, container);\n }\n }) as EventListener;\n dom.addEventListener(body, 'focusin', onFocusIn);\n return () => {\n dom.removeEventListener(body, 'focusin', onFocusIn);\n const index = containmentStack.lastIndexOf(container);\n if (index !== -1) containmentStack.splice(index, 1);\n };\n}\n\n/**\n * Invoke `handler` when Escape is pressed while focus is within `target`.\n * Returns a cleanup function. Server-safe no-op.\n */\nexport function onEscape(dom: DOMAdapter, target: Element, handler: () => void): () => void {\n const onKeydown = ((event: KeyboardEvent): void => {\n if (event.key === 'Escape') handler();\n }) as EventListener;\n dom.addEventListener(target, 'keydown', onKeydown);\n return () => dom.removeEventListener(target, 'keydown', onKeydown);\n}\n\n/**\n * Roving-focus keyboard navigation for a menu (role=\"menu\") container: the\n * arrow keys move focus between the container's focusable items (wrap-around at\n * both ends), Home/End jump to the first/last item, and Enter/Space activate\n * the currently-focused item (a native `click`, so an item's `onClick` fires).\n * `Tab` and `Escape` are deliberately left alone — the overlay layer wires\n * Escape-to-close separately and a menu does not trap Tab.\n *\n * Items are re-queried on every key (via {@link getFocusable}) so a menu whose\n * items change reactively is always navigated against the live set, and items\n * disabled after mount are skipped. Attaches a keydown listener to the\n * container and returns a cleanup function. Server-safe: `addEventListener` is\n * a no-op and the returned cleanup is still callable.\n */\nexport function rovingMenu(\n dom: DOMAdapter,\n container: Element,\n selector: string = FOCUSABLE_SELECTOR,\n): () => void {\n const onKeydown = ((event: KeyboardEvent): void => {\n const key = event.key;\n const isActivate = key === 'Enter' || key === ' ' || key === 'Spacebar';\n const isMove =\n key === 'ArrowDown' || key === 'ArrowUp' || key === 'Home' || key === 'End';\n if (!isActivate && !isMove) return;\n\n const items = getFocusable(dom, container, selector);\n if (items.length === 0) return;\n const active = dom.activeElement();\n const index = active === null ? -1 : items.indexOf(active);\n\n if (isActivate) {\n // Activating a menu item only makes sense when one is focused; otherwise\n // let the event fall through unchanged.\n if (index < 0) return;\n event.preventDefault();\n (items[index] as unknown as { click?: () => void }).click?.();\n return;\n }\n\n event.preventDefault();\n let next: number;\n if (key === 'Home') next = 0;\n else if (key === 'End') next = items.length - 1;\n else if (key === 'ArrowDown') next = index < 0 ? 0 : (index + 1) % items.length;\n else next = index <= 0 ? items.length - 1 : index - 1; // ArrowUp\n dom.focus(items[next]!);\n }) as EventListener;\n dom.addEventListener(container, 'keydown', onKeydown);\n return () => dom.removeEventListener(container, 'keydown', onKeydown);\n}\n\n","/**\n * Maps semantic node types to HTML tag names.\n */\n\nimport type { SemanticNodeType } from '@streetui/core';\n\nconst TAG_MAP: Partial<Record<SemanticNodeType, string>> = {\n application: 'div',\n page: 'div',\n section: 'section',\n container: 'div',\n heading: 'h1',\n text: 'span',\n button: 'button',\n input: 'input',\n form: 'form',\n list: 'ul',\n 'list-item': 'li',\n image: 'img',\n link: 'a',\n component: 'div',\n slot: 'div',\n fragment: 'div',\n 'reactive-list': 'ul',\n // A portal renders as a neutral inline anchor <div> at its declaration site;\n // its children are relocated to a document.body container on the browser\n // (see the portal branch in mount.ts). On the server (no body) it renders\n // inline, so the anchor tag is what SSR/hydration positionally match on.\n portal: 'div',\n // A `head()` node renders as a neutral, empty inline anchor <div> at its\n // declaration site (like a portal anchor). Its actual contribution — title/\n // meta/link/etc. — is applied to `document.head` by `wireHeadBehavior` on the\n // browser, and emitted separately by `renderHead()` on the server. Keeping a\n // one-node/one-element anchor preserves positional hydration.\n head: 'div',\n};\n\nexport function resolveTag(type: SemanticNodeType): string {\n return TAG_MAP[type] ?? 'div';\n}\n","/**\n * Patch — targeted DOM updates driven by signal changes.\n *\n * When a signal fires, we look up the NodeInstance and apply\n * only the changed prop — no full re-render, no tree diffing.\n */\n\nimport type { RenderContext } from './render-context.js';\nimport type { GraphNode } from '@streetui/graph';\nimport { applyProp, patchProp } from './attributes.js';\n\nexport function patchNode(\n ctx: RenderContext,\n graphNode: GraphNode,\n propKey: string,\n newValue: unknown,\n): void {\n const instance = ctx.instances.get(graphNode.id);\n if (instance === undefined) return;\n\n const domNode = instance.domNode;\n if (!ctx.dom.isElement(domNode)) return;\n\n const oldValue = graphNode.getProp(propKey);\n\n switch (propKey) {\n case 'text':\n if (!Object.is(oldValue, newValue)) {\n ctx.dom.setTextContent(domNode, String(newValue ?? ''));\n graphNode.setProp('text', String(newValue ?? ''));\n }\n break;\n case 'label':\n if (!Object.is(oldValue, newValue)) {\n ctx.dom.setTextContent(domNode, String(newValue ?? ''));\n graphNode.setProp('label', String(newValue ?? ''));\n }\n break;\n case 'disabled':\n if (newValue === true) {\n ctx.dom.setAttribute(domNode, 'disabled', '');\n } else {\n ctx.dom.removeAttribute(domNode, 'disabled');\n }\n graphNode.setProp('disabled', Boolean(newValue));\n break;\n case 'value':\n if (!Object.is(oldValue, newValue)) {\n ctx.dom.setProperty(domNode, 'value', String(newValue ?? ''));\n graphNode.setProp('value', String(newValue ?? ''));\n }\n break;\n default:\n patchProp(ctx.dom, domNode, propKey, oldValue, newValue);\n graphNode.setProp(propKey, newValue as string);\n break;\n }\n}\n","/**\n * Reconciliation — diff-based child list updates.\n *\n * When the children of a node change (e.g. a list driven by state),\n * this reconciler:\n * 1. Matches old instances to new graph nodes by key\n * 2. Reuses matched instances (updates their props)\n * 3. Applies a targeted content update to a reused item whose data changed\n * 4. Creates new instances for additions\n * 5. Removes stale instances (and prunes their handler registrations)\n * 6. Moves DOM nodes to match new order\n *\n * This is keyed reconciliation over the semantic graph — there is no virtual\n * DOM. A reused item keeps its own DOM element; only its changed content is\n * updated in place (falling back to remounting a subtree only where its shape\n * actually changed).\n */\n\nimport type { RenderContext } from './render-context.js';\nimport type { GraphNode } from '@streetui/graph';\nimport type { NodeInstance } from './node-instance.js';\nimport type { TransitionHooks } from './transition.js';\nimport { patchNode } from './patch.js';\n\nexport type MountFn = (node: GraphNode, parent: Element) => NodeInstance;\n\nexport interface ReconcileResult {\n /** Instances in the new order. */\n instances: NodeInstance[];\n /** Instances that were removed and must be disposed. */\n removed: NodeInstance[];\n /**\n * GraphNodes freshly materialised during this reconcile (new rows + rebuilt\n * changed rows). The caller detaches any of these that were not adopted as a\n * live instance's graph node, so no orphan subtree lingers in the graph index.\n */\n built?: GraphNode[];\n}\n\n/**\n * A lazy reconciliation descriptor for one reactive-list row (mirrors the DSL's\n * `ListPlanEntry`). `sig()` and `build()` are only invoked for rows that are\n * genuinely new or whose source reference changed — the whole point of the\n * plan path (spec §15).\n */\nexport interface PlanEntry {\n readonly key: string;\n readonly item: unknown;\n readonly sig: () => string;\n readonly build: () => GraphNode;\n}\n\n/**\n * Reconcile children of a container element against a new list of graph nodes.\n *\n * @param ctx Render context\n * @param parentDom The DOM parent element\n * @param oldInstances Current child instances (in order)\n * @param newNodes New graph children (in desired order)\n * @param mountFn Factory to create a new NodeInstance for a graph node\n */\nexport function reconcileChildren(\n ctx: RenderContext,\n parentDom: Element,\n oldInstances: NodeInstance[],\n newNodes: readonly GraphNode[],\n mountFn: MountFn,\n hooks?: TransitionHooks,\n): ReconcileResult {\n // Build key → old instance map\n const oldByKey = new Map<string, NodeInstance>();\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n oldByKey.set(key, inst);\n }\n\n const newInstances: NodeInstance[] = [];\n const usedKeys = new Set<string>();\n\n for (const newNode of newNodes) {\n const key = newNode.key ?? newNode.id;\n const existing = oldByKey.get(key);\n\n if (existing !== undefined) {\n // Reuse — identity is stable, so the DOM element is preserved.\n usedKeys.add(key);\n const oldSig = existing.graphNode.getProp('_sig');\n const newSig = newNode.getProp('_sig');\n patchExistingInstance(ctx, existing, newNode);\n // Data changed but identity did not → targeted content update in place.\n if (!Object.is(oldSig, newSig)) {\n reconcileItemChildren(ctx, existing, newNode, mountFn);\n }\n newInstances.push(existing);\n } else {\n // Leave→enter cancellation (§6): if this key is currently animating out,\n // reclaim its live instance instead of mounting a duplicate.\n const reclaimed = hooks?.takeLeaving(key);\n if (reclaimed !== undefined) {\n patchExistingInstance(ctx, reclaimed, newNode);\n reconcileItemChildren(ctx, reclaimed, newNode, mountFn);\n hooks?.onEnter(reclaimed);\n newInstances.push(reclaimed);\n } else {\n // New — create and mount, then play its enter animation (if any).\n const inst = mountFn(newNode, parentDom);\n hooks?.onEnter(inst);\n newInstances.push(inst);\n }\n }\n }\n\n // Determine + remove stale instances. A removed instance that carries a\n // transition has its DOM-remove + dispose deferred to leave-animation end by\n // `beginLeave` (which then also forgets + detaches it), so it is excluded from\n // `removed` and the caller does not tear it down (§3/§7).\n const removed: NodeInstance[] = [];\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n if (usedKeys.has(key)) continue;\n if (hooks !== undefined && hooks.beginLeave(inst)) continue;\n const parent = ctx.dom.parentNode(inst.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, inst.domNode);\n inst.dispose();\n removed.push(inst);\n }\n\n // Reorder DOM nodes to match new order\n reorderDom(ctx, parentDom, newInstances);\n\n return { instances: newInstances, removed };\n}\n\n/**\n * Plan-based keyed reconciliation (spec §15 — the optimised reactive-list path).\n *\n * Identical observable result to {@link reconcileChildren}, but driven by lazy\n * {@link PlanEntry} descriptors instead of a pre-built array of GraphNodes:\n *\n * - a reused row whose `item` reference is unchanged does **zero** work — no\n * signature hash, no subtree build, no prop patch (the common case for\n * append / prepend / remove / reorder / reverse, where existing item objects\n * keep their identity);\n * - a reused row whose reference changed hashes lazily and, only on a real\n * signature change, materialises a fresh subtree for a targeted in-place\n * content update;\n * - a genuinely new key builds + mounts exactly one subtree.\n *\n * DOM reordering uses a longest-increasing-subsequence pass so the number of\n * moves is minimal (e.g. a prepend into a 10k list moves 1 node, not 10k).\n */\nexport function reconcileChildrenByPlan(\n ctx: RenderContext,\n parentDom: Element,\n oldInstances: NodeInstance[],\n plan: readonly PlanEntry[],\n mountFn: MountFn,\n hooks?: TransitionHooks,\n): ReconcileResult {\n const oldByKey = new Map<string, NodeInstance>();\n for (const inst of oldInstances) {\n oldByKey.set(inst.graphNode.key ?? inst.graphNode.id, inst);\n }\n\n const newInstances: NodeInstance[] = [];\n const usedKeys = new Set<string>();\n const built: GraphNode[] = [];\n\n for (const entry of plan) {\n const existing = oldByKey.get(entry.key);\n if (existing !== undefined) {\n usedKeys.add(entry.key);\n const oldItem = existing.graphNode.getProp('_item');\n // Identity short-circuit: same reference ⇒ data cannot have changed.\n if (!Object.is(oldItem, entry.item)) {\n const newSig = entry.sig();\n const oldSig = existing.graphNode.getProp('_sig');\n if (!Object.is(oldSig, newSig)) {\n const freshNode = entry.build();\n built.push(freshNode);\n patchExistingInstance(ctx, existing, freshNode);\n reconcileItemChildren(ctx, existing, freshNode, mountFn);\n existing.graphNode.setProp('_sig', newSig);\n }\n // Cache the new reference so the next pass can short-circuit again.\n existing.graphNode.setProp('_item', entry.item as never);\n }\n newInstances.push(existing);\n } else {\n // Leave→enter reclaim (§6/§7): a key removed then re-added mid-leave keeps\n // its identity and its live DOM node rather than mounting a duplicate.\n const reclaimed = hooks?.takeLeaving(entry.key);\n if (reclaimed !== undefined) {\n const freshNode = entry.build();\n built.push(freshNode);\n patchExistingInstance(ctx, reclaimed, freshNode);\n reconcileItemChildren(ctx, reclaimed, freshNode, mountFn);\n reclaimed.graphNode.setProp('_sig', freshNode.getProp('_sig') as never);\n reclaimed.graphNode.setProp('_item', entry.item as never);\n hooks?.onEnter(reclaimed);\n newInstances.push(reclaimed);\n } else {\n const freshNode = entry.build();\n built.push(freshNode);\n const inst = mountFn(freshNode, parentDom);\n hooks?.onEnter(inst);\n newInstances.push(inst);\n }\n }\n }\n\n // Determine + remove stale instances. Transitioned rows defer their whole\n // teardown chain to leave-animation end (§7) and are excluded from `removed`.\n const removed: NodeInstance[] = [];\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n if (usedKeys.has(key)) continue;\n if (hooks !== undefined && hooks.beginLeave(inst)) continue;\n const parent = ctx.dom.parentNode(inst.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, inst.domNode);\n inst.dispose();\n removed.push(inst);\n }\n\n // Minimal-move reorder to the desired order.\n reorderDomMinimal(ctx, parentDom, oldInstances, newInstances);\n\n return { instances: newInstances, removed, built };\n}\n\n/**\n * Minimal-move DOM reorder.\n *\n * Reused nodes retain their previous DOM slots and newly-mounted nodes sit at\n * the end. We compute the longest increasing subsequence of the reused nodes'\n * previous positions; those are already in correct relative order and stay put.\n * Every other node is inserted before its right-hand neighbour, walking\n * right-to-left. This yields exactly (n − |LIS|) `insertBefore` calls — the\n * minimum — instead of the O(n) sweep the naive reorder performs on a prepend.\n */\nfunction reorderDomMinimal(\n ctx: RenderContext,\n parentDom: Element,\n oldInstances: NodeInstance[],\n newInstances: NodeInstance[],\n): void {\n const n = newInstances.length;\n if (n === 0) return;\n\n const oldIndexOf = new Map<NodeInstance, number>();\n for (let i = 0; i < oldInstances.length; i++) oldIndexOf.set(oldInstances[i]!, i);\n\n const source = new Array<number>(n);\n let moved = false;\n let lastSeen = -1;\n for (let i = 0; i < n; i++) {\n const oi = oldIndexOf.get(newInstances[i]!);\n if (oi === undefined) {\n source[i] = -1; // freshly mounted row\n moved = true;\n } else {\n source[i] = oi;\n if (oi < lastSeen) moved = true; // an out-of-order reused row exists\n else lastSeen = oi;\n }\n }\n\n // Fast path: nothing is out of order and there are no new rows to reposition.\n if (!moved) return;\n\n const keep = longestIncreasingSubsequence(source);\n\n let refNode: Node | null = null;\n for (let i = n - 1; i >= 0; i--) {\n const domNode = newInstances[i]!.domNode;\n if (source[i] === -1 || !keep.has(i)) {\n if (ctx.dom.nextSibling(domNode) !== refNode) {\n ctx.dom.insertBefore(parentDom, domNode, refNode);\n }\n }\n refNode = domNode;\n }\n}\n\n/**\n * Indices (into `source`) forming a longest strictly-increasing subsequence,\n * ignoring `-1` entries (new rows, which always move). O(n log n) with\n * predecessor reconstruction.\n */\nfunction longestIncreasingSubsequence(source: readonly number[]): Set<number> {\n const keep = new Set<number>();\n const n = source.length;\n const tails: number[] = []; // tails[k] = source-index of smallest tail of an LIS of length k+1\n const prev = new Array<number>(n).fill(-1);\n\n for (let i = 0; i < n; i++) {\n const v = source[i]!;\n if (v < 0) continue;\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (source[tails[mid]!]! < v) lo = mid + 1;\n else hi = mid;\n }\n if (lo > 0) prev[i] = tails[lo - 1]!;\n tails[lo] = i;\n }\n\n let idx = tails.length > 0 ? tails[tails.length - 1]! : -1;\n while (idx >= 0) {\n keep.add(idx);\n idx = prev[idx]!;\n }\n return keep;\n}\n\n/**\n * Targeted in-place content update for a reused list item whose data changed.\n *\n * The item's DOM element is kept; only its contents are updated. Children are\n * matched positionally against the freshly-built subtree:\n * - same node type at a position → the existing child is reused and its props\n * are patched in place (e.g. a text node's text is rewritten), then we\n * recurse into its children;\n * - different type / new position → the fresh child node is reparented onto the\n * live item node and mounted;\n * - surplus old children → disposed, with DOM, subscriptions, listeners and\n * handler registrations all torn down.\n *\n * This deliberately reuses the same keyed/positional strategy rather than a\n * virtual DOM, and never destroys the item element itself.\n */\nfunction reconcileItemChildren(\n ctx: RenderContext,\n itemInstance: NodeInstance,\n newItemNode: GraphNode,\n mountFn: MountFn,\n): void {\n const el = itemInstance.domNode;\n if (!ctx.dom.isElement(el)) return;\n\n const oldChildren = [...itemInstance.children];\n const newChildNodes = [...newItemNode.children];\n const nextChildren: NodeInstance[] = [];\n const kept = new Set<NodeInstance>();\n\n for (let i = 0; i < newChildNodes.length; i++) {\n const newChild = newChildNodes[i]!;\n const oldChild = oldChildren[i];\n\n if (oldChild !== undefined && oldChild.graphNode.type === newChild.type) {\n // Reuse in place — patch this node's props and recurse into descendants.\n patchExistingInstance(ctx, oldChild, newChild);\n reconcileItemChildren(ctx, oldChild, newChild, mountFn);\n nextChildren.push(oldChild);\n kept.add(oldChild);\n } else {\n // Structural change at this position — mount the fresh child. Reparent it\n // out of the freshly-built subtree so the wholesale detach of the\n // unadopted item node (in mount.ts) does not remove this now-live node.\n itemInstance.graphNode.appendChild(newChild);\n const inst = mountFn(newChild, el);\n nextChildren.push(inst);\n }\n }\n\n // Dispose old children that were not reused (surplus or type-mismatched).\n for (const old of oldChildren) {\n if (kept.has(old)) continue;\n const parent = ctx.dom.parentNode(old.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, old.domNode);\n old.dispose();\n forgetInstanceTree(ctx, old);\n ctx.graph.detachNode(old.graphNode);\n }\n\n // Restore correct DOM order within the item element.\n reorderDom(ctx, el, nextChildren);\n\n // Sync the live instance's children.\n itemInstance.children.length = 0;\n for (const c of nextChildren) itemInstance.children.push(c);\n\n // Keep the graph model's item children consistent with the reconciled order.\n for (const c of [...itemInstance.graphNode.children]) {\n itemInstance.graphNode.removeChild(c);\n }\n for (const c of nextChildren) itemInstance.graphNode.appendChild(c.graphNode);\n}\n\n/** Move a parent's DOM children to match the given instance order (minimal moves). */\nfunction reorderDom(\n ctx: RenderContext,\n parentDom: Element,\n instances: NodeInstance[],\n): void {\n let referenceNode: Node | null = null;\n for (let i = instances.length - 1; i >= 0; i--) {\n const inst = instances[i];\n if (inst === undefined) continue;\n const domNode = inst.domNode;\n const currentNext = ctx.dom.nextSibling(domNode);\n if (currentNext !== referenceNode) {\n ctx.dom.insertBefore(parentDom, domNode, referenceNode);\n }\n referenceNode = domNode;\n }\n}\n\n/** Recursively drop an instance subtree from the renderer's instance index. */\nfunction forgetInstanceTree(ctx: RenderContext, instance: NodeInstance): void {\n ctx.instances.delete(instance.graphNode.id);\n for (const child of instance.children) forgetInstanceTree(ctx, child);\n}\n\nfunction patchExistingInstance(\n ctx: RenderContext,\n instance: NodeInstance,\n newNode: GraphNode,\n): void {\n const oldNode = instance.graphNode;\n for (const [key, newVal] of Object.entries(newNode.props)) {\n const oldVal = oldNode.getProp(key);\n if (!Object.is(oldVal, newVal)) {\n patchNode(ctx, instance.graphNode, key, newVal);\n }\n }\n}\n","/**\n * CSS class-based enter/leave transition controller (§2–§8).\n *\n * This is the browser-only runtime that consumes the `__transition__<nodeId>`\n * descriptor the DSL registers (a pre-resolved {@link ResolvedTransitionLike}).\n * It is deliberately structural about that descriptor — like the renderer's\n * `__overlay__`/`__component__` handling — so the renderer takes NO compile-time\n * dependency on the DSL package.\n *\n * Engine (confirmed decision): CSS classes, no Web Animations API, no\n * browser-only API referenced at module scope. Every timer / rAF / event\n * binding is reached lazily through `globalThis` and only ever runs when\n * `dom.body() !== null` (the same SSR guard `wireOverlayBehavior` uses), so:\n * - server output is byte-identical (nothing here runs during SSR — §21);\n * - happy-dom, which dispatches no `transitionend`/`animationend`, still\n * completes deterministically via the fallback timeout (§24).\n *\n * The controller is created once per reactive container instance (reactive-list\n * or conditional) so its `leaving` map survives across reconcile passes — that\n * is what makes leave→enter reclaim (§6) and keyed-identity list leave (§7)\n * correct.\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { NodeInstance } from './node-instance.js';\n\n/**\n * The renderer's structural view of the resolved transition the DSL stores in\n * `__transition__<id>`. Mirrors `@streetui/dsl`'s `ResolvedTransition` without\n * importing it (no renderer→dsl dependency).\n */\nexport interface ResolvedTransitionLike {\n readonly enterActive: readonly string[];\n readonly enterFrom: readonly string[];\n readonly enterTo: readonly string[];\n readonly leaveActive: readonly string[];\n readonly leaveFrom: readonly string[];\n readonly leaveTo: readonly string[];\n readonly appear: boolean;\n readonly duration: number;\n}\n\n/**\n * Hooks handed to the reconciler so it can (a) reclaim an instance that is\n * mid-leave when its key re-enters (leave→enter cancellation), (b) defer the\n * remove/dispose/forget/detach chain for a leaving instance until its animation\n * ends, and (c) play the enter animation for a freshly-inserted instance. When\n * no transition applies (or we are on the server) every hook degrades to the\n * pre-transition synchronous behaviour.\n */\nexport interface TransitionHooks {\n /**\n * If an instance for `key` is currently animating out, cancel its leave and\n * return it for reuse; otherwise undefined. The caller re-mounts nothing and\n * reuses the returned instance's live DOM node.\n */\n takeLeaving(key: string): NodeInstance | undefined;\n /**\n * Begin a leave animation for a removed instance. Returns true when the whole\n * teardown chain has been deferred to animation-end (caller must NOT remove,\n * dispose, forget or detach it), or false when there is no transition / no\n * browser and the caller should tear it down synchronously as before.\n */\n beginLeave(inst: NodeInstance): boolean;\n /** Play the enter animation for a freshly-inserted (or reclaimed) instance. */\n onEnter(inst: NodeInstance): void;\n}\n\n/** Read the pre-resolved transition descriptor for a node, if any. */\nexport function getResolvedTransition(\n graph: ApplicationGraph,\n nodeId: string,\n): ResolvedTransitionLike | undefined {\n const fn = graph.getHandler(`__transition__${nodeId}`) as\n | (() => ResolvedTransitionLike)\n | undefined;\n return fn === undefined ? undefined : fn();\n}\n\n// ── Browser-global access (lazy, never at module scope) ──────────────────────\n\ninterface RafHost {\n requestAnimationFrame?: (cb: () => void) => number;\n setTimeout: (cb: () => void, ms: number) => unknown;\n clearTimeout: (h: unknown) => void;\n}\n\nfunction host(): RafHost {\n return globalThis as unknown as RafHost;\n}\n\n/** Schedule a callback for the next frame (falls back to a macrotask). */\nfunction nextFrame(cb: () => void): void {\n const h = host();\n const raf = h.requestAnimationFrame;\n if (typeof raf === 'function') {\n // Double rAF: ensures the \"from\" classes have been painted before we flip\n // to the \"to\" classes, so the transition actually runs in real browsers.\n raf(() => raf(cb));\n } else {\n h.setTimeout(cb, 0);\n }\n}\n\n// ── Class list manipulation via the adapter (no classList dependency) ─────────\n\nfunction splitClass(value: string | null): string[] {\n if (value === null) return [];\n const out: string[] = [];\n for (const t of value.split(/\\s+/)) if (t.length > 0) out.push(t);\n return out;\n}\n\nfunction addClasses(dom: DOMAdapter, el: Element, classes: readonly string[]): void {\n if (classes.length === 0) return;\n const current = splitClass(dom.getAttribute(el, 'class'));\n let changed = false;\n for (const c of classes) {\n if (!current.includes(c)) {\n current.push(c);\n changed = true;\n }\n }\n if (changed) dom.setAttribute(el, 'class', current.join(' '));\n}\n\nfunction removeClasses(dom: DOMAdapter, el: Element, classes: readonly string[]): void {\n if (classes.length === 0) return;\n const current = splitClass(dom.getAttribute(el, 'class'));\n const next = current.filter((c) => !classes.includes(c));\n if (next.length !== current.length) {\n if (next.length === 0) dom.removeAttribute(el, 'class');\n else dom.setAttribute(el, 'class', next.join(' '));\n }\n}\n\n/**\n * One running enter-or-leave animation on a single element. Owns exactly one set\n * of DOM listeners + one fallback timer, and guarantees `settle`/`cancel` run\n * their cleanup at most once — no stale callbacks, no duplicate listeners, no\n * duplicate cleanup (§6).\n */\ninterface Run {\n /** Force the animation to its end synchronously (used by cancellation). */\n cancel(): void;\n}\n\nfunction startRun(\n dom: DOMAdapter,\n el: Element,\n active: readonly string[],\n from: readonly string[],\n to: readonly string[],\n duration: number,\n onDone: () => void,\n): Run {\n const h = host();\n let finished = false;\n let timer: unknown = null;\n\n const onEvent = ((e: Event): void => {\n // Ignore bubbling transition/animation events from descendants.\n if (e.target !== el) return;\n finish();\n }) as EventListener;\n\n const detach = (): void => {\n dom.removeEventListener(el, 'transitionend', onEvent);\n dom.removeEventListener(el, 'animationend', onEvent);\n if (timer !== null) {\n h.clearTimeout(timer);\n timer = null;\n }\n };\n\n const finish = (): void => {\n if (finished) return;\n finished = true;\n detach();\n // Clear all transition classes so the element rests in its natural state.\n removeClasses(dom, el, active);\n removeClasses(dom, el, to);\n removeClasses(dom, el, from);\n onDone();\n };\n\n // Phase 1: apply the starting + active classes immediately.\n addClasses(dom, el, from);\n addClasses(dom, el, active);\n\n dom.addEventListener(el, 'transitionend', onEvent);\n dom.addEventListener(el, 'animationend', onEvent);\n // Fallback completion: the safety net for elements that fire no transition\n // event (and the ONLY completion signal under happy-dom, where tests set a\n // small duration). 0 → next macrotask.\n timer = h.setTimeout(finish, duration);\n\n // Phase 2: on the next frame flip from → to so the CSS transition runs.\n nextFrame(() => {\n if (finished) return;\n removeClasses(dom, el, from);\n addClasses(dom, el, to);\n });\n\n return {\n cancel: () => {\n // Cancel = settle immediately (removes classes, clears listeners/timer)\n // but WITHOUT invoking onDone, so a cancelled leave never finalizes the\n // node it was about to destroy.\n if (finished) return;\n finished = true;\n detach();\n removeClasses(dom, el, active);\n removeClasses(dom, el, to);\n removeClasses(dom, el, from);\n },\n };\n}\n\ninterface LeavingEntry {\n readonly inst: NodeInstance;\n readonly run: Run;\n}\n\n/** Which half of a transition to play on a bare element. */\nexport type TransitionPhase = 'enter' | 'leave';\n\n/**\n * Play one enter/leave transition on a bare DOM element, outside the keyed\n * reconciler — the seam the router uses for route leave/enter (§9) and any other\n * consumer that owns a single host element rather than a reactive container.\n *\n * Reuses the exact same {@link startRun} mechanics as list/conditional\n * transitions (from+active applied immediately, next-frame flip to `to`,\n * completion on transitionend/animationend or the fallback timer), so there is\n * one transition engine, not two. The returned handle's `cancel()` settles the\n * run immediately WITHOUT invoking `onDone` — the caller uses it to abort an\n * in-flight enter when the same host is about to start leaving (rapid\n * navigation), avoiding overlapping runs/duplicate listeners on one element.\n *\n * On the server (or any non-element target) there is nothing to animate, so\n * `onDone` runs synchronously and `cancel()` is a no-op — the caller's teardown\n * still happens exactly once.\n */\nexport function runElementTransition(\n dom: DOMAdapter,\n el: Element,\n rt: ResolvedTransitionLike,\n phase: TransitionPhase,\n onDone: () => void,\n): { cancel(): void } {\n if (dom.body() === null || !dom.isElement(el)) {\n onDone();\n return { cancel: () => {} };\n }\n const active = phase === 'enter' ? rt.enterActive : rt.leaveActive;\n const from = phase === 'enter' ? rt.enterFrom : rt.leaveFrom;\n const to = phase === 'enter' ? rt.enterTo : rt.leaveTo;\n return startRun(dom, el, active, from, to, rt.duration, onDone);\n}\n\n\n/**\n * Per-container transition controller. One instance is created for each\n * reactive-list / conditional NodeInstance in {@link wireReactiveList}; its\n * `leaving` map persists across every reconcile of that container.\n */\nexport class TransitionController {\n private readonly leaving = new Map<string, LeavingEntry>();\n\n constructor(\n private readonly dom: DOMAdapter,\n private readonly graph: ApplicationGraph,\n /** Full teardown of a leaving instance (remove + dispose + forget + detach). */\n private readonly finalize: (inst: NodeInstance) => void,\n ) {}\n\n /** True only in a real DOM environment (browser). */\n private get browser(): boolean {\n return this.dom.body() !== null;\n }\n\n private keyOf(inst: NodeInstance): string {\n return inst.graphNode.key ?? inst.graphNode.id;\n }\n\n private resolved(node: GraphNode): ResolvedTransitionLike | undefined {\n return getResolvedTransition(this.graph, node.id);\n }\n\n /** Run the enter animation for `inst` if it carries a transition (browser only). */\n enter(inst: NodeInstance): void {\n if (!this.browser) return;\n const rt = this.resolved(inst.graphNode);\n if (rt === undefined) return;\n const el = inst.domNode;\n if (!this.dom.isElement(el)) return;\n startRun(this.dom, el, rt.enterActive, rt.enterFrom, rt.enterTo, rt.duration, () => {\n /* enter has no teardown; classes already cleared by the run */\n });\n }\n\n /**\n * Play `appear` for any initial child that opted into it (fresh browser mount\n * only — hydration must never animate appear, §22, and this is called only on\n * the mount path).\n */\n appear(children: readonly NodeInstance[]): void {\n if (!this.browser) return;\n for (const child of children) {\n const rt = this.resolved(child.graphNode);\n if (rt !== undefined && rt.appear) this.enter(child);\n }\n }\n\n hooks(): TransitionHooks {\n return {\n takeLeaving: (key) => {\n const entry = this.leaving.get(key);\n if (entry === undefined) return undefined;\n entry.run.cancel(); // leave→enter: stop the leave, keep the live node\n this.leaving.delete(key);\n return entry.inst;\n },\n beginLeave: (inst) => {\n if (!this.browser) return false;\n const rt = this.resolved(inst.graphNode);\n if (rt === undefined) return false;\n const el = inst.domNode;\n if (!this.dom.isElement(el)) return false;\n const key = this.keyOf(inst);\n // If a prior leave for this key is somehow still running, settle it.\n const prior = this.leaving.get(key);\n if (prior !== undefined) prior.run.cancel();\n const run = startRun(\n this.dom,\n el,\n rt.leaveActive,\n rt.leaveFrom,\n rt.leaveTo,\n rt.duration,\n () => {\n // Only finalize if THIS run is still the registered one (it may have\n // been reclaimed by a re-entering key, which cancels without done).\n const current = this.leaving.get(key);\n if (current !== undefined && current.run === run) {\n this.leaving.delete(key);\n this.finalize(inst);\n }\n },\n );\n this.leaving.set(key, { inst, run });\n return true;\n },\n onEnter: (inst) => this.enter(inst),\n };\n }\n}\n","/**\n * Document head / metadata runtime (2.0 §1–§3).\n *\n * Two entry points, sharing the normalized {@link HeadEntry} model the DSL's\n * `head()` produces (mirrored here as a local structural type so the renderer\n * takes no compile-time dependency on the DSL package — the same convention as\n * the overlay/component descriptors):\n *\n * • `wireHeadBehavior(ctx, node, instance)` — BROWSER. Reads the\n * `__head__<id>` descriptor, registers this node's contribution with a\n * per-render {@link HeadManager} (created lazily on `ctx`), subscribes to any\n * reactive attr/text signals, and tracks cleanup on the NodeInstance so the\n * contribution is withdrawn (and the manager re-applies the merged result)\n * when the node unmounts or the route changes. Server-safe: when\n * `dom.head()` is null (SSR) it is a no-op.\n *\n * • `renderHead(compiled)` — SERVER. Walks the compiled graph in document\n * order, merges every live `head()` contribution (last-in-document-order\n * wins per dedup key — §3), and serializes the effective tags to an HTML\n * string for the caller to place inside `<head>`. Only the active graph is\n * walked, so only active-route metadata is emitted (§2). Each tag carries\n * `data-streetui-head` + `data-streetui-head-key=\"…\"` so the browser adopts\n * it on hydration instead of creating a duplicate.\n */\n\nimport type { GraphNode, ApplicationGraph } from '@streetui/graph';\nimport { ServerDOMAdapter } from '@streetui/dom';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport type { DOMAdapter } from '@streetui/dom';\nimport type { RenderContext } from './render-context.js';\nimport type { NodeInstance } from './node-instance.js';\n\n/** The marker attribute stamped on every framework-managed head tag. */\nconst HEAD_MARKER = 'data-streetui-head';\n/** The attribute carrying a tag's dedup key, so hydration can match server tags. */\nconst HEAD_KEY = 'data-streetui-head-key';\n\n// ── Structural mirror of the DSL's head entry model ─────────────────────────────\n\ninterface HeadEntryLike {\n readonly tag: 'title' | 'meta' | 'link' | 'base';\n readonly dedupKey: string;\n readonly attrs: Readonly<Record<string, unknown>>;\n readonly text?: unknown;\n}\ninterface HeadContributionLike {\n readonly entries: readonly HeadEntryLike[];\n}\n\ninterface SignalLike {\n subscribe: (fn: (v: unknown) => void) => () => void;\n peek: () => unknown;\n}\n\nfunction isSignalLike(v: unknown): v is SignalLike {\n return (\n v !== null &&\n typeof v === 'object' &&\n typeof (v as Record<string, unknown>)['subscribe'] === 'function' &&\n typeof (v as Record<string, unknown>)['peek'] === 'function'\n );\n}\n\n/** Read a bindable value to its current string (peeking a signal, else stringifying). */\nfunction readValue(v: unknown): string {\n if (isSignalLike(v)) return String(v.peek() ?? '');\n return String(v ?? '');\n}\n\n/** A fully-resolved head tag: concrete strings, ready to write to the DOM/serialize. */\ninterface ResolvedTag {\n readonly tag: 'title' | 'meta' | 'link' | 'base';\n readonly attrs: Record<string, string>;\n readonly text?: string;\n}\n\nfunction resolveEntry(entry: HeadEntryLike): ResolvedTag {\n const attrs: Record<string, string> = {};\n for (const key of Object.keys(entry.attrs)) {\n attrs[key] = readValue(entry.attrs[key]);\n }\n const resolved: ResolvedTag = { tag: entry.tag, attrs };\n if (entry.tag === 'title') {\n return { ...resolved, text: readValue(entry.text) };\n }\n return resolved;\n}\n\n// ── Browser head manager ────────────────────────────────────────────────────────\n\ninterface AppliedRecord {\n el: Element;\n attrKeys: Set<string>;\n tag: string;\n}\n\n/**\n * Coordinates every live `head()` node's contribution into a single\n * `document.head`. One instance per render (lazily created on `ctx`). Merges by\n * dedup key with last-in-document-order winning, and applies the minimal diff to\n * the DOM on every register/unregister/signal change. Adopts server-emitted tags\n * on the first apply so hydration produces no duplicates.\n */\nexport class HeadManager {\n private readonly _dom: DOMAdapter;\n private readonly _head: Element;\n private readonly _contributions = new Map<string, { order: number; entries: readonly HeadEntryLike[] }>();\n private readonly _applied = new Map<string, AppliedRecord>();\n private _order = 0;\n private _adopted = false;\n\n constructor(dom: DOMAdapter, head: Element) {\n this._dom = dom;\n this._head = head;\n }\n\n /** Register (or replace) a node's contribution and re-apply the merged result. */\n register(nodeId: string, entries: readonly HeadEntryLike[]): void {\n this._contributions.set(nodeId, { order: this._order++, entries });\n this.apply();\n }\n\n /** Withdraw a node's contribution (unmount / route change) and re-apply. */\n unregister(nodeId: string): void {\n if (this._contributions.delete(nodeId)) this.apply();\n }\n\n /** Recompute the merged head and patch `document.head` to match. */\n apply(): void {\n if (!this._adopted) {\n this._adoptServerTags();\n this._adopted = true;\n }\n\n // Merge: iterate contributions in document order; per dedup key the last\n // writer wins (§3). Within a contribution, later entries win too.\n const ordered = [...this._contributions.values()].sort((a, b) => a.order - b.order);\n const merged = new Map<string, ResolvedTag>();\n for (const contribution of ordered) {\n for (const entry of contribution.entries) {\n merged.set(entry.dedupKey, resolveEntry(entry));\n }\n }\n\n // Upsert desired tags.\n for (const [key, desired] of merged) {\n const existing = this._applied.get(key);\n if (existing !== undefined && existing.tag === desired.tag) {\n this._reconcileAttrs(existing, desired);\n } else {\n if (existing !== undefined) {\n // Tag kind changed for this key (rare) — drop the old element.\n this._dom.removeChild(this._head, existing.el);\n this._applied.delete(key);\n }\n const el = this._createTag(key, desired);\n this._dom.appendChild(this._head, el);\n this._applied.set(key, { el, attrKeys: new Set(Object.keys(desired.attrs)), tag: desired.tag });\n }\n }\n\n // Remove managed tags no longer desired.\n for (const [key, record] of [...this._applied]) {\n if (!merged.has(key)) {\n this._dom.removeChild(this._head, record.el);\n this._applied.delete(key);\n }\n }\n }\n\n private _createTag(key: string, desired: ResolvedTag): Element {\n const el = this._dom.createElement(desired.tag);\n this._dom.setAttribute(el, HEAD_MARKER, '');\n this._dom.setAttribute(el, HEAD_KEY, key);\n for (const attr of Object.keys(desired.attrs)) {\n this._dom.setAttribute(el, attr, desired.attrs[attr]!);\n }\n if (desired.tag === 'title') this._dom.setTextContent(el, desired.text ?? '');\n return el;\n }\n\n private _reconcileAttrs(record: AppliedRecord, desired: ResolvedTag): void {\n const nextKeys = new Set(Object.keys(desired.attrs));\n // Remove attrs that are no longer present.\n for (const attr of record.attrKeys) {\n if (!nextKeys.has(attr)) this._dom.removeAttribute(record.el, attr);\n }\n // Set/overwrite desired attrs (idempotent when unchanged — matters on the\n // hydration adopt path, where the element is a server tag being re-asserted).\n for (const attr of nextKeys) {\n this._dom.setAttribute(record.el, attr, desired.attrs[attr]!);\n }\n if (desired.tag === 'title') this._dom.setTextContent(record.el, desired.text ?? '');\n record.attrKeys = nextKeys;\n }\n\n /**\n * Seed `_applied` from server-emitted `[data-streetui-head-key]` tags already\n * in `document.head`. The subsequent diff reuses these elements when the\n * client desires the same key (no duplicate), rewrites them if the value\n * changed, or removes them if the client graph no longer wants them.\n */\n private _adoptServerTags(): void {\n for (const child of this._dom.childNodes(this._head)) {\n if (!this._dom.isElement(child)) continue;\n const el = child as Element;\n const key = this._dom.getAttribute(el, HEAD_KEY);\n if (key === null) continue;\n this._applied.set(key, {\n el,\n attrKeys: new Set(this._attrNames(el)),\n tag: this._dom.tagName(el),\n });\n }\n }\n\n /** The framework-managed attribute names currently on a server tag. */\n private _attrNames(el: Element): string[] {\n // We cannot enumerate a live element's attributes through the minimal\n // DOMAdapter surface, so we re-assert from the desired set on first apply\n // (see `_reconcileAttrs`, which sets desired keys and removes only tracked\n // ones). Tracking the marker keys is enough to keep them from lingering.\n const names: string[] = [];\n if (this._dom.getAttribute(el, HEAD_MARKER) !== null) names.push(HEAD_MARKER);\n if (this._dom.getAttribute(el, HEAD_KEY) !== null) names.push(HEAD_KEY);\n return names;\n }\n}\n\n/** Lazily get (or create) the render's HeadManager. Null on the server. */\nfunction getHeadManager(ctx: RenderContext): HeadManager | null {\n const head = ctx.dom.head();\n if (head === null) return null; // server render pass — renderHead handles SSR\n const mutable = ctx as { head?: HeadManager };\n if (mutable.head === undefined) mutable.head = new HeadManager(ctx.dom, head);\n return mutable.head;\n}\n\n/**\n * Wire a mounted/hydrated `head` node's contribution into `document.head`.\n * Server-safe (no-op when there is no document). Shared by the mount and hydrate\n * paths so both establish identical ownership + cleanup.\n */\nexport function wireHeadBehavior(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n): void {\n const manager = getHeadManager(ctx);\n if (manager === null) return;\n\n const descFn = ctx.graph.getHandler(`__head__${graphNode.id}`) as\n | (() => HeadContributionLike)\n | undefined;\n if (descFn === undefined) return;\n\n const contribution = descFn();\n const nodeId = graphNode.id;\n manager.register(nodeId, contribution.entries);\n\n // Subscribe to any reactive attr/text signals; a change re-applies the merged\n // head. All subscriptions + the contribution withdrawal are tracked on the\n // instance, so a route change / unmount tears them down and re-applies.\n for (const entry of contribution.entries) {\n for (const attrKey of Object.keys(entry.attrs)) {\n const v = entry.attrs[attrKey];\n if (isSignalLike(v)) {\n instance.trackCleanup(v.subscribe(() => manager.apply()));\n }\n }\n if (isSignalLike(entry.text)) {\n instance.trackCleanup(entry.text.subscribe(() => manager.apply()));\n }\n }\n\n instance.trackCleanup(() => manager.unregister(nodeId));\n}\n\n// ── Server-side head emission ─────────────────────────────────────────────────\n\n/**\n * Render the active graph's merged document metadata to an HTML string suitable\n * for placing inside `<head>`. Walks the graph in document order, merges every\n * `head()` contribution (last-in-document-order wins per dedup key), and\n * serializes each effective tag with the `data-streetui-head` marker so the\n * browser adopts it on hydration. Returns `''` when the app declares no metadata\n * — so apps that never call `head()` emit nothing extra and existing SSR output\n * is unchanged.\n */\nexport function renderHead(compiled: CompiledApplication): string {\n const graph: ApplicationGraph = compiled.graph;\n\n const merged = new Map<string, ResolvedTag>();\n graph.walk((node) => {\n if (node.type !== 'head') return;\n const descFn = graph.getHandler(`__head__${node.id}`) as\n | (() => HeadContributionLike)\n | undefined;\n if (descFn === undefined) return;\n for (const entry of descFn().entries) {\n merged.set(entry.dedupKey, resolveEntry(entry));\n }\n });\n\n if (merged.size === 0) return '';\n\n const dom = new ServerDOMAdapter();\n let out = '';\n for (const [key, desired] of merged) {\n const el = dom.createElement(desired.tag);\n dom.setAttribute(el, HEAD_MARKER, '');\n dom.setAttribute(el, HEAD_KEY, key);\n for (const attr of Object.keys(desired.attrs)) {\n dom.setAttribute(el, attr, desired.attrs[attr]!);\n }\n if (desired.tag === 'title') dom.setTextContent(el, desired.text ?? '');\n out += dom.serializeOuter(el);\n }\n return out;\n}\n","/**\n * Initial mount — creates DOM nodes for every GraphNode and\n * attaches them into the container.\n *\n * This is a recursive depth-first walk. For each GraphNode:\n * 1. Create the DOM element (or text node)\n * 2. Apply props/attributes\n * 3. Wire events\n * 4. Wire signal subscriptions for reactive props\n * 5. Recurse into children\n * 6. Insert into the DOM\n */\n\nimport type { GraphNode, ApplicationGraph } from '@streetui/graph';\nimport type { DOMAdapter } from '@streetui/dom';\nimport {\n focusInitial,\n trapFocus,\n containFocus,\n onEscape,\n rovingMenu,\n saveFocus,\n restoreFocus,\n} from '@streetui/dom';\nimport type { RenderContext } from './render-context.js';\nimport { NodeInstance } from './node-instance.js';\nimport { applyProp } from './attributes.js';\nimport { wireEvents } from './events.js';\nimport { resolveTag } from './tag-map.js';\nimport {\n reconcileChildren,\n reconcileChildrenByPlan,\n type PlanEntry,\n} from './reconciliation.js';\nimport { TransitionController, type TransitionHooks } from './transition.js';\nimport { wireHeadBehavior } from './head.js';\n\n/**\n * Prop keys handled by the per-type mount branches (or reserved internals), so\n * `applyNodeProps` must skip them to avoid double-applying. This set is\n * invariant across nodes, so it is hoisted to module scope: allocating it once\n * (rather than per node) removes N Set allocations per mount/SSR pass and the\n * GC pressure they create. Treat as read-only — never mutate.\n */\nconst SKIP_PROP_KEYS: ReadonlySet<string> = new Set([\n 'text', 'label', 'level', 'inputType', 'src', 'alt', 'href', 'external',\n 'value', 'placeholder', 'disabled', '_renderKey', 'key', 'name',\n]);\n\nexport function mountGraph(ctx: RenderContext): NodeInstance {\n return mountNode(ctx, ctx.graph.root, ctx.container);\n}\n\nexport function mountNode(\n ctx: RenderContext,\n graphNode: GraphNode,\n parentDom: Node,\n): NodeInstance {\n const { dom, graph } = ctx;\n\n // ── v1.7 static SSR fast path (SSR-only) ──────────────────────────────────\n // When a compiler-derived static SSR plan is present (server render only)\n // and this node is a maximal static-subtree root, emit its precomputed HTML\n // verbatim instead of recursively constructing ServerElement/ServerText/\n // NodeInstance for the whole subtree. `ctx.staticHTML` is always undefined on\n // the browser path, so this is a single short-circuiting check there — the\n // client hot path and its semantics are untouched (§5/§6/§23). The stored\n // string is produced by this same mount+serialize pipeline, so output is\n // byte-identical (§8). We still register ONE NodeInstance for the root so the\n // parent's children bookkeeping and post-render dispose behave normally.\n const staticHTML = ctx.staticHTML;\n if (staticHTML !== undefined && dom.createRawHTML !== undefined) {\n const precomputed = staticHTML.get(graphNode.id);\n if (precomputed !== undefined) {\n const raw = dom.createRawHTML(precomputed);\n dom.appendChild(parentDom, raw);\n const instance = new NodeInstance(graphNode, raw);\n ctx.instances.set(graphNode.id, instance);\n return instance;\n }\n }\n\n // The application root node maps to the container itself — don't create a duplicate element\n if (graphNode.type === 'application') {\n const instance = new NodeInstance(graphNode, parentDom);\n ctx.instances.set(graphNode.id, instance);\n for (const child of graphNode.children) {\n const childInstance = mountNode(ctx, child, parentDom);\n instance.addChild(childInstance);\n }\n return instance;\n }\n\n // Text-only nodes render as a <span> containing a text node\n if (graphNode.type === 'text') {\n const text = String(graphNode.getProp('text') ?? '');\n const el = dom.createElement('span');\n const textNode = dom.createTextNode(text);\n dom.appendChild(el, textNode);\n applyNodeProps(ctx, graphNode, el);\n\n // Create the live instance up front and reuse it for event wiring. The\n // previous code allocated a throwaway NodeInstance solely to satisfy\n // wireEvents' signature, wasting one NodeInstance (+ its children array and\n // CleanupRegistry) per text node — pure GC pressure on the hottest mount\n // path. wireEvents/wireSignalBindings each early-return on empty arrays.\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n // Reactive text binding — only build the update closure when the node has\n // bindings. wireSignalBindings early-returns on empty stateRefs, so for a\n // static text node (the common case in a large initial render) the\n // textUpdate closure would be allocated and thrown away: avoidable GC\n // pressure on the hottest mount path.\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, textUpdate(dom, el, textNode));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Heading nodes\n if (graphNode.type === 'heading') {\n const level = (graphNode.getProp('level') as number | undefined) ?? 1;\n const tag = `h${level}` as string;\n const el = dom.createElement(tag);\n const text = String(graphNode.getProp('text') ?? '');\n dom.setTextContent(el, text);\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, headingUpdate(dom, el));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Input nodes\n if (graphNode.type === 'input') {\n const el = dom.createElement('input') as HTMLInputElement;\n const inputType = String(graphNode.getProp('inputType') ?? 'text');\n dom.setAttribute(el, 'type', inputType);\n const placeholder = graphNode.getProp('placeholder');\n if (placeholder !== undefined) dom.setAttribute(el, 'placeholder', String(placeholder));\n const value = graphNode.getProp('value');\n if (value !== undefined) dom.setProperty(el, 'value', String(value));\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, inputUpdate(dom, el));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Image nodes\n if (graphNode.type === 'image') {\n const el = dom.createElement('img') as HTMLImageElement;\n const src = graphNode.getProp('src');\n const alt = graphNode.getProp('alt');\n if (src !== undefined) dom.setAttribute(el, 'src', String(src));\n if (alt !== undefined) dom.setAttribute(el, 'alt', String(alt));\n const width = graphNode.getProp('width');\n const height = graphNode.getProp('height');\n if (width !== undefined) dom.setAttribute(el, 'width', String(width));\n if (height !== undefined) dom.setAttribute(el, 'height', String(height));\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Link nodes\n if (graphNode.type === 'link') {\n const el = dom.createElement('a') as HTMLAnchorElement;\n const href = graphNode.getProp('href');\n const label = graphNode.getProp('label');\n const external = graphNode.getProp('external');\n if (href !== undefined) dom.setAttribute(el, 'href', String(href));\n if (label !== undefined) dom.setTextContent(el, String(label));\n if (external === true) {\n dom.setAttribute(el, 'target', '_blank');\n dom.setAttribute(el, 'rel', 'noopener noreferrer');\n }\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n // A link's label/href may be bound to signals (e.g. i18n `t()` in nav). Wire\n // the same signal-binding path buttons use so the text updates reactively.\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, linkUpdate(dom, el));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Button nodes\n if (graphNode.type === 'button') {\n const el = dom.createElement('button') as HTMLButtonElement;\n const label = graphNode.getProp('label');\n if (label !== undefined) dom.setTextContent(el, String(label));\n const disabled = graphNode.getProp('disabled');\n if (disabled === true) dom.setAttribute(el, 'disabled', '');\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, buttonUpdate(dom, el));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Reactive list / conditional — a container whose children are driven by a\n // Signal. Initial child subtrees are already built into the graph by the DSL;\n // on signal change we reconcile the freshly-built desired children against the\n // live DOM using the keyed reconciler (no virtual DOM). A `conditional` uses\n // the identical machinery but renders as a neutral <div> holding 0..1 branch.\n if (graphNode.type === 'reactive-list' || graphNode.type === 'conditional') {\n const tag = resolveTag(graphNode.type);\n const el = dom.createElement(tag);\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n\n for (const child of graphNode.children) {\n const childInstance = mountNode(ctx, child, el);\n instance.addChild(childInstance);\n }\n\n dom.appendChild(parentDom, el);\n wireReactiveList(ctx, graphNode, instance, el, true);\n return instance;\n }\n\n // Portal — a container whose children are relocated to a different DOM\n // location (document.body) on the browser, while a neutral inline anchor\n // stays at the declaration site. On the server there is no body, so the\n // children render inline in the anchor (deterministic HTML; hydration then\n // relocates them). This is the substrate for overlays (dialog/popover/…):\n // `wireOverlayBehavior` reads an optional `__overlay__<id>` descriptor and,\n // when present, wires focus trap/restore/containment/escape to the open\n // signal. A plain portal has no descriptor, so overlay wiring is a no-op.\n if (graphNode.type === 'portal') {\n const anchor = dom.createElement(resolveTag('portal'));\n dom.setAttribute(anchor, 'data-streetui-portal', '');\n applyNodeProps(ctx, graphNode, anchor);\n const instance = new NodeInstance(graphNode, anchor);\n ctx.instances.set(graphNode.id, instance);\n\n const body = dom.body();\n let target: Element = anchor; // SSR / no body → render inline in the anchor\n if (body !== null) {\n const portalContainer = dom.createElement('div');\n dom.setAttribute(portalContainer, 'data-streetui-portal-container', '');\n dom.appendChild(body, portalContainer);\n instance.trackCleanup(() => dom.removeChild(body, portalContainer));\n target = portalContainer;\n }\n\n for (const child of graphNode.children) {\n instance.addChild(mountNode(ctx, child, target));\n }\n\n dom.appendChild(parentDom, anchor);\n wireOverlayBehavior(ctx, graphNode, instance, target);\n return instance;\n }\n\n // Head — a metadata node (title/meta/link/base). Renders as a neutral inline\n // anchor at the declaration site (like a portal), while its contribution is\n // applied to `document.head` by `wireHeadBehavior` (browser) or emitted by\n // `renderHead` (server). No visible children; the anchor keeps hydration\n // structurally aligned with the SSR output.\n if (graphNode.type === 'head') {\n const anchor = dom.createElement(resolveTag('head'));\n dom.setAttribute(anchor, 'data-streetui-head-anchor', '');\n applyNodeProps(ctx, graphNode, anchor);\n const instance = new NodeInstance(graphNode, anchor);\n ctx.instances.set(graphNode.id, instance);\n\n dom.appendChild(parentDom, anchor);\n wireHeadBehavior(ctx, graphNode, instance);\n return instance;\n }\n\n // Container / section / page / form / list / list-item — structural nodes\n const tag = resolveTag(graphNode.type);\n const el = dom.createElement(tag);\n applyNodeProps(ctx, graphNode, el);\n\n // Surface a reactive-list item's stable, identity-only reconciliation key as a\n // public `data-streetui-key` attribute (e.g. \"id:1\"). This exposes only the\n // identity part — never the internal `_sig` value signature, signal ids or\n // graph node ids — so a row is directly selectable and its identity is\n // inspectable across reorders and in-place data updates.\n if (graphNode.type === 'list-item') {\n const itemKey = graphNode.getProp('key');\n if (itemKey !== undefined) {\n dom.setAttribute(el, 'data-streetui-key', String(itemKey));\n }\n }\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n\n // wire form submit (reuse the live instance rather than a throwaway)\n if (graphNode.type === 'form') {\n wireEvents(dom, graph, graphNode, el, instance);\n }\n\n // Recurse into children\n for (const child of graphNode.children) {\n const childInstance = mountNode(ctx, child, el);\n instance.addChild(childInstance);\n }\n\n dom.appendChild(parentDom, el);\n if (graphNode.type === 'component') wireComponentBehavior(ctx, graphNode, instance);\n return instance;\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\n/**\n * Per-node-type reactive-binding factories. Each returns the `onUpdate`\n * callback that `wireSignalBindings` invokes when a bound signal changes.\n * Extracted so both the browser mount path and the hydration path apply the\n * exact same DOM mutation semantics for each prop — no duplicated rendering\n * logic.\n */\nexport function textUpdate(\n dom: DOMAdapter,\n el: Element,\n textNode: Text,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'text') {\n dom.setTextContent(textNode, String(value ?? ''));\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function headingUpdate(\n dom: DOMAdapter,\n el: Element,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'text') {\n dom.setTextContent(el, String(value ?? ''));\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function inputUpdate(\n dom: DOMAdapter,\n el: Element,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'value') {\n dom.setProperty(el, 'value', String(value ?? ''));\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function buttonUpdate(\n dom: DOMAdapter,\n el: Element,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'label') {\n dom.setTextContent(el, String(value ?? ''));\n } else if (propKey === 'disabled') {\n if (value === true) {\n dom.setAttribute(el, 'disabled', '');\n } else {\n dom.removeAttribute(el, 'disabled');\n }\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function linkUpdate(\n dom: DOMAdapter,\n el: Element,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'label') {\n dom.setTextContent(el, String(value ?? ''));\n } else if (propKey === 'href') {\n dom.setAttribute(el, 'href', String(value ?? ''));\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function applyNodeProps(ctx: RenderContext, graphNode: GraphNode, el: Element): void {\n // Iterate own enumerable keys directly rather than via Object.entries, which\n // allocates a wrapper array plus one [key,value] tuple per prop — measurable\n // GC pressure when multiplied across every node in a large initial render.\n const props = graphNode.props;\n for (const key in props) {\n if (!Object.hasOwn(props, key)) continue;\n if (SKIP_PROP_KEYS.has(key)) continue;\n applyProp(ctx.dom, el, key, props[key]);\n }\n}\n\nexport function wireSignalBindings(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n onUpdate: (propKey: string, value: unknown) => void,\n): void {\n // Fast exit for the common non-reactive node — avoids allocating a for-of\n // iterator over an empty stateRefs array on every static node.\n if (graphNode.stateRefs.length === 0) return;\n for (const stateRef of graphNode.stateRefs) {\n const signalKey = `__signal__${stateRef.signalId}`;\n const maybeSig = ctx.graph.getHandler(signalKey) as\n | { subscribe: (fn: (v: unknown) => void) => () => void; peek: () => unknown }\n | undefined;\n if (maybeSig === undefined || typeof maybeSig.subscribe !== 'function') continue;\n\n // Subscribe directly — avoids the ReadonlySignal<T> generic variance issue\n const unsub = maybeSig.subscribe((value) => {\n onUpdate(stateRef.propKey, value);\n });\n instance.trackCleanup(unsub);\n }\n}\n\n// ── Reactive list wiring ────────────────────────────────────────────────────────\n\ntype ListBuildFn = (items: unknown) => GraphNode[];\ntype ListPlanFn = (items: unknown) => PlanEntry[];\n\n/**\n * Subscribe a reactive-list instance to its driving signal. On each change the\n * DSL-registered plan factory produces lightweight per-row descriptors, which\n * are reconciled against the live DOM with the keyed, minimal-move reconciler\n * (spec §15). A `conditional` node has no plan handler and falls back to the\n * eager build factory (it only ever renders 0..1 branch, so eager is fine).\n */\nexport function wireReactiveList(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n el: Element,\n runAppear = false,\n): void {\n const plan = ctx.graph.getHandler(`__listplan__${graphNode.id}`) as\n | ListPlanFn\n | undefined;\n const build = ctx.graph.getHandler(`__listbuild__${graphNode.id}`) as\n | ListBuildFn\n | undefined;\n if (plan === undefined && build === undefined) return;\n\n // One transition controller per reactive container, created here so its\n // leaving-instance map survives across every reconcile of this container\n // (that persistence is what makes leave→enter reclaim and keyed list-leave\n // correct — §6/§7). `finalize` runs the full deferred teardown chain when a\n // leave animation completes: DOM-remove + dispose + forget + detach, exactly\n // the work the synchronous path splits between the reconciler and the two\n // reconcile* helpers below. On the server (no body) the controller's hooks\n // no-op, so SSR is unchanged (§21).\n const controller = new TransitionController(ctx.dom, ctx.graph, (leaving) => {\n // Full teardown at leave-animation end — the same four steps the synchronous\n // path splits between the reconciler (DOM-remove + dispose) and this helper\n // (forget + detach). Deferred here because `beginLeave` excluded this\n // instance from `result.removed`, so nothing else will tear it down.\n const parent = ctx.dom.parentNode(leaving.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, leaving.domNode);\n leaving.dispose();\n forgetInstance(ctx, leaving);\n ctx.graph.detachNode(leaving.graphNode);\n });\n const hooks = controller.hooks();\n\n // `appear`: animate any initial child that opted in — but ONLY on a fresh\n // browser mount, never on hydration (§22: the DOM is already present and\n // correct, so appear must not run). The hydrate path calls this with\n // `runAppear` omitted (false).\n if (runAppear) controller.appear(instance.children);\n\n for (const stateRef of graphNode.stateRefs) {\n if (stateRef.propKey !== 'items') continue;\n const sig = ctx.graph.getHandler(`__signal__${stateRef.signalId}`) as\n | { subscribe: (fn: (v: unknown) => void) => () => void }\n | undefined;\n if (sig === undefined || typeof sig.subscribe !== 'function') continue;\n\n const unsub = sig.subscribe((value) => {\n if (plan !== undefined) {\n reconcileReactiveListByPlan(ctx, graphNode, instance, el, plan(value), hooks);\n } else {\n reconcileReactiveList(ctx, graphNode, instance, el, build!(value), hooks);\n }\n });\n instance.trackCleanup(unsub);\n }\n}\n\nfunction reconcileReactiveListByPlan(\n ctx: RenderContext,\n listNode: GraphNode,\n listInstance: NodeInstance,\n listEl: Element,\n plan: PlanEntry[],\n hooks: TransitionHooks,\n): void {\n const oldInstances = [...listInstance.children];\n const result = reconcileChildrenByPlan(\n ctx,\n listEl,\n oldInstances,\n plan,\n (node, parent) => mountNode(ctx, node, parent),\n hooks,\n );\n\n // Sync the live instance's children to the reconciled order.\n listInstance.children.length = 0;\n for (const inst of result.instances) listInstance.children.push(inst);\n\n // Forget removed instances, and drop their graph nodes.\n for (const removed of result.removed) {\n forgetInstance(ctx, removed);\n ctx.graph.detachNode(removed.graphNode);\n }\n // Detach any freshly-built subtree that was not adopted as a live instance\n // (e.g. the top node of a rebuilt changed row, whose live instance keeps its\n // original graph node).\n const adopted = new Set(result.instances.map((i) => i.graphNode));\n for (const node of result.built ?? []) {\n if (!adopted.has(node)) ctx.graph.detachNode(node);\n }\n\n // Keep the graph model consistent: list node children match the new order.\n for (const child of [...listNode.children]) listNode.removeChild(child);\n for (const inst of result.instances) listNode.appendChild(inst.graphNode);\n}\n\nfunction reconcileReactiveList(\n ctx: RenderContext,\n listNode: GraphNode,\n listInstance: NodeInstance,\n listEl: Element,\n newNodes: GraphNode[],\n hooks: TransitionHooks,\n): void {\n const oldInstances = [...listInstance.children];\n const result = reconcileChildren(\n ctx,\n listEl,\n oldInstances,\n newNodes,\n (node, parent) => mountNode(ctx, node, parent),\n hooks,\n );\n\n // Sync the live instance's children to the reconciled order.\n listInstance.children.length = 0;\n for (const inst of result.instances) listInstance.children.push(inst);\n\n // Forget removed instances from the renderer index, and drop their graph\n // nodes (and any un-adopted freshly-built duplicates) from the graph index.\n for (const removed of result.removed) {\n forgetInstance(ctx, removed);\n ctx.graph.detachNode(removed.graphNode);\n }\n const adopted = new Set(result.instances.map((i) => i.graphNode));\n for (const built of newNodes) {\n if (!adopted.has(built)) ctx.graph.detachNode(built);\n }\n\n // Keep the graph model consistent: list node children match the new order.\n for (const child of [...listNode.children]) listNode.removeChild(child);\n for (const inst of result.instances) listNode.appendChild(inst.graphNode);\n}\n\n/** Recursively remove an instance subtree from the renderer's instance index. */\nfunction forgetInstance(ctx: RenderContext, instance: NodeInstance): void {\n ctx.instances.delete(instance.graphNode.id);\n for (const child of instance.children) forgetInstance(ctx, child);\n}\n\n// ── Overlay behavior wiring ─────────────────────────────────────────────────────\n\n/**\n * Opaque overlay descriptor, read from the `__overlay__<portalId>` handler that\n * the DSL registers for dialog/popover/tooltip/dropdown/toast. Declared here as\n * a local structural type (mirroring the list plan/build handler pattern) so the\n * renderer never takes a compile-time dependency on the DSL package.\n */\ninterface OverlayBehavior {\n /** Reactive open/visibility state — the same signal that drives the panel's `when()`. */\n readonly open: {\n subscribe: (fn: (v: boolean) => void) => () => void;\n peek: () => unknown;\n };\n /** Trap Tab focus within, and redirect escaped focus back inside (modal semantics). */\n readonly modal: boolean;\n /** Move focus into the panel when it opens. */\n readonly takesFocus: boolean;\n /** Wire arrow/Home/End/Enter/Space roving-focus navigation (role=\"menu\"). */\n readonly menu: boolean;\n /** Escape key invokes `onClose`. */\n readonly closeOnEscape: boolean;\n /** Restore focus to the pre-open element on close. */\n readonly restoreFocus: boolean;\n /** id of the element to focus first when opening. */\n readonly initialFocusId?: string;\n /** Requested-close callback (Escape). The app flips its own open signal here. */\n readonly onClose?: () => void;\n}\n\n/**\n * Attach overlay focus/keyboard behavior to a mounted portal. Server-safe: on\n * the server `dom.body()` is null so this returns immediately (SSR emits inert\n * markup, no focus concept). A plain portal has no `__overlay__` descriptor, so\n * this also returns immediately — the behavior is purely additive.\n *\n * The panel is mounted/unmounted by the portal's inner `when(open, …)`, whose\n * signal subscription is registered *before* this one (the conditional child is\n * mounted earlier in the portal branch). Signal subscribers fire synchronously\n * in subscription order, so on open→true the panel DOM exists before we move\n * focus into it, and on open→false the panel is torn down before we restore\n * focus. All listeners are tracked on the instance and torn down on unmount.\n */\nexport function wireOverlayBehavior(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n target: Element,\n): void {\n const { dom, graph } = ctx;\n if (dom.body() === null) return; // server / no DOM environment\n\n const descFn = graph.getHandler(`__overlay__${graphNode.id}`) as\n | (() => OverlayBehavior)\n | undefined;\n if (descFn === undefined) return; // plain portal — no overlay behavior\n\n const desc = descFn();\n const openSig = desc.open;\n if (openSig === undefined || typeof openSig.subscribe !== 'function') return;\n\n let active: Array<() => void> = [];\n let saved: Element | null = null;\n\n const teardown = (): void => {\n for (const fn of active) fn();\n active = [];\n };\n\n const onOpenChange = (isOpen: boolean): void => {\n if (isOpen) {\n if (desc.restoreFocus) saved = saveFocus(dom);\n // Establish containment/roving BEFORE moving focus in, so that when a\n // nested modal opens it becomes the authoritative focus owner before its\n // initial focus fires — otherwise the outer modal's still-active\n // containment would pull that focus back out (§16).\n if (desc.modal) {\n active.push(trapFocus(dom, target));\n active.push(containFocus(dom, target));\n }\n if (desc.menu) {\n active.push(rovingMenu(dom, target));\n }\n if (desc.takesFocus) focusInitial(dom, target, desc.initialFocusId);\n if (desc.closeOnEscape && desc.onClose !== undefined) {\n active.push(onEscape(dom, target, desc.onClose));\n }\n } else {\n teardown();\n if (desc.restoreFocus && saved !== null) {\n restoreFocus(dom, saved);\n saved = null;\n }\n }\n };\n\n const unsub = openSig.subscribe(onOpenChange);\n instance.trackCleanup(unsub);\n instance.trackCleanup(teardown);\n\n // `subscribe` fires only on change; an overlay that is open on initial mount\n // has its panel already built into the graph, so run the open path now.\n if (openSig.peek() === true) onOpenChange(true);\n}\n\n/**\n * Wire a component instance's lifecycle (§9). Reads the optional\n * `__component__<id>` descriptor — an array of teardown callbacks the DSL's\n * `component()` collected from the setup's `ctx.effect`/`ctx.onCleanup` — and\n * routes each into `NodeInstance.trackCleanup`, so they run (children-first)\n * when the component leaves the graph. Shared by the mount and hydrate paths so\n * both attach identical ownership. A `'component'` node with no cleanups (no\n * effects/resources) registers no descriptor and this is a no-op.\n */\nexport function wireComponentBehavior(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n): void {\n const fn = ctx.graph.getHandler(`__component__${graphNode.id}`) as\n | (() => Array<() => void>)\n | undefined;\n if (fn === undefined) return;\n for (const cleanup of fn()) instance.trackCleanup(cleanup);\n}\n","/**\n * SSR state transfer (dehydration) — move server-resolved data to the client.\n *\n * When the server resolves resources before rendering, their data must reach\n * the client so hydration can seed them (via `resource({ initialData })`)\n * instead of refetching. StreetUI does this with a single, framework-scoped\n * `<script>` payload rather than blindly interpolating `JSON.stringify` into\n * markup.\n *\n * Safety (v0.4 rule #16): the JSON is emitted into a\n * `<script type=\"application/json\">` block — an inert data island the browser\n * never executes — and every character that could terminate that block or be\n * reinterpreted by the HTML/JS parser is escaped to its `\\uXXXX` form. Because\n * `<` inside JSON parses back to `<`, the payload round-trips exactly\n * while being impossible to break out of. This is deterministic (stable key\n * order is the caller's responsibility) and typed at the boundary as\n * `Record<string, unknown>` — never `any`.\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\n\n/** Attribute marking StreetUI's state island so the client can find it. */\nexport const STATE_MARKER_ATTR = 'data-streetui-state';\n\n/**\n * Escape a JSON string for safe embedding inside a `<script>` element:\n * < > & → HTML / `</script>` breakout and entity ambiguity\n * U+2028 / U+2029 → invalid raw in JS string literals\n * Uses code-point checks so no raw separator characters live in this source.\n */\nfunction escapeForScript(json: string): string {\n let out = '';\n for (const ch of json) {\n const code = ch.charCodeAt(0);\n if (ch === '<') out += '\\\\u003c';\n else if (ch === '>') out += '\\\\u003e';\n else if (ch === '&') out += '\\\\u0026';\n else if (code === 0x2028) out += '\\\\u2028';\n else if (code === 0x2029) out += '\\\\u2029';\n else out += ch;\n }\n return out;\n}\n\n/**\n * Serialize a state map to an HTML `<script>` island for inclusion in the\n * server-rendered document (typically just before the closing tag of the\n * mount container). Returns an empty string for an empty map.\n */\nexport function serializeState(state: Record<string, unknown>): string {\n if (Object.keys(state).length === 0) return '';\n const json = escapeForScript(JSON.stringify(state));\n return `<script type=\"application/json\" ${STATE_MARKER_ATTR}>${json}</script>`;\n}\n\n/**\n * Read the state island back on the client. Searches `root` for StreetUI's\n * state `<script>` and parses it. Returns an empty object when absent or\n * unparseable (hydration then proceeds as a cold client render). Routed through\n * the DOM adapter so it is testable and never assumes a global `document`.\n */\nexport function readState(\n dom: DOMAdapter,\n root: Element | Document,\n): Record<string, unknown> {\n const el = dom.querySelector(root, `script[${STATE_MARKER_ATTR}]`);\n if (el === null) return {};\n const text = dom.getTextContent(el);\n if (text === null || text.length === 0) return {};\n try {\n const parsed: unknown = JSON.parse(text);\n if (parsed !== null && typeof parsed === 'object') {\n return parsed as Record<string, unknown>;\n }\n return {};\n } catch {\n return {};\n }\n}\n","/**\n * Static graph analysis (v1.2, spec §3/§12/§14).\n *\n * A single post-order walk over the Semantic Application Graph that classifies\n * every node as static (no bound signals, no events, not a reactive\n * region) or dynamic, and rolls that up into whole-static-subtree flags. This\n * is COMPILE-TIME metadata only — it introduces no virtual DOM, no second tree\n * and no runtime reactive system. It is consumed by:\n * - the hydration path, to skip per-node attribute/text re-verification on\n * provably-static subtrees (§12), and\n * - the diagnostic compiler-inspection report (§14).\n *\n * The renderer's initial-mount fast path does not need this map: it already\n * skips reactive wiring per node via cheap `events.length`/`stateRefs.length`\n * guards. Keeping the analysis out of the mount hot path avoids adding lookup\n * cost (and keeps the shipped runtime lean).\n */\n\nimport type { NodeId } from '@streetui/core';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\n\n/** Prop keys whose bound signal drives text content rather than an attribute. */\nconst TEXT_PROP_KEYS: ReadonlySet<string> = new Set(['text', 'label', 'value']);\n\nexport interface NodeAnalysis {\n /** No bound signals, no events, and not a reactive-list/conditional region. */\n readonly isStatic: boolean;\n /** This node is static AND every descendant is a static subtree. */\n readonly isStaticSubtree: boolean;\n /** A signal is bound to this node's text/label/value content. */\n readonly hasDynamicText: boolean;\n /** A signal is bound to a non-content prop (a reactive attribute). */\n readonly hasDynamicAttr: boolean;\n /** This node wires one or more DOM event handlers. */\n readonly hasEvents: boolean;\n /** This node is a keyed reactive list. */\n readonly isList: boolean;\n /** This node is a conditional (0..1 branch) region. */\n readonly isConditional: boolean;\n}\n\nexport interface GraphAnalysisSummary {\n readonly totalNodes: number;\n readonly staticNodes: number;\n readonly staticSubtrees: number;\n readonly dynamicTextNodes: number;\n readonly dynamicAttrNodes: number;\n readonly eventNodes: number;\n readonly lists: number;\n readonly conditionals: number;\n}\n\nexport interface GraphAnalysis {\n readonly nodes: ReadonlyMap<NodeId, NodeAnalysis>;\n readonly summary: GraphAnalysisSummary;\n}\n\n/**\n * Analyze a fully-built graph. O(n) single post-order pass; allocates one small\n * record per node. Safe to skip entirely when neither hydration nor diagnostics\n * need it.\n */\nexport function analyzeGraph(graph: ApplicationGraph): GraphAnalysis {\n const nodes = new Map<NodeId, NodeAnalysis>();\n const summary = {\n totalNodes: 0, staticNodes: 0, staticSubtrees: 0, dynamicTextNodes: 0,\n dynamicAttrNodes: 0, eventNodes: 0, lists: 0, conditionals: 0,\n };\n\n const visit = (node: GraphNode): boolean => {\n // Post-order: children first so subtree rollup is exact.\n let allChildrenStatic = true;\n for (const child of node.children) {\n const childSubtreeStatic = visit(child);\n if (!childSubtreeStatic) allChildrenStatic = false;\n }\n\n let hasDynamicText = false;\n let hasDynamicAttr = false;\n for (const ref of node.stateRefs) {\n if (TEXT_PROP_KEYS.has(ref.propKey)) hasDynamicText = true;\n else hasDynamicAttr = true;\n }\n const hasEvents = node.events.length > 0;\n const isList = node.type === 'reactive-list';\n const isConditional = node.type === 'conditional';\n // A portal relocates its children to a different DOM location (document.body)\n // at mount time, so its subtree is never a contiguous inline static blob.\n // Treating it as dynamic stops the static-subtree rollup at the portal, so\n // both SSR and hydration always take the real portal mount/hydrate branch\n // (which does the relocation) rather than emitting/adopting a raw HTML blob.\n const isPortal = node.type === 'portal';\n // A component owns per-instance lifecycle wiring (a `__component__<id>`\n // cleanup handler read at mount/hydrate). Treating it as dynamic stops the\n // static-subtree rollup at the component boundary so it always takes the\n // real mount/hydrate branch (which wires cleanups) instead of collapsing\n // into a serialized raw-HTML blob that would drop that per-instance wiring.\n const isComponent = node.type === 'component';\n // A `head` node contributes document metadata via a `__head__<id>` handler\n // wired at mount/hydrate (`wireHeadBehavior`). Treating it as dynamic stops\n // the static-subtree rollup at the head boundary so it always takes the real\n // mount/hydrate branch (which registers/cleans up the contribution) instead\n // of collapsing into a serialized raw-HTML blob that would drop that wiring.\n const isHead = node.type === 'head';\n const isStatic =\n node.stateRefs.length === 0 && !hasEvents && !isList && !isConditional && !isPortal && !isComponent && !isHead;\n const isStaticSubtree = isStatic && allChildrenStatic;\n\n nodes.set(node.id, {\n isStatic, isStaticSubtree, hasDynamicText, hasDynamicAttr,\n hasEvents, isList, isConditional,\n });\n\n summary.totalNodes += 1;\n if (isStatic) summary.staticNodes += 1;\n if (isStaticSubtree) summary.staticSubtrees += 1;\n if (hasDynamicText) summary.dynamicTextNodes += 1;\n if (hasDynamicAttr) summary.dynamicAttrNodes += 1;\n if (hasEvents) summary.eventNodes += 1;\n if (isList) summary.lists += 1;\n if (isConditional) summary.conditionals += 1;\n\n return isStaticSubtree;\n };\n\n visit(graph.root);\n return { nodes, summary };\n}\n","/**\n * Diagnostic compiler-inspection mode (v1.2, spec §14).\n *\n * Produces a machine-readable (and optionally text-formatted) description of\n * what the compiler understands about an application: which nodes are static\n * vs dynamic, which carry dynamic text or attributes, which wire events, and\n * which are conditional regions or keyed lists — plus the hydration metadata\n * derived from that classification.\n *\n * This is a DIAGNOSTIC tool. It is not part of the runtime, is not consulted\n * during mount, and is tree-shakeable out of any app that never calls it.\n */\n\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport { analyzeGraph, type GraphAnalysisSummary } from './analyze.js';\n\nexport interface InspectedCompilationNode {\n readonly id: string;\n readonly type: string;\n readonly depth: number;\n readonly classification: 'static' | 'static-subtree-root' | 'dynamic';\n readonly dynamicText: boolean;\n readonly dynamicAttrs: boolean;\n readonly events: readonly string[];\n readonly boundProps: readonly string[];\n readonly isList: boolean;\n readonly isConditional: boolean;\n /** Hydration hint: how the hydration path should treat this node. */\n readonly hydration: 'adopt-static' | 'verify-dynamic';\n}\n\nexport interface CompilerInspection {\n readonly name: string;\n readonly version: string;\n readonly summary: GraphAnalysisSummary & {\n /** Fraction of nodes provably static (0..1). */\n readonly staticRatio: number;\n };\n readonly nodes: readonly InspectedCompilationNode[];\n}\n\n/**\n * Inspect a compiled/built graph and return a structured diagnostic report.\n * Purely observational — never mutates the graph.\n */\nexport function inspectCompilation(graph: ApplicationGraph): CompilerInspection {\n const analysis = analyzeGraph(graph);\n const nodes: InspectedCompilationNode[] = [];\n\n const walk = (node: GraphNode, depth: number): void => {\n const a = analysis.nodes.get(node.id);\n if (a !== undefined) {\n const classification: InspectedCompilationNode['classification'] = a.isStaticSubtree\n ? 'static-subtree-root'\n : a.isStatic\n ? 'static'\n : 'dynamic';\n nodes.push({\n id: node.id,\n type: node.type,\n depth,\n classification,\n dynamicText: a.hasDynamicText,\n dynamicAttrs: a.hasDynamicAttr,\n events: node.events.map((e) => e.type),\n boundProps: node.stateRefs.map((r) => r.propKey),\n isList: a.isList,\n isConditional: a.isConditional,\n hydration: a.isStaticSubtree ? 'adopt-static' : 'verify-dynamic',\n });\n }\n for (const child of node.children) walk(child, depth + 1);\n };\n walk(graph.root, 0);\n\n const staticRatio =\n analysis.summary.totalNodes === 0\n ? 0\n : analysis.summary.staticNodes / analysis.summary.totalNodes;\n\n return {\n name: graph.name,\n version: graph.version,\n summary: { ...analysis.summary, staticRatio: +staticRatio.toFixed(4) },\n nodes,\n };\n}\n\n/** Render an inspection as a compact human-readable text report. */\nexport function formatInspection(inspection: CompilerInspection): string {\n const s = inspection.summary;\n const lines: string[] = [];\n lines.push(`StreetUI compiler inspection — ${inspection.name} v${inspection.version}`);\n lines.push(\n ` nodes=${s.totalNodes} static=${s.staticNodes} ` +\n `staticSubtrees=${s.staticSubtrees} dynamicText=${s.dynamicTextNodes} ` +\n `dynamicAttrs=${s.dynamicAttrNodes} events=${s.eventNodes} ` +\n `lists=${s.lists} conditionals=${s.conditionals} ` +\n `staticRatio=${(s.staticRatio * 100).toFixed(1)}%`,\n );\n for (const n of inspection.nodes) {\n const flags: string[] = [];\n if (n.dynamicText) flags.push('text');\n if (n.dynamicAttrs) flags.push('attr:' + n.boundProps.join(','));\n if (n.events.length > 0) flags.push('on:' + n.events.join(','));\n if (n.isList) flags.push('list');\n if (n.isConditional) flags.push('cond');\n lines.push(\n ` ${' '.repeat(n.depth)}${n.type}#${n.id} [${n.classification}]` +\n (flags.length > 0 ? ` {${flags.join(' ')}}` : ''),\n );\n }\n return lines.join('\\n');\n}\n","/**\n * Static SSR Plan (v1.7, spec §4/§6) — internal.\n *\n * A compiler-derived plan that precomputes the verbatim HTML of every *maximal\n * static subtree* in an application graph. During SSR, the renderer emits that\n * precomputed string directly (via `ServerDOMAdapter.createRawHTML`) instead of\n * recursively constructing a `ServerElement`/`ServerText`/`NodeInstance` for\n * every node in the subtree. On the 10k-row `/users` corpus, ~100% of the node\n * mass lives in 10,000 static 8-node row subtrees, so collapsing each row into\n * one precomputed string removes the bulk of the mount-phase construction work.\n *\n * Design constraints honoured here:\n * - §3 REUSE the existing compiler analysis (`analyzeGraph`) to classify nodes;\n * no new/expensive analysis, and nothing runs during normal `compile()`.\n * - §5/§15 Only *maximal static-subtree roots* are collapsed. A dynamic region\n * (reactive-list container, conditional, dynamic-text/attr node) is never\n * treated as static — the list itself stays dynamic; only the provably-static\n * subtree *inside* each repeated item is precomputed.\n * - §8 The precomputed HTML is produced by the SAME mount + serialize pipeline\n * as the runtime path, so full-render output is byte-identical.\n * - §19 The plan retains ONLY strings keyed by GraphNode.id. No ServerDOM node,\n * NodeInstance or application object is retained (the throwaway build tree is\n * disposed + cleared). The per-app cache is a WeakMap, so a plan is released\n * when its CompiledApplication is collected.\n * - §24 Everything here is internal: not re-exported from the `streetui` or\n * `streetui/server` runtime barrels.\n *\n * This module is only ever imported by the SSR entry (`renderToString`), which\n * is itself reachable solely through the server path, so it tree-shakes out of\n * client bundles (§20, verified by bundle measurement).\n */\n\nimport type { NodeId } from '@streetui/core';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport { analyzeGraph } from '@streetui/compiler/diagnostics';\nimport { ServerDOMAdapter } from '@streetui/dom';\nimport { createRenderContext } from './render-context.js';\nimport { mountNode } from './mount.js';\n\n/**\n * Internal representation of the static SSR plan: maximal static-subtree root\n * GraphNode.id → its precomputed, verbatim outer HTML. A plain `Map<string,\n * string>` is deliberate — it holds no DOM/application references (§19).\n */\nexport type StaticSSRPlan = ReadonlyMap<NodeId, string>;\n\n/**\n * Collect the ids of every *maximal* static-subtree root under `graph`.\n *\n * Walk from the root; when a node is itself a whole static subtree, it is a\n * maximal root — record it and stop (its static descendants are subsumed).\n * Otherwise descend into its children, so a dynamic node's individually-static\n * children are still captured (the mixed-tree case, §5). The `application` root\n * is never recorded: it maps onto the render container rather than emitting its\n * own element, so we always descend past it into its real top-level children.\n */\nfunction collectMaximalStaticRoots(graph: ApplicationGraph): GraphNode[] {\n const analysis = analyzeGraph(graph);\n const roots: GraphNode[] = [];\n\n const walk = (node: GraphNode): void => {\n if (node.type !== 'application') {\n const a = analysis.nodes.get(node.id);\n if (a !== undefined && a.isStaticSubtree) {\n roots.push(node);\n return;\n }\n }\n for (const child of node.children) walk(child);\n };\n\n walk(graph.root);\n return roots;\n}\n\n/**\n * Serialize the outer HTML of a single static subtree using the exact runtime\n * mount + serialize pipeline (so the bytes match a full render). The throwaway\n * tree is disposed immediately, so nothing is retained.\n */\nfunction serializeStaticSubtree(\n dom: ServerDOMAdapter,\n graph: ApplicationGraph,\n root: GraphNode,\n): string {\n const container = dom.createElement('div');\n // No `staticHTML` on this ctx → mountNode builds the subtree fully.\n const ctx = createRenderContext(dom, graph, container);\n const instance = mountNode(ctx, root, container);\n const html = dom.serializeInner(container);\n // Tear down (static subtrees open no subscriptions, but keep symmetry with\n // renderToString's lifecycle) and drop all references.\n instance.dispose();\n ctx.instances.clear();\n return html;\n}\n\n/**\n * Build the static SSR plan for a compiled application. O(n) analysis + one\n * mount/serialize per maximal static subtree. Returns an empty map when the app\n * has no static subtrees (e.g. a highly-dynamic page) — the SSR path then\n * behaves exactly as v1.6.\n */\nexport function buildStaticSSRPlan(compiled: CompiledApplication): StaticSSRPlan {\n const graph = compiled.graph;\n const roots = collectMaximalStaticRoots(graph);\n const plan = new Map<NodeId, string>();\n if (roots.length === 0) return plan;\n\n const dom = new ServerDOMAdapter();\n for (const root of roots) {\n plan.set(root.id, serializeStaticSubtree(dom, graph, root));\n }\n return plan;\n}\n\n/**\n * Per-application plan cache. A WeakMap keyed by the CompiledApplication so a\n * plan is built once and reused across renders, and is released together with\n * the compiled app it belongs to — no long-lived retention of app state (§19).\n */\nconst PLAN_CACHE = new WeakMap<CompiledApplication, StaticSSRPlan>();\n\n/** Get the cached static SSR plan for a compiled app, building it on first use. */\nexport function getStaticSSRPlan(compiled: CompiledApplication): StaticSSRPlan {\n let plan = PLAN_CACHE.get(compiled);\n if (plan === undefined) {\n plan = buildStaticSSRPlan(compiled);\n PLAN_CACHE.set(compiled, plan);\n }\n return plan;\n}\n","/**\n * Server-side rendering — `renderToString`.\n *\n * Runs the *exact same* mount pipeline used in the browser (`mountGraph`), but\n * against a `ServerDOMAdapter` that builds a lightweight in-memory node tree\n * instead of a real browser DOM. The tree is then serialized to a normal HTML\n * string. Because both browser and server share the DSL → Compiler → Graph →\n * Runtime → Renderer pipeline, there is no second, SSR-specific renderer and no\n * virtual DOM.\n *\n * Lifecycle (v0.4 rule #20): the initial synchronous mount may open signal\n * subscriptions (via `wireSignalBindings`/`wireReactiveList`). On the server\n * those would be live forever, so once the HTML is serialized we dispose the\n * root instance — tearing down every subscription and listener. SSR therefore\n * has a *render* lifecycle only; the live *runtime* lifecycle is established\n * later on the client by `hydrate`.\n */\n\nimport { ServerDOMAdapter } from '@streetui/dom';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport { createRenderContext } from './render-context.js';\nimport { mountGraph } from './mount.js';\nimport { getStaticSSRPlan } from './static-ssr-plan.js';\n\nexport interface RenderToStringOptions {\n /**\n * Override the server DOM adapter (rarely needed). Defaults to a fresh\n * `ServerDOMAdapter` per call so concurrent renders never share state.\n */\n readonly domAdapter?: ServerDOMAdapter;\n /**\n * @internal — testing/benchmark knob for the v1.7 static SSR plan.\n *\n * `undefined` (default): use the per-app cached plan (build once, reuse).\n * `null`: disable the plan entirely — the exact v1.6 runtime mount path, used\n * by the byte-identity gate and A/B benchmark as the \"legacy\" baseline.\n * a map: use this explicit plan.\n *\n * Not part of the supported public API; output is byte-identical regardless\n * of this value (§8).\n */\n readonly staticPlan?: ReadonlyMap<string, string> | null;\n}\n\n/**\n * Render a compiled StreetUI application to an HTML string.\n *\n * The returned markup contains only the application's own elements (the\n * synthetic container is not emitted), so callers embed it wherever they mount\n * on the client — e.g. inside `<div id=\"app\">…</div>`.\n */\nexport function renderToString(\n compiled: CompiledApplication,\n options: RenderToStringOptions = {},\n): string {\n const dom = options.domAdapter ?? new ServerDOMAdapter();\n\n // Resolve the v1.7 static SSR plan: cached-by-default, `null` forces the v1.6\n // path, an explicit map is used as-is. Only maximal static-subtree roots are\n // collapsed; dynamic regions still mount through the runtime path (§5).\n const plan =\n options.staticPlan === null\n ? undefined\n : (options.staticPlan ?? getStaticSSRPlan(compiled));\n const staticHTML = plan !== undefined && plan.size > 0 ? plan : undefined;\n\n // Synthetic container — the application root maps onto it, and the app's\n // top-level nodes are appended directly into it (mirroring browser mount).\n const container = dom.createElement('div');\n\n const ctx = createRenderContext(dom, compiled.graph, container, undefined, staticHTML);\n const rootInstance = mountGraph(ctx);\n\n const html = dom.serializeInner(container);\n\n // Tear down any subscriptions/listeners opened during mount — the server has\n // no live runtime. (rule #20)\n rootInstance.dispose();\n ctx.instances.clear();\n\n return html;\n}\n","/**\n * The single authoritative StreetUI framework version.\n *\n * This constant is the one source of truth for the version of the shipped\n * `streetui` package. It is kept in lock-step with this package's\n * `package.json` `version` field and with the bundled CLI's reported version\n * (`streetui --version`) — the consolidated test-suite pins all three to the\n * same coordinated release so they can never silently drift apart.\n */\nexport const VERSION = '2.2.0';\n"],"mappings":";AA8CO,SAAS,oBACd,KACA,OACA,WACA,sBACA,YACe;AACf,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,WAAW,oBAAI,IAAI;AAAA,IACnB;AAAA,IACA,GAAI,yBAAyB,SAAY,EAAE,qBAAqB,IAAI,CAAC;AAAA,IACrE,GAAI,eAAe,SAAY,EAAE,WAAW,IAAI,CAAC;AAAA,EACnD;AACF;;;ACOO,IAAM,kBAAN,MAAsB;AAAA,EACV,OAA0B,CAAC;AAAA,EAE5C,IAAI,IAAsB;AACxB,SAAK,KAAK,KAAK,EAAE;AAAA,EACnB;AAAA,EAEA,MAAY;AACV,eAAW,MAAM,KAAK,MAAM;AAC1B,UAAI;AACF,WAAG;AAAA,MACL,QAAQ;AAAA,MAER;AAAA,IACF;AACA,SAAK,KAA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AQ,cAAc,iBAAiB,QAAQ;AACtD,QAAM,aAAa,SAAS,UAAa,KAAK,OAAO,IAAI,OAAO;AAIhE,QAAM,YAAY,IAAI,cAAc,KAAK;AAEzC,QAAM,MAAM,oBAAoB,KAAK,SAAS,OAAO,WAAW,QAAW,UAAU;AACrF,QAAM,eAAe,WAAW,GAAG;AAEnC,QAAM,OAAO,IAAI,eAAe,SAAS;AAIzC,eAAa,QAAQ;AACrB,MAAI,UAAU,MAAM;AAEpB,SAAO;AACT;;;ACxEO,IAAM,UAAU;","names":["instance","el","tag"]}
|
|
1
|
+
{"version":3,"sources":["../../renderer/src/render-context.ts","../../core/src/lifecycle.ts","../../renderer/src/node-instance.ts","../../renderer/src/attributes.ts","../../renderer/src/events.ts","../../dom/src/server-node.ts","../../dom/src/server-adapter.ts","../../dom/src/focus.ts","../../renderer/src/tag-map.ts","../../renderer/src/patch.ts","../../renderer/src/reconciliation.ts","../../renderer/src/transition.ts","../../renderer/src/head.ts","../../renderer/src/mount.ts","../../renderer/src/dehydrate.ts","../../compiler/src/analysis/analyze.ts","../../compiler/src/analysis/inspect.ts","../../renderer/src/static-ssr-plan.ts","../../renderer/src/ssr.ts","../src/version.ts"],"sourcesContent":["/**\n * RenderContext — shared state for a single mount operation.\n *\n * Passed through the render pipeline so every sub-function has access\n * to the DOM adapter, graph, and instance map without prop-drilling.\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { NodeInstance } from './node-instance.js';\nimport type { HydrationDiagnosticSink } from './hydration-diagnostics.js';\nimport type { HeadManager } from './head.js';\n\nexport interface RenderContext {\n readonly dom: DOMAdapter;\n readonly graph: ApplicationGraph;\n /** Maps GraphNode.id → its live NodeInstance */\n readonly instances: Map<string, NodeInstance>;\n /** The root container element. */\n readonly container: Element;\n /**\n * Optional dev-only sink that observes hydration mismatch repairs. When\n * absent (the default) the hydration path does no extra work — this is how\n * DevTools/diagnostics stay off the production runtime path.\n */\n readonly hydrationDiagnostics?: HydrationDiagnosticSink;\n /**\n * Optional SSR-only static-subtree plan (v1.7). Maps a maximal\n * static-subtree root GraphNode.id → its precomputed, verbatim HTML string.\n * Present only on the server render path when a plan has been built; on the\n * browser mount path it is always `undefined`, so the client hot path is\n * unaffected (a single `=== undefined` check short-circuits). When a mounted\n * node's id is in this map, the renderer emits the precomputed HTML via\n * `dom.createRawHTML` instead of recursively constructing the subtree.\n */\n readonly staticHTML?: ReadonlyMap<string, string>;\n /**\n * Lazily-created coordinator for `head()` metadata nodes (2.0 §1). Created on\n * first `wireHeadBehavior` call on the browser (never on the server, where\n * `dom.head()` is null and `renderHead` emits the metadata instead). Mutable\n * because it is attached on demand; a render with no `head()` nodes never\n * allocates one.\n */\n head?: HeadManager;\n}\n\nexport function createRenderContext(\n dom: DOMAdapter,\n graph: ApplicationGraph,\n container: Element,\n hydrationDiagnostics?: HydrationDiagnosticSink,\n staticHTML?: ReadonlyMap<string, string>,\n): RenderContext {\n return {\n dom,\n graph,\n instances: new Map(),\n container,\n ...(hydrationDiagnostics !== undefined ? { hydrationDiagnostics } : {}),\n ...(staticHTML !== undefined ? { staticHTML } : {}),\n };\n}\n","/**\n * Application and component lifecycle primitives.\n *\n * Lifecycle phases:\n * created → mounted → active ⇄ updating → unmounting → destroyed\n */\n\nexport type LifecyclePhase =\n | 'created'\n | 'mounted'\n | 'active'\n | 'updating'\n | 'unmounting'\n | 'destroyed';\n\nexport type LifecycleHook = () => void | Promise<void>;\n\nexport class Lifecycle {\n private _phase: LifecyclePhase = 'created';\n private readonly _hooks: Map<LifecyclePhase, LifecycleHook[]> = new Map();\n\n get phase(): LifecyclePhase {\n return this._phase;\n }\n\n get isMounted(): boolean {\n return this._phase === 'mounted' || this._phase === 'active' || this._phase === 'updating';\n }\n\n get isDestroyed(): boolean {\n return this._phase === 'destroyed';\n }\n\n on(phase: LifecyclePhase, hook: LifecycleHook): () => void {\n const hooks = this._hooks.get(phase) ?? [];\n hooks.push(hook);\n this._hooks.set(phase, hooks);\n return () => {\n const current = this._hooks.get(phase);\n if (current !== undefined) {\n const idx = current.indexOf(hook);\n if (idx !== -1) current.splice(idx, 1);\n }\n };\n }\n\n async transition(to: LifecyclePhase): Promise<void> {\n this._phase = to;\n const hooks = this._hooks.get(to) ?? [];\n for (const hook of hooks) {\n await hook();\n }\n }\n\n onMount(hook: LifecycleHook): () => void {\n return this.on('mounted', hook);\n }\n\n onUnmount(hook: LifecycleHook): () => void {\n return this.on('unmounting', hook);\n }\n\n onDestroy(hook: LifecycleHook): () => void {\n return this.on('destroyed', hook);\n }\n}\n\n/** A simple cleanup registry — collect teardown functions and run them all at once. */\nexport class CleanupRegistry {\n private readonly _fns: Array<() => void> = [];\n\n add(fn: () => void): void {\n this._fns.push(fn);\n }\n\n run(): void {\n for (const fn of this._fns) {\n try {\n fn();\n } catch {\n // Best-effort cleanup; don't let one failure block others\n }\n }\n this._fns.length = 0;\n }\n}\n","/**\n * NodeInstance — the renderer's live counterpart to a GraphNode.\n *\n * Tracks the actual DOM node(s), all signal subscriptions that drive\n * targeted DOM updates, and DOM event listener teardowns.\n */\n\nimport { CleanupRegistry } from '@streetui/core';\nimport type { GraphNode } from '@streetui/graph';\nimport type { ReadonlySignal } from '@streetui/state';\n\nexport class NodeInstance {\n readonly graphNode: GraphNode;\n /** The primary DOM node for this instance (element or text node). */\n domNode: Node;\n readonly children: NodeInstance[] = [];\n readonly cleanup: CleanupRegistry = new CleanupRegistry();\n\n constructor(graphNode: GraphNode, domNode: Node) {\n this.graphNode = graphNode;\n this.domNode = domNode;\n }\n\n addChild(child: NodeInstance): void {\n this.children.push(child);\n }\n\n /** Subscribe to a signal; auto-cleanup on unmount. */\n trackSignal<T>(sig: ReadonlySignal<T>, handler: (v: T) => void): void {\n const unsub = sig.subscribe(handler);\n this.cleanup.add(unsub);\n }\n\n /** Register a raw cleanup fn (DOM event removal, etc.). */\n trackCleanup(fn: () => void): void {\n this.cleanup.add(fn);\n }\n\n dispose(): void {\n for (const child of this.children) {\n child.dispose();\n }\n this.cleanup.run();\n }\n}\n","/**\n * Attribute and property application helpers.\n *\n * Decides whether a prop should be set as a DOM attribute or a JS property,\n * handling special cases (boolean attrs, event-like props, style, class).\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\n\n// Properties that must be set as JS object properties, not HTML attributes\nconst DOM_PROPERTIES = new Set([\n 'value', 'checked', 'selected', 'indeterminate',\n 'innerHTML', 'textContent', 'innerText',\n 'scrollTop', 'scrollLeft',\n]);\n\n// Boolean attributes — present means true, absent means false\nconst BOOLEAN_ATTRS = new Set([\n 'disabled', 'readonly', 'required', 'checked', 'selected',\n 'multiple', 'autofocus', 'autoplay', 'controls', 'default',\n 'defer', 'formnovalidate', 'hidden', 'ismap', 'loop',\n 'novalidate', 'open', 'reversed', 'scoped', 'seamless',\n]);\n\nexport function applyProp(\n dom: DOMAdapter,\n element: Element,\n name: string,\n value: unknown,\n): void {\n // Skip internal renderer metadata\n if (name.startsWith('_')) return;\n // Skip event handlers (handled separately)\n if (name.startsWith('on')) return;\n\n if (DOM_PROPERTIES.has(name)) {\n dom.setProperty(element, name, value);\n return;\n }\n\n if (BOOLEAN_ATTRS.has(name)) {\n if (value === true || value === '' || value === name) {\n dom.setAttribute(element, name, '');\n } else {\n dom.removeAttribute(element, name);\n }\n return;\n }\n\n if (name === 'class' || name === 'className') {\n dom.setAttribute(element, 'class', String(value ?? ''));\n return;\n }\n\n if (name === 'style' && typeof value === 'object' && value !== null) {\n const el = element as HTMLElement;\n const styles = value as Record<string, string>;\n for (const [k, v] of Object.entries(styles)) {\n el.style.setProperty(k, v);\n }\n return;\n }\n\n if (value === null || value === undefined || value === false) {\n dom.removeAttribute(element, name);\n return;\n }\n\n dom.setAttribute(element, name, String(value));\n}\n\nexport function patchProp(\n dom: DOMAdapter,\n element: Element,\n name: string,\n oldValue: unknown,\n newValue: unknown,\n): void {\n if (Object.is(oldValue, newValue)) return;\n applyProp(dom, element, name, newValue);\n}\n","/**\n * Event wiring for the renderer.\n *\n * Given a GraphNode with event descriptors, this wires DOM listeners\n * that call the handlers stored in the graph's handler registry.\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { NodeInstance } from './node-instance.js';\n\nexport function wireEvents(\n dom: DOMAdapter,\n graph: ApplicationGraph,\n node: GraphNode,\n element: Element,\n instance: NodeInstance,\n): void {\n // Fast exit for event-free nodes — avoids allocating a for-of iterator over\n // an empty array on every node during a large mount/hydrate.\n if (node.events.length === 0) return;\n for (const eventDesc of node.events) {\n const handler = graph.getHandler(eventDesc.handlerKey);\n if (handler === undefined) continue;\n\n const domListener: EventListener = (domEvent: Event) => {\n // For input events, pass the current value as first arg\n if (eventDesc.type === 'input' || eventDesc.type === 'change') {\n const input = domEvent.target as HTMLInputElement;\n (handler as (v: string) => void)(input.value);\n } else if (eventDesc.type === 'submit') {\n domEvent.preventDefault();\n (handler as (e: Event) => void)(domEvent);\n } else {\n (handler as () => void)();\n }\n };\n\n dom.addEventListener(element, eventDesc.type, domListener);\n instance.trackCleanup(() => {\n dom.removeEventListener(element, eventDesc.type, domListener);\n });\n }\n}\n","/**\n * Server-side DOM node model.\n *\n * A tiny, dependency-free tree of plain objects that mirrors just enough of the\n * browser DOM for StreetUI's renderer to build a tree on the server and\n * serialize it to an HTML string. There is NO browser global here — these are\n * ordinary classes usable in any JavaScript environment (Node, workers, tests).\n *\n * The renderer never touches these types directly; it goes through the\n * `DOMAdapter` interface, and `ServerDOMAdapter` translates adapter calls into\n * operations on this model.\n */\n\nexport type ServerNodeKind = 'element' | 'text' | 'comment' | 'fragment' | 'raw';\n\nexport interface ServerNode {\n readonly kind: ServerNodeKind;\n parent: ServerParent | null;\n}\n\nexport type ServerParent = ServerElement | ServerFragment;\n\n/** A minimal inline-style holder mirroring `element.style.setProperty`. */\nexport class ServerStyle {\n readonly declarations = new Map<string, string>();\n setProperty(name: string, value: string): void {\n this.declarations.set(name, value);\n }\n get isEmpty(): boolean {\n return this.declarations.size === 0;\n }\n toCss(): string {\n return [...this.declarations.entries()].map(([k, v]) => `${k}: ${v}`).join('; ');\n }\n}\n\nexport class ServerText implements ServerNode {\n readonly kind = 'text' as const;\n parent: ServerParent | null = null;\n data: string;\n constructor(data: string) {\n this.data = data;\n }\n}\n\nexport class ServerComment implements ServerNode {\n readonly kind = 'comment' as const;\n parent: ServerParent | null = null;\n data: string;\n constructor(data: string) {\n this.data = data;\n }\n}\n\nexport class ServerFragment implements ServerNode {\n readonly kind = 'fragment' as const;\n parent: ServerParent | null = null;\n readonly children: ServerNode[] = [];\n}\n\n/**\n * A pre-serialized, verbatim HTML fragment (v1.7 static SSR plan).\n *\n * Emitted for provably-static subtrees whose HTML the compiler-derived static\n * SSR plan already computed once. Serializing this node copies its stored\n * string directly — it allocates no ServerElement/ServerText, no attribute Map\n * and no children array for the collapsed subtree. The stored `html` is\n * produced by the exact same mount + serialize pipeline as the runtime path, so\n * the output is byte-identical (the v1.7 byte-identity gate proves this).\n *\n * This node is SSR-only: it is created solely via `ServerDOMAdapter.createRawHTML`\n * on the server render path and never appears in a browser build.\n */\nexport class ServerRawHTML implements ServerNode {\n readonly kind = 'raw' as const;\n parent: ServerParent | null = null;\n readonly html: string;\n constructor(html: string) {\n this.html = html;\n }\n}\n\nexport class ServerElement implements ServerNode {\n readonly kind = 'element' as const;\n parent: ServerParent | null = null;\n readonly tagName: string;\n readonly attributes = new Map<string, string>();\n readonly children: ServerNode[] = [];\n\n // Lazily-allocated stores. On the 10k-row SSR corpus ~0% of elements carry JS\n // properties or inline styles (measured, §5: 1 of 80,029 elements uses\n // `properties`, 0 use `style`), so eagerly allocating a `properties` Map plus\n // a `ServerStyle` (which itself holds a Map) per element wasted ~240k\n // allocations per /users render — all in the dominant mount phase. These are\n // created on first WRITE via the `properties`/`style` getters; the serializer\n // reads the raw `_properties`/`_style` fields so a READ never forces an\n // allocation. Output is byte-identical: an unset store previously serialized\n // to nothing (empty `properties.has(...)` / `style.isEmpty`), and a null store\n // is skipped the same way.\n _properties: Map<string, unknown> | null = null;\n _style: ServerStyle | null = null;\n\n constructor(tagName: string) {\n this.tagName = tagName.toLowerCase();\n }\n\n /** JS properties set via `setProperty` (e.g. input `value`, `checked`). Allocated on first access. */\n get properties(): Map<string, unknown> {\n return (this._properties ??= new Map());\n }\n\n /** Inline-style holder mirroring `element.style`. Allocated on first access. */\n get style(): ServerStyle {\n return (this._style ??= new ServerStyle());\n }\n}\n\n// ── HTML serialization ─────────────────────────────────────────────────────────\n\n/**\n * HTML \"void\" elements — self-closing, never given a closing tag or children.\n */\nconst VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr',\n]);\n\n/**\n * Element properties that should be reflected into the serialized HTML so the\n * hydrated DOM carries the same initial state. `value`/`checked` matter for\n * form controls whose live state is a JS property, not an attribute.\n */\nconst SERIALIZED_PROPERTIES: Record<string, 'attr' | 'boolean'> = {\n value: 'attr',\n checked: 'boolean',\n selected: 'boolean',\n};\n\n/**\n * Precomputed `[name, kind]` pairs of SERIALIZED_PROPERTIES. Hoisted to module\n * scope so `serializeAttributes` does not allocate a fresh entries array for\n * every element serialized (measured hot: ~80k elements on the 10k-row route).\n */\nconst SERIALIZED_PROPERTY_ENTRIES: ReadonlyArray<readonly [string, 'attr' | 'boolean']> =\n Object.entries(SERIALIZED_PROPERTIES) as Array<[string, 'attr' | 'boolean']>;\n\n// Fast-path escaping. The chained `.replace(/…/g, …)` form makes 3–4 full\n// passes and allocates an intermediate string per pass even when nothing needs\n// escaping. These variants scan once and, in the overwhelmingly common case of\n// no special character, return the input unchanged (zero allocation). Output is\n// byte-identical to the chained form (verified over the real SSR corpus).\nconst TEXT_SPECIAL = /[&<>]/;\nconst ATTR_SPECIAL = /[&<>\"]/;\n\n/** Escape text node content. */\nexport function escapeHtmlText(value: string): string {\n if (!TEXT_SPECIAL.test(value)) return value;\n let out = '';\n let last = 0;\n for (let i = 0; i < value.length; i++) {\n let esc: string;\n switch (value.charCodeAt(i)) {\n case 38: esc = '&'; break; // &\n case 60: esc = '<'; break; // <\n case 62: esc = '>'; break; // >\n default: continue;\n }\n out += value.slice(last, i) + esc;\n last = i + 1;\n }\n return out + value.slice(last);\n}\n\n/** Escape a double-quoted attribute value. */\nexport function escapeHtmlAttr(value: string): string {\n if (!ATTR_SPECIAL.test(value)) return value;\n let out = '';\n let last = 0;\n for (let i = 0; i < value.length; i++) {\n let esc: string;\n switch (value.charCodeAt(i)) {\n case 38: esc = '&'; break; // &\n case 60: esc = '<'; break; // <\n case 62: esc = '>'; break; // >\n case 34: esc = '"'; break; // \"\n default: continue;\n }\n out += value.slice(last, i) + esc;\n last = i + 1;\n }\n return out + value.slice(last);\n}\n\nfunction serializeAttributes(el: ServerElement): string {\n const parts: string[] = [];\n\n for (const [name, value] of el.attributes) {\n if (value === '') {\n parts.push(` ${name}`);\n } else {\n parts.push(` ${name}=\"${escapeHtmlAttr(value)}\"`);\n }\n }\n\n // Read the raw backing field (may be null): most elements have no JS\n // properties, so skipping the whole loop avoids touching a store that was\n // never allocated (§5).\n const props = el._properties;\n if (props !== null) {\n for (const [name, kind] of SERIALIZED_PROPERTY_ENTRIES) {\n if (!props.has(name)) continue;\n if (el.attributes.has(name)) continue; // an explicit attribute already won\n const raw = props.get(name);\n if (kind === 'boolean') {\n if (raw === true) parts.push(` ${name}`);\n } else {\n if (raw !== undefined && raw !== null) {\n parts.push(` ${name}=\"${escapeHtmlAttr(String(raw))}\"`);\n }\n }\n }\n }\n\n const style = el._style;\n if (style !== null && !style.isEmpty && !el.attributes.has('style')) {\n parts.push(` style=\"${escapeHtmlAttr(style.toCss())}\"`);\n }\n\n return parts.join('');\n}\n\n/** Serialize a single server node (element/text/comment/fragment/raw) to HTML. */\nexport function serializeServerNode(node: ServerNode): string {\n switch (node.kind) {\n case 'text':\n return escapeHtmlText((node as ServerText).data);\n case 'comment':\n return `<!--${(node as ServerComment).data}-->`;\n case 'fragment':\n return serializeChildren(node as ServerFragment);\n case 'raw':\n // Verbatim: the string was produced by this same serializer for a static\n // subtree, so it is already correctly escaped. Copy it as-is (§8).\n return (node as ServerRawHTML).html;\n case 'element': {\n const el = node as ServerElement;\n const tag = el.tagName;\n const attrs = serializeAttributes(el);\n if (VOID_ELEMENTS.has(tag)) {\n return `<${tag}${attrs}>`;\n }\n return `<${tag}${attrs}>${serializeChildren(el)}</${tag}>`;\n }\n }\n}\n\n/** Serialize the children of an element or fragment (its \"inner HTML\"). */\nexport function serializeChildren(node: ServerElement | ServerFragment): string {\n let out = '';\n for (const child of node.children) {\n out += serializeServerNode(child);\n }\n return out;\n}\n","/**\n * Server implementation of `DOMAdapter`.\n *\n * Builds a lightweight in-memory tree (see `server-node.ts`) instead of touching\n * a real browser DOM, then lets the caller serialize it to an HTML string. It is\n * completely free of browser globals, so the exact same renderer that runs in\n * the browser can produce HTML on the server.\n *\n * The `DOMAdapter` interface is typed against the lib DOM types (`Element`,\n * `Node`, `Text`, …). Our server nodes structurally stand in for those at\n * runtime, so the boundary uses `as unknown as` casts in one place. Everything\n * inside operates on the real server-node model.\n */\n\nimport type { DOMAdapter } from './adapter.js';\nimport {\n ServerElement,\n ServerText,\n ServerComment,\n ServerFragment,\n ServerRawHTML,\n serializeChildren,\n serializeServerNode,\n type ServerNode,\n type ServerParent,\n} from './server-node.js';\n\nfunction asServer(node: unknown): ServerNode {\n return node as unknown as ServerNode;\n}\nfunction asParent(node: unknown): ServerParent {\n return node as unknown as ServerParent;\n}\n\nexport class ServerDOMAdapter implements DOMAdapter {\n createElement(tag: string, _ns?: string): Element {\n return new ServerElement(tag) as unknown as Element;\n }\n\n createTextNode(data: string): Text {\n return new ServerText(data) as unknown as Text;\n }\n\n createComment(data: string): Comment {\n return new ServerComment(data) as unknown as Comment;\n }\n\n createFragment(): DocumentFragment {\n return new ServerFragment() as unknown as DocumentFragment;\n }\n\n /**\n * Create a verbatim pre-serialized HTML node (v1.7 static SSR plan, §6).\n * Server-only: the browser adapter does not implement this, and the renderer\n * fast path only invokes it when a static SSR plan is present (SSR). The\n * stored HTML was produced by this same serializer, so it is emitted as-is.\n */\n createRawHTML(html: string): Node {\n return new ServerRawHTML(html) as unknown as Node;\n }\n\n appendChild(parent: Node, child: Node): void {\n const p = asParent(parent);\n const c = asServer(child);\n this._detach(c);\n c.parent = p;\n p.children.push(c);\n }\n\n insertBefore(parent: Node, child: Node, reference: Node | null): void {\n const p = asParent(parent);\n const c = asServer(child);\n this._detach(c);\n c.parent = p;\n if (reference === null) {\n p.children.push(c);\n return;\n }\n const ref = asServer(reference);\n const idx = p.children.indexOf(ref);\n if (idx === -1) p.children.push(c);\n else p.children.splice(idx, 0, c);\n }\n\n removeChild(parent: Node, child: Node): void {\n const p = asParent(parent);\n const c = asServer(child);\n const idx = p.children.indexOf(c);\n if (idx !== -1) {\n p.children.splice(idx, 1);\n c.parent = null;\n }\n }\n\n replaceChild(parent: Node, newChild: Node, oldChild: Node): void {\n const p = asParent(parent);\n const nc = asServer(newChild);\n const oc = asServer(oldChild);\n const idx = p.children.indexOf(oc);\n if (idx === -1) return;\n this._detach(nc);\n nc.parent = p;\n p.children.splice(idx, 1, nc);\n oc.parent = null;\n }\n\n private _detach(node: ServerNode): void {\n if (node.parent !== null) {\n const siblings = node.parent.children;\n const idx = siblings.indexOf(node);\n if (idx !== -1) siblings.splice(idx, 1);\n node.parent = null;\n }\n }\n\n setAttribute(element: Element, name: string, value: string): void {\n (element as unknown as ServerElement).attributes.set(name, value);\n }\n\n removeAttribute(element: Element, name: string): void {\n (element as unknown as ServerElement).attributes.delete(name);\n }\n\n getAttribute(element: Element, name: string): string | null {\n return (element as unknown as ServerElement).attributes.get(name) ?? null;\n }\n\n setProperty(element: Element, name: string, value: unknown): void {\n (element as unknown as ServerElement).properties.set(name, value);\n }\n\n setTextContent(node: Node, text: string): void {\n const n = asServer(node);\n if (n.kind === 'element' || n.kind === 'fragment') {\n const el = n as ServerElement | ServerFragment;\n el.children.length = 0;\n const t = new ServerText(text);\n t.parent = el;\n el.children.push(t);\n } else if (n.kind === 'text') {\n (n as ServerText).data = text;\n }\n }\n\n getTextContent(node: Node): string | null {\n const n = asServer(node);\n if (n.kind === 'text') return (n as ServerText).data;\n if (n.kind === 'element' || n.kind === 'fragment') {\n let out = '';\n for (const c of (n as ServerElement | ServerFragment).children) {\n out += this.getTextContent(c as unknown as Node) ?? '';\n }\n return out;\n }\n return null;\n }\n\n // Server nodes never dispatch events — listeners are a no-op on the server.\n addEventListener(): void {\n /* no-op on the server */\n }\n removeEventListener(): void {\n /* no-op on the server */\n }\n\n querySelector(): Element | null {\n return null;\n }\n querySelectorAll(): NodeListOf<Element> {\n return [] as unknown as NodeListOf<Element>;\n }\n getElementById(): Element | null {\n return null;\n }\n\n focus(): void {\n // No focus concept on the server — intentional no-op (SSR-safe).\n }\n\n body(): Element | null {\n // No document on the server — portals degrade to inline rendering.\n return null;\n }\n\n head(): Element | null {\n // No document on the server — head metadata is emitted as a string by\n // `renderHead()` instead of being applied to a live document.head.\n return null;\n }\n\n activeElement(): Element | null {\n return null;\n }\n\n contains(_ancestor: Element, _node: Node): boolean {\n return false;\n }\n\n matches(_element: Element, _selector: string): boolean {\n return false;\n }\n\n isElement(node: Node): node is Element {\n return asServer(node).kind === 'element';\n }\n\n isTextNode(node: Node): node is Text {\n return asServer(node).kind === 'text';\n }\n\n tagName(element: Element): string {\n return (element as unknown as ServerElement).tagName;\n }\n\n parentNode(node: Node): Node | null {\n return (asServer(node).parent as unknown as Node | null) ?? null;\n }\n\n nextSibling(node: Node): Node | null {\n const n = asServer(node);\n const parent = n.parent;\n if (parent === null) return null;\n const idx = parent.children.indexOf(n);\n if (idx === -1 || idx + 1 >= parent.children.length) return null;\n return parent.children[idx + 1] as unknown as Node;\n }\n\n firstChild(node: Node): Node | null {\n const n = asServer(node);\n if (n.kind === 'element' || n.kind === 'fragment') {\n const el = n as ServerElement | ServerFragment;\n return (el.children[0] as unknown as Node) ?? null;\n }\n return null;\n }\n\n childNodes(node: Node): Node[] {\n const n = asServer(node);\n if (n.kind === 'element' || n.kind === 'fragment') {\n return (n as ServerElement | ServerFragment).children as unknown as Node[];\n }\n return [];\n }\n\n // ── Server-only ────────────────────────────────────────────────────────────\n\n /** Serialize a node's children (\"inner HTML\") to an HTML string. */\n serializeInner(node: Node): string {\n const n = asServer(node);\n if (n.kind === 'element' || n.kind === 'fragment') {\n return serializeChildren(n as ServerElement | ServerFragment);\n }\n return '';\n }\n\n /** Serialize a node (including itself) to an HTML string. */\n serializeOuter(node: Node): string {\n return serializeServerNode(asServer(node));\n }\n}\n\n// `/* @__PURE__ */`: this singleton is a convenience export only (no internal\n// runtime path references it). Marking construction pure lets bundlers drop it —\n// and with it the whole server serializer chain (serializeServerNode/escape/\n// VOID_ELEMENTS) — out of client bundles that never import SSR. Without this,\n// the un-annotated `new` is treated as a side effect and retained everywhere.\nexport const serverDOMAdapter = /* @__PURE__ */ new ServerDOMAdapter();\n","/**\n * Focus helpers built on the {@link DOMAdapter} abstraction.\n *\n * These are the minimal, genuinely-useful focus operations an app needs:\n * focus a specific element (e.g. the first field when a route or modal opens)\n * or focus the first focusable element inside a container (e.g. move focus\n * into a dialog). Both go through the adapter, so they are no-ops on the server\n * (`ServerDOMAdapter.querySelector` returns null / `focus` does nothing) and\n * therefore safe to call from universal code.\n */\n\nimport type { DOMAdapter } from './adapter.js';\n\n/** Default selector for natively focusable / tabbable elements. */\nexport const FOCUSABLE_SELECTOR =\n 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex=\"-1\"])';\n\n/**\n * Focus the element with the given id, scoped to `root`.\n * Returns true if an element was found and focused.\n */\nexport function focusById(dom: DOMAdapter, root: Element | Document, id: string): boolean {\n const el = dom.querySelector(root, `[id=\"${id}\"]`);\n if (el === null) return false;\n dom.focus(el);\n return true;\n}\n\n/**\n * Focus the first focusable element inside `container`.\n * Returns true if a focusable element was found and focused.\n */\nexport function focusFirst(\n dom: DOMAdapter,\n container: Element | Document,\n selector: string = FOCUSABLE_SELECTOR,\n): boolean {\n const el = dom.querySelector(container, selector);\n if (el === null) return false;\n dom.focus(el);\n return true;\n}\n\n/**\n * Ordered list of focusable/tabbable descendants of `container`.\n * Re-checks each candidate against the selector so elements disabled after the\n * initial query (e.g. a button toggled to `disabled`) are excluded.\n */\nexport function getFocusable(\n dom: DOMAdapter,\n container: Element,\n selector: string = FOCUSABLE_SELECTOR,\n): Element[] {\n return Array.from(dom.querySelectorAll(container, selector)).filter((el) =>\n dom.matches(el, selector),\n );\n}\n\n/**\n * Capture the currently-focused element so it can be restored later (e.g. when\n * a dialog closes). Returns null on the server or when nothing is focused.\n */\nexport function saveFocus(dom: DOMAdapter): Element | null {\n return dom.activeElement();\n}\n\n/** Restore focus to a previously {@link saveFocus}-d element. No-op if null. */\nexport function restoreFocus(dom: DOMAdapter, saved: Element | null): void {\n if (saved !== null) dom.focus(saved);\n}\n\n/**\n * Move focus into `container` on open: the element with id `initialFocusId` if\n * given and present, otherwise the first focusable element. Server-safe no-op.\n */\nexport function focusInitial(\n dom: DOMAdapter,\n container: Element,\n initialFocusId?: string,\n): void {\n if (initialFocusId !== undefined && focusById(dom, container, initialFocusId)) return;\n focusFirst(dom, container);\n}\n\n/**\n * Trap Tab / Shift+Tab focus within `container` (wrap-around at both ends).\n * Attaches a keydown listener to the container and returns a cleanup function\n * that detaches it. Server-safe: `addEventListener` is a no-op, and the returned\n * cleanup is still callable.\n */\nexport function trapFocus(dom: DOMAdapter, container: Element): () => void {\n const onKeydown = ((event: KeyboardEvent): void => {\n if (event.key !== 'Tab') return;\n const items = getFocusable(dom, container);\n if (items.length === 0) {\n event.preventDefault();\n return;\n }\n const first = items[0]!;\n const last = items[items.length - 1]!;\n const active = dom.activeElement();\n if (active === null || !dom.contains(container, active)) {\n event.preventDefault();\n dom.focus(first);\n } else if (event.shiftKey && active === first) {\n event.preventDefault();\n dom.focus(last);\n } else if (!event.shiftKey && active === last) {\n event.preventDefault();\n dom.focus(first);\n }\n }) as EventListener;\n dom.addEventListener(container, 'keydown', onKeydown);\n return () => dom.removeEventListener(container, 'keydown', onKeydown);\n}\n\n/**\n * Modal containment: if focus moves to an element outside `container`, redirect\n * it back inside. Listens on the document body (focusin bubbles there) and\n * returns a cleanup function. Server-safe no-op (body() is null).\n *\n * Nested modals (§16): every active containment pushes its container onto a\n * module-level stack, and a handler only redirects while ITS container is the\n * top of the stack — i.e. the most recently opened modal. This is the framework's\n * minimal \"focus owner\" concept: because overlay panels are relocated to\n * body-level portals (siblings, not descendants), two overlapping `containFocus`\n * handlers would otherwise fight over every `focusin`. The stack makes exactly\n * one owner authoritative at a time; cleanup pops it so the previous modal\n * resumes ownership. State is internal and torn down on cleanup — nothing is\n * retained on the graph (§18).\n */\nconst containmentStack: Element[] = [];\n\nexport function containFocus(dom: DOMAdapter, container: Element): () => void {\n const body = dom.body();\n if (body === null) return () => {};\n containmentStack.push(container);\n const onFocusIn = ((event: FocusEvent): void => {\n // Only the topmost owner enforces containment (nested-modal correctness).\n if (containmentStack[containmentStack.length - 1] !== container) return;\n const target = event.target as Node | null;\n if (target !== null && !dom.contains(container, target)) {\n focusFirst(dom, container);\n }\n }) as EventListener;\n dom.addEventListener(body, 'focusin', onFocusIn);\n return () => {\n dom.removeEventListener(body, 'focusin', onFocusIn);\n const index = containmentStack.lastIndexOf(container);\n if (index !== -1) containmentStack.splice(index, 1);\n };\n}\n\n/**\n * Invoke `handler` when Escape is pressed while focus is within `target`.\n * Returns a cleanup function. Server-safe no-op.\n */\nexport function onEscape(dom: DOMAdapter, target: Element, handler: () => void): () => void {\n const onKeydown = ((event: KeyboardEvent): void => {\n if (event.key === 'Escape') handler();\n }) as EventListener;\n dom.addEventListener(target, 'keydown', onKeydown);\n return () => dom.removeEventListener(target, 'keydown', onKeydown);\n}\n\n/**\n * Roving-focus keyboard navigation for a menu (role=\"menu\") container: the\n * arrow keys move focus between the container's focusable items (wrap-around at\n * both ends), Home/End jump to the first/last item, and Enter/Space activate\n * the currently-focused item (a native `click`, so an item's `onClick` fires).\n * `Tab` and `Escape` are deliberately left alone — the overlay layer wires\n * Escape-to-close separately and a menu does not trap Tab.\n *\n * Items are re-queried on every key (via {@link getFocusable}) so a menu whose\n * items change reactively is always navigated against the live set, and items\n * disabled after mount are skipped. Attaches a keydown listener to the\n * container and returns a cleanup function. Server-safe: `addEventListener` is\n * a no-op and the returned cleanup is still callable.\n */\nexport function rovingMenu(\n dom: DOMAdapter,\n container: Element,\n selector: string = FOCUSABLE_SELECTOR,\n): () => void {\n const onKeydown = ((event: KeyboardEvent): void => {\n const key = event.key;\n const isActivate = key === 'Enter' || key === ' ' || key === 'Spacebar';\n const isMove =\n key === 'ArrowDown' || key === 'ArrowUp' || key === 'Home' || key === 'End';\n if (!isActivate && !isMove) return;\n\n const items = getFocusable(dom, container, selector);\n if (items.length === 0) return;\n const active = dom.activeElement();\n const index = active === null ? -1 : items.indexOf(active);\n\n if (isActivate) {\n // Activating a menu item only makes sense when one is focused; otherwise\n // let the event fall through unchanged.\n if (index < 0) return;\n event.preventDefault();\n (items[index] as unknown as { click?: () => void }).click?.();\n return;\n }\n\n event.preventDefault();\n let next: number;\n if (key === 'Home') next = 0;\n else if (key === 'End') next = items.length - 1;\n else if (key === 'ArrowDown') next = index < 0 ? 0 : (index + 1) % items.length;\n else next = index <= 0 ? items.length - 1 : index - 1; // ArrowUp\n dom.focus(items[next]!);\n }) as EventListener;\n dom.addEventListener(container, 'keydown', onKeydown);\n return () => dom.removeEventListener(container, 'keydown', onKeydown);\n}\n\n","/**\n * Maps semantic node types to HTML tag names.\n */\n\nimport type { SemanticNodeType } from '@streetui/core';\n\nconst TAG_MAP: Partial<Record<SemanticNodeType, string>> = {\n application: 'div',\n page: 'div',\n section: 'section',\n container: 'div',\n heading: 'h1',\n text: 'span',\n button: 'button',\n input: 'input',\n form: 'form',\n list: 'ul',\n 'list-item': 'li',\n image: 'img',\n link: 'a',\n component: 'div',\n slot: 'div',\n fragment: 'div',\n 'reactive-list': 'ul',\n // A portal renders as a neutral inline anchor <div> at its declaration site;\n // its children are relocated to a document.body container on the browser\n // (see the portal branch in mount.ts). On the server (no body) it renders\n // inline, so the anchor tag is what SSR/hydration positionally match on.\n portal: 'div',\n // A `head()` node renders as a neutral, empty inline anchor <div> at its\n // declaration site (like a portal anchor). Its actual contribution — title/\n // meta/link/etc. — is applied to `document.head` by `wireHeadBehavior` on the\n // browser, and emitted separately by `renderHead()` on the server. Keeping a\n // one-node/one-element anchor preserves positional hydration.\n head: 'div',\n};\n\nexport function resolveTag(type: SemanticNodeType): string {\n return TAG_MAP[type] ?? 'div';\n}\n","/**\n * Patch — targeted DOM updates driven by signal changes.\n *\n * When a signal fires, we look up the NodeInstance and apply\n * only the changed prop — no full re-render, no tree diffing.\n */\n\nimport type { RenderContext } from './render-context.js';\nimport type { GraphNode } from '@streetui/graph';\nimport { applyProp, patchProp } from './attributes.js';\n\nexport function patchNode(\n ctx: RenderContext,\n graphNode: GraphNode,\n propKey: string,\n newValue: unknown,\n): void {\n const instance = ctx.instances.get(graphNode.id);\n if (instance === undefined) return;\n\n const domNode = instance.domNode;\n if (!ctx.dom.isElement(domNode)) return;\n\n const oldValue = graphNode.getProp(propKey);\n\n switch (propKey) {\n case 'text':\n if (!Object.is(oldValue, newValue)) {\n ctx.dom.setTextContent(domNode, String(newValue ?? ''));\n graphNode.setProp('text', String(newValue ?? ''));\n }\n break;\n case 'label':\n if (!Object.is(oldValue, newValue)) {\n ctx.dom.setTextContent(domNode, String(newValue ?? ''));\n graphNode.setProp('label', String(newValue ?? ''));\n }\n break;\n case 'disabled':\n if (newValue === true) {\n ctx.dom.setAttribute(domNode, 'disabled', '');\n } else {\n ctx.dom.removeAttribute(domNode, 'disabled');\n }\n graphNode.setProp('disabled', Boolean(newValue));\n break;\n case 'value':\n if (!Object.is(oldValue, newValue)) {\n ctx.dom.setProperty(domNode, 'value', String(newValue ?? ''));\n graphNode.setProp('value', String(newValue ?? ''));\n }\n break;\n default:\n patchProp(ctx.dom, domNode, propKey, oldValue, newValue);\n graphNode.setProp(propKey, newValue as string);\n break;\n }\n}\n","/**\n * Reconciliation — diff-based child list updates.\n *\n * When the children of a node change (e.g. a list driven by state),\n * this reconciler:\n * 1. Matches old instances to new graph nodes by key\n * 2. Reuses matched instances (updates their props)\n * 3. Applies a targeted content update to a reused item whose data changed\n * 4. Creates new instances for additions\n * 5. Removes stale instances (and prunes their handler registrations)\n * 6. Moves DOM nodes to match new order\n *\n * This is keyed reconciliation over the semantic graph — there is no virtual\n * DOM. A reused item keeps its own DOM element; only its changed content is\n * updated in place (falling back to remounting a subtree only where its shape\n * actually changed).\n */\n\nimport type { RenderContext } from './render-context.js';\nimport type { GraphNode } from '@streetui/graph';\nimport type { NodeInstance } from './node-instance.js';\nimport type { TransitionHooks } from './transition.js';\nimport { patchNode } from './patch.js';\n\nexport type MountFn = (node: GraphNode, parent: Element) => NodeInstance;\n\nexport interface ReconcileResult {\n /** Instances in the new order. */\n instances: NodeInstance[];\n /** Instances that were removed and must be disposed. */\n removed: NodeInstance[];\n /**\n * GraphNodes freshly materialised during this reconcile (new rows + rebuilt\n * changed rows). The caller detaches any of these that were not adopted as a\n * live instance's graph node, so no orphan subtree lingers in the graph index.\n */\n built?: GraphNode[];\n}\n\n/**\n * A lazy reconciliation descriptor for one reactive-list row (mirrors the DSL's\n * `ListPlanEntry`). `sig()` and `build()` are only invoked for rows that are\n * genuinely new or whose source reference changed — the whole point of the\n * plan path (spec §15).\n */\nexport interface PlanEntry {\n readonly key: string;\n readonly item: unknown;\n readonly sig: () => string;\n readonly build: () => GraphNode;\n}\n\n/**\n * Reconcile children of a container element against a new list of graph nodes.\n *\n * @param ctx Render context\n * @param parentDom The DOM parent element\n * @param oldInstances Current child instances (in order)\n * @param newNodes New graph children (in desired order)\n * @param mountFn Factory to create a new NodeInstance for a graph node\n */\nexport function reconcileChildren(\n ctx: RenderContext,\n parentDom: Element,\n oldInstances: NodeInstance[],\n newNodes: readonly GraphNode[],\n mountFn: MountFn,\n hooks?: TransitionHooks,\n): ReconcileResult {\n // Build key → old instance map\n const oldByKey = new Map<string, NodeInstance>();\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n oldByKey.set(key, inst);\n }\n\n const newInstances: NodeInstance[] = [];\n const usedKeys = new Set<string>();\n\n for (const newNode of newNodes) {\n const key = newNode.key ?? newNode.id;\n const existing = oldByKey.get(key);\n\n if (existing !== undefined) {\n // Reuse — identity is stable, so the DOM element is preserved.\n usedKeys.add(key);\n const oldSig = existing.graphNode.getProp('_sig');\n const newSig = newNode.getProp('_sig');\n patchExistingInstance(ctx, existing, newNode);\n // Data changed but identity did not → targeted content update in place.\n if (!Object.is(oldSig, newSig)) {\n reconcileItemChildren(ctx, existing, newNode, mountFn);\n }\n newInstances.push(existing);\n } else {\n // Leave→enter cancellation (§6): if this key is currently animating out,\n // reclaim its live instance instead of mounting a duplicate.\n const reclaimed = hooks?.takeLeaving(key);\n if (reclaimed !== undefined) {\n patchExistingInstance(ctx, reclaimed, newNode);\n reconcileItemChildren(ctx, reclaimed, newNode, mountFn);\n hooks?.onEnter(reclaimed);\n newInstances.push(reclaimed);\n } else {\n // New — create and mount, then play its enter animation (if any).\n const inst = mountFn(newNode, parentDom);\n hooks?.onEnter(inst);\n newInstances.push(inst);\n }\n }\n }\n\n // Determine + remove stale instances. A removed instance that carries a\n // transition has its DOM-remove + dispose deferred to leave-animation end by\n // `beginLeave` (which then also forgets + detaches it), so it is excluded from\n // `removed` and the caller does not tear it down (§3/§7).\n const removed: NodeInstance[] = [];\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n if (usedKeys.has(key)) continue;\n if (hooks !== undefined && hooks.beginLeave(inst)) continue;\n const parent = ctx.dom.parentNode(inst.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, inst.domNode);\n inst.dispose();\n removed.push(inst);\n }\n\n // Reorder DOM nodes to match new order\n reorderDom(ctx, parentDom, newInstances);\n\n return { instances: newInstances, removed };\n}\n\n/**\n * Plan-based keyed reconciliation (spec §15 — the optimised reactive-list path).\n *\n * Identical observable result to {@link reconcileChildren}, but driven by lazy\n * {@link PlanEntry} descriptors instead of a pre-built array of GraphNodes:\n *\n * - a reused row whose `item` reference is unchanged does **zero** work — no\n * signature hash, no subtree build, no prop patch (the common case for\n * append / prepend / remove / reorder / reverse, where existing item objects\n * keep their identity);\n * - a reused row whose reference changed hashes lazily and, only on a real\n * signature change, materialises a fresh subtree for a targeted in-place\n * content update;\n * - a genuinely new key builds + mounts exactly one subtree.\n *\n * DOM reordering uses a longest-increasing-subsequence pass so the number of\n * moves is minimal (e.g. a prepend into a 10k list moves 1 node, not 10k).\n */\nexport function reconcileChildrenByPlan(\n ctx: RenderContext,\n parentDom: Element,\n oldInstances: NodeInstance[],\n plan: readonly PlanEntry[],\n mountFn: MountFn,\n hooks?: TransitionHooks,\n): ReconcileResult {\n const oldByKey = new Map<string, NodeInstance>();\n for (const inst of oldInstances) {\n oldByKey.set(inst.graphNode.key ?? inst.graphNode.id, inst);\n }\n\n const newInstances: NodeInstance[] = [];\n const usedKeys = new Set<string>();\n const built: GraphNode[] = [];\n\n for (const entry of plan) {\n const existing = oldByKey.get(entry.key);\n if (existing !== undefined) {\n usedKeys.add(entry.key);\n const oldItem = existing.graphNode.getProp('_item');\n // Identity short-circuit: same reference ⇒ data cannot have changed.\n if (!Object.is(oldItem, entry.item)) {\n const newSig = entry.sig();\n const oldSig = existing.graphNode.getProp('_sig');\n if (!Object.is(oldSig, newSig)) {\n const freshNode = entry.build();\n built.push(freshNode);\n patchExistingInstance(ctx, existing, freshNode);\n reconcileItemChildren(ctx, existing, freshNode, mountFn);\n existing.graphNode.setProp('_sig', newSig);\n }\n // Cache the new reference so the next pass can short-circuit again.\n existing.graphNode.setProp('_item', entry.item as never);\n }\n newInstances.push(existing);\n } else {\n // Leave→enter reclaim (§6/§7): a key removed then re-added mid-leave keeps\n // its identity and its live DOM node rather than mounting a duplicate.\n const reclaimed = hooks?.takeLeaving(entry.key);\n if (reclaimed !== undefined) {\n const freshNode = entry.build();\n built.push(freshNode);\n patchExistingInstance(ctx, reclaimed, freshNode);\n reconcileItemChildren(ctx, reclaimed, freshNode, mountFn);\n reclaimed.graphNode.setProp('_sig', freshNode.getProp('_sig') as never);\n reclaimed.graphNode.setProp('_item', entry.item as never);\n hooks?.onEnter(reclaimed);\n newInstances.push(reclaimed);\n } else {\n const freshNode = entry.build();\n built.push(freshNode);\n const inst = mountFn(freshNode, parentDom);\n hooks?.onEnter(inst);\n newInstances.push(inst);\n }\n }\n }\n\n // Determine + remove stale instances. Transitioned rows defer their whole\n // teardown chain to leave-animation end (§7) and are excluded from `removed`.\n const removed: NodeInstance[] = [];\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n if (usedKeys.has(key)) continue;\n if (hooks !== undefined && hooks.beginLeave(inst)) continue;\n const parent = ctx.dom.parentNode(inst.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, inst.domNode);\n inst.dispose();\n removed.push(inst);\n }\n\n // Minimal-move reorder to the desired order.\n reorderDomMinimal(ctx, parentDom, oldInstances, newInstances);\n\n return { instances: newInstances, removed, built };\n}\n\n/**\n * Minimal-move DOM reorder.\n *\n * Reused nodes retain their previous DOM slots and newly-mounted nodes sit at\n * the end. We compute the longest increasing subsequence of the reused nodes'\n * previous positions; those are already in correct relative order and stay put.\n * Every other node is inserted before its right-hand neighbour, walking\n * right-to-left. This yields exactly (n − |LIS|) `insertBefore` calls — the\n * minimum — instead of the O(n) sweep the naive reorder performs on a prepend.\n */\nfunction reorderDomMinimal(\n ctx: RenderContext,\n parentDom: Element,\n oldInstances: NodeInstance[],\n newInstances: NodeInstance[],\n): void {\n const n = newInstances.length;\n if (n === 0) return;\n\n const oldIndexOf = new Map<NodeInstance, number>();\n for (let i = 0; i < oldInstances.length; i++) oldIndexOf.set(oldInstances[i]!, i);\n\n const source = new Array<number>(n);\n let moved = false;\n let lastSeen = -1;\n for (let i = 0; i < n; i++) {\n const oi = oldIndexOf.get(newInstances[i]!);\n if (oi === undefined) {\n source[i] = -1; // freshly mounted row\n moved = true;\n } else {\n source[i] = oi;\n if (oi < lastSeen) moved = true; // an out-of-order reused row exists\n else lastSeen = oi;\n }\n }\n\n // Fast path: nothing is out of order and there are no new rows to reposition.\n if (!moved) return;\n\n const keep = longestIncreasingSubsequence(source);\n\n let refNode: Node | null = null;\n for (let i = n - 1; i >= 0; i--) {\n const domNode = newInstances[i]!.domNode;\n if (source[i] === -1 || !keep.has(i)) {\n if (ctx.dom.nextSibling(domNode) !== refNode) {\n ctx.dom.insertBefore(parentDom, domNode, refNode);\n }\n }\n refNode = domNode;\n }\n}\n\n/**\n * Indices (into `source`) forming a longest strictly-increasing subsequence,\n * ignoring `-1` entries (new rows, which always move). O(n log n) with\n * predecessor reconstruction.\n */\nfunction longestIncreasingSubsequence(source: readonly number[]): Set<number> {\n const keep = new Set<number>();\n const n = source.length;\n const tails: number[] = []; // tails[k] = source-index of smallest tail of an LIS of length k+1\n const prev = new Array<number>(n).fill(-1);\n\n for (let i = 0; i < n; i++) {\n const v = source[i]!;\n if (v < 0) continue;\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (source[tails[mid]!]! < v) lo = mid + 1;\n else hi = mid;\n }\n if (lo > 0) prev[i] = tails[lo - 1]!;\n tails[lo] = i;\n }\n\n let idx = tails.length > 0 ? tails[tails.length - 1]! : -1;\n while (idx >= 0) {\n keep.add(idx);\n idx = prev[idx]!;\n }\n return keep;\n}\n\n/**\n * Targeted in-place content update for a reused list item whose data changed.\n *\n * The item's DOM element is kept; only its contents are updated. Children are\n * matched positionally against the freshly-built subtree:\n * - same node type at a position → the existing child is reused and its props\n * are patched in place (e.g. a text node's text is rewritten), then we\n * recurse into its children;\n * - different type / new position → the fresh child node is reparented onto the\n * live item node and mounted;\n * - surplus old children → disposed, with DOM, subscriptions, listeners and\n * handler registrations all torn down.\n *\n * This deliberately reuses the same keyed/positional strategy rather than a\n * virtual DOM, and never destroys the item element itself.\n */\nfunction reconcileItemChildren(\n ctx: RenderContext,\n itemInstance: NodeInstance,\n newItemNode: GraphNode,\n mountFn: MountFn,\n): void {\n const el = itemInstance.domNode;\n if (!ctx.dom.isElement(el)) return;\n\n const oldChildren = [...itemInstance.children];\n const newChildNodes = [...newItemNode.children];\n const nextChildren: NodeInstance[] = [];\n const kept = new Set<NodeInstance>();\n\n for (let i = 0; i < newChildNodes.length; i++) {\n const newChild = newChildNodes[i]!;\n const oldChild = oldChildren[i];\n\n if (oldChild !== undefined && oldChild.graphNode.type === newChild.type) {\n // Reuse in place — patch this node's props and recurse into descendants.\n patchExistingInstance(ctx, oldChild, newChild);\n reconcileItemChildren(ctx, oldChild, newChild, mountFn);\n nextChildren.push(oldChild);\n kept.add(oldChild);\n } else {\n // Structural change at this position — mount the fresh child. Reparent it\n // out of the freshly-built subtree so the wholesale detach of the\n // unadopted item node (in mount.ts) does not remove this now-live node.\n itemInstance.graphNode.appendChild(newChild);\n const inst = mountFn(newChild, el);\n nextChildren.push(inst);\n }\n }\n\n // Dispose old children that were not reused (surplus or type-mismatched).\n for (const old of oldChildren) {\n if (kept.has(old)) continue;\n const parent = ctx.dom.parentNode(old.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, old.domNode);\n old.dispose();\n forgetInstanceTree(ctx, old);\n ctx.graph.detachNode(old.graphNode);\n }\n\n // Restore correct DOM order within the item element.\n reorderDom(ctx, el, nextChildren);\n\n // Sync the live instance's children.\n itemInstance.children.length = 0;\n for (const c of nextChildren) itemInstance.children.push(c);\n\n // Keep the graph model's item children consistent with the reconciled order.\n for (const c of [...itemInstance.graphNode.children]) {\n itemInstance.graphNode.removeChild(c);\n }\n for (const c of nextChildren) itemInstance.graphNode.appendChild(c.graphNode);\n}\n\n/** Move a parent's DOM children to match the given instance order (minimal moves). */\nfunction reorderDom(\n ctx: RenderContext,\n parentDom: Element,\n instances: NodeInstance[],\n): void {\n let referenceNode: Node | null = null;\n for (let i = instances.length - 1; i >= 0; i--) {\n const inst = instances[i];\n if (inst === undefined) continue;\n const domNode = inst.domNode;\n const currentNext = ctx.dom.nextSibling(domNode);\n if (currentNext !== referenceNode) {\n ctx.dom.insertBefore(parentDom, domNode, referenceNode);\n }\n referenceNode = domNode;\n }\n}\n\n/** Recursively drop an instance subtree from the renderer's instance index. */\nfunction forgetInstanceTree(ctx: RenderContext, instance: NodeInstance): void {\n ctx.instances.delete(instance.graphNode.id);\n for (const child of instance.children) forgetInstanceTree(ctx, child);\n}\n\nfunction patchExistingInstance(\n ctx: RenderContext,\n instance: NodeInstance,\n newNode: GraphNode,\n): void {\n const oldNode = instance.graphNode;\n for (const [key, newVal] of Object.entries(newNode.props)) {\n const oldVal = oldNode.getProp(key);\n if (!Object.is(oldVal, newVal)) {\n patchNode(ctx, instance.graphNode, key, newVal);\n }\n }\n}\n","/**\n * CSS class-based enter/leave transition controller (§2–§8).\n *\n * This is the browser-only runtime that consumes the `__transition__<nodeId>`\n * descriptor the DSL registers (a pre-resolved {@link ResolvedTransitionLike}).\n * It is deliberately structural about that descriptor — like the renderer's\n * `__overlay__`/`__component__` handling — so the renderer takes NO compile-time\n * dependency on the DSL package.\n *\n * Engine (confirmed decision): CSS classes, no Web Animations API, no\n * browser-only API referenced at module scope. Every timer / rAF / event\n * binding is reached lazily through `globalThis` and only ever runs when\n * `dom.body() !== null` (the same SSR guard `wireOverlayBehavior` uses), so:\n * - server output is byte-identical (nothing here runs during SSR — §21);\n * - happy-dom, which dispatches no `transitionend`/`animationend`, still\n * completes deterministically via the fallback timeout (§24).\n *\n * The controller is created once per reactive container instance (reactive-list\n * or conditional) so its `leaving` map survives across reconcile passes — that\n * is what makes leave→enter reclaim (§6) and keyed-identity list leave (§7)\n * correct.\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { NodeInstance } from './node-instance.js';\n\n/**\n * The renderer's structural view of the resolved transition the DSL stores in\n * `__transition__<id>`. Mirrors `@streetui/dsl`'s `ResolvedTransition` without\n * importing it (no renderer→dsl dependency).\n */\nexport interface ResolvedTransitionLike {\n readonly enterActive: readonly string[];\n readonly enterFrom: readonly string[];\n readonly enterTo: readonly string[];\n readonly leaveActive: readonly string[];\n readonly leaveFrom: readonly string[];\n readonly leaveTo: readonly string[];\n readonly appear: boolean;\n readonly duration: number;\n}\n\n/**\n * Hooks handed to the reconciler so it can (a) reclaim an instance that is\n * mid-leave when its key re-enters (leave→enter cancellation), (b) defer the\n * remove/dispose/forget/detach chain for a leaving instance until its animation\n * ends, and (c) play the enter animation for a freshly-inserted instance. When\n * no transition applies (or we are on the server) every hook degrades to the\n * pre-transition synchronous behaviour.\n */\nexport interface TransitionHooks {\n /**\n * If an instance for `key` is currently animating out, cancel its leave and\n * return it for reuse; otherwise undefined. The caller re-mounts nothing and\n * reuses the returned instance's live DOM node.\n */\n takeLeaving(key: string): NodeInstance | undefined;\n /**\n * Begin a leave animation for a removed instance. Returns true when the whole\n * teardown chain has been deferred to animation-end (caller must NOT remove,\n * dispose, forget or detach it), or false when there is no transition / no\n * browser and the caller should tear it down synchronously as before.\n */\n beginLeave(inst: NodeInstance): boolean;\n /** Play the enter animation for a freshly-inserted (or reclaimed) instance. */\n onEnter(inst: NodeInstance): void;\n}\n\n/** Read the pre-resolved transition descriptor for a node, if any. */\nexport function getResolvedTransition(\n graph: ApplicationGraph,\n nodeId: string,\n): ResolvedTransitionLike | undefined {\n const fn = graph.getHandler(`__transition__${nodeId}`) as\n | (() => ResolvedTransitionLike)\n | undefined;\n return fn === undefined ? undefined : fn();\n}\n\n// ── Browser-global access (lazy, never at module scope) ──────────────────────\n\ninterface RafHost {\n requestAnimationFrame?: (cb: () => void) => number;\n setTimeout: (cb: () => void, ms: number) => unknown;\n clearTimeout: (h: unknown) => void;\n}\n\nfunction host(): RafHost {\n return globalThis as unknown as RafHost;\n}\n\n/** Schedule a callback for the next frame (falls back to a macrotask). */\nfunction nextFrame(cb: () => void): void {\n const h = host();\n const raf = h.requestAnimationFrame;\n if (typeof raf === 'function') {\n // Double rAF: ensures the \"from\" classes have been painted before we flip\n // to the \"to\" classes, so the transition actually runs in real browsers.\n raf(() => raf(cb));\n } else {\n h.setTimeout(cb, 0);\n }\n}\n\n// ── Class list manipulation via the adapter (no classList dependency) ─────────\n\nfunction splitClass(value: string | null): string[] {\n if (value === null) return [];\n const out: string[] = [];\n for (const t of value.split(/\\s+/)) if (t.length > 0) out.push(t);\n return out;\n}\n\nfunction addClasses(dom: DOMAdapter, el: Element, classes: readonly string[]): void {\n if (classes.length === 0) return;\n const current = splitClass(dom.getAttribute(el, 'class'));\n let changed = false;\n for (const c of classes) {\n if (!current.includes(c)) {\n current.push(c);\n changed = true;\n }\n }\n if (changed) dom.setAttribute(el, 'class', current.join(' '));\n}\n\nfunction removeClasses(dom: DOMAdapter, el: Element, classes: readonly string[]): void {\n if (classes.length === 0) return;\n const current = splitClass(dom.getAttribute(el, 'class'));\n const next = current.filter((c) => !classes.includes(c));\n if (next.length !== current.length) {\n if (next.length === 0) dom.removeAttribute(el, 'class');\n else dom.setAttribute(el, 'class', next.join(' '));\n }\n}\n\n/**\n * One running enter-or-leave animation on a single element. Owns exactly one set\n * of DOM listeners + one fallback timer, and guarantees `settle`/`cancel` run\n * their cleanup at most once — no stale callbacks, no duplicate listeners, no\n * duplicate cleanup (§6).\n */\ninterface Run {\n /** Force the animation to its end synchronously (used by cancellation). */\n cancel(): void;\n}\n\nfunction startRun(\n dom: DOMAdapter,\n el: Element,\n active: readonly string[],\n from: readonly string[],\n to: readonly string[],\n duration: number,\n onDone: () => void,\n): Run {\n const h = host();\n let finished = false;\n let timer: unknown = null;\n\n const onEvent = ((e: Event): void => {\n // Ignore bubbling transition/animation events from descendants.\n if (e.target !== el) return;\n finish();\n }) as EventListener;\n\n const detach = (): void => {\n dom.removeEventListener(el, 'transitionend', onEvent);\n dom.removeEventListener(el, 'animationend', onEvent);\n if (timer !== null) {\n h.clearTimeout(timer);\n timer = null;\n }\n };\n\n const finish = (): void => {\n if (finished) return;\n finished = true;\n detach();\n // Clear all transition classes so the element rests in its natural state.\n removeClasses(dom, el, active);\n removeClasses(dom, el, to);\n removeClasses(dom, el, from);\n onDone();\n };\n\n // Phase 1: apply the starting + active classes immediately.\n addClasses(dom, el, from);\n addClasses(dom, el, active);\n\n dom.addEventListener(el, 'transitionend', onEvent);\n dom.addEventListener(el, 'animationend', onEvent);\n // Fallback completion: the safety net for elements that fire no transition\n // event (and the ONLY completion signal under happy-dom, where tests set a\n // small duration). 0 → next macrotask.\n timer = h.setTimeout(finish, duration);\n\n // Phase 2: on the next frame flip from → to so the CSS transition runs.\n nextFrame(() => {\n if (finished) return;\n removeClasses(dom, el, from);\n addClasses(dom, el, to);\n });\n\n return {\n cancel: () => {\n // Cancel = settle immediately (removes classes, clears listeners/timer)\n // but WITHOUT invoking onDone, so a cancelled leave never finalizes the\n // node it was about to destroy.\n if (finished) return;\n finished = true;\n detach();\n removeClasses(dom, el, active);\n removeClasses(dom, el, to);\n removeClasses(dom, el, from);\n },\n };\n}\n\ninterface LeavingEntry {\n readonly inst: NodeInstance;\n readonly run: Run;\n}\n\n/** Which half of a transition to play on a bare element. */\nexport type TransitionPhase = 'enter' | 'leave';\n\n/**\n * Play one enter/leave transition on a bare DOM element, outside the keyed\n * reconciler — the seam the router uses for route leave/enter (§9) and any other\n * consumer that owns a single host element rather than a reactive container.\n *\n * Reuses the exact same {@link startRun} mechanics as list/conditional\n * transitions (from+active applied immediately, next-frame flip to `to`,\n * completion on transitionend/animationend or the fallback timer), so there is\n * one transition engine, not two. The returned handle's `cancel()` settles the\n * run immediately WITHOUT invoking `onDone` — the caller uses it to abort an\n * in-flight enter when the same host is about to start leaving (rapid\n * navigation), avoiding overlapping runs/duplicate listeners on one element.\n *\n * On the server (or any non-element target) there is nothing to animate, so\n * `onDone` runs synchronously and `cancel()` is a no-op — the caller's teardown\n * still happens exactly once.\n */\nexport function runElementTransition(\n dom: DOMAdapter,\n el: Element,\n rt: ResolvedTransitionLike,\n phase: TransitionPhase,\n onDone: () => void,\n): { cancel(): void } {\n if (dom.body() === null || !dom.isElement(el)) {\n onDone();\n return { cancel: () => {} };\n }\n const active = phase === 'enter' ? rt.enterActive : rt.leaveActive;\n const from = phase === 'enter' ? rt.enterFrom : rt.leaveFrom;\n const to = phase === 'enter' ? rt.enterTo : rt.leaveTo;\n return startRun(dom, el, active, from, to, rt.duration, onDone);\n}\n\n\n/**\n * Per-container transition controller. One instance is created for each\n * reactive-list / conditional NodeInstance in {@link wireReactiveList}; its\n * `leaving` map persists across every reconcile of that container.\n */\nexport class TransitionController {\n private readonly leaving = new Map<string, LeavingEntry>();\n\n constructor(\n private readonly dom: DOMAdapter,\n private readonly graph: ApplicationGraph,\n /** Full teardown of a leaving instance (remove + dispose + forget + detach). */\n private readonly finalize: (inst: NodeInstance) => void,\n ) {}\n\n /** True only in a real DOM environment (browser). */\n private get browser(): boolean {\n return this.dom.body() !== null;\n }\n\n private keyOf(inst: NodeInstance): string {\n return inst.graphNode.key ?? inst.graphNode.id;\n }\n\n private resolved(node: GraphNode): ResolvedTransitionLike | undefined {\n return getResolvedTransition(this.graph, node.id);\n }\n\n /** Run the enter animation for `inst` if it carries a transition (browser only). */\n enter(inst: NodeInstance): void {\n if (!this.browser) return;\n const rt = this.resolved(inst.graphNode);\n if (rt === undefined) return;\n const el = inst.domNode;\n if (!this.dom.isElement(el)) return;\n startRun(this.dom, el, rt.enterActive, rt.enterFrom, rt.enterTo, rt.duration, () => {\n /* enter has no teardown; classes already cleared by the run */\n });\n }\n\n /**\n * Play `appear` for any initial child that opted into it (fresh browser mount\n * only — hydration must never animate appear, §22, and this is called only on\n * the mount path).\n */\n appear(children: readonly NodeInstance[]): void {\n if (!this.browser) return;\n for (const child of children) {\n const rt = this.resolved(child.graphNode);\n if (rt !== undefined && rt.appear) this.enter(child);\n }\n }\n\n hooks(): TransitionHooks {\n return {\n takeLeaving: (key) => {\n const entry = this.leaving.get(key);\n if (entry === undefined) return undefined;\n entry.run.cancel(); // leave→enter: stop the leave, keep the live node\n this.leaving.delete(key);\n return entry.inst;\n },\n beginLeave: (inst) => {\n if (!this.browser) return false;\n const rt = this.resolved(inst.graphNode);\n if (rt === undefined) return false;\n const el = inst.domNode;\n if (!this.dom.isElement(el)) return false;\n const key = this.keyOf(inst);\n // If a prior leave for this key is somehow still running, settle it.\n const prior = this.leaving.get(key);\n if (prior !== undefined) prior.run.cancel();\n const run = startRun(\n this.dom,\n el,\n rt.leaveActive,\n rt.leaveFrom,\n rt.leaveTo,\n rt.duration,\n () => {\n // Only finalize if THIS run is still the registered one (it may have\n // been reclaimed by a re-entering key, which cancels without done).\n const current = this.leaving.get(key);\n if (current !== undefined && current.run === run) {\n this.leaving.delete(key);\n this.finalize(inst);\n }\n },\n );\n this.leaving.set(key, { inst, run });\n return true;\n },\n onEnter: (inst) => this.enter(inst),\n };\n }\n}\n","/**\n * Document head / metadata runtime (2.0 §1–§3).\n *\n * Two entry points, sharing the normalized {@link HeadEntry} model the DSL's\n * `head()` produces (mirrored here as a local structural type so the renderer\n * takes no compile-time dependency on the DSL package — the same convention as\n * the overlay/component descriptors):\n *\n * • `wireHeadBehavior(ctx, node, instance)` — BROWSER. Reads the\n * `__head__<id>` descriptor, registers this node's contribution with a\n * per-render {@link HeadManager} (created lazily on `ctx`), subscribes to any\n * reactive attr/text signals, and tracks cleanup on the NodeInstance so the\n * contribution is withdrawn (and the manager re-applies the merged result)\n * when the node unmounts or the route changes. Server-safe: when\n * `dom.head()` is null (SSR) it is a no-op.\n *\n * • `renderHead(compiled)` — SERVER. Walks the compiled graph in document\n * order, merges every live `head()` contribution (last-in-document-order\n * wins per dedup key — §3), and serializes the effective tags to an HTML\n * string for the caller to place inside `<head>`. Only the active graph is\n * walked, so only active-route metadata is emitted (§2). Each tag carries\n * `data-streetui-head` + `data-streetui-head-key=\"…\"` so the browser adopts\n * it on hydration instead of creating a duplicate.\n */\n\nimport type { GraphNode, ApplicationGraph } from '@streetui/graph';\nimport { ServerDOMAdapter } from '@streetui/dom';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport type { DOMAdapter } from '@streetui/dom';\nimport type { RenderContext } from './render-context.js';\nimport type { NodeInstance } from './node-instance.js';\n\n/** The marker attribute stamped on every framework-managed head tag. */\nconst HEAD_MARKER = 'data-streetui-head';\n/** The attribute carrying a tag's dedup key, so hydration can match server tags. */\nconst HEAD_KEY = 'data-streetui-head-key';\n\n// ── Structural mirror of the DSL's head entry model ─────────────────────────────\n\ninterface HeadEntryLike {\n readonly tag: 'title' | 'meta' | 'link' | 'base';\n readonly dedupKey: string;\n readonly attrs: Readonly<Record<string, unknown>>;\n readonly text?: unknown;\n}\ninterface HeadContributionLike {\n readonly entries: readonly HeadEntryLike[];\n}\n\ninterface SignalLike {\n subscribe: (fn: (v: unknown) => void) => () => void;\n peek: () => unknown;\n}\n\nfunction isSignalLike(v: unknown): v is SignalLike {\n return (\n v !== null &&\n typeof v === 'object' &&\n typeof (v as Record<string, unknown>)['subscribe'] === 'function' &&\n typeof (v as Record<string, unknown>)['peek'] === 'function'\n );\n}\n\n/** Read a bindable value to its current string (peeking a signal, else stringifying). */\nfunction readValue(v: unknown): string {\n if (isSignalLike(v)) return String(v.peek() ?? '');\n return String(v ?? '');\n}\n\n/** A fully-resolved head tag: concrete strings, ready to write to the DOM/serialize. */\ninterface ResolvedTag {\n readonly tag: 'title' | 'meta' | 'link' | 'base';\n readonly attrs: Record<string, string>;\n readonly text?: string;\n}\n\nfunction resolveEntry(entry: HeadEntryLike): ResolvedTag {\n const attrs: Record<string, string> = {};\n for (const key of Object.keys(entry.attrs)) {\n attrs[key] = readValue(entry.attrs[key]);\n }\n const resolved: ResolvedTag = { tag: entry.tag, attrs };\n if (entry.tag === 'title') {\n return { ...resolved, text: readValue(entry.text) };\n }\n return resolved;\n}\n\n// ── Browser head manager ────────────────────────────────────────────────────────\n\ninterface AppliedRecord {\n el: Element;\n attrKeys: Set<string>;\n tag: string;\n}\n\n/**\n * Coordinates every live `head()` node's contribution into a single\n * `document.head`. One instance per render (lazily created on `ctx`). Merges by\n * dedup key with last-in-document-order winning, and applies the minimal diff to\n * the DOM on every register/unregister/signal change. Adopts server-emitted tags\n * on the first apply so hydration produces no duplicates.\n */\nexport class HeadManager {\n private readonly _dom: DOMAdapter;\n private readonly _head: Element;\n private readonly _contributions = new Map<string, { order: number; entries: readonly HeadEntryLike[] }>();\n private readonly _applied = new Map<string, AppliedRecord>();\n private _order = 0;\n private _adopted = false;\n\n constructor(dom: DOMAdapter, head: Element) {\n this._dom = dom;\n this._head = head;\n }\n\n /** Register (or replace) a node's contribution and re-apply the merged result. */\n register(nodeId: string, entries: readonly HeadEntryLike[]): void {\n this._contributions.set(nodeId, { order: this._order++, entries });\n this.apply();\n }\n\n /** Withdraw a node's contribution (unmount / route change) and re-apply. */\n unregister(nodeId: string): void {\n if (this._contributions.delete(nodeId)) this.apply();\n }\n\n /** Recompute the merged head and patch `document.head` to match. */\n apply(): void {\n if (!this._adopted) {\n this._adoptServerTags();\n this._adopted = true;\n }\n\n // Merge: iterate contributions in document order; per dedup key the last\n // writer wins (§3). Within a contribution, later entries win too.\n const ordered = [...this._contributions.values()].sort((a, b) => a.order - b.order);\n const merged = new Map<string, ResolvedTag>();\n for (const contribution of ordered) {\n for (const entry of contribution.entries) {\n merged.set(entry.dedupKey, resolveEntry(entry));\n }\n }\n\n // Upsert desired tags.\n for (const [key, desired] of merged) {\n const existing = this._applied.get(key);\n if (existing !== undefined && existing.tag === desired.tag) {\n this._reconcileAttrs(existing, desired);\n } else {\n if (existing !== undefined) {\n // Tag kind changed for this key (rare) — drop the old element.\n this._dom.removeChild(this._head, existing.el);\n this._applied.delete(key);\n }\n const el = this._createTag(key, desired);\n this._dom.appendChild(this._head, el);\n this._applied.set(key, { el, attrKeys: new Set(Object.keys(desired.attrs)), tag: desired.tag });\n }\n }\n\n // Remove managed tags no longer desired.\n for (const [key, record] of [...this._applied]) {\n if (!merged.has(key)) {\n this._dom.removeChild(this._head, record.el);\n this._applied.delete(key);\n }\n }\n }\n\n private _createTag(key: string, desired: ResolvedTag): Element {\n const el = this._dom.createElement(desired.tag);\n this._dom.setAttribute(el, HEAD_MARKER, '');\n this._dom.setAttribute(el, HEAD_KEY, key);\n for (const attr of Object.keys(desired.attrs)) {\n this._dom.setAttribute(el, attr, desired.attrs[attr]!);\n }\n if (desired.tag === 'title') this._dom.setTextContent(el, desired.text ?? '');\n return el;\n }\n\n private _reconcileAttrs(record: AppliedRecord, desired: ResolvedTag): void {\n const nextKeys = new Set(Object.keys(desired.attrs));\n // Remove attrs that are no longer present.\n for (const attr of record.attrKeys) {\n if (!nextKeys.has(attr)) this._dom.removeAttribute(record.el, attr);\n }\n // Set/overwrite desired attrs (idempotent when unchanged — matters on the\n // hydration adopt path, where the element is a server tag being re-asserted).\n for (const attr of nextKeys) {\n this._dom.setAttribute(record.el, attr, desired.attrs[attr]!);\n }\n if (desired.tag === 'title') this._dom.setTextContent(record.el, desired.text ?? '');\n record.attrKeys = nextKeys;\n }\n\n /**\n * Seed `_applied` from server-emitted `[data-streetui-head-key]` tags already\n * in `document.head`. The subsequent diff reuses these elements when the\n * client desires the same key (no duplicate), rewrites them if the value\n * changed, or removes them if the client graph no longer wants them.\n */\n private _adoptServerTags(): void {\n for (const child of this._dom.childNodes(this._head)) {\n if (!this._dom.isElement(child)) continue;\n const el = child as Element;\n const key = this._dom.getAttribute(el, HEAD_KEY);\n if (key === null) continue;\n this._applied.set(key, {\n el,\n attrKeys: new Set(this._attrNames(el)),\n tag: this._dom.tagName(el),\n });\n }\n }\n\n /** The framework-managed attribute names currently on a server tag. */\n private _attrNames(el: Element): string[] {\n // We cannot enumerate a live element's attributes through the minimal\n // DOMAdapter surface, so we re-assert from the desired set on first apply\n // (see `_reconcileAttrs`, which sets desired keys and removes only tracked\n // ones). Tracking the marker keys is enough to keep them from lingering.\n const names: string[] = [];\n if (this._dom.getAttribute(el, HEAD_MARKER) !== null) names.push(HEAD_MARKER);\n if (this._dom.getAttribute(el, HEAD_KEY) !== null) names.push(HEAD_KEY);\n return names;\n }\n}\n\n/** Lazily get (or create) the render's HeadManager. Null on the server. */\nfunction getHeadManager(ctx: RenderContext): HeadManager | null {\n const head = ctx.dom.head();\n if (head === null) return null; // server render pass — renderHead handles SSR\n const mutable = ctx as { head?: HeadManager };\n if (mutable.head === undefined) mutable.head = new HeadManager(ctx.dom, head);\n return mutable.head;\n}\n\n/**\n * Wire a mounted/hydrated `head` node's contribution into `document.head`.\n * Server-safe (no-op when there is no document). Shared by the mount and hydrate\n * paths so both establish identical ownership + cleanup.\n */\nexport function wireHeadBehavior(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n): void {\n const manager = getHeadManager(ctx);\n if (manager === null) return;\n\n const descFn = ctx.graph.getHandler(`__head__${graphNode.id}`) as\n | (() => HeadContributionLike)\n | undefined;\n if (descFn === undefined) return;\n\n const contribution = descFn();\n const nodeId = graphNode.id;\n manager.register(nodeId, contribution.entries);\n\n // Subscribe to any reactive attr/text signals; a change re-applies the merged\n // head. All subscriptions + the contribution withdrawal are tracked on the\n // instance, so a route change / unmount tears them down and re-applies.\n for (const entry of contribution.entries) {\n for (const attrKey of Object.keys(entry.attrs)) {\n const v = entry.attrs[attrKey];\n if (isSignalLike(v)) {\n instance.trackCleanup(v.subscribe(() => manager.apply()));\n }\n }\n if (isSignalLike(entry.text)) {\n instance.trackCleanup(entry.text.subscribe(() => manager.apply()));\n }\n }\n\n instance.trackCleanup(() => manager.unregister(nodeId));\n}\n\n// ── Server-side head emission ─────────────────────────────────────────────────\n\n/**\n * Render the active graph's merged document metadata to an HTML string suitable\n * for placing inside `<head>`. Walks the graph in document order, merges every\n * `head()` contribution (last-in-document-order wins per dedup key), and\n * serializes each effective tag with the `data-streetui-head` marker so the\n * browser adopts it on hydration. Returns `''` when the app declares no metadata\n * — so apps that never call `head()` emit nothing extra and existing SSR output\n * is unchanged.\n */\nexport function renderHead(compiled: CompiledApplication): string {\n const graph: ApplicationGraph = compiled.graph;\n\n const merged = new Map<string, ResolvedTag>();\n graph.walk((node) => {\n if (node.type !== 'head') return;\n const descFn = graph.getHandler(`__head__${node.id}`) as\n | (() => HeadContributionLike)\n | undefined;\n if (descFn === undefined) return;\n for (const entry of descFn().entries) {\n merged.set(entry.dedupKey, resolveEntry(entry));\n }\n });\n\n if (merged.size === 0) return '';\n\n const dom = new ServerDOMAdapter();\n let out = '';\n for (const [key, desired] of merged) {\n const el = dom.createElement(desired.tag);\n dom.setAttribute(el, HEAD_MARKER, '');\n dom.setAttribute(el, HEAD_KEY, key);\n for (const attr of Object.keys(desired.attrs)) {\n dom.setAttribute(el, attr, desired.attrs[attr]!);\n }\n if (desired.tag === 'title') dom.setTextContent(el, desired.text ?? '');\n out += dom.serializeOuter(el);\n }\n return out;\n}\n","/**\n * Initial mount — creates DOM nodes for every GraphNode and\n * attaches them into the container.\n *\n * This is a recursive depth-first walk. For each GraphNode:\n * 1. Create the DOM element (or text node)\n * 2. Apply props/attributes\n * 3. Wire events\n * 4. Wire signal subscriptions for reactive props\n * 5. Recurse into children\n * 6. Insert into the DOM\n */\n\nimport type { GraphNode, ApplicationGraph } from '@streetui/graph';\nimport type { DOMAdapter } from '@streetui/dom';\nimport {\n focusInitial,\n trapFocus,\n containFocus,\n onEscape,\n rovingMenu,\n saveFocus,\n restoreFocus,\n} from '@streetui/dom';\nimport type { RenderContext } from './render-context.js';\nimport { NodeInstance } from './node-instance.js';\nimport { applyProp } from './attributes.js';\nimport { wireEvents } from './events.js';\nimport { resolveTag } from './tag-map.js';\nimport {\n reconcileChildren,\n reconcileChildrenByPlan,\n type PlanEntry,\n} from './reconciliation.js';\nimport { TransitionController, type TransitionHooks } from './transition.js';\nimport { wireHeadBehavior } from './head.js';\n\n/**\n * Prop keys handled by the per-type mount branches (or reserved internals), so\n * `applyNodeProps` must skip them to avoid double-applying. This set is\n * invariant across nodes, so it is hoisted to module scope: allocating it once\n * (rather than per node) removes N Set allocations per mount/SSR pass and the\n * GC pressure they create. Treat as read-only — never mutate.\n */\nconst SKIP_PROP_KEYS: ReadonlySet<string> = new Set([\n 'text', 'label', 'level', 'inputType', 'src', 'alt', 'href', 'external',\n 'value', 'placeholder', 'disabled', '_renderKey', 'key', 'name',\n]);\n\nexport function mountGraph(ctx: RenderContext): NodeInstance {\n return mountNode(ctx, ctx.graph.root, ctx.container);\n}\n\nexport function mountNode(\n ctx: RenderContext,\n graphNode: GraphNode,\n parentDom: Node,\n): NodeInstance {\n const { dom, graph } = ctx;\n\n // ── v1.7 static SSR fast path (SSR-only) ──────────────────────────────────\n // When a compiler-derived static SSR plan is present (server render only)\n // and this node is a maximal static-subtree root, emit its precomputed HTML\n // verbatim instead of recursively constructing ServerElement/ServerText/\n // NodeInstance for the whole subtree. `ctx.staticHTML` is always undefined on\n // the browser path, so this is a single short-circuiting check there — the\n // client hot path and its semantics are untouched (§5/§6/§23). The stored\n // string is produced by this same mount+serialize pipeline, so output is\n // byte-identical (§8). We still register ONE NodeInstance for the root so the\n // parent's children bookkeeping and post-render dispose behave normally.\n const staticHTML = ctx.staticHTML;\n if (staticHTML !== undefined && dom.createRawHTML !== undefined) {\n const precomputed = staticHTML.get(graphNode.id);\n if (precomputed !== undefined) {\n const raw = dom.createRawHTML(precomputed);\n dom.appendChild(parentDom, raw);\n const instance = new NodeInstance(graphNode, raw);\n ctx.instances.set(graphNode.id, instance);\n return instance;\n }\n }\n\n // The application root node maps to the container itself — don't create a duplicate element\n if (graphNode.type === 'application') {\n const instance = new NodeInstance(graphNode, parentDom);\n ctx.instances.set(graphNode.id, instance);\n for (const child of graphNode.children) {\n const childInstance = mountNode(ctx, child, parentDom);\n instance.addChild(childInstance);\n }\n return instance;\n }\n\n // Text-only nodes render as a <span> containing a text node\n if (graphNode.type === 'text') {\n const text = String(graphNode.getProp('text') ?? '');\n const el = dom.createElement('span');\n const textNode = dom.createTextNode(text);\n dom.appendChild(el, textNode);\n applyNodeProps(ctx, graphNode, el);\n\n // Create the live instance up front and reuse it for event wiring. The\n // previous code allocated a throwaway NodeInstance solely to satisfy\n // wireEvents' signature, wasting one NodeInstance (+ its children array and\n // CleanupRegistry) per text node — pure GC pressure on the hottest mount\n // path. wireEvents/wireSignalBindings each early-return on empty arrays.\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n // Reactive text binding — only build the update closure when the node has\n // bindings. wireSignalBindings early-returns on empty stateRefs, so for a\n // static text node (the common case in a large initial render) the\n // textUpdate closure would be allocated and thrown away: avoidable GC\n // pressure on the hottest mount path.\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, textUpdate(dom, el, textNode));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Heading nodes\n if (graphNode.type === 'heading') {\n const level = (graphNode.getProp('level') as number | undefined) ?? 1;\n const tag = `h${level}` as string;\n const el = dom.createElement(tag);\n const text = String(graphNode.getProp('text') ?? '');\n dom.setTextContent(el, text);\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, headingUpdate(dom, el));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Input nodes\n if (graphNode.type === 'input') {\n const el = dom.createElement('input') as HTMLInputElement;\n const inputType = String(graphNode.getProp('inputType') ?? 'text');\n dom.setAttribute(el, 'type', inputType);\n const placeholder = graphNode.getProp('placeholder');\n if (placeholder !== undefined) dom.setAttribute(el, 'placeholder', String(placeholder));\n const value = graphNode.getProp('value');\n if (value !== undefined) dom.setProperty(el, 'value', String(value));\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, inputUpdate(dom, el));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Image nodes\n if (graphNode.type === 'image') {\n const el = dom.createElement('img') as HTMLImageElement;\n const src = graphNode.getProp('src');\n const alt = graphNode.getProp('alt');\n if (src !== undefined) dom.setAttribute(el, 'src', String(src));\n if (alt !== undefined) dom.setAttribute(el, 'alt', String(alt));\n const width = graphNode.getProp('width');\n const height = graphNode.getProp('height');\n if (width !== undefined) dom.setAttribute(el, 'width', String(width));\n if (height !== undefined) dom.setAttribute(el, 'height', String(height));\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Link nodes\n if (graphNode.type === 'link') {\n const el = dom.createElement('a') as HTMLAnchorElement;\n const href = graphNode.getProp('href');\n const label = graphNode.getProp('label');\n const external = graphNode.getProp('external');\n if (href !== undefined) dom.setAttribute(el, 'href', String(href));\n if (label !== undefined) dom.setTextContent(el, String(label));\n if (external === true) {\n dom.setAttribute(el, 'target', '_blank');\n dom.setAttribute(el, 'rel', 'noopener noreferrer');\n }\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n // A link's label/href may be bound to signals (e.g. i18n `t()` in nav). Wire\n // the same signal-binding path buttons use so the text updates reactively.\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, linkUpdate(dom, el));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Button nodes\n if (graphNode.type === 'button') {\n const el = dom.createElement('button') as HTMLButtonElement;\n const label = graphNode.getProp('label');\n if (label !== undefined) dom.setTextContent(el, String(label));\n const disabled = graphNode.getProp('disabled');\n if (disabled === true) dom.setAttribute(el, 'disabled', '');\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, el, instance);\n\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, buttonUpdate(dom, el));\n }\n\n dom.appendChild(parentDom, el);\n return instance;\n }\n\n // Reactive list / conditional — a container whose children are driven by a\n // Signal. Initial child subtrees are already built into the graph by the DSL;\n // on signal change we reconcile the freshly-built desired children against the\n // live DOM using the keyed reconciler (no virtual DOM). A `conditional` uses\n // the identical machinery but renders as a neutral <div> holding 0..1 branch.\n if (graphNode.type === 'reactive-list' || graphNode.type === 'conditional') {\n const tag = resolveTag(graphNode.type);\n const el = dom.createElement(tag);\n applyNodeProps(ctx, graphNode, el);\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n\n for (const child of graphNode.children) {\n const childInstance = mountNode(ctx, child, el);\n instance.addChild(childInstance);\n }\n\n dom.appendChild(parentDom, el);\n wireReactiveList(ctx, graphNode, instance, el, true);\n return instance;\n }\n\n // Portal — a container whose children are relocated to a different DOM\n // location (document.body) on the browser, while a neutral inline anchor\n // stays at the declaration site. On the server there is no body, so the\n // children render inline in the anchor (deterministic HTML; hydration then\n // relocates them). This is the substrate for overlays (dialog/popover/…):\n // `wireOverlayBehavior` reads an optional `__overlay__<id>` descriptor and,\n // when present, wires focus trap/restore/containment/escape to the open\n // signal. A plain portal has no descriptor, so overlay wiring is a no-op.\n if (graphNode.type === 'portal') {\n const anchor = dom.createElement(resolveTag('portal'));\n dom.setAttribute(anchor, 'data-streetui-portal', '');\n applyNodeProps(ctx, graphNode, anchor);\n const instance = new NodeInstance(graphNode, anchor);\n ctx.instances.set(graphNode.id, instance);\n\n const body = dom.body();\n let target: Element = anchor; // SSR / no body → render inline in the anchor\n if (body !== null) {\n const portalContainer = dom.createElement('div');\n dom.setAttribute(portalContainer, 'data-streetui-portal-container', '');\n dom.appendChild(body, portalContainer);\n instance.trackCleanup(() => dom.removeChild(body, portalContainer));\n target = portalContainer;\n }\n\n for (const child of graphNode.children) {\n instance.addChild(mountNode(ctx, child, target));\n }\n\n dom.appendChild(parentDom, anchor);\n wireOverlayBehavior(ctx, graphNode, instance, target);\n return instance;\n }\n\n // Head — a metadata node (title/meta/link/base). Renders as a neutral inline\n // anchor at the declaration site (like a portal), while its contribution is\n // applied to `document.head` by `wireHeadBehavior` (browser) or emitted by\n // `renderHead` (server). No visible children; the anchor keeps hydration\n // structurally aligned with the SSR output.\n if (graphNode.type === 'head') {\n const anchor = dom.createElement(resolveTag('head'));\n dom.setAttribute(anchor, 'data-streetui-head-anchor', '');\n applyNodeProps(ctx, graphNode, anchor);\n const instance = new NodeInstance(graphNode, anchor);\n ctx.instances.set(graphNode.id, instance);\n\n dom.appendChild(parentDom, anchor);\n wireHeadBehavior(ctx, graphNode, instance);\n return instance;\n }\n\n // Container / section / page / form / list / list-item — structural nodes\n const tag = resolveTag(graphNode.type);\n const el = dom.createElement(tag);\n applyNodeProps(ctx, graphNode, el);\n\n // Surface a reactive-list item's stable, identity-only reconciliation key as a\n // public `data-streetui-key` attribute (e.g. \"id:1\"). This exposes only the\n // identity part — never the internal `_sig` value signature, signal ids or\n // graph node ids — so a row is directly selectable and its identity is\n // inspectable across reorders and in-place data updates.\n if (graphNode.type === 'list-item') {\n const itemKey = graphNode.getProp('key');\n if (itemKey !== undefined) {\n dom.setAttribute(el, 'data-streetui-key', String(itemKey));\n }\n }\n\n const instance = new NodeInstance(graphNode, el);\n ctx.instances.set(graphNode.id, instance);\n\n // wire form submit (reuse the live instance rather than a throwaway)\n if (graphNode.type === 'form') {\n wireEvents(dom, graph, graphNode, el, instance);\n }\n\n // Recurse into children\n for (const child of graphNode.children) {\n const childInstance = mountNode(ctx, child, el);\n instance.addChild(childInstance);\n }\n\n dom.appendChild(parentDom, el);\n if (graphNode.type === 'component') wireComponentBehavior(ctx, graphNode, instance);\n return instance;\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\n/**\n * Per-node-type reactive-binding factories. Each returns the `onUpdate`\n * callback that `wireSignalBindings` invokes when a bound signal changes.\n * Extracted so both the browser mount path and the hydration path apply the\n * exact same DOM mutation semantics for each prop — no duplicated rendering\n * logic.\n */\nexport function textUpdate(\n dom: DOMAdapter,\n el: Element,\n textNode: Text,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'text') {\n dom.setTextContent(textNode, String(value ?? ''));\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function headingUpdate(\n dom: DOMAdapter,\n el: Element,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'text') {\n dom.setTextContent(el, String(value ?? ''));\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function inputUpdate(\n dom: DOMAdapter,\n el: Element,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'value') {\n dom.setProperty(el, 'value', String(value ?? ''));\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function buttonUpdate(\n dom: DOMAdapter,\n el: Element,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'label') {\n dom.setTextContent(el, String(value ?? ''));\n } else if (propKey === 'disabled') {\n if (value === true) {\n dom.setAttribute(el, 'disabled', '');\n } else {\n dom.removeAttribute(el, 'disabled');\n }\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function linkUpdate(\n dom: DOMAdapter,\n el: Element,\n): (propKey: string, value: unknown) => void {\n return (propKey, value) => {\n if (propKey === 'label') {\n dom.setTextContent(el, String(value ?? ''));\n } else if (propKey === 'href') {\n dom.setAttribute(el, 'href', String(value ?? ''));\n } else {\n applyProp(dom, el, propKey, value);\n }\n };\n}\n\nexport function applyNodeProps(ctx: RenderContext, graphNode: GraphNode, el: Element): void {\n // Iterate own enumerable keys directly rather than via Object.entries, which\n // allocates a wrapper array plus one [key,value] tuple per prop — measurable\n // GC pressure when multiplied across every node in a large initial render.\n const props = graphNode.props;\n for (const key in props) {\n if (!Object.hasOwn(props, key)) continue;\n if (SKIP_PROP_KEYS.has(key)) continue;\n applyProp(ctx.dom, el, key, props[key]);\n }\n}\n\nexport function wireSignalBindings(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n onUpdate: (propKey: string, value: unknown) => void,\n): void {\n // Fast exit for the common non-reactive node — avoids allocating a for-of\n // iterator over an empty stateRefs array on every static node.\n if (graphNode.stateRefs.length === 0) return;\n for (const stateRef of graphNode.stateRefs) {\n const signalKey = `__signal__${stateRef.signalId}`;\n const maybeSig = ctx.graph.getHandler(signalKey) as\n | { subscribe: (fn: (v: unknown) => void) => () => void; peek: () => unknown }\n | undefined;\n if (maybeSig === undefined || typeof maybeSig.subscribe !== 'function') continue;\n\n // Subscribe directly — avoids the ReadonlySignal<T> generic variance issue\n const unsub = maybeSig.subscribe((value) => {\n onUpdate(stateRef.propKey, value);\n });\n instance.trackCleanup(unsub);\n }\n}\n\n// ── Reactive list wiring ────────────────────────────────────────────────────────\n\ntype ListBuildFn = (items: unknown) => GraphNode[];\ntype ListPlanFn = (items: unknown) => PlanEntry[];\n\n/**\n * Subscribe a reactive-list instance to its driving signal. On each change the\n * DSL-registered plan factory produces lightweight per-row descriptors, which\n * are reconciled against the live DOM with the keyed, minimal-move reconciler\n * (spec §15). A `conditional` node has no plan handler and falls back to the\n * eager build factory (it only ever renders 0..1 branch, so eager is fine).\n */\nexport function wireReactiveList(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n el: Element,\n runAppear = false,\n): void {\n const plan = ctx.graph.getHandler(`__listplan__${graphNode.id}`) as\n | ListPlanFn\n | undefined;\n const build = ctx.graph.getHandler(`__listbuild__${graphNode.id}`) as\n | ListBuildFn\n | undefined;\n if (plan === undefined && build === undefined) return;\n\n // One transition controller per reactive container, created here so its\n // leaving-instance map survives across every reconcile of this container\n // (that persistence is what makes leave→enter reclaim and keyed list-leave\n // correct — §6/§7). `finalize` runs the full deferred teardown chain when a\n // leave animation completes: DOM-remove + dispose + forget + detach, exactly\n // the work the synchronous path splits between the reconciler and the two\n // reconcile* helpers below. On the server (no body) the controller's hooks\n // no-op, so SSR is unchanged (§21).\n const controller = new TransitionController(ctx.dom, ctx.graph, (leaving) => {\n // Full teardown at leave-animation end — the same four steps the synchronous\n // path splits between the reconciler (DOM-remove + dispose) and this helper\n // (forget + detach). Deferred here because `beginLeave` excluded this\n // instance from `result.removed`, so nothing else will tear it down.\n const parent = ctx.dom.parentNode(leaving.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, leaving.domNode);\n leaving.dispose();\n forgetInstance(ctx, leaving);\n ctx.graph.detachNode(leaving.graphNode);\n });\n const hooks = controller.hooks();\n\n // `appear`: animate any initial child that opted in — but ONLY on a fresh\n // browser mount, never on hydration (§22: the DOM is already present and\n // correct, so appear must not run). The hydrate path calls this with\n // `runAppear` omitted (false).\n if (runAppear) controller.appear(instance.children);\n\n for (const stateRef of graphNode.stateRefs) {\n if (stateRef.propKey !== 'items') continue;\n const sig = ctx.graph.getHandler(`__signal__${stateRef.signalId}`) as\n | { subscribe: (fn: (v: unknown) => void) => () => void }\n | undefined;\n if (sig === undefined || typeof sig.subscribe !== 'function') continue;\n\n const unsub = sig.subscribe((value) => {\n if (plan !== undefined) {\n reconcileReactiveListByPlan(ctx, graphNode, instance, el, plan(value), hooks);\n } else {\n reconcileReactiveList(ctx, graphNode, instance, el, build!(value), hooks);\n }\n });\n instance.trackCleanup(unsub);\n }\n}\n\nfunction reconcileReactiveListByPlan(\n ctx: RenderContext,\n listNode: GraphNode,\n listInstance: NodeInstance,\n listEl: Element,\n plan: PlanEntry[],\n hooks: TransitionHooks,\n): void {\n const oldInstances = [...listInstance.children];\n const result = reconcileChildrenByPlan(\n ctx,\n listEl,\n oldInstances,\n plan,\n (node, parent) => mountNode(ctx, node, parent),\n hooks,\n );\n\n // Sync the live instance's children to the reconciled order.\n listInstance.children.length = 0;\n for (const inst of result.instances) listInstance.children.push(inst);\n\n // Forget removed instances, and drop their graph nodes.\n for (const removed of result.removed) {\n forgetInstance(ctx, removed);\n ctx.graph.detachNode(removed.graphNode);\n }\n // Detach any freshly-built subtree that was not adopted as a live instance\n // (e.g. the top node of a rebuilt changed row, whose live instance keeps its\n // original graph node).\n const adopted = new Set(result.instances.map((i) => i.graphNode));\n for (const node of result.built ?? []) {\n if (!adopted.has(node)) ctx.graph.detachNode(node);\n }\n\n // Keep the graph model consistent: list node children match the new order.\n for (const child of [...listNode.children]) listNode.removeChild(child);\n for (const inst of result.instances) listNode.appendChild(inst.graphNode);\n}\n\nfunction reconcileReactiveList(\n ctx: RenderContext,\n listNode: GraphNode,\n listInstance: NodeInstance,\n listEl: Element,\n newNodes: GraphNode[],\n hooks: TransitionHooks,\n): void {\n const oldInstances = [...listInstance.children];\n const result = reconcileChildren(\n ctx,\n listEl,\n oldInstances,\n newNodes,\n (node, parent) => mountNode(ctx, node, parent),\n hooks,\n );\n\n // Sync the live instance's children to the reconciled order.\n listInstance.children.length = 0;\n for (const inst of result.instances) listInstance.children.push(inst);\n\n // Forget removed instances from the renderer index, and drop their graph\n // nodes (and any un-adopted freshly-built duplicates) from the graph index.\n for (const removed of result.removed) {\n forgetInstance(ctx, removed);\n ctx.graph.detachNode(removed.graphNode);\n }\n const adopted = new Set(result.instances.map((i) => i.graphNode));\n for (const built of newNodes) {\n if (!adopted.has(built)) ctx.graph.detachNode(built);\n }\n\n // Keep the graph model consistent: list node children match the new order.\n for (const child of [...listNode.children]) listNode.removeChild(child);\n for (const inst of result.instances) listNode.appendChild(inst.graphNode);\n}\n\n/** Recursively remove an instance subtree from the renderer's instance index. */\nfunction forgetInstance(ctx: RenderContext, instance: NodeInstance): void {\n ctx.instances.delete(instance.graphNode.id);\n for (const child of instance.children) forgetInstance(ctx, child);\n}\n\n// ── Overlay behavior wiring ─────────────────────────────────────────────────────\n\n/**\n * Opaque overlay descriptor, read from the `__overlay__<portalId>` handler that\n * the DSL registers for dialog/popover/tooltip/dropdown/toast. Declared here as\n * a local structural type (mirroring the list plan/build handler pattern) so the\n * renderer never takes a compile-time dependency on the DSL package.\n */\ninterface OverlayBehavior {\n /** Reactive open/visibility state — the same signal that drives the panel's `when()`. */\n readonly open: {\n subscribe: (fn: (v: boolean) => void) => () => void;\n peek: () => unknown;\n };\n /** Trap Tab focus within, and redirect escaped focus back inside (modal semantics). */\n readonly modal: boolean;\n /** Move focus into the panel when it opens. */\n readonly takesFocus: boolean;\n /** Wire arrow/Home/End/Enter/Space roving-focus navigation (role=\"menu\"). */\n readonly menu: boolean;\n /** Escape key invokes `onClose`. */\n readonly closeOnEscape: boolean;\n /** Restore focus to the pre-open element on close. */\n readonly restoreFocus: boolean;\n /** id of the element to focus first when opening. */\n readonly initialFocusId?: string;\n /** Requested-close callback (Escape). The app flips its own open signal here. */\n readonly onClose?: () => void;\n}\n\n/**\n * Attach overlay focus/keyboard behavior to a mounted portal. Server-safe: on\n * the server `dom.body()` is null so this returns immediately (SSR emits inert\n * markup, no focus concept). A plain portal has no `__overlay__` descriptor, so\n * this also returns immediately — the behavior is purely additive.\n *\n * The panel is mounted/unmounted by the portal's inner `when(open, …)`, whose\n * signal subscription is registered *before* this one (the conditional child is\n * mounted earlier in the portal branch). Signal subscribers fire synchronously\n * in subscription order, so on open→true the panel DOM exists before we move\n * focus into it, and on open→false the panel is torn down before we restore\n * focus. All listeners are tracked on the instance and torn down on unmount.\n */\nexport function wireOverlayBehavior(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n target: Element,\n): void {\n const { dom, graph } = ctx;\n if (dom.body() === null) return; // server / no DOM environment\n\n const descFn = graph.getHandler(`__overlay__${graphNode.id}`) as\n | (() => OverlayBehavior)\n | undefined;\n if (descFn === undefined) return; // plain portal — no overlay behavior\n\n const desc = descFn();\n const openSig = desc.open;\n if (openSig === undefined || typeof openSig.subscribe !== 'function') return;\n\n let active: Array<() => void> = [];\n let saved: Element | null = null;\n\n const teardown = (): void => {\n for (const fn of active) fn();\n active = [];\n };\n\n const onOpenChange = (isOpen: boolean): void => {\n if (isOpen) {\n if (desc.restoreFocus) saved = saveFocus(dom);\n // Establish containment/roving BEFORE moving focus in, so that when a\n // nested modal opens it becomes the authoritative focus owner before its\n // initial focus fires — otherwise the outer modal's still-active\n // containment would pull that focus back out (§16).\n if (desc.modal) {\n active.push(trapFocus(dom, target));\n active.push(containFocus(dom, target));\n }\n if (desc.menu) {\n active.push(rovingMenu(dom, target));\n }\n if (desc.takesFocus) focusInitial(dom, target, desc.initialFocusId);\n if (desc.closeOnEscape && desc.onClose !== undefined) {\n active.push(onEscape(dom, target, desc.onClose));\n }\n } else {\n teardown();\n if (desc.restoreFocus && saved !== null) {\n restoreFocus(dom, saved);\n saved = null;\n }\n }\n };\n\n const unsub = openSig.subscribe(onOpenChange);\n instance.trackCleanup(unsub);\n instance.trackCleanup(teardown);\n\n // `subscribe` fires only on change; an overlay that is open on initial mount\n // has its panel already built into the graph, so run the open path now.\n if (openSig.peek() === true) onOpenChange(true);\n}\n\n/**\n * Wire a component instance's lifecycle (§9). Reads the optional\n * `__component__<id>` descriptor — an array of teardown callbacks the DSL's\n * `component()` collected from the setup's `ctx.effect`/`ctx.onCleanup` — and\n * routes each into `NodeInstance.trackCleanup`, so they run (children-first)\n * when the component leaves the graph. Shared by the mount and hydrate paths so\n * both attach identical ownership. A `'component'` node with no cleanups (no\n * effects/resources) registers no descriptor and this is a no-op.\n */\nexport function wireComponentBehavior(\n ctx: RenderContext,\n graphNode: GraphNode,\n instance: NodeInstance,\n): void {\n const fn = ctx.graph.getHandler(`__component__${graphNode.id}`) as\n | (() => Array<() => void>)\n | undefined;\n if (fn === undefined) return;\n for (const cleanup of fn()) instance.trackCleanup(cleanup);\n}\n","/**\n * SSR state transfer (dehydration) — move server-resolved data to the client.\n *\n * When the server resolves resources before rendering, their data must reach\n * the client so hydration can seed them (via `resource({ initialData })`)\n * instead of refetching. StreetUI does this with a single, framework-scoped\n * `<script>` payload rather than blindly interpolating `JSON.stringify` into\n * markup.\n *\n * Safety (v0.4 rule #16): the JSON is emitted into a\n * `<script type=\"application/json\">` block — an inert data island the browser\n * never executes — and every character that could terminate that block or be\n * reinterpreted by the HTML/JS parser is escaped to its `\\uXXXX` form. Because\n * `<` inside JSON parses back to `<`, the payload round-trips exactly\n * while being impossible to break out of. This is deterministic (stable key\n * order is the caller's responsibility) and typed at the boundary as\n * `Record<string, unknown>` — never `any`.\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\n\n/** Attribute marking StreetUI's state island so the client can find it. */\nexport const STATE_MARKER_ATTR = 'data-streetui-state';\n\n/**\n * Escape a JSON string for safe embedding inside a `<script>` element:\n * < > & → HTML / `</script>` breakout and entity ambiguity\n * U+2028 / U+2029 → invalid raw in JS string literals\n * Uses code-point checks so no raw separator characters live in this source.\n */\nfunction escapeForScript(json: string): string {\n let out = '';\n for (const ch of json) {\n const code = ch.charCodeAt(0);\n if (ch === '<') out += '\\\\u003c';\n else if (ch === '>') out += '\\\\u003e';\n else if (ch === '&') out += '\\\\u0026';\n else if (code === 0x2028) out += '\\\\u2028';\n else if (code === 0x2029) out += '\\\\u2029';\n else out += ch;\n }\n return out;\n}\n\n/**\n * Serialize a state map to an HTML `<script>` island for inclusion in the\n * server-rendered document (typically just before the closing tag of the\n * mount container). Returns an empty string for an empty map.\n */\nexport function serializeState(state: Record<string, unknown>): string {\n if (Object.keys(state).length === 0) return '';\n const json = escapeForScript(JSON.stringify(state));\n return `<script type=\"application/json\" ${STATE_MARKER_ATTR}>${json}</script>`;\n}\n\n/**\n * Read the state island back on the client. Searches `root` for StreetUI's\n * state `<script>` and parses it. Returns an empty object when absent or\n * unparseable (hydration then proceeds as a cold client render). Routed through\n * the DOM adapter so it is testable and never assumes a global `document`.\n */\nexport function readState(\n dom: DOMAdapter,\n root: Element | Document,\n): Record<string, unknown> {\n const el = dom.querySelector(root, `script[${STATE_MARKER_ATTR}]`);\n if (el === null) return {};\n const text = dom.getTextContent(el);\n if (text === null || text.length === 0) return {};\n try {\n const parsed: unknown = JSON.parse(text);\n if (parsed !== null && typeof parsed === 'object') {\n return parsed as Record<string, unknown>;\n }\n return {};\n } catch {\n return {};\n }\n}\n","/**\n * Static graph analysis (v1.2, spec §3/§12/§14).\n *\n * A single post-order walk over the Semantic Application Graph that classifies\n * every node as static (no bound signals, no events, not a reactive\n * region) or dynamic, and rolls that up into whole-static-subtree flags. This\n * is COMPILE-TIME metadata only — it introduces no virtual DOM, no second tree\n * and no runtime reactive system. It is consumed by:\n * - the hydration path, to skip per-node attribute/text re-verification on\n * provably-static subtrees (§12), and\n * - the diagnostic compiler-inspection report (§14).\n *\n * The renderer's initial-mount fast path does not need this map: it already\n * skips reactive wiring per node via cheap `events.length`/`stateRefs.length`\n * guards. Keeping the analysis out of the mount hot path avoids adding lookup\n * cost (and keeps the shipped runtime lean).\n */\n\nimport type { NodeId } from '@streetui/core';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\n\n/** Prop keys whose bound signal drives text content rather than an attribute. */\nconst TEXT_PROP_KEYS: ReadonlySet<string> = new Set(['text', 'label', 'value']);\n\nexport interface NodeAnalysis {\n /** No bound signals, no events, and not a reactive-list/conditional region. */\n readonly isStatic: boolean;\n /** This node is static AND every descendant is a static subtree. */\n readonly isStaticSubtree: boolean;\n /** A signal is bound to this node's text/label/value content. */\n readonly hasDynamicText: boolean;\n /** A signal is bound to a non-content prop (a reactive attribute). */\n readonly hasDynamicAttr: boolean;\n /** This node wires one or more DOM event handlers. */\n readonly hasEvents: boolean;\n /** This node is a keyed reactive list. */\n readonly isList: boolean;\n /** This node is a conditional (0..1 branch) region. */\n readonly isConditional: boolean;\n}\n\nexport interface GraphAnalysisSummary {\n readonly totalNodes: number;\n readonly staticNodes: number;\n readonly staticSubtrees: number;\n readonly dynamicTextNodes: number;\n readonly dynamicAttrNodes: number;\n readonly eventNodes: number;\n readonly lists: number;\n readonly conditionals: number;\n}\n\nexport interface GraphAnalysis {\n readonly nodes: ReadonlyMap<NodeId, NodeAnalysis>;\n readonly summary: GraphAnalysisSummary;\n}\n\n/**\n * Analyze a fully-built graph. O(n) single post-order pass; allocates one small\n * record per node. Safe to skip entirely when neither hydration nor diagnostics\n * need it.\n */\nexport function analyzeGraph(graph: ApplicationGraph): GraphAnalysis {\n const nodes = new Map<NodeId, NodeAnalysis>();\n const summary = {\n totalNodes: 0, staticNodes: 0, staticSubtrees: 0, dynamicTextNodes: 0,\n dynamicAttrNodes: 0, eventNodes: 0, lists: 0, conditionals: 0,\n };\n\n const visit = (node: GraphNode): boolean => {\n // Post-order: children first so subtree rollup is exact.\n let allChildrenStatic = true;\n for (const child of node.children) {\n const childSubtreeStatic = visit(child);\n if (!childSubtreeStatic) allChildrenStatic = false;\n }\n\n let hasDynamicText = false;\n let hasDynamicAttr = false;\n for (const ref of node.stateRefs) {\n if (TEXT_PROP_KEYS.has(ref.propKey)) hasDynamicText = true;\n else hasDynamicAttr = true;\n }\n const hasEvents = node.events.length > 0;\n const isList = node.type === 'reactive-list';\n const isConditional = node.type === 'conditional';\n // A portal relocates its children to a different DOM location (document.body)\n // at mount time, so its subtree is never a contiguous inline static blob.\n // Treating it as dynamic stops the static-subtree rollup at the portal, so\n // both SSR and hydration always take the real portal mount/hydrate branch\n // (which does the relocation) rather than emitting/adopting a raw HTML blob.\n const isPortal = node.type === 'portal';\n // A component owns per-instance lifecycle wiring (a `__component__<id>`\n // cleanup handler read at mount/hydrate). Treating it as dynamic stops the\n // static-subtree rollup at the component boundary so it always takes the\n // real mount/hydrate branch (which wires cleanups) instead of collapsing\n // into a serialized raw-HTML blob that would drop that per-instance wiring.\n const isComponent = node.type === 'component';\n // A `head` node contributes document metadata via a `__head__<id>` handler\n // wired at mount/hydrate (`wireHeadBehavior`). Treating it as dynamic stops\n // the static-subtree rollup at the head boundary so it always takes the real\n // mount/hydrate branch (which registers/cleans up the contribution) instead\n // of collapsing into a serialized raw-HTML blob that would drop that wiring.\n const isHead = node.type === 'head';\n const isStatic =\n node.stateRefs.length === 0 && !hasEvents && !isList && !isConditional && !isPortal && !isComponent && !isHead;\n const isStaticSubtree = isStatic && allChildrenStatic;\n\n nodes.set(node.id, {\n isStatic, isStaticSubtree, hasDynamicText, hasDynamicAttr,\n hasEvents, isList, isConditional,\n });\n\n summary.totalNodes += 1;\n if (isStatic) summary.staticNodes += 1;\n if (isStaticSubtree) summary.staticSubtrees += 1;\n if (hasDynamicText) summary.dynamicTextNodes += 1;\n if (hasDynamicAttr) summary.dynamicAttrNodes += 1;\n if (hasEvents) summary.eventNodes += 1;\n if (isList) summary.lists += 1;\n if (isConditional) summary.conditionals += 1;\n\n return isStaticSubtree;\n };\n\n visit(graph.root);\n return { nodes, summary };\n}\n","/**\n * Diagnostic compiler-inspection mode (v1.2, spec §14).\n *\n * Produces a machine-readable (and optionally text-formatted) description of\n * what the compiler understands about an application: which nodes are static\n * vs dynamic, which carry dynamic text or attributes, which wire events, and\n * which are conditional regions or keyed lists — plus the hydration metadata\n * derived from that classification.\n *\n * This is a DIAGNOSTIC tool. It is not part of the runtime, is not consulted\n * during mount, and is tree-shakeable out of any app that never calls it.\n */\n\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport { analyzeGraph, type GraphAnalysisSummary } from './analyze.js';\n\nexport interface InspectedCompilationNode {\n readonly id: string;\n readonly type: string;\n readonly depth: number;\n readonly classification: 'static' | 'static-subtree-root' | 'dynamic';\n readonly dynamicText: boolean;\n readonly dynamicAttrs: boolean;\n readonly events: readonly string[];\n readonly boundProps: readonly string[];\n readonly isList: boolean;\n readonly isConditional: boolean;\n /** Hydration hint: how the hydration path should treat this node. */\n readonly hydration: 'adopt-static' | 'verify-dynamic';\n}\n\nexport interface CompilerInspection {\n readonly name: string;\n readonly version: string;\n readonly summary: GraphAnalysisSummary & {\n /** Fraction of nodes provably static (0..1). */\n readonly staticRatio: number;\n };\n readonly nodes: readonly InspectedCompilationNode[];\n}\n\n/**\n * Inspect a compiled/built graph and return a structured diagnostic report.\n * Purely observational — never mutates the graph.\n */\nexport function inspectCompilation(graph: ApplicationGraph): CompilerInspection {\n const analysis = analyzeGraph(graph);\n const nodes: InspectedCompilationNode[] = [];\n\n const walk = (node: GraphNode, depth: number): void => {\n const a = analysis.nodes.get(node.id);\n if (a !== undefined) {\n const classification: InspectedCompilationNode['classification'] = a.isStaticSubtree\n ? 'static-subtree-root'\n : a.isStatic\n ? 'static'\n : 'dynamic';\n nodes.push({\n id: node.id,\n type: node.type,\n depth,\n classification,\n dynamicText: a.hasDynamicText,\n dynamicAttrs: a.hasDynamicAttr,\n events: node.events.map((e) => e.type),\n boundProps: node.stateRefs.map((r) => r.propKey),\n isList: a.isList,\n isConditional: a.isConditional,\n hydration: a.isStaticSubtree ? 'adopt-static' : 'verify-dynamic',\n });\n }\n for (const child of node.children) walk(child, depth + 1);\n };\n walk(graph.root, 0);\n\n const staticRatio =\n analysis.summary.totalNodes === 0\n ? 0\n : analysis.summary.staticNodes / analysis.summary.totalNodes;\n\n return {\n name: graph.name,\n version: graph.version,\n summary: { ...analysis.summary, staticRatio: +staticRatio.toFixed(4) },\n nodes,\n };\n}\n\n/** Render an inspection as a compact human-readable text report. */\nexport function formatInspection(inspection: CompilerInspection): string {\n const s = inspection.summary;\n const lines: string[] = [];\n lines.push(`StreetUI compiler inspection — ${inspection.name} v${inspection.version}`);\n lines.push(\n ` nodes=${s.totalNodes} static=${s.staticNodes} ` +\n `staticSubtrees=${s.staticSubtrees} dynamicText=${s.dynamicTextNodes} ` +\n `dynamicAttrs=${s.dynamicAttrNodes} events=${s.eventNodes} ` +\n `lists=${s.lists} conditionals=${s.conditionals} ` +\n `staticRatio=${(s.staticRatio * 100).toFixed(1)}%`,\n );\n for (const n of inspection.nodes) {\n const flags: string[] = [];\n if (n.dynamicText) flags.push('text');\n if (n.dynamicAttrs) flags.push('attr:' + n.boundProps.join(','));\n if (n.events.length > 0) flags.push('on:' + n.events.join(','));\n if (n.isList) flags.push('list');\n if (n.isConditional) flags.push('cond');\n lines.push(\n ` ${' '.repeat(n.depth)}${n.type}#${n.id} [${n.classification}]` +\n (flags.length > 0 ? ` {${flags.join(' ')}}` : ''),\n );\n }\n return lines.join('\\n');\n}\n","/**\n * Static SSR Plan (v1.7, spec §4/§6) — internal.\n *\n * A compiler-derived plan that precomputes the verbatim HTML of every *maximal\n * static subtree* in an application graph. During SSR, the renderer emits that\n * precomputed string directly (via `ServerDOMAdapter.createRawHTML`) instead of\n * recursively constructing a `ServerElement`/`ServerText`/`NodeInstance` for\n * every node in the subtree. On the 10k-row `/users` corpus, ~100% of the node\n * mass lives in 10,000 static 8-node row subtrees, so collapsing each row into\n * one precomputed string removes the bulk of the mount-phase construction work.\n *\n * Design constraints honoured here:\n * - §3 REUSE the existing compiler analysis (`analyzeGraph`) to classify nodes;\n * no new/expensive analysis, and nothing runs during normal `compile()`.\n * - §5/§15 Only *maximal static-subtree roots* are collapsed. A dynamic region\n * (reactive-list container, conditional, dynamic-text/attr node) is never\n * treated as static — the list itself stays dynamic; only the provably-static\n * subtree *inside* each repeated item is precomputed.\n * - §8 The precomputed HTML is produced by the SAME mount + serialize pipeline\n * as the runtime path, so full-render output is byte-identical.\n * - §19 The plan retains ONLY strings keyed by GraphNode.id. No ServerDOM node,\n * NodeInstance or application object is retained (the throwaway build tree is\n * disposed + cleared). The per-app cache is a WeakMap, so a plan is released\n * when its CompiledApplication is collected.\n * - §24 Everything here is internal: not re-exported from the `streetui` or\n * `streetui/server` runtime barrels.\n *\n * This module is only ever imported by the SSR entry (`renderToString`), which\n * is itself reachable solely through the server path, so it tree-shakes out of\n * client bundles (§20, verified by bundle measurement).\n */\n\nimport type { NodeId } from '@streetui/core';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport { analyzeGraph } from '@streetui/compiler/diagnostics';\nimport { ServerDOMAdapter } from '@streetui/dom';\nimport { createRenderContext } from './render-context.js';\nimport { mountNode } from './mount.js';\n\n/**\n * Internal representation of the static SSR plan: maximal static-subtree root\n * GraphNode.id → its precomputed, verbatim outer HTML. A plain `Map<string,\n * string>` is deliberate — it holds no DOM/application references (§19).\n */\nexport type StaticSSRPlan = ReadonlyMap<NodeId, string>;\n\n/**\n * Collect the ids of every *maximal* static-subtree root under `graph`.\n *\n * Walk from the root; when a node is itself a whole static subtree, it is a\n * maximal root — record it and stop (its static descendants are subsumed).\n * Otherwise descend into its children, so a dynamic node's individually-static\n * children are still captured (the mixed-tree case, §5). The `application` root\n * is never recorded: it maps onto the render container rather than emitting its\n * own element, so we always descend past it into its real top-level children.\n */\nfunction collectMaximalStaticRoots(graph: ApplicationGraph): GraphNode[] {\n const analysis = analyzeGraph(graph);\n const roots: GraphNode[] = [];\n\n const walk = (node: GraphNode): void => {\n if (node.type !== 'application') {\n const a = analysis.nodes.get(node.id);\n if (a !== undefined && a.isStaticSubtree) {\n roots.push(node);\n return;\n }\n }\n for (const child of node.children) walk(child);\n };\n\n walk(graph.root);\n return roots;\n}\n\n/**\n * Serialize the outer HTML of a single static subtree using the exact runtime\n * mount + serialize pipeline (so the bytes match a full render). The throwaway\n * tree is disposed immediately, so nothing is retained.\n */\nfunction serializeStaticSubtree(\n dom: ServerDOMAdapter,\n graph: ApplicationGraph,\n root: GraphNode,\n): string {\n const container = dom.createElement('div');\n // No `staticHTML` on this ctx → mountNode builds the subtree fully.\n const ctx = createRenderContext(dom, graph, container);\n const instance = mountNode(ctx, root, container);\n const html = dom.serializeInner(container);\n // Tear down (static subtrees open no subscriptions, but keep symmetry with\n // renderToString's lifecycle) and drop all references.\n instance.dispose();\n ctx.instances.clear();\n return html;\n}\n\n/**\n * Build the static SSR plan for a compiled application. O(n) analysis + one\n * mount/serialize per maximal static subtree. Returns an empty map when the app\n * has no static subtrees (e.g. a highly-dynamic page) — the SSR path then\n * behaves exactly as v1.6.\n */\nexport function buildStaticSSRPlan(compiled: CompiledApplication): StaticSSRPlan {\n const graph = compiled.graph;\n const roots = collectMaximalStaticRoots(graph);\n const plan = new Map<NodeId, string>();\n if (roots.length === 0) return plan;\n\n const dom = new ServerDOMAdapter();\n for (const root of roots) {\n plan.set(root.id, serializeStaticSubtree(dom, graph, root));\n }\n return plan;\n}\n\n/**\n * Per-application plan cache. A WeakMap keyed by the CompiledApplication so a\n * plan is built once and reused across renders, and is released together with\n * the compiled app it belongs to — no long-lived retention of app state (§19).\n */\nconst PLAN_CACHE = new WeakMap<CompiledApplication, StaticSSRPlan>();\n\n/** Get the cached static SSR plan for a compiled app, building it on first use. */\nexport function getStaticSSRPlan(compiled: CompiledApplication): StaticSSRPlan {\n let plan = PLAN_CACHE.get(compiled);\n if (plan === undefined) {\n plan = buildStaticSSRPlan(compiled);\n PLAN_CACHE.set(compiled, plan);\n }\n return plan;\n}\n","/**\n * Server-side rendering — `renderToString`.\n *\n * Runs the *exact same* mount pipeline used in the browser (`mountGraph`), but\n * against a `ServerDOMAdapter` that builds a lightweight in-memory node tree\n * instead of a real browser DOM. The tree is then serialized to a normal HTML\n * string. Because both browser and server share the DSL → Compiler → Graph →\n * Runtime → Renderer pipeline, there is no second, SSR-specific renderer and no\n * virtual DOM.\n *\n * Lifecycle (v0.4 rule #20): the initial synchronous mount may open signal\n * subscriptions (via `wireSignalBindings`/`wireReactiveList`). On the server\n * those would be live forever, so once the HTML is serialized we dispose the\n * root instance — tearing down every subscription and listener. SSR therefore\n * has a *render* lifecycle only; the live *runtime* lifecycle is established\n * later on the client by `hydrate`.\n */\n\nimport { ServerDOMAdapter } from '@streetui/dom';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport { createRenderContext } from './render-context.js';\nimport { mountGraph } from './mount.js';\nimport { getStaticSSRPlan } from './static-ssr-plan.js';\n\nexport interface RenderToStringOptions {\n /**\n * Override the server DOM adapter (rarely needed). Defaults to a fresh\n * `ServerDOMAdapter` per call so concurrent renders never share state.\n */\n readonly domAdapter?: ServerDOMAdapter;\n /**\n * @internal — testing/benchmark knob for the v1.7 static SSR plan.\n *\n * `undefined` (default): use the per-app cached plan (build once, reuse).\n * `null`: disable the plan entirely — the exact v1.6 runtime mount path, used\n * by the byte-identity gate and A/B benchmark as the \"legacy\" baseline.\n * a map: use this explicit plan.\n *\n * Not part of the supported public API; output is byte-identical regardless\n * of this value (§8).\n */\n readonly staticPlan?: ReadonlyMap<string, string> | null;\n}\n\n/**\n * Render a compiled StreetUI application to an HTML string.\n *\n * The returned markup contains only the application's own elements (the\n * synthetic container is not emitted), so callers embed it wherever they mount\n * on the client — e.g. inside `<div id=\"app\">…</div>`.\n */\nexport function renderToString(\n compiled: CompiledApplication,\n options: RenderToStringOptions = {},\n): string {\n const dom = options.domAdapter ?? new ServerDOMAdapter();\n\n // Resolve the v1.7 static SSR plan: cached-by-default, `null` forces the v1.6\n // path, an explicit map is used as-is. Only maximal static-subtree roots are\n // collapsed; dynamic regions still mount through the runtime path (§5).\n const plan =\n options.staticPlan === null\n ? undefined\n : (options.staticPlan ?? getStaticSSRPlan(compiled));\n const staticHTML = plan !== undefined && plan.size > 0 ? plan : undefined;\n\n // Synthetic container — the application root maps onto it, and the app's\n // top-level nodes are appended directly into it (mirroring browser mount).\n const container = dom.createElement('div');\n\n const ctx = createRenderContext(dom, compiled.graph, container, undefined, staticHTML);\n const rootInstance = mountGraph(ctx);\n\n const html = dom.serializeInner(container);\n\n // Tear down any subscriptions/listeners opened during mount — the server has\n // no live runtime. (rule #20)\n rootInstance.dispose();\n ctx.instances.clear();\n\n return html;\n}\n","/**\n * The single authoritative StreetUI framework version.\n *\n * This constant is the one source of truth for the version of the shipped\n * `streetui` package. It is kept in lock-step with this package's\n * `package.json` `version` field and with the bundled CLI's reported version\n * (`streetui --version`) — the consolidated test-suite pins all three to the\n * same coordinated release so they can never silently drift apart.\n */\nexport const VERSION = '2.3.0';\n"],"mappings":";AA8CO,SAAS,oBACd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