streetui 1.2.0 → 1.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/{compile-DsNJm9IJ.d.cts → compile-CTA4MLX6.d.cts} +1 -1
- package/dist/{compile-DsNJm9IJ.d.ts → compile-CTA4MLX6.d.ts} +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-OFIDPD15.d.cts → hydration-diagnostics-Cu2ZRxL1.d.cts} +1 -1
- package/dist/{hydration-diagnostics-BN1S-fbq.d.ts → hydration-diagnostics-DqkNk4EU.d.ts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{server-BYXgNCQK.d.cts → server-BeFSjxkL.d.cts} +1 -1
- package/dist/{server-BYdG0sP_.d.ts → server-CtHBgrxf.d.ts} +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/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/version.ts","../../state/src/signal.ts","../../state/src/store.ts","../../state/src/resource.ts","../../core/src/a11y-ids.ts","../../core/src/identity.ts","../../core/src/lifecycle.ts","../../core/src/environment.ts","../../core/src/diagnostics.ts","../../core/src/application.ts","../../core/src/node.ts","../../core/src/observability.ts","../../graph/src/graph-node.ts","../../graph/src/graph.ts","../../dsl/src/builders.ts","../../dsl/src/dsl.ts","../../compiler/src/validation/validator.ts","../../compiler/src/transform/transform.ts","../../compiler/src/compile.ts","../../runtime/src/node-instance.ts","../../scheduler/src/scheduler.ts","../../runtime/src/runtime.ts","../../events/src/event-types.ts","../../events/src/event-bus.ts","../../events/src/dom-bridge.ts","../../dom/src/browser-adapter.ts","../../dom/src/server-node.ts","../../dom/src/server-adapter.ts","../../dom/src/focus.ts","../../renderer/src/render-context.ts","../../renderer/src/node-instance.ts","../../renderer/src/attributes.ts","../../renderer/src/events.ts","../../renderer/src/tag-map.ts","../../renderer/src/patch.ts","../../renderer/src/reconciliation.ts","../../renderer/src/mount.ts","../../renderer/src/hydration-diagnostics.ts","../../renderer/src/hydrate.ts","../../renderer/src/render-handle.ts","../../renderer/src/renderer.ts","../../renderer/src/dehydrate.ts","../../renderer/src/ssr.ts","../../router/src/matching.ts","../../router/src/history.ts","../../router/src/router.ts","../../router/src/mount-router.ts","../../forms/src/validators.ts","../../forms/src/form.ts","../../context/src/context.ts","../../i18n/src/i18n.ts","../../devtools/src/inspector.ts","../../devtools/src/application.ts","../../devtools/src/diagnostics.ts","../../devtools/src/inspect-reactive.ts","../../devtools/src/panels.ts","../src/config.ts"],"sourcesContent":["/**\n * # StreetUI\n *\n * The complete StreetUI framework, exposed as a single import surface.\n *\n * ```ts\n * import { signal, streetui, compile, createRuntime, createRenderer } from 'streetui';\n * ```\n *\n * StreetUI is internally modular — reactivity, the semantic DSL, the compiler,\n * the semantic application graph, the runtime, the DOM renderer, the router,\n * async resources, forms, context, i18n, devtools and the CLI each live in their\n * own internal module — but a framework user installs and imports only\n * `streetui`. Server-only helpers are also available from `streetui/server`, and\n * the testing utilities from `streetui/testing`.\n *\n * This entry re-exports the **already-implemented, stable public API** of each\n * subsystem. It does not introduce any new API: StreetUI's UI layer is a\n * semantic *builder* DSL (`streetui.app(...)`, `page.section(s => s.button(...))`),\n * not a set of free element functions.\n */\n\n// ── Framework version (single authoritative source; see ./version.ts) ────────\nexport { VERSION } from './version.js';\n\n// ── Reactivity: signals, derived state, effects, batching, stores, resources ─\n// signal, derived, computed, effect, batch, resource, store, …\nexport * from '@streetui/state';\n\n// ── Core: application identity, lifecycle, diagnostics, environment, a11yIds ──\nexport * from '@streetui/core';\n\n// ── Semantic application graph ────────────────────────────────────────────────\nexport * from '@streetui/graph';\n\n// ── Semantic UI DSL: streetui.app(...), builders, DSL types ───────────────────\nexport * from '@streetui/dsl';\n\n// ── Compiler: compile(app) → compiled application ─────────────────────────────\nexport * from '@streetui/compiler';\n\n// ── Runtime: createRuntime, mount, lifecycle wiring ───────────────────────────\nexport * from '@streetui/runtime';\n\n// ── Events: event bus + DOM event bridge ──────────────────────────────────────\nexport * from '@streetui/events';\n\n// ── Scheduler: batched microtask scheduler ────────────────────────────────────\nexport * from '@streetui/scheduler';\n\n// ── DOM adapters: BrowserDOMAdapter, ServerDOMAdapter ─────────────────────────\nexport * from '@streetui/dom';\n\n// ── Renderer: createRenderer, mount/patch/reconcile, SSR (renderToString,\n// serializeState, readState) and hydrate ──────────────────────────────────\nexport * from '@streetui/renderer';\n\n// ── Router: createRouter, navigation, route lifecycle, active links ───────────\nexport * from '@streetui/router';\n\n// ── Forms: createForm + validators (required, email, minLength, …) ────────────\nexport * from '@streetui/forms';\n\n// ── Context: createContext, provide/consume (no prop drilling) ────────────────\nexport * from '@streetui/context';\n\n// ── Internationalization: createI18n (reactive, typed) ────────────────────────\nexport * from '@streetui/i18n';\n\n// ── DevTools foundations: createDevTools + reactive inspectors ────────────────\nexport * from '@streetui/devtools';\n\n// ── Project configuration (used by streetui.config.ts) ────────────────────────\n// Re-exported from a tiny local module (see ./config.ts) so application imports\n// of `streetui` don't pull the CLI's build machinery (esbuild) into the client\n// runtime bundle. The config *type* is still single-sourced from the CLI.\nexport { defineConfig } from './config.js';\nexport type { StreetUIConfig, ResolvedConfig } from './config.js';\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 = '1.2.0';\n","/**\n * StreetUI reactive signals — framework-owned reactivity, no external libraries.\n *\n * Architecture:\n * Signal<T> — writable, holds a value, notifies on change\n * DerivedSignal<T> — read-only, lazily computed from other signals\n * effect() — side-effect that re-runs when dependencies change\n * batch() — run multiple updates before notifying\n */\n\nexport type Subscriber<T> = (value: T) => void;\nexport type Unsubscribe = () => void;\n\n// ── Tracking ──────────────────────────────────────────────────────────────────\n\n/**\n * Any reactive source that can have downstream consumers attached.\n * Both Signal and DerivedSignal implement this.\n */\nexport interface ReactiveSource<T> {\n get(): T;\n peek(): T;\n subscribe(fn: Subscriber<T>): Unsubscribe;\n /** Internal: remove a downstream consumer. */\n _removeConsumer(consumer: ReactiveConsumer): void;\n}\n\n/**\n * A downstream consumer (DerivedSignal or Effect) that can be invalidated\n * and can register itself as depending on a source.\n */\nexport interface ReactiveConsumer {\n _invalidate(): void;\n /** Internal: called by a source to register a dependency. */\n _addSource(src: ReactiveSource<unknown>): void;\n}\n\n/** The active consumer being tracked during a computation. */\nlet _activeConsumer: ReactiveConsumer | null = null;\n\nfunction withConsumer<T>(consumer: ReactiveConsumer, fn: () => T): T {\n const prev = _activeConsumer;\n _activeConsumer = consumer;\n try {\n return fn();\n } finally {\n _activeConsumer = prev;\n }\n}\n\n// ── Batch state (must be before Signal class so .set() can reference it) ──────\n\n/** Depth counter — batches nest; only the outermost flush propagates. */\nlet _batchDepth = 0;\n\ninterface PendingFlush {\n signal: Signal<unknown>;\n value: unknown;\n}\n\n/**\n * Keyed by signal identity — last-write-wins for each signal within a batch.\n * An ordered Map preserves first-seen insertion order for stable flush sequence.\n */\nconst _pendingFlushes = new Map<Signal<unknown>, PendingFlush>();\n\nfunction _enqueueBatchFlush(sig: Signal<unknown>, value: unknown): void {\n _pendingFlushes.set(sig, { signal: sig, value });\n}\n\nfunction _drainBatch(): void {\n const flushes = [..._pendingFlushes.values()];\n _pendingFlushes.clear();\n for (const { signal: sig, value } of flushes) {\n sig._flushBatch(value);\n }\n}\n\n// ── Signal ────────────────────────────────────────────────────────────────────\n\nexport interface ReadonlySignal<T> {\n get(): T;\n peek(): T;\n subscribe(fn: Subscriber<T>): Unsubscribe;\n}\n\nexport class Signal<T> implements ReactiveSource<T>, ReadonlySignal<T> {\n protected _value: T;\n private readonly _subscribers: Set<Subscriber<T>> = new Set();\n private readonly _consumers: Set<ReactiveConsumer> = new Set();\n\n constructor(initial: T) {\n this._value = initial;\n }\n\n get(): T {\n if (_activeConsumer !== null) {\n this._consumers.add(_activeConsumer);\n _activeConsumer._addSource(this as ReactiveSource<unknown>);\n }\n return this._value;\n }\n\n peek(): T {\n return this._value;\n }\n\n set(value: T): void {\n if (Object.is(this._value, value)) return;\n this._value = value;\n if (_batchDepth > 0) {\n // Defer notification until the batch flushes.\n // The stored value is always the latest (last-write-wins for same signal).\n _enqueueBatchFlush(this as unknown as Signal<unknown>, value);\n } else {\n this._flush(value);\n }\n }\n\n update(fn: (current: T) => T): void {\n this.set(fn(this._value));\n }\n\n subscribe(fn: Subscriber<T>): Unsubscribe {\n this._subscribers.add(fn);\n return () => { this._subscribers.delete(fn); };\n }\n\n _removeConsumer(consumer: ReactiveConsumer): void {\n this._consumers.delete(consumer);\n }\n\n /**\n * Called by the batch machinery after the batch has completed.\n * Notifies subscribers with the final coalesced value.\n */\n _flushBatch(value: unknown): void {\n this._flush(value as T);\n }\n\n private _flush(value: T): void {\n for (const sub of [...this._subscribers]) sub(value);\n for (const consumer of [...this._consumers]) consumer._invalidate();\n }\n\n /**\n * @internal DevTools inspection only. The number of live observers\n * (direct subscribers plus derived/effect consumers). Read-only; never\n * mutates reactive state.\n */\n _observerCount(): number {\n return this._subscribers.size + this._consumers.size;\n }\n}\n\n// ── DerivedSignal ─────────────────────────────────────────────────────────────\n\nexport class DerivedSignal<T> implements ReactiveSource<T>, ReactiveConsumer, ReadonlySignal<T> {\n private _value: T | undefined = undefined;\n private _dirty = true;\n private _disposed = false;\n private readonly _fn: () => T;\n private readonly _subscribers: Set<Subscriber<T>> = new Set();\n /** All upstream sources this derived currently reads from. */\n private readonly _sources: Set<ReactiveSource<unknown>> = new Set();\n /** Downstream consumers that depend on this derived. */\n private readonly _consumers: Set<ReactiveConsumer> = new Set();\n\n constructor(fn: () => T) {\n this._fn = fn;\n }\n\n get(): T {\n // Register this derived with the outer consumer if any\n if (_activeConsumer !== null) {\n this._consumers.add(_activeConsumer);\n _activeConsumer._addSource(this as ReactiveSource<unknown>);\n }\n if (this._dirty) this._recompute();\n return this._value as T;\n }\n\n peek(): T {\n if (this._dirty) this._recompute();\n return this._value as T;\n }\n\n subscribe(fn: Subscriber<T>): Unsubscribe {\n // Eagerly compute so sources track this derived as a consumer\n if (this._dirty) this._recompute();\n this._subscribers.add(fn);\n return () => { this._subscribers.delete(fn); };\n }\n\n _addSource(src: ReactiveSource<unknown>): void {\n this._sources.add(src);\n }\n\n _removeConsumer(consumer: ReactiveConsumer): void {\n this._consumers.delete(consumer);\n }\n\n _invalidate(): void {\n if (this._disposed) return;\n this._dirty = true;\n const newVal = this.peek(); // recompute\n for (const sub of [...this._subscribers]) sub(newVal);\n for (const consumer of [...this._consumers]) consumer._invalidate();\n }\n\n private _recompute(): void {\n // Detach from all current sources before re-tracking\n for (const src of this._sources) src._removeConsumer(this);\n this._sources.clear();\n\n this._value = withConsumer(this, this._fn);\n this._dirty = false;\n }\n\n dispose(): void {\n this._disposed = true;\n for (const src of this._sources) src._removeConsumer(this);\n this._sources.clear();\n this._subscribers.clear();\n this._consumers.clear();\n }\n\n /**\n * @internal DevTools inspection only. Live observers (subscribers plus\n * downstream consumers). Read-only.\n */\n _observerCount(): number {\n return this._subscribers.size + this._consumers.size;\n }\n}\n\n// ── effect ────────────────────────────────────────────────────────────────────\n\nclass Effect implements ReactiveConsumer {\n private readonly _fn: () => void | (() => void);\n private _cleanup: (() => void) | undefined = undefined;\n private _disposed = false;\n private readonly _sources: Set<ReactiveSource<unknown>> = new Set();\n\n constructor(fn: () => void | (() => void)) {\n this._fn = fn;\n this._run();\n }\n\n _addSource(src: ReactiveSource<unknown>): void {\n this._sources.add(src);\n }\n\n _invalidate(): void {\n if (this._disposed) return;\n this._run();\n }\n\n private _run(): void {\n // Detach from all current sources before re-tracking\n for (const src of this._sources) src._removeConsumer(this);\n this._sources.clear();\n\n if (typeof this._cleanup === 'function') this._cleanup();\n const result = withConsumer(this, this._fn);\n this._cleanup = typeof result === 'function' ? result : undefined;\n }\n\n dispose(): void {\n this._disposed = true;\n for (const src of this._sources) src._removeConsumer(this);\n this._sources.clear();\n if (typeof this._cleanup === 'function') this._cleanup();\n this._cleanup = undefined;\n }\n}\n\n// ── Public API ─────────────────────────────────────────────────────────────────\n\nexport function signal<T>(initial: T): Signal<T> {\n return new Signal(initial);\n}\n\nexport function derived<T>(fn: () => T): DerivedSignal<T> {\n return new DerivedSignal(fn);\n}\n\nexport function effect(fn: () => void | (() => void)): Unsubscribe {\n const e = new Effect(fn);\n return () => e.dispose();\n}\n\n/**\n * Run multiple signal updates as an atomic batch.\n *\n * Within the callback, calls to signal.set() are deferred — each signal\n * accumulates its latest value. When the outermost batch() returns,\n * each modified signal fires its subscribers exactly once with the final\n * value. Nested batch() calls are supported; the flush only runs when the\n * outermost batch exits.\n *\n * Example:\n * batch(() => {\n * count.set(1);\n * count.set(2);\n * count.set(3);\n * });\n * // subscribers see count = 3 exactly once\n */\nexport function batch(fn: () => void): void {\n _batchDepth++;\n try {\n fn();\n } finally {\n _batchDepth--;\n if (_batchDepth === 0) {\n _drainBatch();\n }\n }\n}\n\n/** True when inside a batch() call. Useful for advanced scheduling integration. */\nexport function isBatching(): boolean {\n return _batchDepth > 0;\n}\n\n// ── Inspection (read-only, DevTools-facing) ─────────────────────────────────\n\n/** Whether a signal is writable (`signal()`) or computed (`derived()`). */\nexport type SignalKind = 'writable' | 'derived';\n\n/** Classify a reactive value as writable or derived. */\nexport function signalKind(source: ReadonlySignal<unknown>): SignalKind {\n return source instanceof DerivedSignal ? 'derived' : 'writable';\n}\n\n/**\n * The number of live observers on a signal — direct subscribers plus derived\n * or effect consumers — or `undefined` if the source does not expose the count.\n * Read-only; safe for DevTools. Never mutates reactive state.\n */\nexport function observerCount(source: ReadonlySignal<unknown>): number | undefined {\n const maybe = source as { _observerCount?: () => number };\n return typeof maybe._observerCount === 'function' ? maybe._observerCount() : undefined;\n}\n","/**\n * A simple reactive store built on top of signals.\n * Useful for structured state with multiple fields.\n */\n\nimport { Signal, signal, type Subscriber, type Unsubscribe } from './signal.js';\n\nexport type StoreState = Record<string, unknown>;\n\nexport class Store<T extends StoreState> {\n private readonly _signals: Record<string, Signal<unknown>>;\n\n constructor(initial: T) {\n const signals: Record<string, Signal<unknown>> = {};\n for (const key in initial) {\n if (Object.prototype.hasOwnProperty.call(initial, key)) {\n signals[key] = signal(initial[key] as unknown);\n }\n }\n this._signals = signals;\n }\n\n get<K extends keyof T>(key: K): T[K] {\n const s = this._signals[key as string];\n if (s === undefined) {\n throw new Error(`Store: unknown key \"${String(key)}\"`);\n }\n return s.get() as T[K];\n }\n\n set<K extends keyof T>(key: K, value: T[K]): void {\n const s = this._signals[key as string];\n if (s === undefined) {\n throw new Error(`Store: unknown key \"${String(key)}\"`);\n }\n s.set(value as unknown);\n }\n\n signal<K extends keyof T>(key: K): Signal<T[K]> {\n const s = this._signals[key as string];\n if (s === undefined) {\n throw new Error(`Store: unknown key \"${String(key)}\"`);\n }\n return s as unknown as Signal<T[K]>;\n }\n\n subscribe<K extends keyof T>(key: K, fn: Subscriber<T[K]>): Unsubscribe {\n return this.signal(key).subscribe(fn);\n }\n\n getSnapshot(): T {\n const snap = {} as T;\n for (const key in this._signals) {\n if (Object.prototype.hasOwnProperty.call(this._signals, key)) {\n (snap as Record<string, unknown>)[key] = this._signals[key]?.peek();\n }\n }\n return snap;\n }\n}\n\nexport function createStore<T extends StoreState>(initial: T): Store<T> {\n return new Store(initial);\n}\n","/**\n * StreetUI async resources — framework-native asynchronous data.\n *\n * A `resource` wraps a Promise-returning loader and exposes its lifecycle as\n * ordinary StreetUI signals (status / data / error), so it composes with\n * `derived`, `effect`, `when()`, `listOf` and the renderer with no second\n * reactive system.\n *\n * State machine:\n *\n * idle ──(load)──▶ loading ──(resolve)──▶ success\n * │\n * └────(reject)──────▶ error\n *\n * Refetch keeps the previously-loaded `data` visible while `status` is\n * `'loading'` again (see `isRefetching`) — there is no separate `'refetching'`\n * status; it is expressed through `status === 'loading'` with `data` still set.\n *\n * The resource is transport-agnostic: the loader is any function returning a\n * value or a Promise. When it accepts the provided `AbortSignal`, in-flight\n * work is cancelled on `dispose()` or when a newer request supersedes it.\n */\n\nimport { signal, derived, batch, type ReadonlySignal, type Unsubscribe } from './signal.js';\n\nexport type ResourceStatus = 'idle' | 'loading' | 'success' | 'error';\n\n/** Context handed to the loader; carries an AbortSignal for cancellation. */\nexport interface ResourceLoaderContext {\n readonly signal: AbortSignal;\n}\n\n/** Any value-or-Promise producing function. Receives an abort-aware context. */\nexport type ResourceLoader<T> = (ctx: ResourceLoaderContext) => Promise<T> | T;\n\nexport interface ResourceOptions<T = unknown> {\n /** Load immediately on creation. Defaults to `true`. When `false`, stays `idle` until `refetch()`. */\n readonly immediate?: boolean;\n /**\n * Explicit reactive dependencies. When any listed signal changes, the\n * resource refetches. Dependencies are explicit (not auto-tracked from the\n * loader body) so there is no risk of an accidental infinite refetch loop.\n */\n readonly watch?: ReadonlyArray<ReadonlySignal<unknown>>;\n /**\n * Optional teardown registrar (e.g. a route's `ctx.onCleanup`). When given,\n * the resource registers its own `dispose` so it is cleaned up automatically\n * when its owner is removed.\n */\n readonly onCleanup?: (fn: () => void) => void;\n /**\n * Server-provided initial value for hydration. When present the resource\n * starts in `'success'` with this data already visible, and the initial\n * auto-load is skipped (so the client does not refetch data the server\n * already resolved). This is the client half of SSR resource transfer; the\n * server side awaits `refetch()` before serializing. Set `immediate: true`\n * explicitly to force a client refetch anyway.\n */\n readonly initialData?: T;\n /** Server-provided initial error for hydration (mirrors `initialData`). */\n readonly initialError?: unknown;\n /**\n * Explicit initial status override. Rarely needed — inferred as `'success'`\n * from `initialData` or `'error'` from `initialError`.\n */\n readonly initialStatus?: ResourceStatus;\n}\n\nexport interface Resource<T> {\n /** Reactive lifecycle status. */\n readonly status: ReadonlySignal<ResourceStatus>;\n /** The last successfully-loaded value, or `undefined` before first success. */\n readonly data: ReadonlySignal<T | undefined>;\n /** The most recent error, or `undefined` when there is none. Typed `unknown` — never `any`. */\n readonly error: ReadonlySignal<unknown>;\n /** Convenience: `status === 'loading'`. */\n readonly loading: ReadonlySignal<boolean>;\n /** Convenience: loading while previously-loaded data is still present (a refetch). */\n readonly isRefetching: ReadonlySignal<boolean>;\n /** Trigger a new request. Resolves when the request settles (or is superseded). */\n refetch(): Promise<void>;\n /** Cancel in-flight work, drop watchers, and ignore any late results. Idempotent. */\n dispose(): void;\n}\n\n/** True for an abort we initiated (so it is not surfaced as a real error). */\nfunction isAbortError(err: unknown): boolean {\n return (\n err instanceof Error && err.name === 'AbortError'\n ) || (\n typeof DOMException !== 'undefined' && err instanceof DOMException && err.name === 'AbortError'\n );\n}\n\nexport function resource<T>(loader: ResourceLoader<T>, options: ResourceOptions<T> = {}): Resource<T> {\n // Seed hydrated initial state (SSR transfer). `initialStatus` wins if given,\n // otherwise infer success/error from the provided value.\n const hasInitial =\n options.initialData !== undefined ||\n options.initialError !== undefined ||\n options.initialStatus !== undefined;\n\n const seededStatus: ResourceStatus =\n options.initialStatus ??\n (options.initialData !== undefined\n ? 'success'\n : options.initialError !== undefined\n ? 'error'\n : 'idle');\n\n const status = signal<ResourceStatus>(seededStatus);\n const data = signal<T | undefined>(options.initialData);\n const error = signal<unknown>(options.initialError);\n\n const loading = derived<boolean>(() => status.get() === 'loading');\n const isRefetching = derived<boolean>(() => status.get() === 'loading' && data.get() !== undefined);\n\n let disposed = false;\n /** Monotonic request id — only the newest request may write state (race guard). */\n let runId = 0;\n let controller: AbortController | null = null;\n\n const load = async (): Promise<void> => {\n if (disposed) return;\n\n // Supersede any in-flight request: abort it and bump the run id so its\n // eventual resolution is ignored.\n controller?.abort();\n const myRun = ++runId;\n const myController = new AbortController();\n controller = myController;\n\n // Enter loading. Preserve `data` (so a refetch keeps showing the old value)\n // and clear any previous error.\n batch(() => {\n error.set(undefined);\n status.set('loading');\n });\n\n try {\n const result = await loader({ signal: myController.signal });\n // Ignore stale or cancelled resolutions.\n if (disposed || myRun !== runId) return;\n batch(() => {\n data.set(result);\n error.set(undefined);\n status.set('success');\n });\n } catch (err) {\n if (disposed || myRun !== runId) return;\n // A self-initiated abort is not a user-visible error.\n if (isAbortError(err)) return;\n batch(() => {\n error.set(err);\n status.set('error');\n });\n }\n };\n\n const refetch = (): Promise<void> => load();\n\n // Explicit reactive dependencies: refetch when any watched signal changes.\n const watchUnsubs: Unsubscribe[] = [];\n if (options.watch !== undefined) {\n for (const dep of options.watch) {\n watchUnsubs.push(\n dep.subscribe(() => {\n if (!disposed) void load();\n }),\n );\n }\n }\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n controller?.abort();\n controller = null;\n for (const unsub of watchUnsubs) unsub();\n watchUnsubs.length = 0;\n };\n\n if (options.onCleanup !== undefined) {\n options.onCleanup(dispose);\n }\n\n // Auto-load on creation unless disabled. When hydrated initial state is\n // present we skip the initial load by default (the server already resolved\n // it); an explicit `immediate: true` still forces a refetch.\n if (options.immediate === true || (options.immediate !== false && !hasInitial)) {\n void load();\n }\n\n return {\n status,\n data,\n error,\n loading,\n isRefetching,\n refetch,\n dispose,\n };\n}\n","/**\n * Deterministic accessibility id helpers.\n *\n * Accessible markup often needs stable id relationships — a `<label for>` (or\n * `aria-labelledby`) pointing at an input, an `aria-describedby` pointing at a\n * hint/error, an `aria-labelledby` on a dialog pointing at its title. Those ids\n * must be IDENTICAL on the server and the client, otherwise a hydrated subtree\n * that re-renders (e.g. a toggled `when()` branch) would compute a different id\n * than the server emitted and break the association.\n *\n * These helpers derive ids purely from a caller-supplied stable base string\n * (typically a form field name or a dialog name). They use NO incrementing\n * counter and NO randomness, so `a11yIds('email')` yields the same ids in every\n * environment and on every call — which is exactly what SSR + hydration needs.\n */\n\nconst UNSAFE = /[^A-Za-z0-9_-]+/g;\n\n/** Normalise an arbitrary base into a token safe for use in an id/selector. */\nexport function toIdToken(base: string): string {\n const token = base.trim().replace(UNSAFE, '-').replace(/^-+|-+$/g, '');\n return token.length > 0 ? token : 'field';\n}\n\nexport interface A11yIds {\n /** The normalised base token. */\n readonly base: string;\n /** Id for the primary interactive element (e.g. the input). */\n readonly input: string;\n /** Id for a label element / labelling text. */\n readonly label: string;\n /** Id for descriptive/help text. */\n readonly description: string;\n /** Id for an error message element. */\n readonly error: string;\n /** Id for a title element (e.g. a dialog title). */\n readonly title: string;\n /** Derive an arbitrary suffixed id from the same base. */\n id(suffix: string): string;\n}\n\n/**\n * Build a set of deterministic, SSR-stable ids from a base string.\n *\n * @example\n * const ids = a11yIds('email');\n * // ids.input === 'email-input', ids.label === 'email-label', ...\n * input({ bind: value, id: ids.input, ariaLabelledBy: ids.label, ariaDescribedBy: ids.error });\n * text('Email', { id: ids.label });\n */\nexport function a11yIds(base: string): A11yIds {\n const token = toIdToken(base);\n return {\n base: token,\n input: `${token}-input`,\n label: `${token}-label`,\n description: `${token}-description`,\n error: `${token}-error`,\n title: `${token}-title`,\n id: (suffix: string) => `${token}-${toIdToken(suffix)}`,\n };\n}\n","/**\n * Node and application identity utilities.\n * Every node in the semantic graph has a stable, unique identity.\n */\n\nlet _counter = 0;\n\n/** Generate a framework-internal monotonic integer ID. */\nexport function nextId(): number {\n return ++_counter;\n}\n\n/** Reset the counter (test use only). */\nexport function resetIdCounter(): void {\n _counter = 0;\n}\n\n/** Opaque branded type for node IDs. */\nexport type NodeId = string & { readonly __brand: 'NodeId' };\n\n/** Create a NodeId from a string (must be unique at call site). */\nexport function createNodeId(value: string): NodeId {\n return value as NodeId;\n}\n\n/** Generate a fresh, unique NodeId. */\nexport function generateNodeId(prefix: string = 'node'): NodeId {\n return createNodeId(`${prefix}:${nextId()}`);\n}\n\n/** Parse the prefix from a NodeId. */\nexport function nodeIdPrefix(id: NodeId): string {\n const colon = id.indexOf(':');\n return colon === -1 ? id : id.slice(0, colon);\n}\n\n/** Branded type for application IDs. */\nexport type ApplicationId = string & { readonly __brand: 'ApplicationId' };\n\n/** Generate a fresh application ID. */\nexport function generateApplicationId(name: string): ApplicationId {\n return `app:${name}:${nextId()}` as ApplicationId;\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 * Environment detection and capability flags.\n * The framework behaves slightly differently in browser vs. server vs. test.\n *\n * We use `typeof` checks throughout to remain safe across environments\n * without depending on @types/node.\n */\n\nexport type EnvironmentKind = 'browser' | 'server' | 'worker' | 'test' | 'unknown';\n\nexport interface EnvironmentCapabilities {\n readonly hasDom: boolean;\n readonly hasWindow: boolean;\n readonly hasDocument: boolean;\n readonly isSecureContext: boolean;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\ndeclare const process: any;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nfunction detectEnvironment(): EnvironmentKind {\n // Explicit test override via process.env\n try {\n if (\n typeof process !== 'undefined' &&\n process !== null &&\n typeof process === 'object' &&\n (process.env?.['NODE_ENV'] === 'test' || process.env?.['VITEST'] === 'true')\n ) {\n return 'test';\n }\n } catch {\n // process may not be defined in all environments\n }\n\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n return 'browser';\n }\n\n if (\n typeof self !== 'undefined' &&\n typeof (self as unknown as Record<string, unknown>)['importScripts'] === 'function'\n ) {\n return 'worker';\n }\n\n try {\n if (typeof process !== 'undefined' && typeof process === 'object') {\n return 'server';\n }\n } catch {\n // ignore\n }\n\n return 'unknown';\n}\n\nfunction detectCapabilities(): EnvironmentCapabilities {\n return {\n hasDom: typeof document !== 'undefined',\n hasWindow: typeof window !== 'undefined',\n hasDocument: typeof document !== 'undefined',\n isSecureContext:\n typeof window !== 'undefined'\n ? ((window as unknown as Record<string, unknown>)['isSecureContext'] === true)\n : false,\n };\n}\n\nexport class Environment {\n readonly kind: EnvironmentKind;\n readonly capabilities: EnvironmentCapabilities;\n\n constructor(kind?: EnvironmentKind) {\n this.kind = kind ?? detectEnvironment();\n this.capabilities = detectCapabilities();\n }\n\n get isBrowser(): boolean {\n return this.kind === 'browser';\n }\n\n get isServer(): boolean {\n return this.kind === 'server';\n }\n\n get isTest(): boolean {\n return this.kind === 'test';\n }\n\n get isWorker(): boolean {\n return this.kind === 'worker';\n }\n}\n\n/** The singleton environment for this execution context. */\nexport const environment = new Environment();\n","/**\n * Framework diagnostics — structured errors, warnings, and hints\n * that flow through the compiler, validator, and runtime.\n */\n\nexport type DiagnosticSeverity = 'error' | 'warning' | 'info';\n\nexport interface DiagnosticLocation {\n readonly file?: string;\n readonly line?: number;\n readonly column?: number;\n readonly nodeId?: string;\n}\n\nexport interface Diagnostic {\n readonly severity: DiagnosticSeverity;\n readonly code: string;\n readonly message: string;\n readonly location: DiagnosticLocation | undefined;\n readonly cause: unknown;\n}\n\nexport class DiagnosticError extends Error {\n readonly diagnostics: readonly Diagnostic[];\n\n constructor(diagnostics: readonly Diagnostic[]) {\n const summary = diagnostics\n .filter(d => d.severity === 'error')\n .map(d => `[${d.code}] ${d.message}`)\n .join('\\n');\n super(`StreetUI diagnostics:\\n${summary}`);\n this.name = 'DiagnosticError';\n this.diagnostics = diagnostics;\n }\n}\n\nexport class DiagnosticCollector {\n private readonly _diagnostics: Diagnostic[] = [];\n\n get diagnostics(): readonly Diagnostic[] {\n return this._diagnostics;\n }\n\n get hasErrors(): boolean {\n return this._diagnostics.some(d => d.severity === 'error');\n }\n\n get hasWarnings(): boolean {\n return this._diagnostics.some(d => d.severity === 'warning');\n }\n\n error(\n code: string,\n message: string,\n location?: DiagnosticLocation,\n cause?: unknown,\n ): void {\n this._diagnostics.push({ severity: 'error', code, message, location: location ?? undefined, cause: cause ?? undefined });\n }\n\n warn(\n code: string,\n message: string,\n location?: DiagnosticLocation,\n ): void {\n this._diagnostics.push({ severity: 'warning', code, message, location: location ?? undefined, cause: undefined });\n }\n\n info(\n code: string,\n message: string,\n location?: DiagnosticLocation,\n ): void {\n this._diagnostics.push({ severity: 'info', code, message, location: location ?? undefined, cause: undefined });\n }\n\n merge(other: DiagnosticCollector): void {\n for (const d of other.diagnostics) {\n this._diagnostics.push(d);\n }\n }\n\n throwIfErrors(): void {\n if (this.hasErrors) {\n throw new DiagnosticError(this._diagnostics);\n }\n }\n\n clear(): void {\n this._diagnostics.length = 0;\n }\n}\n\n/** Format a single diagnostic as a human-readable string. */\nexport function formatDiagnostic(d: Diagnostic): string {\n const loc = d.location !== undefined\n ? ` (${[d.location.file, d.location.line, d.location.column]\n .filter(Boolean)\n .join(':')})`\n : '';\n return `[${d.severity.toUpperCase()}] ${d.code}: ${d.message}${loc}`;\n}\n","/**\n * Top-level Application primitive.\n * Owns lifecycle, identity, and the root of the application graph.\n */\n\nimport { type ApplicationId, generateApplicationId } from './identity.js';\nimport { Lifecycle, CleanupRegistry } from './lifecycle.js';\nimport { Environment, environment as defaultEnvironment } from './environment.js';\nimport { DiagnosticCollector } from './diagnostics.js';\n\nexport interface ApplicationOptions {\n readonly name: string;\n readonly version?: string;\n readonly environment?: Environment;\n}\n\nexport class Application {\n readonly id: ApplicationId;\n readonly name: string;\n readonly version: string;\n readonly lifecycle: Lifecycle;\n readonly cleanup: CleanupRegistry;\n readonly diagnostics: DiagnosticCollector;\n readonly environment: Environment;\n\n constructor(options: ApplicationOptions) {\n this.name = options.name;\n this.version = options.version ?? '0.0.1';\n this.id = generateApplicationId(options.name);\n this.lifecycle = new Lifecycle();\n this.cleanup = new CleanupRegistry();\n this.diagnostics = new DiagnosticCollector();\n this.environment = options.environment ?? defaultEnvironment;\n }\n\n async mount(): Promise<void> {\n if (this.lifecycle.phase !== 'created') {\n throw new Error(`Application \"${this.name}\" is already mounted (phase: ${this.lifecycle.phase})`);\n }\n await this.lifecycle.transition('mounted');\n await this.lifecycle.transition('active');\n }\n\n async unmount(): Promise<void> {\n if (!this.lifecycle.isMounted) {\n return;\n }\n await this.lifecycle.transition('unmounting');\n this.cleanup.run();\n await this.lifecycle.transition('destroyed');\n }\n\n onMount(fn: () => void | Promise<void>): void {\n this.lifecycle.onMount(fn);\n }\n\n onUnmount(fn: () => void | Promise<void>): void {\n this.lifecycle.onUnmount(fn);\n }\n}\n\n/** Factory convenience wrapper. */\nexport function createApplication(options: ApplicationOptions): Application {\n return new Application(options);\n}\n","/**\n * Framework node primitives — the base abstraction for every node\n * in the Semantic Application Graph.\n */\n\nimport { type NodeId, generateNodeId } from './identity.js';\n\nexport type SemanticNodeType =\n | 'application'\n | 'page'\n | 'section'\n | 'container'\n | 'heading'\n | 'text'\n | 'button'\n | 'input'\n | 'form'\n | 'list'\n | 'list-item'\n | 'image'\n | 'link'\n | 'component'\n | 'slot'\n | 'fragment'\n | 'reactive-list'\n | 'conditional';\n\nexport interface NodeMetadata {\n readonly createdAt: number;\n readonly [key: string]: unknown;\n}\n\nexport abstract class BaseNode {\n readonly id: NodeId;\n readonly type: SemanticNodeType;\n readonly metadata: NodeMetadata;\n\n constructor(type: SemanticNodeType, id?: NodeId) {\n this.type = type;\n this.id = id ?? generateNodeId(type);\n this.metadata = { createdAt: Date.now() };\n }\n\n abstract clone(): BaseNode;\n}\n","/**\n * Observability boundary — a tiny, optional logging seam plus contextual\n * framework errors.\n *\n * StreetUI never ships a telemetry service, never sends anything over the\n * network, and never logs on its own by default. Instead an application MAY\n * hand the framework a `DiagnosticSink` — any object with the log methods it\n * cares about — and the framework will route the diagnostics it already\n * produces (runtime errors, resource failures, hydration mismatches, router\n * transitions) to it. With no sink attached there is no logging and no cost.\n *\n * This is deliberately smaller than a logging library: it duplicates neither\n * `console` nor any structured-diagnostic type. It is a boundary, not a logger.\n */\n\n/**\n * Where a framework diagnostic originated. Every field is optional so a caller\n * supplies only what is meaningful for the situation. Values are intended to be\n * non-sensitive identifiers — never tokens, secrets, cookies, or form values.\n */\nexport interface DiagnosticContext {\n /** The package that produced the diagnostic, e.g. `@streetui/renderer`. */\n readonly package?: string;\n /** The operation underway, e.g. `hydrate`, `compile`, `navigate`. */\n readonly operation?: string;\n /** The graph node id involved, when applicable. */\n readonly nodeId?: string;\n /** The route path involved, when applicable. */\n readonly route?: string;\n /** A resource identifier involved, when applicable. */\n readonly resource?: string;\n}\n\n/**\n * The application-provided logging seam. Every method is optional; the\n * framework calls only the ones present. Implementations must not throw.\n */\nexport interface DiagnosticSink {\n debug?(message: string, context?: DiagnosticContext): void;\n info?(message: string, context?: DiagnosticContext): void;\n warn?(message: string, context?: DiagnosticContext): void;\n error?(message: string, context?: DiagnosticContext): void;\n}\n\n/** Format a context object as a compact ` [k=v, …]` suffix (empty when bare). */\nexport function formatDiagnosticContext(context?: DiagnosticContext): string {\n if (context === undefined) return '';\n const parts: string[] = [];\n if (context.package !== undefined) parts.push(`package=${context.package}`);\n if (context.operation !== undefined) parts.push(`operation=${context.operation}`);\n if (context.nodeId !== undefined) parts.push(`node=${context.nodeId}`);\n if (context.route !== undefined) parts.push(`route=${context.route}`);\n if (context.resource !== undefined) parts.push(`resource=${context.resource}`);\n return parts.length > 0 ? ` [${parts.join(', ')}]` : '';\n}\n\n/**\n * A framework error whose message carries structured, non-sensitive context so\n * a developer immediately sees which package/operation/node was involved. The\n * message never embeds a stack or environment values; production stack\n * disclosure decisions stay with the server layer.\n */\nexport class StreetFrameworkError extends Error {\n readonly context: DiagnosticContext | undefined;\n\n constructor(message: string, context?: DiagnosticContext) {\n super(`${message}${formatDiagnosticContext(context)}`);\n this.name = 'StreetFrameworkError';\n this.context = context ?? undefined;\n }\n}\n\n/** Build a `StreetFrameworkError` with the given context. */\nexport function frameworkError(\n message: string,\n context?: DiagnosticContext,\n): StreetFrameworkError {\n return new StreetFrameworkError(message, context);\n}\n\n/**\n * Route a diagnostic to a sink if it implements the matching level. Safe to\n * call with `undefined` — it simply does nothing, which is the default (no\n * logging) posture. Never throws even if the sink method does.\n */\nexport function reportDiagnostic(\n sink: DiagnosticSink | undefined,\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n context?: DiagnosticContext,\n): void {\n if (sink === undefined) return;\n const fn = sink[level];\n if (typeof fn !== 'function') return;\n try {\n fn.call(sink, message, context);\n } catch {\n // A misbehaving sink must never break the framework.\n }\n}\n\n/** A sink that forwards to a `console`-like object, one call per level. */\nexport function consoleDiagnosticSink(\n logger: Partial<Record<'debug' | 'info' | 'warn' | 'error', (msg: string) => void>> = console,\n): DiagnosticSink {\n return {\n debug: (m, c) => logger.debug?.(`${m}${formatDiagnosticContext(c)}`),\n info: (m, c) => logger.info?.(`${m}${formatDiagnosticContext(c)}`),\n warn: (m, c) => logger.warn?.(`${m}${formatDiagnosticContext(c)}`),\n error: (m, c) => logger.error?.(`${m}${formatDiagnosticContext(c)}`),\n };\n}\n","/**\n * Semantic Application Graph nodes.\n *\n * Every element in a StreetUI application is represented as a GraphNode.\n * Nodes form a tree: each has an optional parent and an ordered list of children.\n */\n\nimport { generateNodeId, type NodeId, type SemanticNodeType } from '@streetui/core';\n\n// ── Property values ───────────────────────────────────────────────────────────\n\nexport type PropValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | string[]\n | number[]\n | Record<string, unknown>;\n\nexport type Props = Record<string, PropValue>;\n\n// ── Event descriptors ─────────────────────────────────────────────────────────\n\nexport interface EventDescriptor {\n readonly type: string;\n /** Reference key into the application's handler registry. */\n readonly handlerKey: string;\n}\n\n// ── State references ──────────────────────────────────────────────────────────\n\nexport interface StateRef {\n /** ID of the signal/store this node's property is bound to. */\n readonly signalId: string;\n /** The prop key on this node that is bound. */\n readonly propKey: string;\n}\n\n// ── The core graph node ───────────────────────────────────────────────────────\n\nexport interface GraphNodeData {\n readonly id: NodeId;\n readonly type: SemanticNodeType;\n readonly key: string | undefined;\n props: Props;\n events: EventDescriptor[];\n stateRefs: StateRef[];\n children: GraphNode[];\n parent: GraphNode | null;\n}\n\nexport class GraphNode implements GraphNodeData {\n readonly id: NodeId;\n readonly type: SemanticNodeType;\n readonly key: string | undefined;\n props: Props;\n events: EventDescriptor[];\n stateRefs: StateRef[];\n children: GraphNode[];\n parent: GraphNode | null;\n\n constructor(\n type: SemanticNodeType,\n options: {\n id?: NodeId;\n key?: string;\n props?: Props;\n events?: EventDescriptor[];\n stateRefs?: StateRef[];\n } = {},\n ) {\n this.type = type;\n this.id = options.id ?? generateNodeId(type);\n this.key = options.key;\n this.props = options.props ?? {};\n this.events = options.events ?? [];\n this.stateRefs = options.stateRefs ?? [];\n this.children = [];\n this.parent = null;\n }\n\n // ── Child management ────────────────────────────────────────────────────────\n\n appendChild(child: GraphNode): void {\n if (child.parent !== null) {\n child.parent.removeChild(child);\n }\n child.parent = this;\n this.children.push(child);\n }\n\n insertBefore(child: GraphNode, reference: GraphNode): void {\n const idx = this.children.indexOf(reference);\n if (idx === -1) {\n this.appendChild(child);\n return;\n }\n if (child.parent !== null) {\n child.parent.removeChild(child);\n }\n child.parent = this;\n this.children.splice(idx, 0, child);\n }\n\n removeChild(child: GraphNode): void {\n const idx = this.children.indexOf(child);\n if (idx === -1) return;\n this.children.splice(idx, 1);\n child.parent = null;\n }\n\n replaceChild(newChild: GraphNode, oldChild: GraphNode): void {\n const idx = this.children.indexOf(oldChild);\n if (idx === -1) {\n throw new Error(`GraphNode.replaceChild: oldChild is not a child of this node`);\n }\n if (newChild.parent !== null) {\n newChild.parent.removeChild(newChild);\n }\n oldChild.parent = null;\n newChild.parent = this;\n this.children.splice(idx, 1, newChild);\n }\n\n // ── Prop helpers ────────────────────────────────────────────────────────────\n\n setProp(key: string, value: PropValue): void {\n this.props = { ...this.props, [key]: value };\n }\n\n getProp<T extends PropValue = PropValue>(key: string): T | undefined {\n return this.props[key] as T | undefined;\n }\n\n // ── Event helpers ───────────────────────────────────────────────────────────\n\n addEvent(descriptor: EventDescriptor): void {\n this.events.push(descriptor);\n }\n\n removeEvent(type: string): void {\n this.events = this.events.filter(e => e.type !== type);\n }\n\n // ── Queries ─────────────────────────────────────────────────────────────────\n\n get isLeaf(): boolean {\n return this.children.length === 0;\n }\n\n get depth(): number {\n let d = 0;\n let node: GraphNode | null = this.parent;\n while (node !== null) {\n d++;\n node = node.parent;\n }\n return d;\n }\n\n get root(): GraphNode {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let node: GraphNode = this;\n while (node.parent !== null) {\n node = node.parent;\n }\n return node;\n }\n\n /** Shallow clone — does not clone children. */\n shallowClone(): GraphNode {\n const opts: { key?: string; props: Props; events: EventDescriptor[]; stateRefs: StateRef[] } = {\n props: { ...this.props },\n events: [...this.events],\n stateRefs: [...this.stateRefs],\n };\n if (this.key !== undefined) opts.key = this.key;\n return new GraphNode(this.type, opts);\n }\n}\n","/**\n * The Semantic Application Graph.\n *\n * Holds the application root node and all its descendants.\n * Supports traversal, lookup by ID, validation, and serialization.\n */\n\nimport { type NodeId, DiagnosticCollector } from '@streetui/core';\nimport { GraphNode, type Props, type EventDescriptor } from './graph-node.js';\n\nexport interface ApplicationGraphOptions {\n readonly name: string;\n readonly version?: string;\n}\n\nexport interface HandlerFn {\n (...args: unknown[]): unknown;\n}\n\nexport class ApplicationGraph {\n readonly root: GraphNode;\n readonly name: string;\n readonly version: string;\n private readonly _nodeIndex: Map<NodeId, GraphNode> = new Map();\n /** Handler registry — maps handlerKey → actual function */\n readonly handlers: Map<string, HandlerFn> = new Map();\n\n constructor(options: ApplicationGraphOptions) {\n this.name = options.name;\n this.version = options.version ?? '0.0.1';\n this.root = new GraphNode('application', { props: { name: options.name } });\n this._nodeIndex.set(this.root.id, this.root);\n }\n\n // ── Node creation & attachment ────────────────────────────────────────────\n\n createNode(\n type: GraphNode['type'],\n options: { key?: string; props?: Props; parent?: GraphNode } = {},\n ): GraphNode {\n const nodeOpts: { key?: string; props?: Props } = {};\n if (options.key !== undefined) nodeOpts.key = options.key;\n if (options.props !== undefined) nodeOpts.props = options.props;\n const node = new GraphNode(type, nodeOpts);\n this._nodeIndex.set(node.id, node);\n if (options.parent !== undefined) {\n options.parent.appendChild(node);\n }\n return node;\n }\n\n attachNode(node: GraphNode, parent: GraphNode): void {\n this._nodeIndex.set(node.id, node);\n parent.appendChild(node);\n }\n\n detachNode(node: GraphNode): void {\n if (node.parent !== null) {\n node.parent.removeChild(node);\n }\n this._removeFromIndex(node);\n }\n\n private _removeFromIndex(node: GraphNode): void {\n this._nodeIndex.delete(node.id);\n this._unregisterNodeHandlers(node);\n for (const child of node.children) {\n this._removeFromIndex(child);\n }\n }\n\n /**\n * Remove every handler-registry entry owned by a single node. A node owns:\n * - one entry per event descriptor (its `handlerKey`),\n * - one `__signal__<signalId>` entry per state ref (signalIds are namespaced\n * by node id, so they are never shared between nodes), and\n * - a `__listbuild__<id>` entry if it is a reactive-list.\n * Called for every node in a detached subtree so removing list items (or\n * discarding freshly-built-but-unadopted item subtrees) leaves no stale\n * registrations behind.\n */\n private _unregisterNodeHandlers(node: GraphNode): void {\n for (const event of node.events) {\n this.handlers.delete(event.handlerKey);\n }\n for (const ref of node.stateRefs) {\n this.handlers.delete(`__signal__${ref.signalId}`);\n }\n this.handlers.delete(`__listbuild__${node.id}`);\n this.handlers.delete(`__listplan__${node.id}`);\n }\n\n // ── Handler registry ──────────────────────────────────────────────────────\n\n registerHandler(key: string, fn: HandlerFn): void {\n this.handlers.set(key, fn);\n }\n\n getHandler(key: string): HandlerFn | undefined {\n return this.handlers.get(key);\n }\n\n /** True if a handler is currently registered under `key`. Inspection helper. */\n hasHandler(key: string): boolean {\n return this.handlers.has(key);\n }\n\n /** Number of currently-registered handlers. Inspection helper. */\n get handlerCount(): number {\n return this.handlers.size;\n }\n\n // ── Lookup ────────────────────────────────────────────────────────────────\n\n findById(id: NodeId): GraphNode | undefined {\n return this._nodeIndex.get(id);\n }\n\n findAll(predicate: (node: GraphNode) => boolean): GraphNode[] {\n const results: GraphNode[] = [];\n this._walk(this.root, node => {\n if (predicate(node)) results.push(node);\n });\n return results;\n }\n\n findByType(type: GraphNode['type']): GraphNode[] {\n return this.findAll(n => n.type === type);\n }\n\n // ── Traversal ─────────────────────────────────────────────────────────────\n\n walk(visitor: (node: GraphNode, depth: number) => void): void {\n this._walk(this.root, visitor, 0);\n }\n\n private _walk(\n node: GraphNode,\n visitor: (node: GraphNode, depth: number) => void,\n depth: number = 0,\n ): void {\n visitor(node, depth);\n for (const child of node.children) {\n this._walk(child, visitor, depth + 1);\n }\n }\n\n get nodeCount(): number {\n return this._nodeIndex.size;\n }\n\n // ── Validation ────────────────────────────────────────────────────────────\n\n validate(): DiagnosticCollector {\n const dc = new DiagnosticCollector();\n\n this.walk((node) => {\n // Validate event handler references exist\n for (const event of node.events) {\n if (!this.handlers.has(event.handlerKey)) {\n dc.warn(\n 'GRAPH_MISSING_HANDLER',\n `Node \"${node.id}\" references handler \"${event.handlerKey}\" which is not registered`,\n { nodeId: node.id },\n );\n }\n }\n\n // Validate page nodes are direct children of root\n if (node.type === 'page' && node.parent?.type !== 'application') {\n dc.error(\n 'GRAPH_PAGE_DEPTH',\n `Page node \"${node.id}\" must be a direct child of the application root`,\n { nodeId: node.id },\n );\n }\n });\n\n return dc;\n }\n\n // ── Serialization ─────────────────────────────────────────────────────────\n\n serialize(): SerializedGraph {\n return {\n name: this.name,\n version: this.version,\n root: this._serializeNode(this.root),\n };\n }\n\n private _serializeNode(node: GraphNode): SerializedNode {\n const result: SerializedNode = {\n id: node.id,\n type: node.type,\n key: node.key,\n props: node.props,\n events: node.events,\n stateRefs: node.stateRefs,\n children: node.children.map(c => this._serializeNode(c)),\n };\n return result;\n }\n}\n\nexport interface SerializedNode {\n readonly id: string;\n readonly type: string;\n readonly key: string | undefined;\n readonly props: Props;\n readonly events: EventDescriptor[];\n readonly stateRefs: unknown[];\n readonly children: SerializedNode[];\n}\n\nexport interface SerializedGraph {\n readonly name: string;\n readonly version: string;\n readonly root: SerializedNode;\n}\n","/**\n * DSL builder implementations.\n *\n * Each builder wraps a GraphNode and provides the fluent API\n * for constructing the Semantic Application Graph via the DSL.\n *\n * Builders do NOT render anything — they only build the graph.\n */\n\nimport { ApplicationGraph, GraphNode, type Props } from '@streetui/graph';\nimport type {\n ContentDSL,\n ContainerDSL,\n SectionDSL,\n PageDSL,\n FormDSL,\n ListDSL,\n AppDSL,\n HeadingOptions,\n TextOptions,\n ButtonOptions,\n InputOptions,\n LinkOptions,\n ImageOptions,\n ContainerOptions,\n SectionOptions,\n FormOptions,\n ListOptions,\n A11yOptions,\n Bindable,\n BindableText,\n TextValue,\n ErrorBoundaryOptions,\n ErrorSource,\n PageBuilder,\n SectionBuilder,\n ContainerBuilder as ContainerBuilderFn,\n FormBuilder,\n ListBuilder,\n} from './dsl-types.js';\nimport { signal, derived, type Signal, type ReadonlySignal } from '@streetui/state';\n\n/**\n * A single reactive-list reconciliation descriptor (spec §15).\n *\n * Emitted by the `__listplan__<nodeId>` handler on every list change. `key` is\n * the item's identity-only reconciliation key (cheap to compute); `item` is the\n * source value *reference* used for identity short-circuiting; `sig()` computes\n * the content signature on demand (only when the reference changed); `build()`\n * materialises the full item subtree on demand (only for new/changed rows).\n */\nexport interface ListPlanEntry {\n readonly key: string;\n readonly item: unknown;\n readonly sig: () => string;\n readonly build: () => GraphNode;\n}\n\n// ── Signal helpers ────────────────────────────────────────────────────────────\n\nfunction isSignal(v: unknown): v is Signal<unknown> | ReadonlySignal<unknown> {\n return (\n v !== null &&\n typeof v === 'object' &&\n typeof (v as Record<string, unknown>)['get'] === 'function' &&\n typeof (v as Record<string, unknown>)['subscribe'] === 'function'\n );\n}\n\n/** Register a signal binding on the node and return the current static value. */\nfunction bindValue<T>(\n graph: ApplicationGraph,\n node: GraphNode,\n propKey: string,\n value: Bindable<T>,\n): T {\n if (isSignal(value)) {\n const signalId = `${node.id}:${propKey}`;\n node.stateRefs.push({ signalId, propKey });\n graph.registerHandler(`__signal__${signalId}`, value as unknown as () => unknown);\n return (value as ReadonlySignal<T>).peek();\n }\n return value as T;\n}\n\n// ── Helper to build Props from ContainerOptions ───────────────────────────────\n\n/**\n * Copy accessibility options onto a props bag as their corresponding HTML/ARIA\n * attribute names. Values are written as strings (booleans become \"true\"/\"false\"\n * rather than being dropped) so ARIA state attributes render literally. These\n * flow to the DOM via the renderer's generic attribute pass — no ARIA-specific\n * renderer code is involved.\n */\nfunction applyA11yProps(props: Props, options: A11yOptions): void {\n if (options.role !== undefined) props['role'] = options.role;\n if (options.tabIndex !== undefined) props['tabindex'] = String(options.tabIndex);\n if (options.ariaLabel !== undefined) props['aria-label'] = options.ariaLabel;\n if (options.ariaLabelledBy !== undefined) props['aria-labelledby'] = options.ariaLabelledBy;\n if (options.ariaDescribedBy !== undefined) props['aria-describedby'] = options.ariaDescribedBy;\n if (options.ariaExpanded !== undefined) props['aria-expanded'] = String(options.ariaExpanded);\n if (options.ariaControls !== undefined) props['aria-controls'] = options.ariaControls;\n if (options.ariaHidden !== undefined) props['aria-hidden'] = String(options.ariaHidden);\n if (options.ariaLive !== undefined) props['aria-live'] = options.ariaLive;\n if (options.ariaCurrent !== undefined) props['aria-current'] = String(options.ariaCurrent);\n if (options.ariaInvalid !== undefined) props['aria-invalid'] = String(options.ariaInvalid);\n if (options.ariaRequired !== undefined) props['aria-required'] = String(options.ariaRequired);\n}\n\nfunction containerProps(options: ContainerOptions): Props {\n const props: Props = {};\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n if (options.key !== undefined) props['key'] = options.key;\n applyA11yProps(props, options);\n return props;\n}\n\n// ── Reactive-list item keying ──────────────────────────────────────────────────\n//\n// The `listOf` DSL signature does not take an explicit key extractor, so we\n// derive a stable reconciliation key from each item. The key combines an\n// *identity* part (so reordering the same items reuses their DOM nodes) with a\n// *value signature* (so an item whose data changed is treated as a fresh node\n// and re-rendered rather than silently kept stale by the shallow reconciler).\n\nfunction itemIdentity(item: unknown, index: number): string {\n if (item !== null && typeof item === 'object') {\n const obj = item as Record<string, unknown>;\n if ('id' in obj) return `id:${String(obj['id'])}`;\n if ('key' in obj) return `key:${String(obj['key'])}`;\n return `idx:${index}`;\n }\n return `val:${String(item)}`;\n}\n\nfunction itemValueSignature(item: unknown): string {\n try {\n return JSON.stringify(item) ?? String(item);\n } catch {\n return String(item);\n }\n}\n\n/** Content signature used to detect in-place data changes of a stable item. */\nexport function reactiveListItemSignature(item: unknown): string {\n return itemValueSignature(item);\n}\n\n/** Stable, identity-only reconciliation key for a reactive-list item. */\nexport function reactiveListItemKey(item: unknown, index: number): string {\n return itemIdentity(item, index);\n}\n\n// ── Base content builder ──────────────────────────────────────────────────────\n\nclass ContentBuilderBase implements ContentDSL {\n constructor(\n protected readonly _node: GraphNode,\n protected readonly _graph: ApplicationGraph,\n ) {}\n\n heading(text: BindableText, options: HeadingOptions = {}): void {\n const props: Props = { level: options.level ?? 1 };\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const node = this._graph.createNode('heading', { parent: this._node, props });\n const resolved = bindValue<TextValue>(this._graph, node, 'text', text);\n node.setProp('text', resolved);\n }\n\n text(content: BindableText, options: TextOptions = {}): void {\n const props: Props = {};\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const node = this._graph.createNode('text', { parent: this._node, props });\n const resolved = bindValue<TextValue>(this._graph, node, 'text', content);\n node.setProp('text', resolved);\n }\n\n button(label: BindableText, options: ButtonOptions = {}): void {\n const props: Props = {};\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const node = this._graph.createNode('button', { parent: this._node, props });\n const resolved = bindValue<TextValue>(this._graph, node, 'label', label);\n node.setProp('label', resolved);\n if (options.disabled !== undefined) {\n const resolvedDisabled = bindValue(this._graph, node, 'disabled', options.disabled);\n node.setProp('disabled', resolvedDisabled);\n }\n if (options.onClick !== undefined) {\n const handlerKey = `click:${node.id}`;\n this._graph.registerHandler(handlerKey, options.onClick as () => unknown);\n node.addEvent({ type: 'click', handlerKey });\n }\n }\n\n input(options: InputOptions = {}): void {\n const props: Props = {};\n props['inputType'] = options.type ?? 'text';\n if (options.placeholder !== undefined) props['placeholder'] = options.placeholder;\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const nodeOpts: { key?: string; props: Props; parent: GraphNode } = {\n props,\n parent: this._node,\n };\n if (options.id !== undefined) nodeOpts.key = options.id;\n const node = this._graph.createNode('input', nodeOpts);\n\n // Two-way `bind` expands to a value binding + an input write-back. The type\n // system (BoundInputOptions vs ControlledInputOptions) guarantees `bind` is\n // never combined with explicit `value`/`onInput`, so there is no ambiguity.\n const bindSignal = options.bind;\n const valueBindable: Bindable<string> | undefined =\n bindSignal !== undefined ? bindSignal : options.value;\n const inputHandler: ((value: string) => void) | undefined =\n bindSignal !== undefined ? (v: string) => bindSignal.set(v) : options.onInput;\n\n if (valueBindable !== undefined) {\n const resolved = bindValue(this._graph, node, 'value', valueBindable);\n node.setProp('value', resolved);\n }\n if (options.disabled !== undefined) {\n const resolved = bindValue(this._graph, node, 'disabled', options.disabled);\n node.setProp('disabled', resolved);\n }\n if (inputHandler !== undefined) {\n const handlerKey = `input:${node.id}`;\n this._graph.registerHandler(handlerKey, inputHandler as () => unknown);\n node.addEvent({ type: 'input', handlerKey });\n }\n if (options.onChange !== undefined) {\n const handlerKey = `change:${node.id}`;\n this._graph.registerHandler(handlerKey, options.onChange as () => unknown);\n node.addEvent({ type: 'change', handlerKey });\n }\n }\n\n image(options: ImageOptions): void {\n const props: Props = {\n src: options.src,\n alt: options.alt,\n };\n if (options.width !== undefined) props['width'] = options.width;\n if (options.height !== undefined) props['height'] = options.height;\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const nodeOpts: { key?: string; props: Props; parent: GraphNode } = {\n props,\n parent: this._node,\n };\n if (options.id !== undefined) nodeOpts.key = options.id;\n this._graph.createNode('image', nodeOpts);\n }\n\n link(label: BindableText, options: LinkOptions): void {\n const props: Props = {\n href: options.href,\n external: options.external ?? false,\n };\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const node = this._graph.createNode('link', { parent: this._node, props });\n const resolved = bindValue<TextValue>(this._graph, node, 'label', label);\n node.setProp('label', resolved);\n if (options.onClick !== undefined) {\n const handlerKey = `click:${node.id}`;\n this._graph.registerHandler(handlerKey, options.onClick as () => unknown);\n node.addEvent({ type: 'click', handlerKey });\n }\n }\n}\n\n// ── Container builder ─────────────────────────────────────────────────────────\n\nclass ContainerBuilderBase extends ContentBuilderBase implements ContainerDSL {\n section(key: string, builder: SectionBuilder, options: SectionOptions = {}): void {\n const node = this._graph.createNode('section', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n builder(new SectionBuilderImpl(node, this._graph));\n }\n\n container(key: string, builder: ContainerBuilderFn, options: ContainerOptions = {}): void {\n const node = this._graph.createNode('container', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n builder(new ContainerBuilderImpl(node, this._graph));\n }\n\n list(key: string, builder: ListBuilder, options: ListOptions = {}): void {\n const node = this._graph.createNode('list', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n builder(new ListBuilderImpl(node, this._graph));\n }\n\n listOf<T>(\n key: string,\n items: Signal<T[]> | ReadonlySignal<T[]>,\n renderItem: (item: T, index: number, content: ContentDSL) => void,\n options: ListOptions = {},\n ): void {\n const graph = this._graph;\n const node = graph.createNode('reactive-list', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n\n // Register the driving signal so the runtime/renderer can subscribe to it.\n const signalId = `${node.id}:items`;\n node.stateRefs.push({ signalId, propKey: 'items' });\n graph.registerHandler(`__signal__${signalId}`, items as unknown as () => unknown);\n\n // Build a single detached list-item subtree for one item. The item's\n // reconciliation `key` is identity-only, and its value signature is stored\n // in the internal `_sig` prop so the renderer can detect (and apply a\n // targeted update for) a data change on an item whose identity is stable.\n const buildItem = (item: T, index: number): GraphNode => {\n const itemKey = reactiveListItemKey(item, index);\n const itemNode = graph.createNode('list-item', {\n key: itemKey,\n // `_item` records the source item *reference* so the reconciler can\n // short-circuit unchanged rows by identity (no signature hashing); `_sig`\n // is the content signature used to detect an in-place data change when the\n // reference differs. Both are internal metadata (leading `_`) and never\n // reach the DOM.\n props: {\n key: itemKey,\n _sig: reactiveListItemSignature(item),\n // The item reference is stored as opaque internal metadata (never\n // rendered); cast through `unknown` since `T` is not a `PropValue`.\n _item: item as unknown as Props[string],\n },\n });\n renderItem(item, index, new ContainerBuilderImpl(itemNode, graph));\n return itemNode;\n };\n\n // Lazy reconciliation plan (spec §15 — the measured keyed-list hot path).\n //\n // Instead of eagerly rebuilding all N item GraphNodes (and hashing every item\n // with JSON.stringify) on *every* emission — the dominant cost of the old\n // `buildAll` path — the renderer receives lightweight descriptors and only\n // materialises a subtree for rows that are genuinely new or whose data\n // actually changed. `key` is cheap (identity only); `sig()` and `build()` are\n // thunks the reconciler calls on demand.\n const buildPlan = (raw: unknown): ListPlanEntry[] => {\n const arr = Array.isArray(raw) ? (raw as T[]) : [];\n const plan: ListPlanEntry[] = new Array(arr.length);\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i]!;\n const index = i;\n plan[i] = {\n key: reactiveListItemKey(item, index),\n item,\n sig: () => reactiveListItemSignature(item),\n build: () => buildItem(item, index),\n };\n }\n return plan;\n };\n graph.registerHandler(`__listplan__${node.id}`, buildPlan as unknown as () => unknown);\n\n // Build the initial children into the graph so the first mount renders them.\n const current = isSignal(items)\n ? (items as ReadonlySignal<T[]>).peek()\n : (items as unknown as T[]);\n const initial = Array.isArray(current) ? current : [];\n initial.forEach((item, i) => {\n node.appendChild(buildItem(item, i));\n });\n }\n\n form(key: string, builder: FormBuilder, options: FormOptions = {}): void {\n const props: Props = containerProps(options);\n const node = this._graph.createNode('form', {\n key,\n parent: this._node,\n props,\n });\n if (options.onSubmit !== undefined) {\n const handlerKey = `submit:${node.id}`;\n this._graph.registerHandler(handlerKey, options.onSubmit as () => unknown);\n node.addEvent({ type: 'submit', handlerKey });\n }\n builder(new FormBuilderImpl(node, this._graph));\n }\n\n when(\n condition: Bindable<boolean>,\n builder: ContainerBuilderFn,\n elseBuilder?: ContainerBuilderFn,\n ): void {\n const graph = this._graph;\n // A dedicated 'conditional' node reuses the reactive-list reconciliation\n // machinery (same signal subscription + keyed reconcile) but renders as a\n // neutral <div> rather than a <ul>. It holds zero or one child branch.\n const node = graph.createNode('conditional', {\n parent: this._node,\n props: containerProps({}),\n });\n\n // Build the active branch as a single keyed container. Distinct keys for the\n // then/else branches make a flip a clean swap under the keyed reconciler.\n const buildBranch = (build: ContainerBuilderFn, tag: 'then' | 'else'): GraphNode => {\n const branchKey = `when-${tag}:${node.id}`;\n const branch = graph.createNode('container', {\n key: branchKey,\n props: { key: branchKey },\n });\n build(new ContainerBuilderImpl(branch, graph));\n return branch;\n };\n\n const buildAll = (raw: unknown): GraphNode[] => {\n if (raw) return [buildBranch(builder, 'then')];\n return elseBuilder !== undefined ? [buildBranch(elseBuilder, 'else')] : [];\n };\n\n if (isSignal(condition)) {\n const signalId = `${node.id}:items`;\n node.stateRefs.push({ signalId, propKey: 'items' });\n graph.registerHandler(`__signal__${signalId}`, condition as unknown as () => unknown);\n graph.registerHandler(`__listbuild__${node.id}`, buildAll as unknown as () => unknown);\n const current = (condition as ReadonlySignal<boolean>).peek();\n for (const child of buildAll(current)) node.appendChild(child);\n } else {\n // Static condition — resolve once at build time, no reactive wiring.\n for (const child of buildAll(condition)) node.appendChild(child);\n }\n }\n\n errorBoundary(\n id: string,\n builder: ContainerBuilderFn,\n options: ErrorBoundaryOptions,\n ): void {\n // Normalise the observed error source(s) into an array.\n const sources: ErrorSource[] =\n options.source === undefined\n ? []\n : Array.isArray(options.source)\n ? [...options.source]\n : [options.source];\n\n // The boundary's own captured error (from a synchronous build throw) and a\n // retry nonce that forces a re-evaluation even when the boolean is unchanged.\n const localError = signal<unknown>(undefined);\n const retryNonce = signal<number>(0);\n\n const readError = (): unknown => {\n const local = localError.peek();\n if (local !== undefined && local !== null) return local;\n for (const s of sources) {\n const e = s.peek();\n if (e !== undefined && e !== null) return e;\n }\n return undefined;\n };\n\n // Reactive condition: true while an error is present. Reads every input so a\n // change in any source (or a retry) re-runs the conditional.\n const hasError = derived<boolean>(() => {\n retryNonce.get();\n localError.get();\n for (const s of sources) s.get();\n return readError() !== undefined;\n });\n\n const retry = (): void => {\n localError.set(undefined);\n options.onRetry?.();\n // Force the body branch to re-attempt even if no observed value changed.\n retryNonce.update((n) => n + 1);\n };\n\n // Wrap in a container so the whole boundary is addressable and disposes as a\n // unit. `when` provides the reactive body↔fallback swap (and its cleanup).\n this.container(id, (c) => {\n c.when(\n hasError,\n // Error state → fallback.\n (fb) => options.fallback(fb, readError(), retry),\n // Healthy state → body, guarded against synchronous build throws.\n (body) => {\n try {\n builder(body);\n } catch (err) {\n // Surface the throw as the boundary's error on the next microtask\n // (deferred to avoid re-entrant reconciliation during this build).\n queueMicrotask(() => localError.set(err));\n }\n },\n );\n }, { id });\n }\n}\n\n// ── Concrete builder implementations ─────────────────────────────────────────\n\nexport class SectionBuilderImpl extends ContainerBuilderBase implements SectionDSL {}\nexport class ContainerBuilderImpl extends ContainerBuilderBase implements ContainerDSL {}\nexport class FormBuilderImpl extends ContainerBuilderBase implements FormDSL {}\n\nexport class ListBuilderImpl extends ContentBuilderBase implements ListDSL {\n item(key: string, builder: ContainerBuilderFn, options: ContainerOptions = {}): void {\n const node = this._graph.createNode('list-item', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n builder(new ContainerBuilderImpl(node, this._graph));\n }\n}\n\nexport class PageBuilderImpl extends ContainerBuilderBase implements PageDSL {}\n\n// ── App builder ───────────────────────────────────────────────────────────────\n\nexport class AppBuilder implements AppDSL {\n constructor(private readonly _graph: ApplicationGraph) {}\n\n page(key: string, builder: PageBuilder): void {\n const node = this._graph.createNode('page', {\n key,\n parent: this._graph.root,\n props: { key },\n });\n builder(new PageBuilderImpl(node, this._graph));\n }\n}\n","/**\n * StreetUI DSL entry point.\n *\n * Usage:\n * import { streetui } from '@streetui/dsl';\n *\n * const app = streetui.app({ name: 'My App' });\n * app.page('home', page => {\n * page.section('hero', section => {\n * section.heading('Welcome');\n * section.button('Click me', { onClick: () => {} });\n * });\n * });\n *\n * const graph = app.build();\n */\n\nimport { ApplicationGraph } from '@streetui/graph';\nimport { AppBuilder } from './builders.js';\n\nexport interface AppOptions {\n readonly name: string;\n readonly version?: string;\n}\n\nexport class StreetApp {\n private readonly _graph: ApplicationGraph;\n private readonly _builder: AppBuilder;\n\n constructor(options: AppOptions) {\n const graphOpts: { name: string; version?: string } = { name: options.name };\n if (options.version !== undefined) graphOpts.version = options.version;\n this._graph = new ApplicationGraph(graphOpts);\n this._builder = new AppBuilder(this._graph);\n }\n\n page(key: string, builder: Parameters<AppBuilder['page']>[1]): this {\n this._builder.page(key, builder);\n return this;\n }\n\n /** Compile to ApplicationGraph — validates and returns the graph. */\n build(): ApplicationGraph {\n const dc = this._graph.validate();\n dc.throwIfErrors();\n return this._graph;\n }\n\n /** Access graph before building (useful for inspection). */\n get graph(): ApplicationGraph {\n return this._graph;\n }\n}\n\nexport interface StreetUI {\n app(options: AppOptions): StreetApp;\n}\n\nexport const streetui: StreetUI = {\n app(options: AppOptions): StreetApp {\n return new StreetApp(options);\n },\n};\n","/**\n * Compiler-phase validation of the ApplicationGraph.\n *\n * This runs after the DSL has built the graph but before the runtime\n * receives a CompiledApplication. More checks live here than in the\n * graph's own validate() because the compiler has broader context.\n */\n\nimport { DiagnosticCollector } from '@streetui/core';\nimport { ApplicationGraph, GraphNode } from '@streetui/graph';\n\nexport function validateGraph(graph: ApplicationGraph): DiagnosticCollector {\n const dc = new DiagnosticCollector();\n\n // Merge built-in graph validations\n dc.merge(graph.validate());\n\n // Must have at least one page\n const pages = graph.findByType('page');\n if (pages.length === 0) {\n dc.warn(\n 'COMPILER_NO_PAGES',\n 'Application has no pages defined. At least one page is recommended.',\n );\n }\n\n // Walk and validate individual nodes\n graph.walk((node) => {\n validateNode(node, dc);\n });\n\n return dc;\n}\n\nfunction validateNode(node: GraphNode, dc: DiagnosticCollector): void {\n switch (node.type) {\n case 'heading': {\n const text = node.getProp('text');\n if (text === undefined || text === '') {\n dc.warn('COMPILER_EMPTY_HEADING', `Heading node \"${node.id}\" has no text content`, {\n nodeId: node.id,\n });\n }\n break;\n }\n case 'image': {\n const src = node.getProp('src');\n const alt = node.getProp('alt');\n if (!src) {\n dc.error('COMPILER_IMAGE_NO_SRC', `Image node \"${node.id}\" is missing src`, {\n nodeId: node.id,\n });\n }\n if (!alt) {\n dc.warn('COMPILER_IMAGE_NO_ALT', `Image node \"${node.id}\" is missing alt text`, {\n nodeId: node.id,\n });\n }\n break;\n }\n case 'link': {\n const href = node.getProp('href');\n if (!href) {\n dc.error('COMPILER_LINK_NO_HREF', `Link node \"${node.id}\" is missing href`, {\n nodeId: node.id,\n });\n }\n break;\n }\n default:\n break;\n }\n}\n","/**\n * Graph transformation pass.\n *\n * After validation, the transformer prepares the graph for the runtime by:\n * - Resolving implicit defaults (e.g. heading level defaults to 1)\n * - Normalizing prop names\n * - Assigning deterministic render keys where missing\n * - Flattening / hoisting where beneficial\n */\n\nimport { ApplicationGraph, GraphNode } from '@streetui/graph';\n\nexport function transformGraph(graph: ApplicationGraph): void {\n graph.walk((node, depth) => {\n applyDefaults(node);\n ensureRenderKey(node, depth);\n });\n}\n\nfunction applyDefaults(node: GraphNode): void {\n switch (node.type) {\n case 'heading': {\n if (node.getProp('level') === undefined) {\n node.setProp('level', 1);\n }\n break;\n }\n case 'input': {\n if (node.getProp('inputType') === undefined) {\n node.setProp('inputType', 'text');\n }\n break;\n }\n case 'link': {\n if (node.getProp('external') === undefined) {\n node.setProp('external', false);\n }\n break;\n }\n default:\n break;\n }\n}\n\nfunction ensureRenderKey(node: GraphNode, depth: number): void {\n if (node.getProp('_renderKey') === undefined) {\n const key = node.key ?? `${node.type}:${node.id}:${depth}`;\n node.setProp('_renderKey', key);\n }\n}\n","/**\n * StreetUI compiler entry point.\n *\n * Pipeline:\n * StreetApp (DSL)\n * → ApplicationGraph (build)\n * → validate\n * → transform\n * → CompiledApplication\n */\n\nimport { DiagnosticCollector } from '@streetui/core';\nimport { type ApplicationGraph } from '@streetui/graph';\nimport { type StreetApp } from '@streetui/dsl';\nimport { validateGraph } from './validation/validator.js';\nimport { transformGraph } from './transform/transform.js';\n\nexport interface CompiledApplication {\n /** The fully built, validated, and transformed graph. */\n readonly graph: ApplicationGraph;\n /** Diagnostics accumulated during compilation. */\n readonly diagnostics: DiagnosticCollector;\n /** Metadata */\n readonly name: string;\n readonly version: string;\n readonly compiledAt: number;\n}\n\nexport interface CompileOptions {\n /** If true, compilation throws on errors. Defaults to true. */\n readonly strict?: boolean;\n /** If true, also throw on warnings. Defaults to false. */\n readonly strictWarnings?: boolean;\n}\n\n/**\n * Compile a StreetApp DSL definition into a CompiledApplication\n * ready for the runtime to execute.\n */\nexport function compile(\n app: StreetApp,\n options: CompileOptions = {},\n): CompiledApplication {\n const strict = options.strict ?? true;\n const strictWarnings = options.strictWarnings ?? false;\n const dc = new DiagnosticCollector();\n\n // 1. Build the graph from the DSL\n const graph = app.graph;\n\n // 2. Validate\n const validationDc = validateGraph(graph);\n dc.merge(validationDc);\n\n if (strict && dc.hasErrors) {\n dc.throwIfErrors();\n }\n if (strictWarnings && dc.hasWarnings) {\n throw new Error(\n `[StreetUI Compiler] Compilation failed: warnings treated as errors.\\n` +\n dc.diagnostics\n .filter(d => d.severity === 'warning')\n .map(d => ` [${d.code}] ${d.message}`)\n .join('\\n'),\n );\n }\n\n // 3. Transform\n transformGraph(graph);\n\n return {\n graph,\n diagnostics: dc,\n name: graph.name,\n version: graph.version,\n compiledAt: Date.now(),\n };\n}\n\n/**\n * Compile from a pre-built ApplicationGraph (used when the graph\n * was constructed programmatically rather than through the DSL).\n */\nexport function compileGraph(\n graph: ApplicationGraph,\n options: CompileOptions = {},\n): CompiledApplication {\n const strict = options.strict ?? true;\n const dc = new DiagnosticCollector();\n\n const validationDc = validateGraph(graph);\n dc.merge(validationDc);\n\n if (strict && dc.hasErrors) {\n dc.throwIfErrors();\n }\n\n transformGraph(graph);\n\n return {\n graph,\n diagnostics: dc,\n name: graph.name,\n version: graph.version,\n compiledAt: Date.now(),\n };\n}\n","/**\n * RuntimeNodeInstance — the runtime's live representation of a GraphNode.\n *\n * Each GraphNode in the compiled application gets a corresponding\n * RuntimeNodeInstance during mounting. The instance owns:\n * - the DOM node(s) produced for this graph node\n * - all signal subscriptions that drive updates\n * - all DOM event listeners\n * - child instances\n */\n\nimport { CleanupRegistry } from '@streetui/core';\nimport type { GraphNode } from '@streetui/graph';\nimport type { Signal, ReadonlySignal } from '@streetui/state';\n\nexport interface NodeInstanceOptions {\n readonly graphNode: GraphNode;\n readonly domNode: Node;\n}\n\nexport class RuntimeNodeInstance {\n readonly graphNode: GraphNode;\n domNode: Node;\n readonly children: RuntimeNodeInstance[] = [];\n readonly cleanup: CleanupRegistry = new CleanupRegistry();\n private _mounted = false;\n\n constructor(options: NodeInstanceOptions) {\n this.graphNode = options.graphNode;\n this.domNode = options.domNode;\n }\n\n get isMounted(): boolean {\n return this._mounted;\n }\n\n mount(): void {\n this._mounted = true;\n }\n\n unmount(): void {\n if (!this._mounted) return;\n this._mounted = false;\n for (const child of this.children) {\n child.unmount();\n }\n this.cleanup.run();\n }\n\n addChild(instance: RuntimeNodeInstance): void {\n this.children.push(instance);\n }\n\n /** Subscribe to a signal and register the unsubscribe for cleanup. */\n trackSignal<T>(\n signal: Signal<T> | ReadonlySignal<T>,\n handler: (value: T) => void,\n ): void {\n const unsub = signal.subscribe(handler);\n this.cleanup.add(unsub);\n }\n\n /** Register an arbitrary cleanup function (e.g. DOM event removal). */\n trackCleanup(fn: () => void): void {\n this.cleanup.add(fn);\n }\n}\n","/**\n * StreetUI update scheduler.\n *\n * Responsibilities:\n * - Queue update callbacks\n * - Batch synchronous enqueues into a single microtask flush\n * - Guarantee ordering: higher priority jobs flush first\n * - Prevent duplicate work for the same job key\n * - Allow synchronous flush for tests\n */\n\nexport type Priority = 'immediate' | 'normal' | 'idle';\n\nconst PRIORITY_ORDER: Record<Priority, number> = {\n immediate: 0,\n normal: 1,\n idle: 2,\n};\n\nexport interface Job {\n /** Unique key — if another job with the same key is already queued, it is replaced. */\n readonly key: string;\n readonly priority: Priority;\n readonly fn: () => void;\n}\n\n/**\n * Optional error-reporting hook (v0.9 §26/§27). Structurally compatible with\n * `@streetui/core`'s `DiagnosticSink` (the `error` method) so an application can\n * route swallowed scheduler-job failures through its own logger instead of the\n * default `console.error`. Kept as a local structural type so the scheduler\n * stays dependency-free; no network, no telemetry. When unset, behaviour is\n * exactly as before.\n */\nexport interface SchedulerDiagnostics {\n error?(message: string, context?: unknown): void;\n}\n\nexport class Scheduler {\n private readonly _queue: Map<string, Job> = new Map();\n private _flushScheduled = false;\n private _flushing = false;\n private _diagnostics: SchedulerDiagnostics | undefined = undefined;\n\n /**\n * Install an optional diagnostic sink for swallowed job errors. Pass\n * `undefined` to restore the default `console.error` reporting. Additive and\n * opt-in — the scheduler never sends anything anywhere on its own.\n */\n setDiagnostics(sink: SchedulerDiagnostics | undefined): void {\n this._diagnostics = sink;\n }\n\n /** Total jobs currently queued. */\n get size(): number {\n return this._queue.size;\n }\n\n /** True if a flush has been scheduled but not yet executed. */\n get isPending(): boolean {\n return this._flushScheduled;\n }\n\n /**\n * Enqueue a job. If a job with the same key exists, the new one replaces it\n * (allowing callers to coalesce repeated updates for the same node).\n */\n schedule(job: Job): void {\n this._queue.set(job.key, job);\n if (!this._flushScheduled && !this._flushing) {\n this._flushScheduled = true;\n this._scheduleMicrotask();\n }\n }\n\n /** Schedule multiple jobs atomically. */\n scheduleAll(jobs: readonly Job[]): void {\n for (const job of jobs) {\n this._queue.set(job.key, job);\n }\n if (!this._flushScheduled && !this._flushing && this._queue.size > 0) {\n this._flushScheduled = true;\n this._scheduleMicrotask();\n }\n }\n\n /**\n * Cancel a queued job by key. No-op if not queued.\n */\n cancel(key: string): void {\n this._queue.delete(key);\n }\n\n /**\n * Synchronously flush all queued jobs (sorted by priority).\n * Useful in tests and for immediate rendering.\n */\n flush(): void {\n if (this._flushing) return;\n this._flushScheduled = false;\n this._flushing = true;\n\n const jobs = Array.from(this._queue.values()).sort(\n (a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority],\n );\n this._queue.clear();\n\n try {\n for (const job of jobs) {\n try {\n job.fn();\n } catch (err) {\n // Isolate job failures — report and continue so remaining jobs still run.\n if (this._diagnostics?.error) {\n this._diagnostics.error(`Scheduler job \"${job.key}\" threw`, err);\n } else {\n console.error(`[Scheduler] Job \"${job.key}\" threw:`, err);\n }\n }\n }\n } finally {\n this._flushing = false;\n }\n }\n\n /** Clear all pending jobs without executing them. */\n clear(): void {\n this._queue.clear();\n this._flushScheduled = false;\n }\n\n private _scheduleMicrotask(): void {\n Promise.resolve().then(() => {\n if (this._flushScheduled) {\n this.flush();\n }\n });\n }\n}\n\n/** The shared global scheduler instance. */\nexport const scheduler = new Scheduler();\n\n/** Convenience: schedule a normal-priority job. */\nexport function scheduleUpdate(key: string, fn: () => void): void {\n scheduler.schedule({ key, priority: 'normal', fn });\n}\n\n/** Convenience: schedule an immediate-priority job. */\nexport function scheduleImmediate(key: string, fn: () => void): void {\n scheduler.schedule({ key, priority: 'immediate', fn });\n}\n\n/** Convenience: flush the global scheduler synchronously. */\nexport function flushSync(): void {\n scheduler.flush();\n}\n","/**\n * StreetUI Runtime.\n *\n * Owns:\n * - Signal binding — wires signal subscriptions to renderer update calls\n * - Event dispatch — calls registered handlers from graph events\n * - Lifecycle — orchestrates mount, update cycles, unmount\n *\n * The runtime does NOT create DOM nodes. It calls into StreetRenderer\n * for all DOM operations.\n */\n\nimport { CleanupRegistry } from '@streetui/core';\nimport type { GraphNode, ApplicationGraph } from '@streetui/graph';\nimport type { Signal, ReadonlySignal } from '@streetui/state';\nimport { Scheduler } from '@streetui/scheduler';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport type { StreetRenderer, RenderHandle } from './renderer-interface.js';\n\nexport interface RuntimeOptions {\n readonly renderer: StreetRenderer;\n readonly scheduler?: Scheduler;\n}\n\nexport interface MountedApplication {\n readonly renderHandle: RenderHandle;\n readonly runtime: Runtime;\n unmount(): void;\n flush(): void;\n}\n\nexport class Runtime {\n private readonly _renderer: StreetRenderer;\n private readonly _scheduler: Scheduler;\n private readonly _cleanup: CleanupRegistry = new CleanupRegistry();\n private _renderHandle: RenderHandle | null = null;\n private _mounted = false;\n\n constructor(options: RuntimeOptions) {\n this._renderer = options.renderer;\n this._scheduler = options.scheduler ?? new Scheduler();\n }\n\n get isMounted(): boolean {\n return this._mounted;\n }\n\n /**\n * Mount the compiled application into the given DOM container.\n */\n mount(compiled: CompiledApplication, container: Element): MountedApplication {\n if (this._mounted) {\n throw new Error('[Runtime] Already mounted. Call unmount() first.');\n }\n\n // Hand off to renderer — it creates all DOM nodes\n this._renderHandle = this._renderer.mount(compiled, container);\n this._mounted = true;\n\n // Wire signal subscriptions from the graph\n this._bindSignals(compiled.graph);\n\n const self = this;\n return {\n renderHandle: this._renderHandle,\n runtime: this,\n unmount() { self.unmount(); },\n flush() { self._scheduler.flush(); },\n };\n }\n\n unmount(): void {\n if (!this._mounted) return;\n this._mounted = false;\n this._renderHandle?.unmount();\n this._renderHandle = null;\n this._cleanup.run();\n }\n\n /**\n * Hydrate a container that already holds server-rendered HTML for this\n * application. Delegates to the renderer's `hydrate` (adopting the existing\n * DOM instead of recreating it) and falls back to `mount` for renderers that\n * cannot hydrate. Signal binding is identical to `mount`, so the live client\n * lifecycle is established the same way.\n */\n hydrate(compiled: CompiledApplication, container: Element): MountedApplication {\n if (this._mounted) {\n throw new Error('[Runtime] Already mounted. Call unmount() first.');\n }\n\n this._renderHandle = this._renderer.hydrate !== undefined\n ? this._renderer.hydrate(compiled, container)\n : this._renderer.mount(compiled, container);\n this._mounted = true;\n\n this._bindSignals(compiled.graph);\n\n const self = this;\n return {\n renderHandle: this._renderHandle,\n runtime: this,\n unmount() { self.unmount(); },\n flush() { self._scheduler.flush(); },\n };\n }\n\n /**\n * Walk the graph and subscribe to all signal-bound nodes.\n * When a signal changes, schedule a renderer update for that node.\n */\n private _bindSignals(graph: ApplicationGraph): void {\n graph.walk((node) => {\n for (const stateRef of node.stateRefs) {\n const signalKey = `__signal__${stateRef.signalId}`;\n const maybeSignal = graph.getHandler(signalKey) as\n | (Signal<unknown> & ReadonlySignal<unknown>)\n | undefined;\n\n if (maybeSignal === undefined || typeof maybeSignal.subscribe !== 'function') continue;\n\n const unsub = maybeSignal.subscribe(() => {\n // Schedule a re-render update keyed to this node+prop\n this._scheduler.schedule({\n key: `update:${node.id}:${stateRef.propKey}`,\n priority: 'normal',\n fn: () => {\n // The renderer handles the actual DOM update\n this._renderHandle?.flush();\n },\n });\n });\n this._cleanup.add(unsub);\n }\n });\n }\n}\n\n/**\n * Convenience factory — create a runtime, mount, and return the handle.\n */\nexport function createRuntime(options: RuntimeOptions): Runtime {\n return new Runtime(options);\n}\n","/**\n * StreetUI event type catalogue.\n * Framework events are distinct from raw DOM events.\n */\n\nexport type StreetEventType =\n | 'click'\n | 'dblclick'\n | 'input'\n | 'change'\n | 'submit'\n | 'focus'\n | 'blur'\n | 'keydown'\n | 'keyup'\n | 'keypress'\n | 'mouseenter'\n | 'mouseleave'\n | 'mousemove'\n | 'mousedown'\n | 'mouseup'\n | 'pointerdown'\n | 'pointerup'\n | 'pointermove'\n | 'pointerenter'\n | 'pointerleave'\n | 'scroll'\n | 'resize'\n | 'mount'\n | 'unmount'\n | 'update';\n\nexport interface StreetEvent<T = unknown> {\n readonly type: StreetEventType | string;\n readonly target: unknown;\n readonly data: T | undefined;\n readonly originalEvent: Event | undefined;\n readonly timestamp: number;\n defaultPrevented: boolean;\n stopPropagation(): void;\n preventDefault(): void;\n}\n\nexport function createStreetEvent<T = unknown>(\n type: StreetEventType | string,\n target: unknown,\n data?: T,\n originalEvent?: Event,\n): StreetEvent<T> {\n let _stopped = false;\n const ev: StreetEvent<T> = {\n type,\n target,\n data: data as T | undefined,\n originalEvent: originalEvent as Event | undefined,\n timestamp: Date.now(),\n defaultPrevented: false,\n stopPropagation() { _stopped = true; },\n preventDefault() { ev.defaultPrevented = true; },\n };\n return ev;\n}\n\nexport type EventHandler<T = unknown> = (event: StreetEvent<T>) => void;\n","/**\n * Framework-internal event bus.\n * Decouples emitters from handlers across subsystems.\n */\n\nimport type { StreetEvent, EventHandler } from './event-types.js';\n\nexport class EventBus {\n private readonly _handlers: Map<string, Set<EventHandler>> = new Map();\n\n on<T = unknown>(type: string, handler: EventHandler<T>): () => void {\n let set = this._handlers.get(type);\n if (set === undefined) {\n set = new Set();\n this._handlers.set(type, set);\n }\n set.add(handler as EventHandler);\n return () => this.off(type, handler as EventHandler);\n }\n\n off<T = unknown>(type: string, handler: EventHandler<T>): void {\n this._handlers.get(type)?.delete(handler as EventHandler);\n }\n\n once<T = unknown>(type: string, handler: EventHandler<T>): () => void {\n const wrapped: EventHandler<T> = (event) => {\n handler(event);\n this.off(type, wrapped);\n };\n return this.on(type, wrapped);\n }\n\n emit<T = unknown>(event: StreetEvent<T>): void {\n const handlers = this._handlers.get(event.type);\n if (handlers === undefined) return;\n for (const h of handlers) {\n h(event as StreetEvent);\n }\n }\n\n clear(type?: string): void {\n if (type !== undefined) {\n this._handlers.delete(type);\n } else {\n this._handlers.clear();\n }\n }\n\n listenerCount(type: string): number {\n return this._handlers.get(type)?.size ?? 0;\n }\n}\n\nexport const globalEventBus = new EventBus();\n","/**\n * DOM ↔ StreetUI event bridge.\n *\n * Attaches native DOM event listeners and translates them into\n * StreetUI events dispatched to registered handlers.\n * The renderer uses this to wire events without coupling\n * DOM event mechanics into the render pipeline directly.\n */\n\nimport { createStreetEvent, type EventHandler, type StreetEventType } from './event-types.js';\n\nexport interface DomBinding {\n remove(): void;\n}\n\n/**\n * Attach a DOM event listener that fires the given StreetUI handler.\n * Returns a binding whose `remove()` detaches the listener.\n */\nexport function bindDomEvent<T extends Event = Event>(\n element: EventTarget,\n domEventType: StreetEventType | string,\n handler: EventHandler,\n options?: AddEventListenerOptions,\n): DomBinding {\n const listener = (e: T) => {\n const streetEvent = createStreetEvent(domEventType, element, undefined, e as unknown as Event);\n handler(streetEvent);\n };\n\n element.addEventListener(domEventType, listener as EventListener, options);\n\n return {\n remove() {\n element.removeEventListener(domEventType, listener as EventListener, options);\n },\n };\n}\n\n/**\n * A registry that tracks all DOM bindings for a single node,\n * making bulk teardown easy.\n */\nexport class DomEventRegistry {\n private readonly _bindings: DomBinding[] = [];\n\n bind(\n element: EventTarget,\n type: StreetEventType | string,\n handler: EventHandler,\n options?: AddEventListenerOptions,\n ): void {\n this._bindings.push(bindDomEvent(element, type, handler, options));\n }\n\n removeAll(): void {\n for (const b of this._bindings) {\n b.remove();\n }\n this._bindings.length = 0;\n }\n\n get count(): number {\n return this._bindings.length;\n }\n}\n","/**\n * Browser implementation of DOMAdapter — delegates directly to browser APIs.\n */\n\nimport type { DOMAdapter } from './adapter.js';\n\nexport class BrowserDOMAdapter implements DOMAdapter {\n createElement(tag: string, ns?: string): Element {\n if (ns !== undefined) {\n return document.createElementNS(ns, tag);\n }\n return document.createElement(tag);\n }\n\n createTextNode(data: string): Text {\n return document.createTextNode(data);\n }\n\n createComment(data: string): Comment {\n return document.createComment(data);\n }\n\n createFragment(): DocumentFragment {\n return document.createDocumentFragment();\n }\n\n appendChild(parent: Node, child: Node): void {\n parent.appendChild(child);\n }\n\n insertBefore(parent: Node, child: Node, reference: Node | null): void {\n parent.insertBefore(child, reference);\n }\n\n removeChild(parent: Node, child: Node): void {\n parent.removeChild(child);\n }\n\n replaceChild(parent: Node, newChild: Node, oldChild: Node): void {\n parent.replaceChild(newChild, oldChild);\n }\n\n setAttribute(element: Element, name: string, value: string): void {\n element.setAttribute(name, value);\n }\n\n removeAttribute(element: Element, name: string): void {\n element.removeAttribute(name);\n }\n\n getAttribute(element: Element, name: string): string | null {\n return element.getAttribute(name);\n }\n\n setProperty(element: Element, name: string, value: unknown): void {\n (element as unknown as Record<string, unknown>)[name] = value;\n }\n\n setTextContent(node: Node, text: string): void {\n node.textContent = text;\n }\n\n getTextContent(node: Node): string | null {\n return node.textContent;\n }\n\n addEventListener(\n target: EventTarget,\n type: string,\n handler: EventListener,\n options?: AddEventListenerOptions,\n ): void {\n target.addEventListener(type, handler, options);\n }\n\n removeEventListener(\n target: EventTarget,\n type: string,\n handler: EventListener,\n options?: EventListenerOptions,\n ): void {\n target.removeEventListener(type, handler, options);\n }\n\n querySelector(root: Element | Document, selector: string): Element | null {\n return root.querySelector(selector);\n }\n\n querySelectorAll(root: Element | Document, selector: string): NodeListOf<Element> {\n return root.querySelectorAll(selector);\n }\n\n getElementById(id: string): Element | null {\n return document.getElementById(id);\n }\n\n focus(element: Element): void {\n (element as unknown as { focus?: () => void }).focus?.();\n }\n\n isElement(node: Node): node is Element {\n return node.nodeType === Node.ELEMENT_NODE;\n }\n\n isTextNode(node: Node): node is Text {\n return node.nodeType === Node.TEXT_NODE;\n }\n\n tagName(element: Element): string {\n return element.tagName.toLowerCase();\n }\n\n parentNode(node: Node): Node | null {\n return node.parentNode;\n }\n\n nextSibling(node: Node): Node | null {\n return node.nextSibling;\n }\n\n firstChild(node: Node): Node | null {\n return node.firstChild;\n }\n\n childNodes(node: Node): Node[] {\n return Array.from(node.childNodes);\n }\n}\n\nexport const browserDOMAdapter = new BrowserDOMAdapter();\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';\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\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 /** JS properties set via `setProperty` (e.g. input `value`, `checked`). */\n readonly properties = new Map<string, unknown>();\n readonly children: ServerNode[] = [];\n readonly style = new ServerStyle();\n\n constructor(tagName: string) {\n this.tagName = tagName.toLowerCase();\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/** Escape text node content. */\nexport function escapeHtmlText(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\n\n/** Escape a double-quoted attribute value. */\nexport function escapeHtmlAttr(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\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 for (const [name, kind] of Object.entries(SERIALIZED_PROPERTIES)) {\n if (!el.properties.has(name)) continue;\n if (el.attributes.has(name)) continue; // an explicit attribute already won\n const raw = el.properties.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 if (!el.style.isEmpty && !el.attributes.has('style')) {\n parts.push(` style=\"${escapeHtmlAttr(el.style.toCss())}\"`);\n }\n\n return parts.join('');\n}\n\n/** Serialize a single server node (element/text/comment/fragment) 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 '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 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 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 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\nexport const serverDOMAdapter = 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 * 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';\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\nexport function createRenderContext(\n dom: DOMAdapter,\n graph: ApplicationGraph,\n container: Element,\n hydrationDiagnostics?: HydrationDiagnosticSink,\n): RenderContext {\n return {\n dom,\n graph,\n instances: new Map(),\n container,\n ...(hydrationDiagnostics !== undefined ? { hydrationDiagnostics } : {}),\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 * 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};\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 { 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): 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 // New — create and mount\n const inst = mountFn(newNode, parentDom);\n newInstances.push(inst);\n }\n }\n\n // Determine removed instances\n const removed: NodeInstance[] = [];\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n if (!usedKeys.has(key)) {\n removed.push(inst);\n }\n }\n\n // Remove stale DOM nodes\n for (const inst of removed) {\n const parent = ctx.dom.parentNode(inst.domNode);\n if (parent !== null) {\n ctx.dom.removeChild(parent, inst.domNode);\n }\n inst.dispose();\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): 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 const freshNode = entry.build();\n built.push(freshNode);\n const inst = mountFn(freshNode, parentDom);\n newInstances.push(inst);\n }\n }\n\n // Determine + remove stale instances.\n const removed: NodeInstance[] = [];\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n if (!usedKeys.has(key)) removed.push(inst);\n }\n for (const inst of removed) {\n const parent = ctx.dom.parentNode(inst.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, inst.domNode);\n inst.dispose();\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 * 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 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';\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 // 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 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);\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 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 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): 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 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));\n } else {\n reconcileReactiveList(ctx, graphNode, instance, el, build!(value));\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): 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 );\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): 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 );\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 * Hydration diagnostics — dev-only, opt-in explanations of hydration mismatches.\n *\n * Hydration is self-repairing: when the server-rendered DOM does not match the\n * graph at a position, the renderer mounts a fresh subtree in place and drops\n * the offending element (see `hydrateChildren` in `hydrate.ts`). That recovery\n * is silent by design — a local mismatch must never tear down the whole app.\n *\n * During development, though, a silent repair hides a real problem (usually a\n * server/client divergence). A `HydrationDiagnosticSink` can be attached to the\n * renderer to *observe* those repairs without changing them: for every mismatch\n * the renderer reports what it expected, what it found, where, and what it did\n * to recover. Nothing is thrown, nothing is mutated differently, and when no\n * sink is attached there is zero additional work on the hydration path.\n */\n\n/** What kind of divergence the hydrator encountered at a position. */\nexport type HydrationMismatchType =\n | 'tag-mismatch' // an element existed but was the wrong tag\n | 'missing-element' // the graph expected a child the DOM did not provide\n | 'surplus-element'; // the DOM had a child the graph no longer expects\n\n/** A single, fully-described hydration divergence and the repair taken. */\nexport interface HydrationDiagnostic {\n /** The category of mismatch. */\n readonly type: HydrationMismatchType;\n /** The tag the graph expected at this position (null for a surplus element). */\n readonly expected: string | null;\n /** The tag actually found in the server DOM (null for a missing element). */\n readonly found: string | null;\n /** A human-readable path to the position, e.g. `app / page[0] / section[1]`. */\n readonly path: string;\n /** The graph node id involved, when one exists (null for surplus DOM). */\n readonly nodeId: string | null;\n /** The semantic node type involved, when one exists (null for surplus DOM). */\n readonly nodeType: string | null;\n /** The recovery action the renderer performed. */\n readonly action: string;\n /** A single-line, developer-facing summary of the whole diagnostic. */\n readonly message: string;\n}\n\n/**\n * Receives hydration diagnostics as they are discovered. Kept intentionally\n * tiny so any logger — `console`, a test collector, a `DiagnosticSink` — can\n * satisfy it. Implementations must not throw.\n */\nexport interface HydrationDiagnosticSink {\n report(diagnostic: HydrationDiagnostic): void;\n}\n\n/** Build the canonical one-line message for a diagnostic. */\nexport function formatHydrationDiagnostic(\n d: Omit<HydrationDiagnostic, 'message'>,\n): string {\n const at = ` at ${d.path}`;\n switch (d.type) {\n case 'tag-mismatch':\n return `Hydration mismatch${at} — Expected: ${d.expected} / Found: ${d.found} / Action: ${d.action}`;\n case 'missing-element':\n return `Hydration mismatch${at} — Expected: ${d.expected} / Found: (nothing) / Action: ${d.action}`;\n case 'surplus-element':\n return `Hydration mismatch${at} — Expected: (nothing) / Found: ${d.found} / Action: ${d.action}`;\n }\n}\n\n/**\n * A ready-made sink that accumulates diagnostics into an array — the shape most\n * useful for tests and for a DevTools panel. The returned `diagnostics` array is\n * appended to in-place as repairs happen.\n */\nexport function createHydrationDiagnosticCollector(): {\n readonly sink: HydrationDiagnosticSink;\n readonly diagnostics: HydrationDiagnostic[];\n} {\n const diagnostics: HydrationDiagnostic[] = [];\n return {\n diagnostics,\n sink: {\n report(d) {\n diagnostics.push(d);\n },\n },\n };\n}\n\n/**\n * A sink that forwards each diagnostic to a `console`-like logger as a single\n * warning line. Handy default when you just want the messages surfaced in dev.\n */\nexport function consoleHydrationDiagnosticSink(\n logger: { warn(message: string): void } = console,\n): HydrationDiagnosticSink {\n return {\n report(d) {\n logger.warn(d.message);\n },\n };\n}\n","/**\n * Hydration — attach a live StreetUI runtime to server-rendered HTML.\n *\n * `hydrate` walks the semantic application graph top-down against the DOM that\n * the server already produced. For every graph node it *adopts* the matching\n * existing element (creating a `NodeInstance` that points at it) and attaches\n * behavior — event listeners and signal subscriptions — using the exact same\n * helpers the browser mount path uses (`wireEvents`, `wireSignalBindings`,\n * `wireReactiveList`, and the per-type update factories). Nothing is recreated\n * when the DOM matches.\n *\n * Matching is positional and works because every non-application graph node\n * maps to exactly one element (see mount.ts). When the element at a position\n * does not match the expected tag (or is missing), only that subtree is\n * repaired: the fresh subtree is mounted and spliced into place, leaving the\n * rest of the hydrated tree untouched. A local mismatch never tears down the\n * whole app.\n */\n\nimport type { GraphNode } from '@streetui/graph';\nimport type { RenderContext } from './render-context.js';\nimport { NodeInstance } from './node-instance.js';\nimport { wireEvents } from './events.js';\nimport { resolveTag } from './tag-map.js';\nimport { formatHydrationDiagnostic } from './hydration-diagnostics.js';\nimport {\n mountNode,\n wireSignalBindings,\n wireReactiveList,\n textUpdate,\n headingUpdate,\n inputUpdate,\n buttonUpdate,\n} from './mount.js';\n\n/** Hydrate the whole application graph against `ctx.container`. */\nexport function hydrateGraph(ctx: RenderContext): NodeInstance {\n const root = ctx.graph.root;\n // The application root maps to the container itself (no element of its own),\n // exactly as in mountNode.\n const instance = new NodeInstance(root, ctx.container);\n ctx.instances.set(root.id, instance);\n hydrateChildren(ctx, root, instance, ctx.container, 'app');\n return instance;\n}\n\n/**\n * Adopt `domNode` as the live element for `graphNode` and attach behavior.\n * The caller has already verified `domNode` matches `graphNode` (right tag).\n * `path` is the human-readable position used only for dev diagnostics.\n */\nfunction hydrateNode(\n ctx: RenderContext,\n graphNode: GraphNode,\n domNode: Element,\n path: string,\n): NodeInstance {\n const { dom, graph } = ctx;\n\n switch (graphNode.type) {\n case 'text': {\n // <span> with an inner text node. Adopt the text node (or create one if\n // the server markup somehow lacks it).\n let textNode = dom.firstChild(domNode);\n if (textNode === null || !dom.isTextNode(textNode)) {\n const created = dom.createTextNode(String(graphNode.getProp('text') ?? ''));\n dom.appendChild(domNode, created);\n textNode = created;\n }\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, domNode, instance);\n // Only build the per-type update closure when the node actually has\n // reactive bindings. wireSignalBindings early-returns on an empty\n // stateRefs list, so for a static node the `textUpdate(...)` closure would\n // be allocated and immediately discarded — pure GC pressure on the hot\n // hydration path, where the vast majority of nodes are static.\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, textUpdate(dom, domNode, textNode as Text));\n }\n return instance;\n }\n\n case 'heading': {\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, domNode, instance);\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, headingUpdate(dom, domNode));\n }\n return instance;\n }\n\n case 'input': {\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n // The controlled value is already present in the server HTML (reflected as\n // the `value` attribute). Re-assert it as a live property so the element's\n // current value matches the bound signal exactly.\n const value = graphNode.getProp('value');\n if (value !== undefined) dom.setProperty(domNode, 'value', String(value));\n wireEvents(dom, graph, graphNode, domNode, instance);\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, inputUpdate(dom, domNode));\n }\n return instance;\n }\n\n case 'button': {\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, domNode, instance);\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, buttonUpdate(dom, domNode));\n }\n return instance;\n }\n\n case 'image':\n case 'link': {\n // Leaf elements with no reactive bindings or events beyond what the markup\n // already encodes; links may still carry click handlers.\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n if (graphNode.type === 'link') wireEvents(dom, graph, graphNode, domNode, instance);\n return instance;\n }\n\n case 'reactive-list':\n case 'conditional': {\n // The server rendered the initial children (built into the graph at\n // compile time from the initial signal state). Adopt them positionally,\n // then subscribe for future signal changes — the same keyed reconciler as\n // the browser drives subsequent updates against the adopted instances.\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n hydrateChildren(ctx, graphNode, instance, domNode, path);\n wireReactiveList(ctx, graphNode, instance, domNode);\n return instance;\n }\n\n default: {\n // Structural nodes: container / section / page / form / list / list-item.\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n if (graphNode.type === 'form') {\n wireEvents(dom, graph, graphNode, domNode, instance);\n }\n // Hydration boundary (a \"slot\" such as the router outlet): adopt the\n // element itself but leave its existing children untouched — neither\n // hydrated by this pass nor removed as surplus. Something else (e.g. the\n // router) owns and will hydrate the content already inside it. Without\n // this, an empty-in-the-graph slot would strip the server-rendered\n // content it is meant to preserve.\n if (graphNode.getProp('_hydrationBoundary') === true) {\n return instance;\n }\n hydrateChildren(ctx, graphNode, instance, domNode, path);\n return instance;\n }\n }\n}\n\n// ── Child matching + local mismatch recovery ───────────────────────────────────\n\n/**\n * Positionally match a parent's expected child graph nodes against the actual\n * child *elements* in the DOM. Matching children are hydrated in place; a\n * mismatch (wrong tag or a missing element) triggers a local repair — the fresh\n * subtree is mounted and spliced into the correct position — without disturbing\n * sibling subtrees. Surplus DOM elements are removed.\n */\nfunction hydrateChildren(\n ctx: RenderContext,\n parentGraphNode: GraphNode,\n parentInstance: NodeInstance,\n parentDom: Element,\n parentPath: string,\n): void {\n const expected = parentGraphNode.children;\n const actual = elementChildren(ctx, parentDom);\n let cursor = 0;\n\n // The human-readable `path` is only ever consumed by hydration diagnostics,\n // which are inert unless a sink is attached. Building the\n // `${parentPath} / ${type}[${i}]` string for every child would allocate one\n // throwaway string per node on the hot path (10k+ on a large tree) for output\n // that is discarded in production. Gate the construction on the sink being\n // present; when it is absent, thread the (meaningless-but-unused) parent path\n // through unchanged so nested calls stay allocation-free too.\n const diag = ctx.hydrationDiagnostics !== undefined;\n\n for (let i = 0; i < expected.length; i++) {\n const childNode = expected[i]!;\n const want = expectedTag(ctx, childNode);\n const childPath = diag ? `${parentPath} / ${childNode.type}[${i}]` : parentPath;\n const actualEl = actual[cursor];\n\n if (\n actualEl !== undefined &&\n ctx.dom.isElement(actualEl) &&\n ctx.dom.tagName(actualEl) === want\n ) {\n // Match — adopt the existing element.\n const inst = hydrateNode(ctx, childNode, actualEl, childPath);\n parentInstance.addChild(inst);\n cursor++;\n } else {\n // Mismatch or missing — repair only this subtree. Mount fresh, then move\n // it into the correct position ahead of the offending/absent node.\n const ref = actualEl ?? null;\n const inst = mountFreshAt(ctx, childNode, parentDom, ref);\n parentInstance.addChild(inst);\n if (actualEl !== undefined) {\n // Drop the mismatched element that the fresh node replaces.\n const found = ctx.dom.isElement(actualEl) ? ctx.dom.tagName(actualEl) : null;\n reportHydrationDiagnostic(ctx, {\n type: 'tag-mismatch',\n expected: want,\n found,\n path: childPath,\n nodeId: childNode.id,\n nodeType: childNode.type,\n action: 'mounted fresh subtree in place',\n });\n ctx.dom.removeChild(parentDom, actualEl);\n cursor++;\n } else {\n reportHydrationDiagnostic(ctx, {\n type: 'missing-element',\n expected: want,\n found: null,\n path: childPath,\n nodeId: childNode.id,\n nodeType: childNode.type,\n action: 'mounted fresh subtree',\n });\n }\n }\n }\n\n // Remove any surplus server elements the graph no longer expects.\n for (let i = cursor; i < actual.length; i++) {\n const surplus = actual[i]!;\n reportHydrationDiagnostic(ctx, {\n type: 'surplus-element',\n expected: null,\n found: ctx.dom.isElement(surplus) ? ctx.dom.tagName(surplus) : null,\n path: `${parentPath} / [surplus ${i}]`,\n nodeId: null,\n nodeType: null,\n action: 'removed surplus server element',\n });\n ctx.dom.removeChild(parentDom, surplus);\n }\n}\n\n/**\n * Emit a hydration diagnostic through the (optional) sink. When no sink is\n * attached this is a single cheap `undefined` check — the production default.\n */\nfunction reportHydrationDiagnostic(\n ctx: RenderContext,\n d: {\n type: 'tag-mismatch' | 'missing-element' | 'surplus-element';\n expected: string | null;\n found: string | null;\n path: string;\n nodeId: string | null;\n nodeType: string | null;\n action: string;\n },\n): void {\n const sink = ctx.hydrationDiagnostics;\n if (sink === undefined) return;\n sink.report({ ...d, message: formatHydrationDiagnostic(d) });\n}\n\n/** Mount a fresh subtree for `node` and splice it before `ref` (or append). */\nfunction mountFreshAt(\n ctx: RenderContext,\n node: GraphNode,\n parentDom: Element,\n ref: Node | null,\n): NodeInstance {\n // mountNode appends the new subtree at the end of parentDom.\n const inst = mountNode(ctx, node, parentDom);\n if (ref !== null) {\n ctx.dom.insertBefore(parentDom, inst.domNode, ref);\n }\n return inst;\n}\n\n/** The element (not text/comment) children of a node, in order. */\nfunction elementChildren(ctx: RenderContext, parent: Element): Element[] {\n const out: Element[] = [];\n for (const node of ctx.dom.childNodes(parent)) {\n if (ctx.dom.isElement(node)) out.push(node);\n }\n return out;\n}\n\n/** The HTML tag a graph node is expected to occupy in the DOM. */\nfunction expectedTag(ctx: RenderContext, graphNode: GraphNode): string {\n switch (graphNode.type) {\n case 'text':\n return 'span';\n case 'heading': {\n const level = (graphNode.getProp('level') as number | undefined) ?? 1;\n return `h${level}`;\n }\n case 'input':\n return 'input';\n case 'image':\n return 'img';\n case 'link':\n return 'a';\n case 'button':\n return 'button';\n default:\n // reactive-list → ul, conditional → div, structural → resolveTag.\n return resolveTag(graphNode.type);\n }\n}\n","/**\n * StreetRenderHandle — the live handle returned by both `mount` and `hydrate`.\n *\n * Owns teardown for a mounted/hydrated application: disposes every NodeInstance\n * (removing event listeners and signal subscriptions) and clears the container\n * through the DOM adapter (never raw browser globals), so the same handle works\n * for browser and — in principle — server-driven teardown.\n */\n\nimport type { RenderHandle } from '@streetui/runtime';\nimport type { RenderContext } from './render-context.js';\nimport type { NodeInstance } from './node-instance.js';\n\nexport class StreetRenderHandle implements RenderHandle {\n private _disposed = false;\n private readonly _ctx: RenderContext;\n private readonly _rootInstance: NodeInstance;\n\n constructor(ctx: RenderContext, rootInstance: NodeInstance) {\n this._ctx = ctx;\n this._rootInstance = rootInstance;\n }\n\n flush(): void {\n if (this._disposed) return;\n // Signal subscriptions fire synchronously in StreetUI's state system;\n // flush() is a no-op at the renderer level — the DOM is already up to date\n // unless the scheduler is batching, in which case the scheduler calls\n // flush() after draining its queue.\n }\n\n unmount(): void {\n if (this._disposed) return;\n this._disposed = true;\n\n // Dispose all node instances (removes event listeners, signal subscriptions).\n this._rootInstance.dispose();\n\n // Remove all children from the container. Routed through the DOM adapter\n // (never `container.firstChild`/`removeChild`) so the teardown path is\n // server-safe.\n const dom = this._ctx.dom;\n const container = this._ctx.container;\n for (const child of dom.childNodes(container)) {\n dom.removeChild(container, child);\n }\n\n this._ctx.instances.clear();\n }\n}\n","/**\n * StreetUI Renderer — framework-owned DOM renderer.\n *\n * No React. No Vue. No virtual-dom. No external rendering library.\n *\n * Pipeline:\n * CompiledApplication\n * → mountGraph (creates all DOM nodes)\n * → signal subscriptions drive patchNode (targeted updates)\n * → flush() propagates any pending scheduler jobs\n * → unmount() disposes everything\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\nimport { BrowserDOMAdapter } from '@streetui/dom';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport type { StreetRenderer, RenderHandle } from '@streetui/runtime';\nimport { createRenderContext } from './render-context.js';\nimport { mountGraph } from './mount.js';\nimport { hydrateGraph } from './hydrate.js';\nimport { StreetRenderHandle } from './render-handle.js';\nimport type { NodeInstance } from './node-instance.js';\nimport type { HydrationDiagnosticSink } from './hydration-diagnostics.js';\n\nexport interface StreetRendererOptions {\n /** Override the DOM adapter (e.g. for testing). Defaults to BrowserDOMAdapter. */\n readonly domAdapter?: DOMAdapter;\n /**\n * Optional dev-only sink that observes hydration mismatch repairs. Attach one\n * to surface server/client divergences during development; leave it unset in\n * production so hydration does no extra work.\n */\n readonly hydrationDiagnostics?: HydrationDiagnosticSink;\n}\n\nexport class StreetRendererImpl implements StreetRenderer {\n private readonly _dom: DOMAdapter;\n private readonly _hydrationDiagnostics?: HydrationDiagnosticSink;\n\n constructor(options: StreetRendererOptions = {}) {\n this._dom = options.domAdapter ?? new BrowserDOMAdapter();\n if (options.hydrationDiagnostics !== undefined) {\n this._hydrationDiagnostics = options.hydrationDiagnostics;\n }\n }\n\n mount(compiled: CompiledApplication, container: Element): RenderHandle {\n const ctx = createRenderContext(this._dom, compiled.graph, container);\n\n // Initial mount — creates the full DOM tree\n const rootInstance = mountGraph(ctx);\n\n // Wire all signal subscriptions so that signal → DOM patches happen automatically\n this._wireSignals(ctx, rootInstance);\n\n return new StreetRenderHandle(ctx, rootInstance);\n }\n\n /**\n * Hydrate a container that already holds server-rendered HTML for this\n * application. Instead of recreating the DOM, it walks the semantic graph\n * against the existing nodes, adopting matching elements and attaching\n * behavior (events + signal subscriptions). Mismatched subtrees are locally\n * replaced. Returns the same handle type as `mount`.\n */\n hydrate(compiled: CompiledApplication, container: Element): RenderHandle {\n const ctx = createRenderContext(\n this._dom,\n compiled.graph,\n container,\n this._hydrationDiagnostics,\n );\n const rootInstance = hydrateGraph(ctx);\n this._wireSignals(ctx, rootInstance);\n return new StreetRenderHandle(ctx, rootInstance);\n }\n\n private _wireSignals(\n ctx: ReturnType<typeof createRenderContext>,\n rootInstance: NodeInstance,\n ): void {\n // Each NodeInstance already wired its own signals in mountNode via wireSignalBindings.\n // This method is a hook for any cross-cutting signal concerns at the renderer level.\n // Currently no-op — individual mount calls handle their own subscriptions.\n void ctx;\n void rootInstance;\n }\n}\n\n/**\n * Create the default StreetUI renderer using the browser's DOM APIs.\n */\nexport function createRenderer(options?: StreetRendererOptions): StreetRendererImpl {\n return new StreetRendererImpl(options);\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 * 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';\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\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 // 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);\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 * Route matching — pure functions, no DOM, no reactivity.\n *\n * A pattern is matched segment-by-segment against a pathname:\n * - a literal segment must equal the path segment,\n * - a `:name` segment captures the path segment into `params.name`,\n * - a `*` segment (or a whole-pattern `*`) is a catch-all that matches the\n * remainder of the path and captures it into `params['*']`.\n *\n * Matching is intentionally small: no optional segments, no regex constraints,\n * no nested route trees. Composition of layouts is done in the DSL, not here.\n */\n\n/** Split a path into non-empty segments. `/` → [], `/a/b` → ['a','b']. */\nfunction segments(path: string): string[] {\n return path.split('/').filter((s) => s.length > 0);\n}\n\n/** Normalize a pathname: ensure a single leading slash, drop a trailing slash. */\nexport function normalizePath(path: string): string {\n let p = path.trim();\n if (p === '') return '/';\n if (!p.startsWith('/')) p = `/${p}`;\n if (p.length > 1 && p.endsWith('/')) p = p.slice(0, -1);\n return p;\n}\n\n/**\n * Try to match a single pattern against a pathname.\n * Returns the captured params on success, or `null` on no match.\n */\nexport function matchPattern(\n pattern: string,\n pathname: string,\n): Record<string, string> | null {\n // Whole-pattern wildcard: matches everything.\n if (pattern === '*') {\n return { '*': normalizePath(pathname).slice(1) };\n }\n\n const patSegs = segments(pattern);\n const pathSegs = segments(normalizePath(pathname));\n const params: Record<string, string> = {};\n\n for (let i = 0; i < patSegs.length; i++) {\n const patSeg = patSegs[i]!;\n\n // Trailing catch-all: capture the rest of the path.\n if (patSeg === '*') {\n params['*'] = pathSegs.slice(i).map((s) => decodeURIComponent(s)).join('/');\n return params;\n }\n\n const pathSeg = pathSegs[i];\n if (pathSeg === undefined) return null; // path ran out of segments\n\n if (patSeg.startsWith(':')) {\n const name = patSeg.slice(1);\n if (name === '') return null; // malformed `:` with no name\n params[name] = decodeURIComponent(pathSeg);\n continue;\n }\n\n if (patSeg !== pathSeg) return null; // literal mismatch\n }\n\n // All pattern segments consumed — the path must be fully consumed too.\n if (pathSegs.length !== patSegs.length) return null;\n return params;\n}\n\nexport interface MatchResult<R> {\n readonly route: R;\n readonly params: Record<string, string>;\n}\n\n/**\n * Match a pathname against an ordered list of routes. The first route whose\n * pattern matches wins (definition order), so more specific routes should be\n * listed before a `*` fallback.\n */\nexport function matchRoutes<R extends { path: string }>(\n routes: readonly R[],\n pathname: string,\n): MatchResult<R> | null {\n for (const route of routes) {\n const params = matchPattern(route.path, pathname);\n if (params !== null) return { route, params };\n }\n return null;\n}\n\n/** Split a `to` target into its pathname and (already-stripped) search string. */\nexport function splitTarget(to: string): { pathname: string; search: string } {\n const hashIndex = to.indexOf('#');\n const withoutHash = hashIndex >= 0 ? to.slice(0, hashIndex) : to;\n const qIndex = withoutHash.indexOf('?');\n if (qIndex < 0) return { pathname: normalizePath(withoutHash), search: '' };\n return {\n pathname: normalizePath(withoutHash.slice(0, qIndex)),\n search: withoutHash.slice(qIndex + 1),\n };\n}\n","/**\n * Router history — a small abstraction over the navigation source so the router\n * can run both in the browser (real `window.history` + `popstate`) and in tests\n * (an in-memory stack, fully deterministic, no globals).\n *\n * Internal navigation never triggers a full-page reload: the browser history\n * uses `pushState`/`replaceState` and notifies listeners synchronously.\n */\n\nexport interface RouterLocation {\n /** Pathname, always normalized with a single leading slash. */\n readonly pathname: string;\n /** Query string without the leading `?`. */\n readonly search: string;\n}\n\nexport interface RouterHistory {\n /** The current location. */\n location(): RouterLocation;\n /** Push a new entry and notify listeners. */\n push(pathname: string, search: string): void;\n /** Replace the current entry and notify listeners. */\n replace(pathname: string, search: string): void;\n /** Go back one entry. */\n back(): void;\n /** Go forward one entry. */\n forward(): void;\n /** Subscribe to location changes. Returns an unsubscribe function. */\n listen(cb: () => void): () => void;\n /** Detach any global listeners (browser only). */\n dispose(): void;\n}\n\nfunction buildLocation(pathname: string, search: string): RouterLocation {\n return { pathname, search };\n}\n\nfunction toUrl(pathname: string, search: string): string {\n return search.length > 0 ? `${pathname}?${search}` : pathname;\n}\n\n/**\n * Browser history backed by `window.history`. `pushState`/`replaceState` do not\n * emit `popstate`, so we notify listeners ourselves after those calls; genuine\n * back/forward navigation arrives via the `popstate` event.\n */\nexport function createBrowserHistory(): RouterHistory {\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const cb of listeners) cb();\n };\n const onPopState = (): void => notify();\n window.addEventListener('popstate', onPopState);\n\n const current = (): RouterLocation => {\n const loc = window.location;\n return buildLocation(loc.pathname, loc.search.replace(/^\\?/, ''));\n };\n\n return {\n location: current,\n push(pathname, search) {\n window.history.pushState({}, '', toUrl(pathname, search));\n notify();\n },\n replace(pathname, search) {\n window.history.replaceState({}, '', toUrl(pathname, search));\n notify();\n },\n back() {\n window.history.back(); // async → emits popstate\n },\n forward() {\n window.history.forward(); // async → emits popstate\n },\n listen(cb) {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n dispose() {\n window.removeEventListener('popstate', onPopState);\n listeners.clear();\n },\n };\n}\n\n/**\n * In-memory history for tests and non-DOM environments. Maintains an explicit\n * stack and cursor so `back()`/`forward()` are deterministic.\n */\nexport function createMemoryHistory(initial = '/'): RouterHistory {\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const cb of listeners) cb();\n };\n\n const parse = (entry: string): RouterLocation => {\n const qIndex = entry.indexOf('?');\n if (qIndex < 0) return buildLocation(entry, '');\n return buildLocation(entry.slice(0, qIndex), entry.slice(qIndex + 1));\n };\n\n const stack: string[] = [initial];\n let index = 0;\n\n return {\n location() {\n return parse(stack[index]!);\n },\n push(pathname, search) {\n // Drop any forward entries, then append.\n stack.splice(index + 1);\n stack.push(toUrl(pathname, search));\n index = stack.length - 1;\n notify();\n },\n replace(pathname, search) {\n stack[index] = toUrl(pathname, search);\n notify();\n },\n back() {\n if (index > 0) {\n index--;\n notify();\n }\n },\n forward() {\n if (index < stack.length - 1) {\n index++;\n notify();\n }\n },\n listen(cb) {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n dispose() {\n listeners.clear();\n },\n };\n}\n","/**\n * StreetUI Router core — renderer-agnostic.\n *\n * Holds the route table, resolves the current location into a `RouteMatch`,\n * and exposes that match as a StreetUI `signal`. Navigation is delegated to a\n * `RouterHistory`; when the location changes (via `navigate`, `back`, `forward`,\n * or a browser `popstate`) the router recomputes the match and updates the\n * signal, which is how every consumer (`isActive`, the mount integration, any\n * `derived` the app builds) stays in sync. No second reactive system.\n */\n\nimport { signal, derived, type ReadonlySignal } from '@streetui/state';\nimport type { RouterHistory } from './history.js';\nimport { createBrowserHistory } from './history.js';\nimport { matchRoutes, normalizePath, splitTarget } from './matching.js';\nimport type { RouteDefinition, RouteMatch } from './types.js';\n\nexport interface RouterOptions {\n /** The route table. Order matters — the first matching pattern wins. */\n readonly routes: readonly RouteDefinition[];\n /**\n * Navigation source. Defaults to a browser history. Pass a memory history\n * for tests or non-DOM environments.\n */\n readonly history?: RouterHistory;\n /**\n * Fallback route used when nothing else matches and no `*` route is present.\n * Defaults to a built-in 404 page (a normal StreetUI tree — no special path).\n */\n readonly notFound?: RouteDefinition;\n}\n\nexport interface NavigateOptions {\n /** Replace the current history entry instead of pushing a new one. */\n readonly replace?: boolean;\n}\n\nexport interface IsActiveOptions {\n /** Require an exact pathname match rather than a prefix match. */\n readonly exact?: boolean;\n}\n\nexport interface Router {\n /** Reactive current match. Consumers subscribe via StreetUI signals. */\n readonly currentRoute: ReadonlySignal<RouteMatch>;\n /** Navigate to a target path (may include a query string). */\n navigate(to: string, options?: NavigateOptions): void;\n /** Go back one history entry. */\n back(): void;\n /** Go forward one history entry. */\n forward(): void;\n /** Reactive predicate: is `path` the active route (or a prefix of it)? */\n isActive(path: string, options?: IsActiveOptions): ReadonlySignal<boolean>;\n /** Tear down history listeners. */\n destroy(): void;\n}\n\n/** Built-in 404 route — a normal StreetUI page tree, overridable via a `*` route. */\nconst DEFAULT_NOT_FOUND: RouteDefinition = {\n path: '*',\n builder: (page) => {\n page.section('not-found', (s) => {\n s.heading('404 — Page not found', { level: 1, id: 'not-found-title' });\n s.text('The page you were looking for does not exist.', { id: 'not-found-text' });\n s.link('Go home', { href: '/', id: 'not-found-home' });\n }, { id: 'not-found' });\n },\n};\n\nexport function createRouter(options: RouterOptions): Router {\n const routes = options.routes;\n const history = options.history ?? createBrowserHistory();\n const fallback = options.notFound ?? DEFAULT_NOT_FOUND;\n\n const resolve = (): RouteMatch => {\n const loc = history.location();\n const pathname = normalizePath(loc.pathname);\n const query = new URLSearchParams(loc.search);\n const matched = matchRoutes(routes, pathname);\n if (matched !== null) {\n return {\n path: pathname,\n pattern: matched.route.path,\n params: matched.params,\n query,\n route: matched.route,\n // A catch-all `*` match is the 404 route whether user-supplied or built-in.\n isFallback: matched.route.path === '*',\n };\n }\n // No explicit route matched — use the fallback (a `*` route if the table\n // has one, otherwise the built-in 404).\n const fallbackParams =\n matchRoutes([fallback], pathname)?.params ?? {};\n return {\n path: pathname,\n pattern: fallback.path,\n params: fallbackParams,\n query,\n route: fallback,\n isFallback: true,\n };\n };\n\n const current = signal<RouteMatch>(resolve());\n const stopListening = history.listen(() => {\n current.set(resolve());\n });\n\n const navigate = (to: string, opts: NavigateOptions = {}): void => {\n const { pathname, search } = splitTarget(to);\n if (opts.replace === true) history.replace(pathname, search);\n else history.push(pathname, search);\n };\n\n const isActive = (path: string, opts: IsActiveOptions = {}): ReadonlySignal<boolean> => {\n const target = normalizePath(path);\n const exact = opts.exact === true;\n return derived(() => {\n const activePath = current.get().path;\n if (activePath === target) return true;\n if (exact || target === '/') return false;\n return activePath.startsWith(`${target}/`);\n });\n };\n\n return {\n currentRoute: current,\n navigate,\n back: () => history.back(),\n forward: () => history.forward(),\n isActive,\n destroy: () => {\n stopListening();\n history.dispose();\n },\n };\n}\n","/**\n * StreetUI Router — DOM integration.\n *\n * `mountRouter` wires a `Router` to real DOM:\n *\n * 1. Mounts an optional persistent shell (layout + navigation) ONCE. The shell\n * declares an outlet element (see `routerOutlet`) into which route content\n * is rendered.\n * 2. Subscribes to `router.currentRoute`. On every change it disposes the\n * previous route (route-scoped `CleanupRegistry.run()` + `runtime.unmount()`)\n * and mounts the new route's compiled application into the outlet.\n * Only the outlet subtree is re-created — the shell persists.\n * 3. Intercepts clicks on internal `<a>` elements for client-side navigation.\n * External links (absolute URLs, `target=\"_blank\"`, `mailto:`/`tel:`) keep\n * their normal browser behaviour, and `link()` is used unchanged.\n *\n * Each route is an ordinary compiled StreetUI application — no special renderer\n * path, no virtual DOM, no full-application rerender on navigation.\n */\n\nimport { streetui, type PageDSL, type ContainerDSL } from '@streetui/dsl';\nimport { compile } from '@streetui/compiler';\nimport { createRuntime, type MountedApplication, type StreetRenderer } from '@streetui/runtime';\nimport { createRenderer } from '@streetui/renderer';\nimport { CleanupRegistry } from '@streetui/core';\nimport type { Router } from './router.js';\nimport type { RouteContext, RouteMatch } from './types.js';\n\n/** Default id used for the route outlet element inside a shell. */\nexport const ROUTER_OUTLET_ID = 'streetui-router-outlet';\n\n/**\n * Declare the route outlet inside a shell builder. The router replaces this\n * element's contents on every navigation.\n */\nexport function routerOutlet(scope: ContainerDSL, id: string = ROUTER_OUTLET_ID): void {\n scope.container('router-outlet', () => { /* filled by the router at runtime */ }, { id });\n}\n\nexport type ShellBuilder = (shell: PageDSL, router: Router) => void;\n\nexport interface MountRouterOptions {\n /** Element to mount into. With a shell, the shell fills this; otherwise routes do. */\n readonly container: Element;\n /** Optional persistent layout. Must include a `routerOutlet(...)`. */\n readonly shell?: ShellBuilder;\n /** Id of the outlet element within the shell. Defaults to `ROUTER_OUTLET_ID`. */\n readonly outletId?: string;\n /** Override the renderer (e.g. a custom DOM adapter for tests). */\n readonly renderer?: StreetRenderer;\n /** Intercept internal `<a>` clicks for client-side navigation. Defaults to true. */\n readonly interceptLinks?: boolean;\n /**\n * Hydrate server-rendered HTML already present in the container instead of\n * mounting fresh. The shell and the *initial* route adopt the existing DOM;\n * subsequent client-side navigations mount normally. Defaults to false.\n */\n readonly hydrate?: boolean;\n}\n\nexport interface MountedRouter {\n /** The element route content is rendered into. */\n readonly outlet: Element;\n /** Tear down the current route, the shell, link interception and the router. */\n unmount(): void;\n}\n\n/** A URL is external when it targets another origin or a non-navigational scheme. */\nfunction isExternalHref(href: string): boolean {\n return (\n /^[a-zA-Z][a-zA-Z\\d+.-]*:/.test(href) || // scheme: http:, https:, mailto:, tel:\n href.startsWith('//') // protocol-relative\n );\n}\n\nexport function mountRouter(router: Router, options: MountRouterOptions): MountedRouter {\n const { container } = options;\n const renderer = options.renderer ?? createRenderer();\n const outletId = options.outletId ?? ROUTER_OUTLET_ID;\n const interceptLinks = options.interceptLinks ?? true;\n const hydrateMode = options.hydrate ?? false;\n\n // ── 1. Mount the shell once (if any) and resolve the outlet ──────────────────\n let shellMounted: MountedApplication | null = null;\n let outlet: Element;\n\n if (options.shell !== undefined) {\n const shellApp = streetui.app({ name: 'router-shell' });\n const shellBuilder = options.shell;\n shellApp.page('shell', (page) => shellBuilder(page, router));\n const shellRuntime = createRuntime({ renderer });\n const shellCompiled = compile(shellApp);\n if (hydrateMode) {\n // The outlet is a slot the router fills. When the shell hydrates, mark the\n // outlet node as a hydration boundary so shell hydration adopts the outlet\n // element itself but preserves the server-rendered route content inside it\n // (instead of stripping it as surplus). The initial route then hydrates\n // that content node-for-node.\n for (const node of shellCompiled.graph.findAll((n) => n.getProp('id') === outletId)) {\n node.setProp('_hydrationBoundary', true);\n }\n }\n shellMounted = hydrateMode\n ? shellRuntime.hydrate(shellCompiled, container)\n : shellRuntime.mount(shellCompiled, container);\n\n const found = container.querySelector(`[id=\"${outletId}\"]`);\n if (found === null) {\n throw new Error(\n `[Router] The shell must contain a route outlet. Call routerOutlet(scope) ` +\n `(or add a container with id=\"${outletId}\") inside your shell builder.`,\n );\n }\n outlet = found;\n } else {\n outlet = container;\n }\n\n // ── 2. Route mounting / disposal ─────────────────────────────────────────────\n interface ActiveRoute {\n readonly registry: CleanupRegistry;\n readonly mounted: MountedApplication;\n }\n let active: ActiveRoute | null = null;\n // Only the very first route render hydrates the server HTML in the outlet;\n // client-side navigations after that mount fresh.\n let firstRender = hydrateMode;\n\n const disposeActive = (): void => {\n if (active === null) return;\n // Run user-registered cleanup (effects, subscriptions) FIRST, then tear down\n // the DOM + runtime signal bindings. Both reuse existing machinery.\n active.registry.run();\n active.mounted.unmount();\n active = null;\n };\n\n const renderRoute = (match: RouteMatch): void => {\n disposeActive();\n\n const registry = new CleanupRegistry();\n const ctx: RouteContext = {\n path: match.path,\n pattern: match.pattern,\n params: match.params,\n query: match.query,\n onCleanup: (fn) => registry.add(fn),\n };\n\n const routeApp = streetui.app({ name: `route:${match.pattern}` });\n routeApp.page('route', (page) => match.route.builder(page, ctx));\n const runtime = createRuntime({ renderer });\n const routeCompiled = compile(routeApp);\n const mounted = firstRender\n ? runtime.hydrate(routeCompiled, outlet)\n : runtime.mount(routeCompiled, outlet);\n firstRender = false;\n\n active = { registry, mounted };\n };\n\n // Initial render, then react to every route change.\n renderRoute(router.currentRoute.peek());\n const stopRouteSub = router.currentRoute.subscribe((match) => renderRoute(match));\n\n // ── 3. Client-side link interception ─────────────────────────────────────────\n const onClick = (event: Event): void => {\n if (event.defaultPrevented) return;\n const mouse = event as MouseEvent;\n if (typeof mouse.button === 'number' && mouse.button !== 0) return;\n if (mouse.metaKey || mouse.ctrlKey || mouse.shiftKey || mouse.altKey) return;\n\n const target = event.target as Element | null;\n const anchor = target?.closest?.('a') ?? null;\n if (anchor === null) return;\n\n const targetAttr = anchor.getAttribute('target');\n if (targetAttr !== null && targetAttr !== '_self') return; // _blank etc.\n\n const href = anchor.getAttribute('href');\n if (href === null || href === '' || href.startsWith('#')) return;\n if (isExternalHref(href)) return;\n\n event.preventDefault();\n router.navigate(href);\n };\n\n if (interceptLinks) {\n container.addEventListener('click', onClick);\n }\n\n // ── Teardown ─────────────────────────────────────────────────────────────────\n return {\n outlet,\n unmount() {\n if (interceptLinks) container.removeEventListener('click', onClick);\n stopRouteSub();\n disposeActive();\n shellMounted?.unmount();\n router.destroy();\n },\n };\n}\n","/**\n * A small, sync validation system.\n *\n * A `Validator` maps a string field value to an error message, or `undefined`\n * when the value is acceptable. This is deliberately tiny — the built-ins cover\n * the common cases (`required`, `minLength`, `maxLength`, `email`, `pattern`)\n * and anything else is just a plain function `(value: string) => string | undefined`.\n *\n * Validators for a field run in order and the FIRST error wins, so list\n * `required` first if a field is mandatory.\n *\n * Async validation is intentionally NOT part of this core. It can be layered on\n * top with `@streetui/state`'s `resource()` (kick off a resource on value\n * change and surface `resource.error` alongside the field error) without\n * destabilising the synchronous validity model here.\n */\n\nexport type Validator = (value: string) => string | undefined;\n\n/** Fails when the trimmed value is empty. */\nexport function required(message = 'This field is required'): Validator {\n return (value) => (value.trim().length === 0 ? message : undefined);\n}\n\n/** Fails when the value is shorter than `length` characters. */\nexport function minLength(length: number, message?: string): Validator {\n return (value) =>\n value.length < length\n ? (message ?? `Must be at least ${length} characters`)\n : undefined;\n}\n\n/** Fails when the value is longer than `length` characters. */\nexport function maxLength(length: number, message?: string): Validator {\n return (value) =>\n value.length > length\n ? (message ?? `Must be at most ${length} characters`)\n : undefined;\n}\n\n// Pragmatic, dependency-free email shape check (not a full RFC 5322 parser).\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** Fails when a non-empty value is not a plausible email address. */\nexport function email(message = 'Enter a valid email address'): Validator {\n return (value) => (value.length === 0 || EMAIL_RE.test(value) ? undefined : message);\n}\n\n/** Fails when a non-empty value does not match `regex`. */\nexport function pattern(regex: RegExp, message = 'Invalid format'): Validator {\n return (value) => (value.length === 0 || regex.test(value) ? undefined : message);\n}\n\n/** Run a validator (or ordered list) and return the first error, if any. */\nexport function runValidators(\n value: string,\n validators: Validator | ReadonlyArray<Validator> | undefined,\n): string | undefined {\n if (validators === undefined) return undefined;\n const list = Array.isArray(validators) ? validators : [validators];\n for (const validate of list) {\n const error = validate(value);\n if (error !== undefined) return error;\n }\n return undefined;\n}\n","/**\n * Reactive form model built entirely on `@streetui/state` signals.\n *\n * There is no second state system here: every piece of form state (`values`,\n * `errors`, `touched`, `dirty`, `valid`, submission status) is a signal or a\n * derived signal, so it composes with the renderer's existing reactive bindings.\n * A field's `value` is a writable `Signal<string>`, which plugs straight into\n * the DSL's `input({ bind })` — typing updates form state and programmatic\n * updates update the input, through the one binding the renderer already wires.\n */\n\nimport {\n signal,\n derived,\n batch,\n DerivedSignal,\n type Signal,\n type ReadonlySignal,\n type Unsubscribe,\n} from '@streetui/state';\nimport { type Validator, runValidators } from './validators.js';\n\n/** Form values are a flat, typed record of string fields (HTML input values). */\nexport type FormValues = Record<string, string>;\n\nexport interface Field {\n readonly name: string;\n /** Writable value signal — pass to `input({ bind: field.value })`. */\n readonly value: Signal<string>;\n /** Current validation error, or `undefined` when the field is valid. */\n readonly error: ReadonlySignal<string | undefined>;\n /** True once the field has received a genuine user interaction. */\n readonly touched: ReadonlySignal<boolean>;\n /** True when the value differs from its initial value. */\n readonly dirty: ReadonlySignal<boolean>;\n /** True when the field has no validation error. */\n readonly valid: ReadonlySignal<boolean>;\n /** Programmatically set the value (does not mark the field touched). */\n setValue(next: string): void;\n /** Force the touched flag (defaults to true). */\n markTouched(touched?: boolean): void;\n /** Restore this field's initial value and clear its touched flag. */\n reset(): void;\n}\n\nexport type FormValidators<T extends FormValues> = {\n readonly [K in keyof T]?: Validator | ReadonlyArray<Validator>;\n};\n\nexport interface FormConfig<T extends FormValues> {\n readonly initialValues: T;\n readonly validators?: FormValidators<T>;\n /** Called by `submit()` once all fields are valid. May be async. */\n readonly onSubmit?: (values: T) => void | Promise<void>;\n}\n\nexport type SubmitStatus = 'idle' | 'submitting' | 'success' | 'error';\n\nexport interface Form<T extends FormValues> {\n readonly values: ReadonlySignal<T>;\n readonly errors: ReadonlySignal<Partial<Record<keyof T, string>>>;\n readonly touched: ReadonlySignal<Partial<Record<keyof T, boolean>>>;\n readonly dirty: ReadonlySignal<boolean>;\n readonly valid: ReadonlySignal<boolean>;\n readonly submitting: ReadonlySignal<boolean>;\n readonly submitted: ReadonlySignal<boolean>;\n readonly status: ReadonlySignal<SubmitStatus>;\n readonly submitError: ReadonlySignal<unknown>;\n /** Access the reactive state + setters for one field. */\n field<K extends keyof T & string>(name: K): Field;\n /** Merge a partial set of values in (does not mark fields touched). */\n setValues(partial: Partial<T>): void;\n /** Validate, mark all fields touched, then run `onSubmit` if valid. */\n submit(): Promise<void>;\n /** Restore initial values and clear errors/touched/dirty/submission state. */\n reset(): void;\n /** Tear down all field subscriptions and derived signals. */\n dispose(): void;\n}\n\ninterface FieldInternal {\n readonly api: Field;\n readonly value: Signal<string>;\n readonly touched: Signal<boolean>;\n readonly error: DerivedSignal<string | undefined>;\n readonly valid: DerivedSignal<boolean>;\n readonly dirty: DerivedSignal<boolean>;\n readonly initial: string;\n readonly unsub: Unsubscribe;\n}\n\n// __FORM_IMPL__\n\nexport function createForm<T extends FormValues>(config: FormConfig<T>): Form<T> {\n const names = Object.keys(config.initialValues) as Array<keyof T & string>;\n const validators = config.validators ?? ({} as FormValidators<T>);\n\n // While true, value changes originate from setValues()/reset() and must NOT\n // mark a field touched. Batch flushes run synchronously inside batch(), i.e.\n // before this flag is reset, so guarding around batch() is sound.\n let programmatic = false;\n\n const fields = new Map<string, FieldInternal>();\n\n for (const name of names) {\n // Keys come from Object.keys(initialValues), so the value is always present;\n // the annotation defeats noUncheckedIndexedAccess widening to `| undefined`.\n const initial: string = config.initialValues[name] as string;\n const value = signal<string>(initial);\n const touched = signal<boolean>(false);\n const error = derived<string | undefined>(() =>\n runValidators(value.get(), validators[name]),\n );\n const valid = derived<boolean>(() => error.get() === undefined);\n const dirty = derived<boolean>(() => value.get() !== initial);\n\n // Mark touched on the first genuine (non-programmatic) value change.\n const unsub = value.subscribe(() => {\n if (!programmatic) touched.set(true);\n });\n\n const api: Field = {\n name,\n value,\n error,\n touched,\n dirty,\n valid,\n setValue(next: string): void {\n value.set(next);\n },\n markTouched(next = true): void {\n touched.set(next);\n },\n reset(): void {\n programmatic = true;\n try {\n batch(() => {\n value.set(initial);\n touched.set(false);\n });\n } finally {\n programmatic = false;\n }\n },\n };\n\n fields.set(name, { api, value, touched, error, valid, dirty, initial, unsub });\n }\n\n const field = (name: string): FieldInternal => {\n const f = fields.get(name);\n if (f === undefined) throw new Error(`Unknown form field: ${name}`);\n return f;\n };\n\n const values = derived<T>(() => {\n const out: Record<string, string> = {};\n for (const name of names) out[name] = field(name).value.get();\n return out as T;\n });\n\n const errors = derived<Partial<Record<keyof T, string>>>(() => {\n const out: Partial<Record<keyof T, string>> = {};\n for (const name of names) {\n const e = field(name).error.get();\n if (e !== undefined) out[name] = e;\n }\n return out;\n });\n\n const touchedMap = derived<Partial<Record<keyof T, boolean>>>(() => {\n const out: Partial<Record<keyof T, boolean>> = {};\n for (const name of names) out[name] = field(name).touched.get();\n return out;\n });\n\n const dirty = derived<boolean>(() => names.some((n) => field(n).dirty.get()));\n const valid = derived<boolean>(() => names.every((n) => field(n).valid.get()));\n\n const status = signal<SubmitStatus>('idle');\n const submitting = derived<boolean>(() => status.get() === 'submitting');\n const submitted = derived<boolean>(() => status.get() === 'success');\n const submitError = signal<unknown>(undefined);\n\n function setValues(partial: Partial<T>): void {\n programmatic = true;\n try {\n batch(() => {\n for (const name of names) {\n const next = partial[name];\n if (next !== undefined) field(name).value.set(next);\n }\n });\n } finally {\n programmatic = false;\n }\n }\n\n function reset(): void {\n programmatic = true;\n try {\n batch(() => {\n for (const name of names) {\n const f = field(name);\n f.value.set(f.initial);\n f.touched.set(false);\n }\n status.set('idle');\n submitError.set(undefined);\n });\n } finally {\n programmatic = false;\n }\n }\n\n async function submit(): Promise<void> {\n // Touch every field so validation errors become visible on submit attempts.\n batch(() => {\n for (const name of names) field(name).touched.set(true);\n });\n if (!valid.peek()) {\n // Invalid — do not enter the submitting lifecycle; field errors now show.\n return;\n }\n submitError.set(undefined);\n status.set('submitting');\n try {\n await config.onSubmit?.(values.peek());\n status.set('success');\n } catch (err) {\n submitError.set(err);\n status.set('error');\n }\n }\n\n function dispose(): void {\n for (const f of fields.values()) {\n f.unsub();\n f.error.dispose();\n f.valid.dispose();\n f.dirty.dispose();\n }\n values.dispose();\n errors.dispose();\n touchedMap.dispose();\n dirty.dispose();\n valid.dispose();\n submitting.dispose();\n submitted.dispose();\n }\n\n return {\n values,\n errors,\n touched: touchedMap,\n dirty,\n valid,\n submitting,\n submitted,\n status,\n submitError,\n field: (name) => field(name).api,\n setValues,\n submit,\n reset,\n dispose,\n };\n}\n\n","/**\n * @streetui/context — build-time provider/consumer scoping.\n *\n * StreetUI builds its semantic tree synchronously, top-down, when the DSL\n * builders run. A `Context` mirrors that shape: `provide(value, run)` pushes a\n * value for the duration of the synchronous `run()` (during which the child\n * DSL builders execute and may `consume()`), then pops it. Consumers resolve\n * the *nearest* enclosing provider, falling back to the context default.\n *\n * This is deliberately NOT a second reactive system. A context value can be a\n * signal (see @streetui/state); reactivity then belongs to that signal and is\n * torn down by the normal node lifecycle when the consuming subtree unmounts —\n * the context itself holds no subscriptions and leaves no refs behind after a\n * `provide()` call returns.\n */\n\nexport interface Context<T> {\n /** Unique identity for this context (useful for debugging/inspection). */\n readonly id: symbol;\n /** The value returned by {@link consume} when no provider is active. */\n readonly defaultValue: T;\n /**\n * Provide `value` to any `consume()` calls made synchronously inside `run`.\n * The value is popped again as soon as `run` returns (even if it throws),\n * so nesting resolves to the nearest active provider.\n */\n provide<R>(value: T, run: () => R): R;\n /** Read the nearest active provider's value, or {@link defaultValue}. */\n consume(): T;\n /** True while at least one provider is active for this context. */\n hasProvider(): boolean;\n}\n\n/**\n * Create a typed context with a required default value, so `consume()` always\n * returns a `T` (never `undefined` unless `T` itself permits it).\n */\nexport function createContext<T>(defaultValue: T, description?: string): Context<T> {\n const id = Symbol(description ?? 'streetui.context');\n const stack: T[] = [];\n\n return {\n id,\n defaultValue,\n provide<R>(value: T, run: () => R): R {\n stack.push(value);\n try {\n return run();\n } finally {\n stack.pop();\n }\n },\n consume(): T {\n return stack.length > 0 ? (stack[stack.length - 1] as T) : defaultValue;\n },\n hasProvider(): boolean {\n return stack.length > 0;\n },\n };\n}\n","/**\n * Minimal, framework-native internationalization for StreetUI.\n *\n * Built entirely on `@streetui/state` signals — there is no second reactive\n * system. The active locale is a writable signal; `t()` returns a derived\n * signal that recomputes when the locale changes, so translations plug\n * straight into the DSL's reactive text bindings (`text(() => i18n.t(...).get())`\n * or `text(i18n.t(...))`).\n *\n * Translation is deterministic: a missing key resolves to the key itself, and\n * the same (locale, key, params) always produces the same string on the server\n * and the client. That determinism is what keeps `renderToString()` and\n * `hydrate()` in agreement — provided the app boots the client with the same\n * initial locale it rendered with on the server.\n */\n\nimport {\n signal,\n derived,\n type ReadonlySignal,\n type DerivedSignal,\n} from '@streetui/state';\n\n/** A flat dictionary of message templates for a single locale. */\nexport type MessageMap = Record<string, string>;\n\n/** Values allowed in interpolation params. */\nexport type InterpolationParams = Record<string, string | number>;\n\nexport interface I18nConfig<M extends MessageMap> {\n /** The initial (and server-rendered) locale. */\n readonly locale: string;\n /** Messages keyed by locale, e.g. `{ en: {...}, fr: {...} }`. */\n readonly messages: Readonly<Record<string, M>>;\n /** Locale consulted when a key is absent from the active locale. */\n readonly fallbackLocale?: string;\n}\n\nexport interface I18n<M extends MessageMap> {\n /** The active locale as a reactive, read-only signal. */\n readonly locale: ReadonlySignal<string>;\n /** Switch the active locale; all `t()`/`plural()` signals recompute. */\n setLocale(locale: string): void;\n /** The locales that have a message map, in declaration order. */\n readonly locales: ReadonlyArray<string>;\n /** Reactive translation. Returns a derived signal — call `.get()` to read. */\n t(key: keyof M & string, params?: InterpolationParams): ReadonlySignal<string>;\n /** Non-reactive translation for the current locale (a one-shot read). */\n translate(key: keyof M & string, params?: InterpolationParams): string;\n /**\n * Reactive pluralization via `Intl.PluralRules`. Selects the message whose\n * key is `${key}.${category}` (e.g. `items.one`), falling back to\n * `${key}.other`. `count` is available to interpolation as `{count}`.\n */\n plural(key: string, count: number, params?: InterpolationParams): ReadonlySignal<string>;\n /** True when the active (or fallback) locale defines `key`. */\n has(key: string): boolean;\n}\n\nconst INTERPOLATION = /\\{(\\w+)\\}/g;\n\n/** Replace `{name}` placeholders using `params`; unknown names are left intact. */\nexport function interpolate(template: string, params?: InterpolationParams): string {\n if (params === undefined) return template;\n return template.replace(INTERPOLATION, (whole, name: string) => {\n const value = params[name];\n return value === undefined ? whole : String(value);\n });\n}\n\nexport function createI18n<M extends MessageMap>(config: I18nConfig<M>): I18n<M> {\n const messages = config.messages;\n const fallback = config.fallbackLocale;\n const localeSignal = signal<string>(config.locale);\n const locales = Object.keys(messages);\n\n /** Resolve a raw template for `key` in `loc`, then the fallback locale. */\n function lookup(loc: string, key: string): string | undefined {\n const active = messages[loc];\n const hit = active === undefined ? undefined : active[key];\n if (hit !== undefined) return hit;\n if (fallback !== undefined && fallback !== loc) {\n const fb = messages[fallback];\n if (fb !== undefined) return fb[key];\n }\n return undefined;\n }\n\n function resolve(loc: string, key: string, params?: InterpolationParams): string {\n const template = lookup(loc, key);\n // Deterministic miss: echo the key so output is stable server/client.\n return template === undefined ? key : interpolate(template, params);\n }\n\n function pluralKey(loc: string, key: string, count: number): string {\n const category = new Intl.PluralRules(loc).select(count);\n if (lookup(loc, `${key}.${category}`) !== undefined) return `${key}.${category}`;\n return `${key}.other`;\n }\n\n return {\n locale: localeSignal,\n locales,\n setLocale(loc: string): void {\n localeSignal.set(loc);\n },\n t(key, params): DerivedSignal<string> {\n return derived<string>(() => resolve(localeSignal.get(), key, params));\n },\n translate(key, params): string {\n return resolve(localeSignal.peek(), key, params);\n },\n plural(key, count, params): DerivedSignal<string> {\n const merged: InterpolationParams = { count, ...(params ?? {}) };\n return derived<string>(() => {\n const loc = localeSignal.get();\n return resolve(loc, pluralKey(loc, key, count), merged);\n });\n },\n has(key: string): boolean {\n return lookup(localeSignal.peek(), key) !== undefined;\n },\n };\n}\n","/**\n * StreetUI DevTools — graph inspector and debug utilities.\n */\n\nimport { formatDiagnostic } from '@streetui/core';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { CompiledApplication } from '@streetui/compiler';\n\nexport interface InspectedNode {\n id: string;\n type: string;\n key: string | undefined;\n props: Record<string, unknown>;\n eventTypes: string[];\n stateBindings: string[];\n children: InspectedNode[];\n depth: number;\n}\n\nexport function inspectGraph(graph: ApplicationGraph): InspectedNode {\n return inspectNode(graph.root, 0);\n}\n\nfunction inspectNode(node: GraphNode, depth: number): InspectedNode {\n return {\n id: node.id,\n type: node.type,\n key: node.key,\n props: { ...node.props },\n eventTypes: node.events.map(e => e.type),\n stateBindings: node.stateRefs.map(r => `${r.propKey}→${r.signalId}`),\n depth,\n children: node.children.map(c => inspectNode(c, depth + 1)),\n };\n}\n\n/** Print a human-readable tree of the graph to a string. */\nexport function printGraph(graph: ApplicationGraph): string {\n const lines: string[] = [];\n graph.walk((node, depth) => {\n const indent = ' '.repeat(depth);\n const props = Object.entries(node.props)\n .filter(([k]) => !k.startsWith('_'))\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(', ');\n const events = node.events.length > 0\n ? ` [events: ${node.events.map(e => e.type).join(', ')}]`\n : '';\n const stateRefs = node.stateRefs.length > 0\n ? ` [signals: ${node.stateRefs.map(r => r.propKey).join(', ')}]`\n : '';\n lines.push(`${indent}<${node.type}${props ? ` ${props}` : ''}${events}${stateRefs}>`);\n });\n return lines.join('\\n');\n}\n\n/** Print compilation diagnostics to a string. */\nexport function printDiagnostics(compiled: CompiledApplication): string {\n if (compiled.diagnostics.diagnostics.length === 0) {\n return '(no diagnostics)';\n }\n return compiled.diagnostics.diagnostics.map(formatDiagnostic).join('\\n');\n}\n\n/** Returns node counts per type. */\nexport function nodeTypeStats(graph: ApplicationGraph): Record<string, number> {\n const counts: Record<string, number> = {};\n graph.walk(node => {\n counts[node.type] = (counts[node.type] ?? 0) + 1;\n });\n return counts;\n}\n","/**\n * DevTools foundation (v0.6, Phase 18). A single read-only entry point that\n * aggregates everything an eventual DevTools UI would need — application\n * identity, the graph tree, signal bindings, page/route surface, node\n * statistics, and diagnostics — WITHOUT introducing a second representation of\n * the graph. It reuses `inspectGraph`/`nodeTypeStats` from the inspector and\n * reads `CompiledApplication` metadata directly. This is a foundation, not a\n * UI: it returns plain data so a UI (or a test, or a CLI command) can render it.\n */\n\nimport type { CompiledApplication } from '@streetui/compiler';\nimport { formatDiagnostic } from '@streetui/core';\nimport { inspectGraph, nodeTypeStats, type InspectedNode } from './inspector.js';\n\n/** Stable identity of a compiled application. */\nexport interface ApplicationIdentity {\n readonly name: string;\n readonly version: string;\n /** Epoch millis the application was compiled. */\n readonly compiledAt: number;\n}\n\n/** A page node reachable as a direct child of the application root. */\nexport interface InspectedPage {\n readonly id: string;\n /** The page key when one was supplied in the DSL. */\n readonly key: string | undefined;\n}\n\n/** Compilation diagnostics summarised for display. */\nexport interface DiagnosticsSummary {\n readonly errors: number;\n readonly warnings: number;\n readonly messages: string[];\n}\n\n/**\n * Cheap, count-only performance snapshot (v0.7 §20). These are structural\n * counts derived from a single graph walk — NOT timings and NOT a profiler.\n * They let a DevTools panel or a CI check spot the shapes that correlate with\n * slow apps (very large graphs, deep trees, big lists, many subscriptions)\n * without measuring anything at runtime.\n */\nexport interface PerfSnapshot {\n /** Total GraphNodes in the tree (root included). */\n readonly totalNodes: number;\n /** Maximum nesting depth (root = 0). */\n readonly maxDepth: number;\n /** Total event handler registrations across all nodes. */\n readonly eventHandlers: number;\n /** Total signal→prop bindings across all nodes. */\n readonly stateBindings: number;\n /** Distinct signals referenced anywhere in the graph. */\n readonly distinctSignals: number;\n /** Largest single-node child count (a proxy for the biggest list/section). */\n readonly largestChildCount: number;\n /**\n * Number of reactive keyed-list sites driven by the optimised lazy-plan\n * reconciler (v1.1 §15/§25). Counted from the graph's `__listplan__<id>`\n * handler registrations — one per `listOf(...)` bound to a signal. These are\n * the nodes whose updates take the identity-short-circuit + LIS minimal-move\n * path, so surfacing the count lets a panel or CI check see how much of an app\n * benefits from the keyed-list engine without measuring anything at runtime.\n */\n readonly reactiveLists: number;\n}\n\n/**\n * The complete read-only snapshot of a compiled application. Everything here is\n * derived from the single `CompiledApplication` graph — no state is duplicated.\n */\nexport interface ApplicationInspection {\n readonly identity: ApplicationIdentity;\n readonly graph: InspectedNode;\n /** Count of nodes per DSL type (e.g. `{ section: 2, button: 3 }`). */\n readonly nodeStats: Record<string, number>;\n /** Unique signal ids bound anywhere in the graph, sorted. */\n readonly signals: string[];\n /** Page nodes directly under the root — the app's top-level route surface. */\n readonly pages: InspectedPage[];\n readonly diagnostics: DiagnosticsSummary;\n /** Cheap structural performance counters (v0.7 §20). */\n readonly perf: PerfSnapshot;\n}\n\n/** Walk the inspected tree once, accumulating the count-only perf snapshot. */\nfunction collectPerf(\n node: InspectedNode,\n distinctSignals: number,\n acc: { totalNodes: number; maxDepth: number; eventHandlers: number; stateBindings: number; largestChildCount: number },\n): void {\n acc.totalNodes += 1;\n if (node.depth > acc.maxDepth) acc.maxDepth = node.depth;\n acc.eventHandlers += node.eventTypes.length;\n acc.stateBindings += node.stateBindings.length;\n if (node.children.length > acc.largestChildCount) acc.largestChildCount = node.children.length;\n for (const child of node.children) collectPerf(child, distinctSignals, acc);\n}\n\n/** Collect every distinct signal id referenced by any node in the tree. */\nfunction collectSignals(node: InspectedNode, into: Set<string>): void {\n for (const binding of node.stateBindings) {\n // Bindings are formatted `propKey→signalId` by the inspector.\n const arrow = binding.indexOf('→');\n const signalId = arrow >= 0 ? binding.slice(arrow + 1) : binding;\n if (signalId.length > 0) into.add(signalId);\n }\n for (const child of node.children) collectSignals(child, into);\n}\n\n/**\n * Build the full inspection snapshot for a compiled application. Pure and\n * side-effect free — safe to call in a server, a test, or a DevTools panel.\n */\nexport function inspectApplication(compiled: CompiledApplication): ApplicationInspection {\n const graph = inspectGraph(compiled.graph);\n\n const signals = new Set<string>();\n collectSignals(graph, signals);\n\n const pages: InspectedPage[] = graph.children\n .filter((child) => child.type === 'page')\n .map((child) => ({ id: child.id, key: child.key }));\n\n const diags = compiled.diagnostics.diagnostics;\n const errors = diags.filter((d) => d.severity === 'error').length;\n\n const perfAcc = { totalNodes: 0, maxDepth: 0, eventHandlers: 0, stateBindings: 0, largestChildCount: 0 };\n collectPerf(graph, signals.size, perfAcc);\n\n // Count optimised keyed-list sites from the handler registry (one\n // `__listplan__<id>` per signal-driven `listOf`). Reading the map directly\n // keeps this a pure, count-only derivation — no second graph walk.\n let reactiveLists = 0;\n for (const key of compiled.graph.handlers.keys()) {\n if (key.startsWith('__listplan__')) reactiveLists += 1;\n }\n\n return {\n identity: {\n name: compiled.name,\n version: compiled.version,\n compiledAt: compiled.compiledAt,\n },\n graph,\n nodeStats: nodeTypeStats(compiled.graph),\n signals: [...signals].sort(),\n pages,\n diagnostics: {\n errors,\n warnings: diags.length - errors,\n messages: diags.map(formatDiagnostic),\n },\n perf: {\n totalNodes: perfAcc.totalNodes,\n maxDepth: perfAcc.maxDepth,\n eventHandlers: perfAcc.eventHandlers,\n stateBindings: perfAcc.stateBindings,\n distinctSignals: signals.size,\n largestChildCount: perfAcc.largestChildCount,\n reactiveLists,\n },\n };\n}\n","/**\n * Dev-only performance diagnostics (v0.7 §21).\n *\n * A pure, cheap, count-based check that flags graph *shapes* known to correlate\n * with slow apps — very large graphs, deep trees, oversized lists/sections, and\n * heavy reactive fan-out. It is NOT wired into mount/render and adds ZERO cost\n * to the runtime hot path; a developer (or a CLI command, or a test) calls it\n * explicitly. Thresholds are advisory and overridable.\n *\n * This intentionally reuses the counts already produced by `inspectApplication`\n * — it introduces no second graph walk of its own beyond reading that snapshot.\n */\n\nimport type { CompiledApplication } from '@streetui/compiler';\nimport { inspectApplication } from './application.js';\n\nexport interface PerfThresholds {\n /** Warn when the graph exceeds this many nodes. */\n readonly maxNodes: number;\n /** Warn when nesting depth exceeds this. */\n readonly maxDepth: number;\n /** Warn when any single node has more than this many children (big list). */\n readonly maxChildCount: number;\n /** Warn when distinct signals exceed this (reactive fan-out). */\n readonly maxSignals: number;\n}\n\nexport const DEFAULT_PERF_THRESHOLDS: PerfThresholds = {\n maxNodes: 5000,\n maxDepth: 32,\n maxChildCount: 1000,\n maxSignals: 1000,\n};\n\nexport type PerfDiagnosticCode =\n | 'large-graph'\n | 'deep-tree'\n | 'large-list'\n | 'high-signal-fanout';\n\nexport interface PerfDiagnostic {\n readonly code: PerfDiagnosticCode;\n readonly message: string;\n /** The observed count that tripped the threshold. */\n readonly observed: number;\n /** The threshold it exceeded. */\n readonly threshold: number;\n}\n\n/**\n * Return advisory performance diagnostics for a compiled application. An empty\n * array means nothing tripped a threshold. Never throws; never mutates.\n */\nexport function diagnosePerformance(\n compiled: CompiledApplication,\n thresholds: Partial<PerfThresholds> = {},\n): PerfDiagnostic[] {\n const t = { ...DEFAULT_PERF_THRESHOLDS, ...thresholds };\n const { perf } = inspectApplication(compiled);\n const out: PerfDiagnostic[] = [];\n\n if (perf.totalNodes > t.maxNodes) {\n out.push({\n code: 'large-graph',\n message: `Graph has ${perf.totalNodes} nodes (> ${t.maxNodes}); consider splitting the view or paginating.`,\n observed: perf.totalNodes,\n threshold: t.maxNodes,\n });\n }\n if (perf.maxDepth > t.maxDepth) {\n out.push({\n code: 'deep-tree',\n message: `Graph nests ${perf.maxDepth} levels deep (> ${t.maxDepth}); deep trees slow mount and reconciliation.`,\n observed: perf.maxDepth,\n threshold: t.maxDepth,\n });\n }\n if (perf.largestChildCount > t.maxChildCount) {\n out.push({\n code: 'large-list',\n message: `A single node has ${perf.largestChildCount} children (> ${t.maxChildCount}); large un-windowed lists dominate DOM cost.`,\n observed: perf.largestChildCount,\n threshold: t.maxChildCount,\n });\n }\n if (perf.distinctSignals > t.maxSignals) {\n out.push({\n code: 'high-signal-fanout',\n message: `${perf.distinctSignals} distinct signals are bound (> ${t.maxSignals}); heavy reactive fan-out increases update overhead.`,\n observed: perf.distinctSignals,\n threshold: t.maxSignals,\n });\n }\n\n return out;\n}\n","/**\n * Reactive-surface inspection for DevTools.\n *\n * These functions turn the framework's live objects — signals, resources,\n * router, forms, context, i18n — into plain, read-only snapshots suitable for a\n * DevTools panel. They never mutate anything and never subscribe; each call is a\n * one-shot `peek`. Sensitive-by-default surfaces (resource payloads, form field\n * values) are omitted unless the caller explicitly opts in, so a panel cannot\n * accidentally display tokens, passwords, or private data.\n *\n * Router/forms/context/i18n are described by *structural* interfaces rather than\n * imported types, so DevTools stays decoupled from those packages (no extra\n * dependencies) while still inspecting them when present.\n */\n\nimport {\n type ReadonlySignal,\n type ResourceStatus,\n type SignalKind,\n signalKind,\n observerCount,\n} from '@streetui/state';\n\n// ── Signals ─────────────────────────────────────────────────────────────────\n\nexport interface SignalInspection {\n /** Whether the signal is writable or a derived computation. */\n readonly kind: SignalKind;\n /** The current value (redacted if requested). */\n readonly value: unknown;\n /** Live observer count when the signal exposes it, else undefined. */\n readonly observerCount: number | undefined;\n}\n\nexport interface InspectSignalOptions {\n /**\n * Redact the value: `true` replaces it with `'[redacted]'`; a function maps\n * the raw value to whatever should be shown. Use for signals that may hold\n * sensitive data. Omitted → the value is shown as-is.\n */\n readonly redact?: boolean | ((value: unknown) => unknown);\n}\n\n/** Snapshot a signal's kind, current value, and observer count. Read-only. */\nexport function inspectSignal(\n source: ReadonlySignal<unknown>,\n options: InspectSignalOptions = {},\n): SignalInspection {\n const raw = source.peek();\n let value: unknown = raw;\n if (options.redact === true) value = '[redacted]';\n else if (typeof options.redact === 'function') value = options.redact(raw);\n\n return {\n kind: signalKind(source),\n value,\n observerCount: observerCount(source),\n };\n}\n\n// ── Resources ─────────────────────────────────────────────────────────────\n\n/** The read-only slice of a resource this module needs. */\nexport interface ResourceLike {\n readonly status: ReadonlySignal<ResourceStatus>;\n readonly data: ReadonlySignal<unknown>;\n readonly error: ReadonlySignal<unknown>;\n readonly loading: ReadonlySignal<boolean>;\n readonly isRefetching: ReadonlySignal<boolean>;\n}\n\nexport interface ResourceInspection {\n readonly status: ResourceStatus;\n readonly loading: boolean;\n readonly isRefetching: boolean;\n readonly hasData: boolean;\n readonly hasError: boolean;\n /** The error's constructor name (safe — no message/payload). */\n readonly errorName: string | undefined;\n /** The error message — only present when `includeData` is set. */\n readonly errorMessage?: string;\n /** The loaded value — only present when `includeData` is set. */\n readonly data?: unknown;\n}\n\nexport interface InspectResourceOptions {\n /**\n * Include the loaded `data` and the error `message`. Off by default because a\n * resource payload commonly carries user or secret data.\n */\n readonly includeData?: boolean;\n}\n\n/** Snapshot a resource's lifecycle. Payload/message hidden unless opted in. */\nexport function inspectResource(\n resource: ResourceLike,\n options: InspectResourceOptions = {},\n): ResourceInspection {\n const error = resource.error.peek();\n const hasError = error !== undefined && error !== null;\n const base: ResourceInspection = {\n status: resource.status.peek(),\n loading: resource.loading.peek(),\n isRefetching: resource.isRefetching.peek(),\n hasData: resource.data.peek() !== undefined,\n hasError,\n errorName: hasError ? errorConstructorName(error) : undefined,\n };\n if (options.includeData !== true) return base;\n\n return {\n ...base,\n data: resource.data.peek(),\n ...(hasError ? { errorMessage: errorMessageOf(error) } : {}),\n };\n}\n\nfunction errorConstructorName(error: unknown): string {\n if (error instanceof Error) return error.name;\n return typeof error;\n}\n\nfunction errorMessageOf(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\n// ── Router ──────────────────────────────────────────────────────────────────\n\nexport interface RouteMatchLike {\n readonly path: string;\n readonly pattern: string;\n readonly params: Readonly<Record<string, string>>;\n readonly query: URLSearchParams;\n readonly isFallback?: boolean;\n}\n\nexport interface RouterLike {\n readonly currentRoute: ReadonlySignal<RouteMatchLike>;\n}\n\nexport interface RouterInspection {\n readonly path: string;\n readonly pattern: string;\n readonly params: Record<string, string>;\n readonly query: Record<string, string>;\n readonly isFallback: boolean;\n}\n\n/** Snapshot the router's current route. Read-only. */\nexport function inspectRouter(router: RouterLike): RouterInspection {\n const match = router.currentRoute.peek();\n const query: Record<string, string> = {};\n for (const [k, v] of match.query.entries()) query[k] = v;\n return {\n path: match.path,\n pattern: match.pattern,\n params: { ...match.params },\n query,\n isFallback: match.isFallback === true,\n };\n}\n\n// ── Forms ─────────────────────────────────────────────────────────────────\n\nexport interface FormLike {\n readonly values: ReadonlySignal<Record<string, unknown>>;\n readonly errors: ReadonlySignal<Record<string, string | undefined>>;\n readonly touched: ReadonlySignal<Record<string, boolean | undefined>>;\n readonly dirty: ReadonlySignal<boolean>;\n readonly valid: ReadonlySignal<boolean>;\n readonly status: ReadonlySignal<string>;\n}\n\nexport interface FormInspection {\n readonly fields: string[];\n /** Per-field validation messages (safe — not the entered values). */\n readonly errors: Record<string, string>;\n readonly touched: Record<string, boolean>;\n readonly dirty: boolean;\n readonly valid: boolean;\n readonly status: string;\n /** Entered field values — only present when `includeValues` is set. */\n readonly values?: Record<string, unknown>;\n}\n\nexport interface InspectFormOptions {\n /**\n * Include the entered field `values`. Off by default because form fields\n * frequently hold passwords or other secrets.\n */\n readonly includeValues?: boolean;\n}\n\n/** Snapshot form validation state. Entered values hidden unless opted in. */\nexport function inspectForm(form: FormLike, options: InspectFormOptions = {}): FormInspection {\n const values = form.values.peek();\n const errorsRaw = form.errors.peek();\n const touchedRaw = form.touched.peek();\n\n const errors: Record<string, string> = {};\n for (const [k, v] of Object.entries(errorsRaw)) if (v !== undefined) errors[k] = v;\n const touched: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(touchedRaw)) touched[k] = v === true;\n\n const base: FormInspection = {\n fields: Object.keys(values),\n errors,\n touched,\n dirty: form.dirty.peek(),\n valid: form.valid.peek(),\n status: form.status.peek(),\n };\n if (options.includeValues !== true) return base;\n return { ...base, values: { ...values } };\n}\n\n// ── Context ─────────────────────────────────────────────────────────────────\n\nexport interface ContextLike {\n readonly id: symbol;\n hasProvider(): boolean;\n}\n\nexport interface ContextInspection {\n /** The context's descriptive label (from its Symbol). */\n readonly description: string;\n /** Whether a provider is currently active. */\n readonly hasProvider: boolean;\n}\n\n/** Snapshot a context's identity and provider presence. No value dumped. */\nexport function inspectContext(context: ContextLike): ContextInspection {\n return {\n description: context.id.description ?? 'streetui.context',\n hasProvider: context.hasProvider(),\n };\n}\n\n// ── i18n ──────────────────────────────────────────────────────────────────\n\nexport interface I18nLike {\n readonly locale: ReadonlySignal<string>;\n readonly locales: ReadonlyArray<string>;\n has(key: string): boolean;\n}\n\nexport interface I18nInspection {\n readonly locale: string;\n readonly locales: string[];\n /** Of the probed keys, those with no translation in the active/fallback locale. */\n readonly missingKeys?: string[];\n}\n\nexport interface InspectI18nOptions {\n /** Keys to probe for presence; any absent ones are reported as missing. */\n readonly checkKeys?: readonly string[];\n}\n\n/** Snapshot i18n locale state and (optionally) missing translation keys. */\nexport function inspectI18n(i18n: I18nLike, options: InspectI18nOptions = {}): I18nInspection {\n const base: I18nInspection = {\n locale: i18n.locale.peek(),\n locales: [...i18n.locales],\n };\n if (options.checkKeys === undefined) return base;\n const missingKeys = options.checkKeys.filter((k) => !i18n.has(k));\n return { ...base, missingKeys };\n}\n","/**\n * DevTools session & panels — the first real StreetUI DevTools surface.\n *\n * This is a *headless* DevTools layer: it composes the existing read-only\n * inspection functions (`inspectApplication`, `diagnosePerformance`, and the\n * reactive inspectors) into the panels a DevTools UI shows — Application, Graph,\n * Signals, Router, Resources, Forms, Context, i18n, and Performance — and\n * returns them as plain data plus a text formatter. Any host (a browser panel, a\n * CLI command, a test) can render that data.\n *\n * Design constraints honoured here:\n * - No second graph and no second reactive system — everything is derived from\n * the one `CompiledApplication` and the app's own live signals.\n * - Explicit activation: nothing in the runtime imports this. A session only\n * exists once dev code calls `createDevTools`, so production pays no cost.\n * - Live updates use a simple explicit `refresh()` — DevTools never subscribes\n * to or instruments the reactive graph.\n * - Sensitive surfaces (resource payloads, form values) stay hidden unless the\n * caller opts in per the underlying inspectors.\n */\n\nimport type { CompiledApplication } from '@streetui/compiler';\nimport type { ReadonlySignal } from '@streetui/state';\nimport {\n inspectApplication,\n type ApplicationInspection,\n type ApplicationIdentity,\n type InspectedPage,\n} from './application.js';\nimport type { InspectedNode } from './inspector.js';\nimport { diagnosePerformance, type PerfDiagnostic, type PerfThresholds } from './diagnostics.js';\nimport {\n inspectSignal,\n inspectResource,\n inspectRouter,\n inspectForm,\n inspectContext,\n inspectI18n,\n type SignalInspection,\n type ResourceInspection,\n type RouterInspection,\n type FormInspection,\n type ContextInspection,\n type I18nInspection,\n type ResourceLike,\n type RouterLike,\n type FormLike,\n type ContextLike,\n type I18nLike,\n} from './inspect-reactive.js';\n\n// ── Panel shapes ────────────────────────────────────────────────────────────\n\nexport interface ApplicationPanel {\n readonly identity: ApplicationIdentity;\n readonly nodeCount: number;\n readonly maxDepth: number;\n readonly pages: readonly InspectedPage[];\n readonly signalCount: number;\n readonly eventHandlers: number;\n readonly stateBindings: number;\n readonly errors: number;\n readonly warnings: number;\n}\n\nexport interface SignalsPanel {\n /** Distinct signal ids referenced anywhere in the graph (structural). */\n readonly boundSignalIds: readonly string[];\n /** Live inspections for signals the app registered with DevTools, by label. */\n readonly live: Readonly<Record<string, SignalInspection>>;\n}\n\nexport interface PerformancePanel {\n readonly snapshot: ApplicationInspection['perf'];\n readonly diagnostics: readonly PerfDiagnostic[];\n}\n\n/** All panels captured at one `refresh()`. */\nexport interface DevToolsSnapshot {\n readonly application: ApplicationPanel;\n readonly graph: InspectedNode;\n readonly signals: SignalsPanel;\n readonly performance: PerformancePanel;\n readonly router?: RouterInspection;\n readonly resources?: Readonly<Record<string, ResourceInspection>>;\n readonly forms?: Readonly<Record<string, FormInspection>>;\n readonly contexts?: Readonly<Record<string, ContextInspection>>;\n readonly i18n?: I18nInspection;\n}\n\n// ── Live sources ──────────────────────────────────────────────────────────\n\n/**\n * The app's own live reactive objects, handed to DevTools explicitly so it can\n * inspect them. The compiled graph knows signal *ids* but not the live `Signal`\n * instances, so the app registers whichever surfaces it wants visible. Every\n * field is optional — a session works with none of them (structure-only).\n */\nexport interface DevToolsSources {\n /** Live signals to inspect, keyed by a human label shown in the panel. */\n readonly signals?: Readonly<Record<string, ReadonlySignal<unknown>>>;\n /** Live resources to inspect, keyed by label. */\n readonly resources?: Readonly<Record<string, ResourceLike>>;\n /** The app router, if any. */\n readonly router?: RouterLike;\n /** Live forms to inspect, keyed by label. */\n readonly forms?: Readonly<Record<string, FormLike>>;\n /** Live contexts to inspect, keyed by label. */\n readonly contexts?: Readonly<Record<string, ContextLike>>;\n /** The app i18n instance, if any. */\n readonly i18n?: I18nLike;\n}\n\nexport interface DevToolsOptions {\n /** Thresholds forwarded to `diagnosePerformance`. */\n readonly perfThresholds?: PerfThresholds;\n /**\n * Redact live signal values by default (passed to `inspectSignal`). Use in\n * shared or recorded sessions so values never reach the panel. Off by default.\n */\n readonly redactSignals?: boolean | ((value: unknown) => unknown);\n /** i18n keys to probe for missing translations, forwarded to `inspectI18n`. */\n readonly i18nCheckKeys?: readonly string[];\n}\n\n// ── Session ─────────────────────────────────────────────────────────────────\n\n/**\n * A headless DevTools session over one compiled application.\n *\n * The session holds the compiled app plus the app's registered live sources and\n * produces an immutable {@link DevToolsSnapshot} on demand. Live values are read\n * only when `refresh()` is called (explicit-refresh protocol, §7): the session\n * never subscribes to signals or instruments the reactive graph, so it adds no\n * cost to the running app between refreshes.\n */\nexport interface DevToolsSession {\n /** The most recent snapshot. Recomputed by `refresh()`. */\n readonly snapshot: DevToolsSnapshot;\n /**\n * Recompute every panel from the current live state and return the new\n * snapshot. This is the only way values change — DevTools pulls, it never\n * gets pushed to.\n */\n refresh(): DevToolsSnapshot;\n /**\n * Find a node in the graph by id and return that subtree, or `undefined`.\n * Backs a UI tree inspector's node-selection (§8) without a second graph.\n */\n selectNode(id: string): InspectedNode | undefined;\n /** Render the current snapshot as a plain-text report (for CLI/tests/logs). */\n format(): string;\n}\n\n/**\n * Create a DevTools session. Nothing in the runtime calls this — a session only\n * exists once dev code opts in, so production never pays for it.\n */\nexport function createDevTools(\n compiled: CompiledApplication,\n sources: DevToolsSources = {},\n options: DevToolsOptions = {},\n): DevToolsSession {\n let current = capture(compiled, sources, options);\n\n return {\n get snapshot() {\n return current;\n },\n refresh() {\n current = capture(compiled, sources, options);\n return current;\n },\n selectNode(id: string) {\n return findNode(current.graph, id);\n },\n format() {\n return formatSnapshot(current);\n },\n };\n}\n\n// ── Capture ───────────────────────────────────────────────────────────────\n\nfunction capture(\n compiled: CompiledApplication,\n sources: DevToolsSources,\n options: DevToolsOptions,\n): DevToolsSnapshot {\n const app: ApplicationInspection = inspectApplication(compiled);\n\n const application: ApplicationPanel = {\n identity: app.identity,\n nodeCount: app.perf.totalNodes,\n maxDepth: app.perf.maxDepth,\n pages: app.pages,\n signalCount: app.signals.length,\n eventHandlers: app.perf.eventHandlers,\n stateBindings: app.perf.stateBindings,\n errors: app.diagnostics.errors,\n warnings: app.diagnostics.warnings,\n };\n\n const live: Record<string, SignalInspection> = {};\n if (sources.signals !== undefined) {\n for (const [label, sig] of Object.entries(sources.signals)) {\n live[label] = inspectSignal(\n sig,\n options.redactSignals !== undefined ? { redact: options.redactSignals } : {},\n );\n }\n }\n const signals: SignalsPanel = { boundSignalIds: app.signals, live };\n\n const performance: PerformancePanel = {\n snapshot: app.perf,\n diagnostics: diagnosePerformance(compiled, options.perfThresholds),\n };\n\n const snapshot: DevToolsSnapshot = {\n application,\n graph: app.graph,\n signals,\n performance,\n ...(sources.router !== undefined ? { router: inspectRouter(sources.router) } : {}),\n ...(sources.resources !== undefined\n ? { resources: mapInspect(sources.resources, (r) => inspectResource(r)) }\n : {}),\n ...(sources.forms !== undefined\n ? { forms: mapInspect(sources.forms, (f) => inspectForm(f)) }\n : {}),\n ...(sources.contexts !== undefined\n ? { contexts: mapInspect(sources.contexts, (c) => inspectContext(c)) }\n : {}),\n ...(sources.i18n !== undefined\n ? {\n i18n: inspectI18n(\n sources.i18n,\n options.i18nCheckKeys !== undefined ? { checkKeys: options.i18nCheckKeys } : {},\n ),\n }\n : {}),\n };\n return snapshot;\n}\n\nfunction mapInspect<T, R>(\n source: Readonly<Record<string, T>>,\n inspect: (value: T) => R,\n): Record<string, R> {\n const out: Record<string, R> = {};\n for (const [label, value] of Object.entries(source)) out[label] = inspect(value);\n return out;\n}\n\n// ── Graph node lookup (§8) ──────────────────────────────────────────────────\n\nfunction findNode(node: InspectedNode, id: string): InspectedNode | undefined {\n if (node.id === id) return node;\n for (const child of node.children) {\n const found = findNode(child, id);\n if (found !== undefined) return found;\n }\n return undefined;\n}\n\n// ── Text formatter ────────────────────────────────────────────────────────\n\nfunction formatSnapshot(s: DevToolsSnapshot): string {\n const lines: string[] = [];\n const app = s.application;\n lines.push(`StreetUI DevTools — ${app.identity.name} v${app.identity.version}`);\n lines.push(\n `Application: ${app.nodeCount} nodes, depth ${app.maxDepth}, ${app.pages.length} page(s)`,\n );\n lines.push(\n ` signals ${app.signalCount} · handlers ${app.eventHandlers} · bindings ${app.stateBindings} · errors ${app.errors} · warnings ${app.warnings}`,\n );\n\n lines.push(`Signals: ${s.signals.boundSignalIds.length} bound in graph`);\n for (const [label, sig] of Object.entries(s.signals.live)) {\n lines.push(` ${label} [${sig.kind}] = ${format(sig.value)} · observers ${sig.observerCount ?? '?'}`);\n }\n\n if (s.router !== undefined) {\n lines.push(`Router: ${s.router.path} (${s.router.pattern})${s.router.isFallback ? ' [fallback]' : ''}`);\n }\n\n if (s.resources !== undefined) {\n lines.push('Resources:');\n for (const [label, r] of Object.entries(s.resources)) {\n lines.push(` ${label}: ${r.status}${r.loading ? ' (loading)' : ''}${r.hasError ? ` !${r.errorName}` : ''}`);\n }\n }\n\n if (s.forms !== undefined) {\n lines.push('Forms:');\n for (const [label, f] of Object.entries(s.forms)) {\n lines.push(` ${label}: ${f.valid ? 'valid' : 'invalid'} · ${f.status} · fields ${f.fields.length}`);\n }\n }\n\n if (s.contexts !== undefined) {\n lines.push('Contexts:');\n for (const [label, c] of Object.entries(s.contexts)) {\n lines.push(` ${label} (${c.description}): ${c.hasProvider ? 'provided' : 'no provider'}`);\n }\n }\n\n if (s.i18n !== undefined) {\n const missing = s.i18n.missingKeys;\n lines.push(\n `i18n: ${s.i18n.locale} of [${s.i18n.locales.join(', ')}]${missing !== undefined ? ` · missing ${missing.length}` : ''}`,\n );\n }\n\n lines.push(\n `Performance: ${s.performance.diagnostics.length} diagnostic(s), ${s.performance.snapshot.totalNodes} nodes`,\n );\n for (const d of s.performance.diagnostics) {\n lines.push(` ${d.code}: ${d.message}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction format(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value);\n if (value === null || value === undefined) return String(value);\n if (typeof value === 'object') {\n try {\n return JSON.stringify(value);\n } catch {\n return '[object]';\n }\n }\n return String(value);\n}\n","/**\n * Project-configuration surface for `streetui.config.ts`.\n *\n * The configuration *type* is single-sourced from the internal CLI module (so\n * there is exactly one authoritative `StreetUIConfig` shape). `defineConfig` is\n * the standard one-line identity helper used purely for editor type-inference on\n * the exported config object.\n *\n * This lives in its own tiny module — rather than re-exporting `defineConfig`\n * from the CLI barrel — so that importing `streetui` for application code does\n * **not** drag the CLI's build machinery (and its `esbuild` dependency) into the\n * client runtime bundle. The CLI's own `loadConfig` reads the default export of\n * `streetui.config.ts` regardless of which identity helper wrapped it, so the\n * behaviour is identical to configuring via the CLI directly.\n */\nimport type { StreetUIConfig } from '@streetui/cli';\n\nexport type { StreetUIConfig, ResolvedConfig } from '@streetui/cli';\n\n/** Identity helper that gives `streetui.config.ts` full type-checking + inference. */\nexport function defineConfig(config: StreetUIConfig): StreetUIConfig {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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Q,GAAG;AACnD,YAAM,KAAK,KAAK,KAAK,KAAK,EAAE,WAAW,MAAM,EAAE,cAAc,aAAa,aAAa,EAAE;AAAA,IAC3F;AAAA,EACF;AAEA,MAAI,EAAE,SAAS,QAAW;AACxB,UAAM,UAAU,EAAE,KAAK;AACvB,UAAM;AAAA,MACJ,SAAS,EAAE,KAAK,MAAM,QAAQ,EAAE,KAAK,QAAQ,KAAK,IAAI,CAAC,IAAI,YAAY,SAAY,iBAAc,QAAQ,MAAM,KAAK,EAAE;AAAA,IACxH;AAAA,EACF;AAEA,QAAM;AAAA,IACJ,gBAAgB,EAAE,YAAY,YAAY,MAAM,mBAAmB,EAAE,YAAY,SAAS,UAAU;AAAA,EACtG;AACA,aAAW,KAAK,EAAE,YAAY,aAAa;AACzC,UAAM,KAAK,KAAK,EAAE,IAAI,KAAK,EAAE,OAAO,EAAE;AAAA,EACxC;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;AAEA,SAAS,OAAO,OAAwB;AACtC,MAAI,OAAO,UAAU,SAAU,QAAO,KAAK,UAAU,KAAK;AAC1D,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO,OAAO,KAAK;AAC9D,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI;AACF,aAAO,KAAK,UAAU,KAAK;AAAA,IAC7B,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO,OAAO,KAAK;AACrB;;;AC7TO,SAAS,aAAa,QAAwC;AACnE,SAAO;AACT;","names":["signal","self","instance","el","tag","pattern","valid","dirty","resource"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/version.ts","../../state/src/signal.ts","../../state/src/store.ts","../../state/src/resource.ts","../../core/src/a11y-ids.ts","../../core/src/identity.ts","../../core/src/lifecycle.ts","../../core/src/environment.ts","../../core/src/diagnostics.ts","../../core/src/application.ts","../../core/src/node.ts","../../core/src/observability.ts","../../graph/src/graph-node.ts","../../graph/src/graph.ts","../../dsl/src/builders.ts","../../dsl/src/dsl.ts","../../compiler/src/validation/validator.ts","../../compiler/src/transform/transform.ts","../../compiler/src/compile.ts","../../runtime/src/node-instance.ts","../../scheduler/src/scheduler.ts","../../runtime/src/runtime.ts","../../events/src/event-types.ts","../../events/src/event-bus.ts","../../events/src/dom-bridge.ts","../../dom/src/browser-adapter.ts","../../dom/src/server-node.ts","../../dom/src/server-adapter.ts","../../dom/src/focus.ts","../../renderer/src/render-context.ts","../../renderer/src/node-instance.ts","../../renderer/src/attributes.ts","../../renderer/src/events.ts","../../renderer/src/tag-map.ts","../../renderer/src/patch.ts","../../renderer/src/reconciliation.ts","../../renderer/src/mount.ts","../../renderer/src/hydration-diagnostics.ts","../../renderer/src/hydrate.ts","../../renderer/src/render-handle.ts","../../renderer/src/renderer.ts","../../renderer/src/dehydrate.ts","../../renderer/src/ssr.ts","../../router/src/matching.ts","../../router/src/history.ts","../../router/src/router.ts","../../router/src/mount-router.ts","../../forms/src/validators.ts","../../forms/src/form.ts","../../context/src/context.ts","../../i18n/src/i18n.ts","../../devtools/src/inspector.ts","../../devtools/src/application.ts","../../devtools/src/diagnostics.ts","../../devtools/src/inspect-reactive.ts","../../devtools/src/panels.ts","../src/config.ts"],"sourcesContent":["/**\n * # StreetUI\n *\n * The complete StreetUI framework, exposed as a single import surface.\n *\n * ```ts\n * import { signal, streetui, compile, createRuntime, createRenderer } from 'streetui';\n * ```\n *\n * StreetUI is internally modular — reactivity, the semantic DSL, the compiler,\n * the semantic application graph, the runtime, the DOM renderer, the router,\n * async resources, forms, context, i18n, devtools and the CLI each live in their\n * own internal module — but a framework user installs and imports only\n * `streetui`. Server-only helpers are also available from `streetui/server`, and\n * the testing utilities from `streetui/testing`.\n *\n * This entry re-exports the **already-implemented, stable public API** of each\n * subsystem. It does not introduce any new API: StreetUI's UI layer is a\n * semantic *builder* DSL (`streetui.app(...)`, `page.section(s => s.button(...))`),\n * not a set of free element functions.\n */\n\n// ── Framework version (single authoritative source; see ./version.ts) ────────\nexport { VERSION } from './version.js';\n\n// ── Reactivity: signals, derived state, effects, batching, stores, resources ─\n// signal, derived, computed, effect, batch, resource, store, …\nexport * from '@streetui/state';\n\n// ── Core: application identity, lifecycle, diagnostics, environment, a11yIds ──\nexport * from '@streetui/core';\n\n// ── Semantic application graph ────────────────────────────────────────────────\nexport * from '@streetui/graph';\n\n// ── Semantic UI DSL: streetui.app(...), builders, DSL types ───────────────────\nexport * from '@streetui/dsl';\n\n// ── Compiler: compile(app) → compiled application ─────────────────────────────\nexport * from '@streetui/compiler';\n\n// ── Runtime: createRuntime, mount, lifecycle wiring ───────────────────────────\nexport * from '@streetui/runtime';\n\n// ── Events: event bus + DOM event bridge ──────────────────────────────────────\nexport * from '@streetui/events';\n\n// ── Scheduler: batched microtask scheduler ────────────────────────────────────\nexport * from '@streetui/scheduler';\n\n// ── DOM adapters: BrowserDOMAdapter, ServerDOMAdapter ─────────────────────────\nexport * from '@streetui/dom';\n\n// ── Renderer: createRenderer, mount/patch/reconcile, SSR (renderToString,\n// serializeState, readState) and hydrate ──────────────────────────────────\nexport * from '@streetui/renderer';\n\n// ── Router: createRouter, navigation, route lifecycle, active links ───────────\nexport * from '@streetui/router';\n\n// ── Forms: createForm + validators (required, email, minLength, …) ────────────\nexport * from '@streetui/forms';\n\n// ── Context: createContext, provide/consume (no prop drilling) ────────────────\nexport * from '@streetui/context';\n\n// ── Internationalization: createI18n (reactive, typed) ────────────────────────\nexport * from '@streetui/i18n';\n\n// ── DevTools foundations: createDevTools + reactive inspectors ────────────────\nexport * from '@streetui/devtools';\n\n// ── Project configuration (used by streetui.config.ts) ────────────────────────\n// Re-exported from a tiny local module (see ./config.ts) so application imports\n// of `streetui` don't pull the CLI's build machinery (esbuild) into the client\n// runtime bundle. The config *type* is still single-sourced from the CLI.\nexport { defineConfig } from './config.js';\nexport type { StreetUIConfig, ResolvedConfig } from './config.js';\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 = '1.3.0';\n","/**\n * StreetUI reactive signals — framework-owned reactivity, no external libraries.\n *\n * Architecture:\n * Signal<T> — writable, holds a value, notifies on change\n * DerivedSignal<T> — read-only, lazily computed from other signals\n * effect() — side-effect that re-runs when dependencies change\n * batch() — run multiple updates before notifying\n */\n\nexport type Subscriber<T> = (value: T) => void;\nexport type Unsubscribe = () => void;\n\n// ── Tracking ──────────────────────────────────────────────────────────────────\n\n/**\n * Any reactive source that can have downstream consumers attached.\n * Both Signal and DerivedSignal implement this.\n */\nexport interface ReactiveSource<T> {\n get(): T;\n peek(): T;\n subscribe(fn: Subscriber<T>): Unsubscribe;\n /** Internal: remove a downstream consumer. */\n _removeConsumer(consumer: ReactiveConsumer): void;\n}\n\n/**\n * A downstream consumer (DerivedSignal or Effect) that can be invalidated\n * and can register itself as depending on a source.\n */\nexport interface ReactiveConsumer {\n _invalidate(): void;\n /** Internal: called by a source to register a dependency. */\n _addSource(src: ReactiveSource<unknown>): void;\n}\n\n/** The active consumer being tracked during a computation. */\nlet _activeConsumer: ReactiveConsumer | null = null;\n\nfunction withConsumer<T>(consumer: ReactiveConsumer, fn: () => T): T {\n const prev = _activeConsumer;\n _activeConsumer = consumer;\n try {\n return fn();\n } finally {\n _activeConsumer = prev;\n }\n}\n\n// ── Batch state (must be before Signal class so .set() can reference it) ──────\n\n/** Depth counter — batches nest; only the outermost flush propagates. */\nlet _batchDepth = 0;\n\ninterface PendingFlush {\n signal: Signal<unknown>;\n value: unknown;\n}\n\n/**\n * Keyed by signal identity — last-write-wins for each signal within a batch.\n * An ordered Map preserves first-seen insertion order for stable flush sequence.\n */\nconst _pendingFlushes = new Map<Signal<unknown>, PendingFlush>();\n\nfunction _enqueueBatchFlush(sig: Signal<unknown>, value: unknown): void {\n _pendingFlushes.set(sig, { signal: sig, value });\n}\n\nfunction _drainBatch(): void {\n const flushes = [..._pendingFlushes.values()];\n _pendingFlushes.clear();\n for (const { signal: sig, value } of flushes) {\n sig._flushBatch(value);\n }\n}\n\n// ── Signal ────────────────────────────────────────────────────────────────────\n\nexport interface ReadonlySignal<T> {\n get(): T;\n peek(): T;\n subscribe(fn: Subscriber<T>): Unsubscribe;\n}\n\nexport class Signal<T> implements ReactiveSource<T>, ReadonlySignal<T> {\n protected _value: T;\n private readonly _subscribers: Set<Subscriber<T>> = new Set();\n private readonly _consumers: Set<ReactiveConsumer> = new Set();\n\n constructor(initial: T) {\n this._value = initial;\n }\n\n get(): T {\n if (_activeConsumer !== null) {\n this._consumers.add(_activeConsumer);\n _activeConsumer._addSource(this as ReactiveSource<unknown>);\n }\n return this._value;\n }\n\n peek(): T {\n return this._value;\n }\n\n set(value: T): void {\n if (Object.is(this._value, value)) return;\n this._value = value;\n if (_batchDepth > 0) {\n // Defer notification until the batch flushes.\n // The stored value is always the latest (last-write-wins for same signal).\n _enqueueBatchFlush(this as unknown as Signal<unknown>, value);\n } else {\n this._flush(value);\n }\n }\n\n update(fn: (current: T) => T): void {\n this.set(fn(this._value));\n }\n\n subscribe(fn: Subscriber<T>): Unsubscribe {\n this._subscribers.add(fn);\n return () => { this._subscribers.delete(fn); };\n }\n\n _removeConsumer(consumer: ReactiveConsumer): void {\n this._consumers.delete(consumer);\n }\n\n /**\n * Called by the batch machinery after the batch has completed.\n * Notifies subscribers with the final coalesced value.\n */\n _flushBatch(value: unknown): void {\n this._flush(value as T);\n }\n\n private _flush(value: T): void {\n for (const sub of [...this._subscribers]) sub(value);\n for (const consumer of [...this._consumers]) consumer._invalidate();\n }\n\n /**\n * @internal DevTools inspection only. The number of live observers\n * (direct subscribers plus derived/effect consumers). Read-only; never\n * mutates reactive state.\n */\n _observerCount(): number {\n return this._subscribers.size + this._consumers.size;\n }\n}\n\n// ── DerivedSignal ─────────────────────────────────────────────────────────────\n\nexport class DerivedSignal<T> implements ReactiveSource<T>, ReactiveConsumer, ReadonlySignal<T> {\n private _value: T | undefined = undefined;\n private _dirty = true;\n private _disposed = false;\n private readonly _fn: () => T;\n private readonly _subscribers: Set<Subscriber<T>> = new Set();\n /** All upstream sources this derived currently reads from. */\n private readonly _sources: Set<ReactiveSource<unknown>> = new Set();\n /** Downstream consumers that depend on this derived. */\n private readonly _consumers: Set<ReactiveConsumer> = new Set();\n\n constructor(fn: () => T) {\n this._fn = fn;\n }\n\n get(): T {\n // Register this derived with the outer consumer if any\n if (_activeConsumer !== null) {\n this._consumers.add(_activeConsumer);\n _activeConsumer._addSource(this as ReactiveSource<unknown>);\n }\n if (this._dirty) this._recompute();\n return this._value as T;\n }\n\n peek(): T {\n if (this._dirty) this._recompute();\n return this._value as T;\n }\n\n subscribe(fn: Subscriber<T>): Unsubscribe {\n // Eagerly compute so sources track this derived as a consumer\n if (this._dirty) this._recompute();\n this._subscribers.add(fn);\n return () => { this._subscribers.delete(fn); };\n }\n\n _addSource(src: ReactiveSource<unknown>): void {\n this._sources.add(src);\n }\n\n _removeConsumer(consumer: ReactiveConsumer): void {\n this._consumers.delete(consumer);\n }\n\n _invalidate(): void {\n if (this._disposed) return;\n this._dirty = true;\n const newVal = this.peek(); // recompute\n for (const sub of [...this._subscribers]) sub(newVal);\n for (const consumer of [...this._consumers]) consumer._invalidate();\n }\n\n private _recompute(): void {\n // Detach from all current sources before re-tracking\n for (const src of this._sources) src._removeConsumer(this);\n this._sources.clear();\n\n this._value = withConsumer(this, this._fn);\n this._dirty = false;\n }\n\n dispose(): void {\n this._disposed = true;\n for (const src of this._sources) src._removeConsumer(this);\n this._sources.clear();\n this._subscribers.clear();\n this._consumers.clear();\n }\n\n /**\n * @internal DevTools inspection only. Live observers (subscribers plus\n * downstream consumers). Read-only.\n */\n _observerCount(): number {\n return this._subscribers.size + this._consumers.size;\n }\n}\n\n// ── effect ────────────────────────────────────────────────────────────────────\n\nclass Effect implements ReactiveConsumer {\n private readonly _fn: () => void | (() => void);\n private _cleanup: (() => void) | undefined = undefined;\n private _disposed = false;\n private readonly _sources: Set<ReactiveSource<unknown>> = new Set();\n\n constructor(fn: () => void | (() => void)) {\n this._fn = fn;\n this._run();\n }\n\n _addSource(src: ReactiveSource<unknown>): void {\n this._sources.add(src);\n }\n\n _invalidate(): void {\n if (this._disposed) return;\n this._run();\n }\n\n private _run(): void {\n // Detach from all current sources before re-tracking\n for (const src of this._sources) src._removeConsumer(this);\n this._sources.clear();\n\n if (typeof this._cleanup === 'function') this._cleanup();\n const result = withConsumer(this, this._fn);\n this._cleanup = typeof result === 'function' ? result : undefined;\n }\n\n dispose(): void {\n this._disposed = true;\n for (const src of this._sources) src._removeConsumer(this);\n this._sources.clear();\n if (typeof this._cleanup === 'function') this._cleanup();\n this._cleanup = undefined;\n }\n}\n\n// ── Public API ─────────────────────────────────────────────────────────────────\n\nexport function signal<T>(initial: T): Signal<T> {\n return new Signal(initial);\n}\n\nexport function derived<T>(fn: () => T): DerivedSignal<T> {\n return new DerivedSignal(fn);\n}\n\nexport function effect(fn: () => void | (() => void)): Unsubscribe {\n const e = new Effect(fn);\n return () => e.dispose();\n}\n\n/**\n * Run multiple signal updates as an atomic batch.\n *\n * Within the callback, calls to signal.set() are deferred — each signal\n * accumulates its latest value. When the outermost batch() returns,\n * each modified signal fires its subscribers exactly once with the final\n * value. Nested batch() calls are supported; the flush only runs when the\n * outermost batch exits.\n *\n * Example:\n * batch(() => {\n * count.set(1);\n * count.set(2);\n * count.set(3);\n * });\n * // subscribers see count = 3 exactly once\n */\nexport function batch(fn: () => void): void {\n _batchDepth++;\n try {\n fn();\n } finally {\n _batchDepth--;\n if (_batchDepth === 0) {\n _drainBatch();\n }\n }\n}\n\n/** True when inside a batch() call. Useful for advanced scheduling integration. */\nexport function isBatching(): boolean {\n return _batchDepth > 0;\n}\n\n// ── Inspection (read-only, DevTools-facing) ─────────────────────────────────\n\n/** Whether a signal is writable (`signal()`) or computed (`derived()`). */\nexport type SignalKind = 'writable' | 'derived';\n\n/** Classify a reactive value as writable or derived. */\nexport function signalKind(source: ReadonlySignal<unknown>): SignalKind {\n return source instanceof DerivedSignal ? 'derived' : 'writable';\n}\n\n/**\n * The number of live observers on a signal — direct subscribers plus derived\n * or effect consumers — or `undefined` if the source does not expose the count.\n * Read-only; safe for DevTools. Never mutates reactive state.\n */\nexport function observerCount(source: ReadonlySignal<unknown>): number | undefined {\n const maybe = source as { _observerCount?: () => number };\n return typeof maybe._observerCount === 'function' ? maybe._observerCount() : undefined;\n}\n","/**\n * A simple reactive store built on top of signals.\n * Useful for structured state with multiple fields.\n */\n\nimport { Signal, signal, type Subscriber, type Unsubscribe } from './signal.js';\n\nexport type StoreState = Record<string, unknown>;\n\nexport class Store<T extends StoreState> {\n private readonly _signals: Record<string, Signal<unknown>>;\n\n constructor(initial: T) {\n const signals: Record<string, Signal<unknown>> = {};\n for (const key in initial) {\n if (Object.prototype.hasOwnProperty.call(initial, key)) {\n signals[key] = signal(initial[key] as unknown);\n }\n }\n this._signals = signals;\n }\n\n get<K extends keyof T>(key: K): T[K] {\n const s = this._signals[key as string];\n if (s === undefined) {\n throw new Error(`Store: unknown key \"${String(key)}\"`);\n }\n return s.get() as T[K];\n }\n\n set<K extends keyof T>(key: K, value: T[K]): void {\n const s = this._signals[key as string];\n if (s === undefined) {\n throw new Error(`Store: unknown key \"${String(key)}\"`);\n }\n s.set(value as unknown);\n }\n\n signal<K extends keyof T>(key: K): Signal<T[K]> {\n const s = this._signals[key as string];\n if (s === undefined) {\n throw new Error(`Store: unknown key \"${String(key)}\"`);\n }\n return s as unknown as Signal<T[K]>;\n }\n\n subscribe<K extends keyof T>(key: K, fn: Subscriber<T[K]>): Unsubscribe {\n return this.signal(key).subscribe(fn);\n }\n\n getSnapshot(): T {\n const snap = {} as T;\n for (const key in this._signals) {\n if (Object.prototype.hasOwnProperty.call(this._signals, key)) {\n (snap as Record<string, unknown>)[key] = this._signals[key]?.peek();\n }\n }\n return snap;\n }\n}\n\nexport function createStore<T extends StoreState>(initial: T): Store<T> {\n return new Store(initial);\n}\n","/**\n * StreetUI async resources — framework-native asynchronous data.\n *\n * A `resource` wraps a Promise-returning loader and exposes its lifecycle as\n * ordinary StreetUI signals (status / data / error), so it composes with\n * `derived`, `effect`, `when()`, `listOf` and the renderer with no second\n * reactive system.\n *\n * State machine:\n *\n * idle ──(load)──▶ loading ──(resolve)──▶ success\n * │\n * └────(reject)──────▶ error\n *\n * Refetch keeps the previously-loaded `data` visible while `status` is\n * `'loading'` again (see `isRefetching`) — there is no separate `'refetching'`\n * status; it is expressed through `status === 'loading'` with `data` still set.\n *\n * The resource is transport-agnostic: the loader is any function returning a\n * value or a Promise. When it accepts the provided `AbortSignal`, in-flight\n * work is cancelled on `dispose()` or when a newer request supersedes it.\n */\n\nimport { signal, derived, batch, type ReadonlySignal, type Unsubscribe } from './signal.js';\n\nexport type ResourceStatus = 'idle' | 'loading' | 'success' | 'error';\n\n/** Context handed to the loader; carries an AbortSignal for cancellation. */\nexport interface ResourceLoaderContext {\n readonly signal: AbortSignal;\n}\n\n/** Any value-or-Promise producing function. Receives an abort-aware context. */\nexport type ResourceLoader<T> = (ctx: ResourceLoaderContext) => Promise<T> | T;\n\nexport interface ResourceOptions<T = unknown> {\n /** Load immediately on creation. Defaults to `true`. When `false`, stays `idle` until `refetch()`. */\n readonly immediate?: boolean;\n /**\n * Explicit reactive dependencies. When any listed signal changes, the\n * resource refetches. Dependencies are explicit (not auto-tracked from the\n * loader body) so there is no risk of an accidental infinite refetch loop.\n */\n readonly watch?: ReadonlyArray<ReadonlySignal<unknown>>;\n /**\n * Optional teardown registrar (e.g. a route's `ctx.onCleanup`). When given,\n * the resource registers its own `dispose` so it is cleaned up automatically\n * when its owner is removed.\n */\n readonly onCleanup?: (fn: () => void) => void;\n /**\n * Server-provided initial value for hydration. When present the resource\n * starts in `'success'` with this data already visible, and the initial\n * auto-load is skipped (so the client does not refetch data the server\n * already resolved). This is the client half of SSR resource transfer; the\n * server side awaits `refetch()` before serializing. Set `immediate: true`\n * explicitly to force a client refetch anyway.\n */\n readonly initialData?: T;\n /** Server-provided initial error for hydration (mirrors `initialData`). */\n readonly initialError?: unknown;\n /**\n * Explicit initial status override. Rarely needed — inferred as `'success'`\n * from `initialData` or `'error'` from `initialError`.\n */\n readonly initialStatus?: ResourceStatus;\n}\n\nexport interface Resource<T> {\n /** Reactive lifecycle status. */\n readonly status: ReadonlySignal<ResourceStatus>;\n /** The last successfully-loaded value, or `undefined` before first success. */\n readonly data: ReadonlySignal<T | undefined>;\n /** The most recent error, or `undefined` when there is none. Typed `unknown` — never `any`. */\n readonly error: ReadonlySignal<unknown>;\n /** Convenience: `status === 'loading'`. */\n readonly loading: ReadonlySignal<boolean>;\n /** Convenience: loading while previously-loaded data is still present (a refetch). */\n readonly isRefetching: ReadonlySignal<boolean>;\n /** Trigger a new request. Resolves when the request settles (or is superseded). */\n refetch(): Promise<void>;\n /** Cancel in-flight work, drop watchers, and ignore any late results. Idempotent. */\n dispose(): void;\n}\n\n/** True for an abort we initiated (so it is not surfaced as a real error). */\nfunction isAbortError(err: unknown): boolean {\n return (\n err instanceof Error && err.name === 'AbortError'\n ) || (\n typeof DOMException !== 'undefined' && err instanceof DOMException && err.name === 'AbortError'\n );\n}\n\nexport function resource<T>(loader: ResourceLoader<T>, options: ResourceOptions<T> = {}): Resource<T> {\n // Seed hydrated initial state (SSR transfer). `initialStatus` wins if given,\n // otherwise infer success/error from the provided value.\n const hasInitial =\n options.initialData !== undefined ||\n options.initialError !== undefined ||\n options.initialStatus !== undefined;\n\n const seededStatus: ResourceStatus =\n options.initialStatus ??\n (options.initialData !== undefined\n ? 'success'\n : options.initialError !== undefined\n ? 'error'\n : 'idle');\n\n const status = signal<ResourceStatus>(seededStatus);\n const data = signal<T | undefined>(options.initialData);\n const error = signal<unknown>(options.initialError);\n\n const loading = derived<boolean>(() => status.get() === 'loading');\n const isRefetching = derived<boolean>(() => status.get() === 'loading' && data.get() !== undefined);\n\n let disposed = false;\n /** Monotonic request id — only the newest request may write state (race guard). */\n let runId = 0;\n let controller: AbortController | null = null;\n\n const load = async (): Promise<void> => {\n if (disposed) return;\n\n // Supersede any in-flight request: abort it and bump the run id so its\n // eventual resolution is ignored.\n controller?.abort();\n const myRun = ++runId;\n const myController = new AbortController();\n controller = myController;\n\n // Enter loading. Preserve `data` (so a refetch keeps showing the old value)\n // and clear any previous error.\n batch(() => {\n error.set(undefined);\n status.set('loading');\n });\n\n try {\n const result = await loader({ signal: myController.signal });\n // Ignore stale or cancelled resolutions.\n if (disposed || myRun !== runId) return;\n batch(() => {\n data.set(result);\n error.set(undefined);\n status.set('success');\n });\n } catch (err) {\n if (disposed || myRun !== runId) return;\n // A self-initiated abort is not a user-visible error.\n if (isAbortError(err)) return;\n batch(() => {\n error.set(err);\n status.set('error');\n });\n }\n };\n\n const refetch = (): Promise<void> => load();\n\n // Explicit reactive dependencies: refetch when any watched signal changes.\n const watchUnsubs: Unsubscribe[] = [];\n if (options.watch !== undefined) {\n for (const dep of options.watch) {\n watchUnsubs.push(\n dep.subscribe(() => {\n if (!disposed) void load();\n }),\n );\n }\n }\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n controller?.abort();\n controller = null;\n for (const unsub of watchUnsubs) unsub();\n watchUnsubs.length = 0;\n };\n\n if (options.onCleanup !== undefined) {\n options.onCleanup(dispose);\n }\n\n // Auto-load on creation unless disabled. When hydrated initial state is\n // present we skip the initial load by default (the server already resolved\n // it); an explicit `immediate: true` still forces a refetch.\n if (options.immediate === true || (options.immediate !== false && !hasInitial)) {\n void load();\n }\n\n return {\n status,\n data,\n error,\n loading,\n isRefetching,\n refetch,\n dispose,\n };\n}\n","/**\n * Deterministic accessibility id helpers.\n *\n * Accessible markup often needs stable id relationships — a `<label for>` (or\n * `aria-labelledby`) pointing at an input, an `aria-describedby` pointing at a\n * hint/error, an `aria-labelledby` on a dialog pointing at its title. Those ids\n * must be IDENTICAL on the server and the client, otherwise a hydrated subtree\n * that re-renders (e.g. a toggled `when()` branch) would compute a different id\n * than the server emitted and break the association.\n *\n * These helpers derive ids purely from a caller-supplied stable base string\n * (typically a form field name or a dialog name). They use NO incrementing\n * counter and NO randomness, so `a11yIds('email')` yields the same ids in every\n * environment and on every call — which is exactly what SSR + hydration needs.\n */\n\nconst UNSAFE = /[^A-Za-z0-9_-]+/g;\n\n/** Normalise an arbitrary base into a token safe for use in an id/selector. */\nexport function toIdToken(base: string): string {\n const token = base.trim().replace(UNSAFE, '-').replace(/^-+|-+$/g, '');\n return token.length > 0 ? token : 'field';\n}\n\nexport interface A11yIds {\n /** The normalised base token. */\n readonly base: string;\n /** Id for the primary interactive element (e.g. the input). */\n readonly input: string;\n /** Id for a label element / labelling text. */\n readonly label: string;\n /** Id for descriptive/help text. */\n readonly description: string;\n /** Id for an error message element. */\n readonly error: string;\n /** Id for a title element (e.g. a dialog title). */\n readonly title: string;\n /** Derive an arbitrary suffixed id from the same base. */\n id(suffix: string): string;\n}\n\n/**\n * Build a set of deterministic, SSR-stable ids from a base string.\n *\n * @example\n * const ids = a11yIds('email');\n * // ids.input === 'email-input', ids.label === 'email-label', ...\n * input({ bind: value, id: ids.input, ariaLabelledBy: ids.label, ariaDescribedBy: ids.error });\n * text('Email', { id: ids.label });\n */\nexport function a11yIds(base: string): A11yIds {\n const token = toIdToken(base);\n return {\n base: token,\n input: `${token}-input`,\n label: `${token}-label`,\n description: `${token}-description`,\n error: `${token}-error`,\n title: `${token}-title`,\n id: (suffix: string) => `${token}-${toIdToken(suffix)}`,\n };\n}\n","/**\n * Node and application identity utilities.\n * Every node in the semantic graph has a stable, unique identity.\n */\n\nlet _counter = 0;\n\n/** Generate a framework-internal monotonic integer ID. */\nexport function nextId(): number {\n return ++_counter;\n}\n\n/** Reset the counter (test use only). */\nexport function resetIdCounter(): void {\n _counter = 0;\n}\n\n/** Opaque branded type for node IDs. */\nexport type NodeId = string & { readonly __brand: 'NodeId' };\n\n/** Create a NodeId from a string (must be unique at call site). */\nexport function createNodeId(value: string): NodeId {\n return value as NodeId;\n}\n\n/** Generate a fresh, unique NodeId. */\nexport function generateNodeId(prefix: string = 'node'): NodeId {\n return createNodeId(`${prefix}:${nextId()}`);\n}\n\n/** Parse the prefix from a NodeId. */\nexport function nodeIdPrefix(id: NodeId): string {\n const colon = id.indexOf(':');\n return colon === -1 ? id : id.slice(0, colon);\n}\n\n/** Branded type for application IDs. */\nexport type ApplicationId = string & { readonly __brand: 'ApplicationId' };\n\n/** Generate a fresh application ID. */\nexport function generateApplicationId(name: string): ApplicationId {\n return `app:${name}:${nextId()}` as ApplicationId;\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 * Environment detection and capability flags.\n * The framework behaves slightly differently in browser vs. server vs. test.\n *\n * We use `typeof` checks throughout to remain safe across environments\n * without depending on @types/node.\n */\n\nexport type EnvironmentKind = 'browser' | 'server' | 'worker' | 'test' | 'unknown';\n\nexport interface EnvironmentCapabilities {\n readonly hasDom: boolean;\n readonly hasWindow: boolean;\n readonly hasDocument: boolean;\n readonly isSecureContext: boolean;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\ndeclare const process: any;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nfunction detectEnvironment(): EnvironmentKind {\n // Explicit test override via process.env\n try {\n if (\n typeof process !== 'undefined' &&\n process !== null &&\n typeof process === 'object' &&\n (process.env?.['NODE_ENV'] === 'test' || process.env?.['VITEST'] === 'true')\n ) {\n return 'test';\n }\n } catch {\n // process may not be defined in all environments\n }\n\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n return 'browser';\n }\n\n if (\n typeof self !== 'undefined' &&\n typeof (self as unknown as Record<string, unknown>)['importScripts'] === 'function'\n ) {\n return 'worker';\n }\n\n try {\n if (typeof process !== 'undefined' && typeof process === 'object') {\n return 'server';\n }\n } catch {\n // ignore\n }\n\n return 'unknown';\n}\n\nfunction detectCapabilities(): EnvironmentCapabilities {\n return {\n hasDom: typeof document !== 'undefined',\n hasWindow: typeof window !== 'undefined',\n hasDocument: typeof document !== 'undefined',\n isSecureContext:\n typeof window !== 'undefined'\n ? ((window as unknown as Record<string, unknown>)['isSecureContext'] === true)\n : false,\n };\n}\n\nexport class Environment {\n readonly kind: EnvironmentKind;\n readonly capabilities: EnvironmentCapabilities;\n\n constructor(kind?: EnvironmentKind) {\n this.kind = kind ?? detectEnvironment();\n this.capabilities = detectCapabilities();\n }\n\n get isBrowser(): boolean {\n return this.kind === 'browser';\n }\n\n get isServer(): boolean {\n return this.kind === 'server';\n }\n\n get isTest(): boolean {\n return this.kind === 'test';\n }\n\n get isWorker(): boolean {\n return this.kind === 'worker';\n }\n}\n\n/** The singleton environment for this execution context. */\nexport const environment = new Environment();\n","/**\n * Framework diagnostics — structured errors, warnings, and hints\n * that flow through the compiler, validator, and runtime.\n */\n\nexport type DiagnosticSeverity = 'error' | 'warning' | 'info';\n\nexport interface DiagnosticLocation {\n readonly file?: string;\n readonly line?: number;\n readonly column?: number;\n readonly nodeId?: string;\n}\n\nexport interface Diagnostic {\n readonly severity: DiagnosticSeverity;\n readonly code: string;\n readonly message: string;\n readonly location: DiagnosticLocation | undefined;\n readonly cause: unknown;\n}\n\nexport class DiagnosticError extends Error {\n readonly diagnostics: readonly Diagnostic[];\n\n constructor(diagnostics: readonly Diagnostic[]) {\n const summary = diagnostics\n .filter(d => d.severity === 'error')\n .map(d => `[${d.code}] ${d.message}`)\n .join('\\n');\n super(`StreetUI diagnostics:\\n${summary}`);\n this.name = 'DiagnosticError';\n this.diagnostics = diagnostics;\n }\n}\n\nexport class DiagnosticCollector {\n private readonly _diagnostics: Diagnostic[] = [];\n\n get diagnostics(): readonly Diagnostic[] {\n return this._diagnostics;\n }\n\n get hasErrors(): boolean {\n return this._diagnostics.some(d => d.severity === 'error');\n }\n\n get hasWarnings(): boolean {\n return this._diagnostics.some(d => d.severity === 'warning');\n }\n\n error(\n code: string,\n message: string,\n location?: DiagnosticLocation,\n cause?: unknown,\n ): void {\n this._diagnostics.push({ severity: 'error', code, message, location: location ?? undefined, cause: cause ?? undefined });\n }\n\n warn(\n code: string,\n message: string,\n location?: DiagnosticLocation,\n ): void {\n this._diagnostics.push({ severity: 'warning', code, message, location: location ?? undefined, cause: undefined });\n }\n\n info(\n code: string,\n message: string,\n location?: DiagnosticLocation,\n ): void {\n this._diagnostics.push({ severity: 'info', code, message, location: location ?? undefined, cause: undefined });\n }\n\n merge(other: DiagnosticCollector): void {\n for (const d of other.diagnostics) {\n this._diagnostics.push(d);\n }\n }\n\n throwIfErrors(): void {\n if (this.hasErrors) {\n throw new DiagnosticError(this._diagnostics);\n }\n }\n\n clear(): void {\n this._diagnostics.length = 0;\n }\n}\n\n/** Format a single diagnostic as a human-readable string. */\nexport function formatDiagnostic(d: Diagnostic): string {\n const loc = d.location !== undefined\n ? ` (${[d.location.file, d.location.line, d.location.column]\n .filter(Boolean)\n .join(':')})`\n : '';\n return `[${d.severity.toUpperCase()}] ${d.code}: ${d.message}${loc}`;\n}\n","/**\n * Top-level Application primitive.\n * Owns lifecycle, identity, and the root of the application graph.\n */\n\nimport { type ApplicationId, generateApplicationId } from './identity.js';\nimport { Lifecycle, CleanupRegistry } from './lifecycle.js';\nimport { Environment, environment as defaultEnvironment } from './environment.js';\nimport { DiagnosticCollector } from './diagnostics.js';\n\nexport interface ApplicationOptions {\n readonly name: string;\n readonly version?: string;\n readonly environment?: Environment;\n}\n\nexport class Application {\n readonly id: ApplicationId;\n readonly name: string;\n readonly version: string;\n readonly lifecycle: Lifecycle;\n readonly cleanup: CleanupRegistry;\n readonly diagnostics: DiagnosticCollector;\n readonly environment: Environment;\n\n constructor(options: ApplicationOptions) {\n this.name = options.name;\n this.version = options.version ?? '0.0.1';\n this.id = generateApplicationId(options.name);\n this.lifecycle = new Lifecycle();\n this.cleanup = new CleanupRegistry();\n this.diagnostics = new DiagnosticCollector();\n this.environment = options.environment ?? defaultEnvironment;\n }\n\n async mount(): Promise<void> {\n if (this.lifecycle.phase !== 'created') {\n throw new Error(`Application \"${this.name}\" is already mounted (phase: ${this.lifecycle.phase})`);\n }\n await this.lifecycle.transition('mounted');\n await this.lifecycle.transition('active');\n }\n\n async unmount(): Promise<void> {\n if (!this.lifecycle.isMounted) {\n return;\n }\n await this.lifecycle.transition('unmounting');\n this.cleanup.run();\n await this.lifecycle.transition('destroyed');\n }\n\n onMount(fn: () => void | Promise<void>): void {\n this.lifecycle.onMount(fn);\n }\n\n onUnmount(fn: () => void | Promise<void>): void {\n this.lifecycle.onUnmount(fn);\n }\n}\n\n/** Factory convenience wrapper. */\nexport function createApplication(options: ApplicationOptions): Application {\n return new Application(options);\n}\n","/**\n * Framework node primitives — the base abstraction for every node\n * in the Semantic Application Graph.\n */\n\nimport { type NodeId, generateNodeId } from './identity.js';\n\nexport type SemanticNodeType =\n | 'application'\n | 'page'\n | 'section'\n | 'container'\n | 'heading'\n | 'text'\n | 'button'\n | 'input'\n | 'form'\n | 'list'\n | 'list-item'\n | 'image'\n | 'link'\n | 'component'\n | 'slot'\n | 'fragment'\n | 'reactive-list'\n | 'conditional';\n\nexport interface NodeMetadata {\n readonly createdAt: number;\n readonly [key: string]: unknown;\n}\n\nexport abstract class BaseNode {\n readonly id: NodeId;\n readonly type: SemanticNodeType;\n readonly metadata: NodeMetadata;\n\n constructor(type: SemanticNodeType, id?: NodeId) {\n this.type = type;\n this.id = id ?? generateNodeId(type);\n this.metadata = { createdAt: Date.now() };\n }\n\n abstract clone(): BaseNode;\n}\n","/**\n * Observability boundary — a tiny, optional logging seam plus contextual\n * framework errors.\n *\n * StreetUI never ships a telemetry service, never sends anything over the\n * network, and never logs on its own by default. Instead an application MAY\n * hand the framework a `DiagnosticSink` — any object with the log methods it\n * cares about — and the framework will route the diagnostics it already\n * produces (runtime errors, resource failures, hydration mismatches, router\n * transitions) to it. With no sink attached there is no logging and no cost.\n *\n * This is deliberately smaller than a logging library: it duplicates neither\n * `console` nor any structured-diagnostic type. It is a boundary, not a logger.\n */\n\n/**\n * Where a framework diagnostic originated. Every field is optional so a caller\n * supplies only what is meaningful for the situation. Values are intended to be\n * non-sensitive identifiers — never tokens, secrets, cookies, or form values.\n */\nexport interface DiagnosticContext {\n /** The package that produced the diagnostic, e.g. `@streetui/renderer`. */\n readonly package?: string;\n /** The operation underway, e.g. `hydrate`, `compile`, `navigate`. */\n readonly operation?: string;\n /** The graph node id involved, when applicable. */\n readonly nodeId?: string;\n /** The route path involved, when applicable. */\n readonly route?: string;\n /** A resource identifier involved, when applicable. */\n readonly resource?: string;\n}\n\n/**\n * The application-provided logging seam. Every method is optional; the\n * framework calls only the ones present. Implementations must not throw.\n */\nexport interface DiagnosticSink {\n debug?(message: string, context?: DiagnosticContext): void;\n info?(message: string, context?: DiagnosticContext): void;\n warn?(message: string, context?: DiagnosticContext): void;\n error?(message: string, context?: DiagnosticContext): void;\n}\n\n/** Format a context object as a compact ` [k=v, …]` suffix (empty when bare). */\nexport function formatDiagnosticContext(context?: DiagnosticContext): string {\n if (context === undefined) return '';\n const parts: string[] = [];\n if (context.package !== undefined) parts.push(`package=${context.package}`);\n if (context.operation !== undefined) parts.push(`operation=${context.operation}`);\n if (context.nodeId !== undefined) parts.push(`node=${context.nodeId}`);\n if (context.route !== undefined) parts.push(`route=${context.route}`);\n if (context.resource !== undefined) parts.push(`resource=${context.resource}`);\n return parts.length > 0 ? ` [${parts.join(', ')}]` : '';\n}\n\n/**\n * A framework error whose message carries structured, non-sensitive context so\n * a developer immediately sees which package/operation/node was involved. The\n * message never embeds a stack or environment values; production stack\n * disclosure decisions stay with the server layer.\n */\nexport class StreetFrameworkError extends Error {\n readonly context: DiagnosticContext | undefined;\n\n constructor(message: string, context?: DiagnosticContext) {\n super(`${message}${formatDiagnosticContext(context)}`);\n this.name = 'StreetFrameworkError';\n this.context = context ?? undefined;\n }\n}\n\n/** Build a `StreetFrameworkError` with the given context. */\nexport function frameworkError(\n message: string,\n context?: DiagnosticContext,\n): StreetFrameworkError {\n return new StreetFrameworkError(message, context);\n}\n\n/**\n * Route a diagnostic to a sink if it implements the matching level. Safe to\n * call with `undefined` — it simply does nothing, which is the default (no\n * logging) posture. Never throws even if the sink method does.\n */\nexport function reportDiagnostic(\n sink: DiagnosticSink | undefined,\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n context?: DiagnosticContext,\n): void {\n if (sink === undefined) return;\n const fn = sink[level];\n if (typeof fn !== 'function') return;\n try {\n fn.call(sink, message, context);\n } catch {\n // A misbehaving sink must never break the framework.\n }\n}\n\n/** A sink that forwards to a `console`-like object, one call per level. */\nexport function consoleDiagnosticSink(\n logger: Partial<Record<'debug' | 'info' | 'warn' | 'error', (msg: string) => void>> = console,\n): DiagnosticSink {\n return {\n debug: (m, c) => logger.debug?.(`${m}${formatDiagnosticContext(c)}`),\n info: (m, c) => logger.info?.(`${m}${formatDiagnosticContext(c)}`),\n warn: (m, c) => logger.warn?.(`${m}${formatDiagnosticContext(c)}`),\n error: (m, c) => logger.error?.(`${m}${formatDiagnosticContext(c)}`),\n };\n}\n","/**\n * Semantic Application Graph nodes.\n *\n * Every element in a StreetUI application is represented as a GraphNode.\n * Nodes form a tree: each has an optional parent and an ordered list of children.\n */\n\nimport { generateNodeId, type NodeId, type SemanticNodeType } from '@streetui/core';\n\n// ── Property values ───────────────────────────────────────────────────────────\n\nexport type PropValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | string[]\n | number[]\n | Record<string, unknown>;\n\nexport type Props = Record<string, PropValue>;\n\n// ── Event descriptors ─────────────────────────────────────────────────────────\n\nexport interface EventDescriptor {\n readonly type: string;\n /** Reference key into the application's handler registry. */\n readonly handlerKey: string;\n}\n\n// ── State references ──────────────────────────────────────────────────────────\n\nexport interface StateRef {\n /** ID of the signal/store this node's property is bound to. */\n readonly signalId: string;\n /** The prop key on this node that is bound. */\n readonly propKey: string;\n}\n\n// ── The core graph node ───────────────────────────────────────────────────────\n\nexport interface GraphNodeData {\n readonly id: NodeId;\n readonly type: SemanticNodeType;\n readonly key: string | undefined;\n props: Props;\n events: EventDescriptor[];\n stateRefs: StateRef[];\n children: GraphNode[];\n parent: GraphNode | null;\n}\n\nexport class GraphNode implements GraphNodeData {\n readonly id: NodeId;\n readonly type: SemanticNodeType;\n readonly key: string | undefined;\n props: Props;\n events: EventDescriptor[];\n stateRefs: StateRef[];\n children: GraphNode[];\n parent: GraphNode | null;\n\n constructor(\n type: SemanticNodeType,\n options: {\n id?: NodeId;\n key?: string;\n props?: Props;\n events?: EventDescriptor[];\n stateRefs?: StateRef[];\n } = {},\n ) {\n this.type = type;\n this.id = options.id ?? generateNodeId(type);\n this.key = options.key;\n this.props = options.props ?? {};\n this.events = options.events ?? [];\n this.stateRefs = options.stateRefs ?? [];\n this.children = [];\n this.parent = null;\n }\n\n // ── Child management ────────────────────────────────────────────────────────\n\n appendChild(child: GraphNode): void {\n if (child.parent !== null) {\n child.parent.removeChild(child);\n }\n child.parent = this;\n this.children.push(child);\n }\n\n insertBefore(child: GraphNode, reference: GraphNode): void {\n const idx = this.children.indexOf(reference);\n if (idx === -1) {\n this.appendChild(child);\n return;\n }\n if (child.parent !== null) {\n child.parent.removeChild(child);\n }\n child.parent = this;\n this.children.splice(idx, 0, child);\n }\n\n removeChild(child: GraphNode): void {\n const idx = this.children.indexOf(child);\n if (idx === -1) return;\n this.children.splice(idx, 1);\n child.parent = null;\n }\n\n replaceChild(newChild: GraphNode, oldChild: GraphNode): void {\n const idx = this.children.indexOf(oldChild);\n if (idx === -1) {\n throw new Error(`GraphNode.replaceChild: oldChild is not a child of this node`);\n }\n if (newChild.parent !== null) {\n newChild.parent.removeChild(newChild);\n }\n oldChild.parent = null;\n newChild.parent = this;\n this.children.splice(idx, 1, newChild);\n }\n\n // ── Prop helpers ────────────────────────────────────────────────────────────\n\n setProp(key: string, value: PropValue): void {\n this.props = { ...this.props, [key]: value };\n }\n\n getProp<T extends PropValue = PropValue>(key: string): T | undefined {\n return this.props[key] as T | undefined;\n }\n\n // ── Event helpers ───────────────────────────────────────────────────────────\n\n addEvent(descriptor: EventDescriptor): void {\n this.events.push(descriptor);\n }\n\n removeEvent(type: string): void {\n this.events = this.events.filter(e => e.type !== type);\n }\n\n // ── Queries ─────────────────────────────────────────────────────────────────\n\n get isLeaf(): boolean {\n return this.children.length === 0;\n }\n\n get depth(): number {\n let d = 0;\n let node: GraphNode | null = this.parent;\n while (node !== null) {\n d++;\n node = node.parent;\n }\n return d;\n }\n\n get root(): GraphNode {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let node: GraphNode = this;\n while (node.parent !== null) {\n node = node.parent;\n }\n return node;\n }\n\n /** Shallow clone — does not clone children. */\n shallowClone(): GraphNode {\n const opts: { key?: string; props: Props; events: EventDescriptor[]; stateRefs: StateRef[] } = {\n props: { ...this.props },\n events: [...this.events],\n stateRefs: [...this.stateRefs],\n };\n if (this.key !== undefined) opts.key = this.key;\n return new GraphNode(this.type, opts);\n }\n}\n","/**\n * The Semantic Application Graph.\n *\n * Holds the application root node and all its descendants.\n * Supports traversal, lookup by ID, validation, and serialization.\n */\n\nimport { type NodeId, DiagnosticCollector } from '@streetui/core';\nimport { GraphNode, type Props, type EventDescriptor } from './graph-node.js';\n\nexport interface ApplicationGraphOptions {\n readonly name: string;\n readonly version?: string;\n}\n\nexport interface HandlerFn {\n (...args: unknown[]): unknown;\n}\n\nexport class ApplicationGraph {\n readonly root: GraphNode;\n readonly name: string;\n readonly version: string;\n private readonly _nodeIndex: Map<NodeId, GraphNode> = new Map();\n /** Handler registry — maps handlerKey → actual function */\n readonly handlers: Map<string, HandlerFn> = new Map();\n\n constructor(options: ApplicationGraphOptions) {\n this.name = options.name;\n this.version = options.version ?? '0.0.1';\n this.root = new GraphNode('application', { props: { name: options.name } });\n this._nodeIndex.set(this.root.id, this.root);\n }\n\n // ── Node creation & attachment ────────────────────────────────────────────\n\n createNode(\n type: GraphNode['type'],\n options: { key?: string; props?: Props; parent?: GraphNode } = {},\n ): GraphNode {\n const nodeOpts: { key?: string; props?: Props } = {};\n if (options.key !== undefined) nodeOpts.key = options.key;\n if (options.props !== undefined) nodeOpts.props = options.props;\n const node = new GraphNode(type, nodeOpts);\n this._nodeIndex.set(node.id, node);\n if (options.parent !== undefined) {\n options.parent.appendChild(node);\n }\n return node;\n }\n\n attachNode(node: GraphNode, parent: GraphNode): void {\n this._nodeIndex.set(node.id, node);\n parent.appendChild(node);\n }\n\n detachNode(node: GraphNode): void {\n if (node.parent !== null) {\n node.parent.removeChild(node);\n }\n this._removeFromIndex(node);\n }\n\n private _removeFromIndex(node: GraphNode): void {\n this._nodeIndex.delete(node.id);\n this._unregisterNodeHandlers(node);\n for (const child of node.children) {\n this._removeFromIndex(child);\n }\n }\n\n /**\n * Remove every handler-registry entry owned by a single node. A node owns:\n * - one entry per event descriptor (its `handlerKey`),\n * - one `__signal__<signalId>` entry per state ref (signalIds are namespaced\n * by node id, so they are never shared between nodes), and\n * - a `__listbuild__<id>` entry if it is a reactive-list.\n * Called for every node in a detached subtree so removing list items (or\n * discarding freshly-built-but-unadopted item subtrees) leaves no stale\n * registrations behind.\n */\n private _unregisterNodeHandlers(node: GraphNode): void {\n for (const event of node.events) {\n this.handlers.delete(event.handlerKey);\n }\n for (const ref of node.stateRefs) {\n this.handlers.delete(`__signal__${ref.signalId}`);\n }\n this.handlers.delete(`__listbuild__${node.id}`);\n this.handlers.delete(`__listplan__${node.id}`);\n }\n\n // ── Handler registry ──────────────────────────────────────────────────────\n\n registerHandler(key: string, fn: HandlerFn): void {\n this.handlers.set(key, fn);\n }\n\n getHandler(key: string): HandlerFn | undefined {\n return this.handlers.get(key);\n }\n\n /** True if a handler is currently registered under `key`. Inspection helper. */\n hasHandler(key: string): boolean {\n return this.handlers.has(key);\n }\n\n /** Number of currently-registered handlers. Inspection helper. */\n get handlerCount(): number {\n return this.handlers.size;\n }\n\n // ── Lookup ────────────────────────────────────────────────────────────────\n\n findById(id: NodeId): GraphNode | undefined {\n return this._nodeIndex.get(id);\n }\n\n findAll(predicate: (node: GraphNode) => boolean): GraphNode[] {\n const results: GraphNode[] = [];\n this._walk(this.root, node => {\n if (predicate(node)) results.push(node);\n });\n return results;\n }\n\n findByType(type: GraphNode['type']): GraphNode[] {\n return this.findAll(n => n.type === type);\n }\n\n // ── Traversal ─────────────────────────────────────────────────────────────\n\n walk(visitor: (node: GraphNode, depth: number) => void): void {\n this._walk(this.root, visitor, 0);\n }\n\n private _walk(\n node: GraphNode,\n visitor: (node: GraphNode, depth: number) => void,\n depth: number = 0,\n ): void {\n visitor(node, depth);\n for (const child of node.children) {\n this._walk(child, visitor, depth + 1);\n }\n }\n\n get nodeCount(): number {\n return this._nodeIndex.size;\n }\n\n // ── Validation ────────────────────────────────────────────────────────────\n\n validate(): DiagnosticCollector {\n const dc = new DiagnosticCollector();\n\n this.walk((node) => {\n // Validate event handler references exist\n for (const event of node.events) {\n if (!this.handlers.has(event.handlerKey)) {\n dc.warn(\n 'GRAPH_MISSING_HANDLER',\n `Node \"${node.id}\" references handler \"${event.handlerKey}\" which is not registered`,\n { nodeId: node.id },\n );\n }\n }\n\n // Validate page nodes are direct children of root\n if (node.type === 'page' && node.parent?.type !== 'application') {\n dc.error(\n 'GRAPH_PAGE_DEPTH',\n `Page node \"${node.id}\" must be a direct child of the application root`,\n { nodeId: node.id },\n );\n }\n });\n\n return dc;\n }\n\n // ── Serialization ─────────────────────────────────────────────────────────\n\n serialize(): SerializedGraph {\n return {\n name: this.name,\n version: this.version,\n root: this._serializeNode(this.root),\n };\n }\n\n private _serializeNode(node: GraphNode): SerializedNode {\n const result: SerializedNode = {\n id: node.id,\n type: node.type,\n key: node.key,\n props: node.props,\n events: node.events,\n stateRefs: node.stateRefs,\n children: node.children.map(c => this._serializeNode(c)),\n };\n return result;\n }\n}\n\nexport interface SerializedNode {\n readonly id: string;\n readonly type: string;\n readonly key: string | undefined;\n readonly props: Props;\n readonly events: EventDescriptor[];\n readonly stateRefs: unknown[];\n readonly children: SerializedNode[];\n}\n\nexport interface SerializedGraph {\n readonly name: string;\n readonly version: string;\n readonly root: SerializedNode;\n}\n","/**\n * DSL builder implementations.\n *\n * Each builder wraps a GraphNode and provides the fluent API\n * for constructing the Semantic Application Graph via the DSL.\n *\n * Builders do NOT render anything — they only build the graph.\n */\n\nimport { ApplicationGraph, GraphNode, type Props } from '@streetui/graph';\nimport type {\n ContentDSL,\n ContainerDSL,\n SectionDSL,\n PageDSL,\n FormDSL,\n ListDSL,\n AppDSL,\n HeadingOptions,\n TextOptions,\n ButtonOptions,\n InputOptions,\n LinkOptions,\n ImageOptions,\n ContainerOptions,\n SectionOptions,\n FormOptions,\n ListOptions,\n A11yOptions,\n Bindable,\n BindableText,\n TextValue,\n ErrorBoundaryOptions,\n ErrorSource,\n PageBuilder,\n SectionBuilder,\n ContainerBuilder as ContainerBuilderFn,\n FormBuilder,\n ListBuilder,\n} from './dsl-types.js';\nimport { signal, derived, type Signal, type ReadonlySignal } from '@streetui/state';\n\n/**\n * A single reactive-list reconciliation descriptor (spec §15).\n *\n * Emitted by the `__listplan__<nodeId>` handler on every list change. `key` is\n * the item's identity-only reconciliation key (cheap to compute); `item` is the\n * source value *reference* used for identity short-circuiting; `sig()` computes\n * the content signature on demand (only when the reference changed); `build()`\n * materialises the full item subtree on demand (only for new/changed rows).\n */\nexport interface ListPlanEntry {\n readonly key: string;\n readonly item: unknown;\n readonly sig: () => string;\n readonly build: () => GraphNode;\n}\n\n// ── Signal helpers ────────────────────────────────────────────────────────────\n\nfunction isSignal(v: unknown): v is Signal<unknown> | ReadonlySignal<unknown> {\n return (\n v !== null &&\n typeof v === 'object' &&\n typeof (v as Record<string, unknown>)['get'] === 'function' &&\n typeof (v as Record<string, unknown>)['subscribe'] === 'function'\n );\n}\n\n/** Register a signal binding on the node and return the current static value. */\nfunction bindValue<T>(\n graph: ApplicationGraph,\n node: GraphNode,\n propKey: string,\n value: Bindable<T>,\n): T {\n if (isSignal(value)) {\n const signalId = `${node.id}:${propKey}`;\n node.stateRefs.push({ signalId, propKey });\n graph.registerHandler(`__signal__${signalId}`, value as unknown as () => unknown);\n return (value as ReadonlySignal<T>).peek();\n }\n return value as T;\n}\n\n// ── Helper to build Props from ContainerOptions ───────────────────────────────\n\n/**\n * Copy accessibility options onto a props bag as their corresponding HTML/ARIA\n * attribute names. Values are written as strings (booleans become \"true\"/\"false\"\n * rather than being dropped) so ARIA state attributes render literally. These\n * flow to the DOM via the renderer's generic attribute pass — no ARIA-specific\n * renderer code is involved.\n */\nfunction applyA11yProps(props: Props, options: A11yOptions): void {\n if (options.role !== undefined) props['role'] = options.role;\n if (options.tabIndex !== undefined) props['tabindex'] = String(options.tabIndex);\n if (options.ariaLabel !== undefined) props['aria-label'] = options.ariaLabel;\n if (options.ariaLabelledBy !== undefined) props['aria-labelledby'] = options.ariaLabelledBy;\n if (options.ariaDescribedBy !== undefined) props['aria-describedby'] = options.ariaDescribedBy;\n if (options.ariaExpanded !== undefined) props['aria-expanded'] = String(options.ariaExpanded);\n if (options.ariaControls !== undefined) props['aria-controls'] = options.ariaControls;\n if (options.ariaHidden !== undefined) props['aria-hidden'] = String(options.ariaHidden);\n if (options.ariaLive !== undefined) props['aria-live'] = options.ariaLive;\n if (options.ariaCurrent !== undefined) props['aria-current'] = String(options.ariaCurrent);\n if (options.ariaInvalid !== undefined) props['aria-invalid'] = String(options.ariaInvalid);\n if (options.ariaRequired !== undefined) props['aria-required'] = String(options.ariaRequired);\n}\n\nfunction containerProps(options: ContainerOptions): Props {\n const props: Props = {};\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n if (options.key !== undefined) props['key'] = options.key;\n applyA11yProps(props, options);\n return props;\n}\n\n// ── Reactive-list item keying ──────────────────────────────────────────────────\n//\n// The `listOf` DSL signature does not take an explicit key extractor, so we\n// derive a stable reconciliation key from each item. The key combines an\n// *identity* part (so reordering the same items reuses their DOM nodes) with a\n// *value signature* (so an item whose data changed is treated as a fresh node\n// and re-rendered rather than silently kept stale by the shallow reconciler).\n\nfunction itemIdentity(item: unknown, index: number): string {\n if (item !== null && typeof item === 'object') {\n const obj = item as Record<string, unknown>;\n if ('id' in obj) return `id:${String(obj['id'])}`;\n if ('key' in obj) return `key:${String(obj['key'])}`;\n return `idx:${index}`;\n }\n return `val:${String(item)}`;\n}\n\nfunction itemValueSignature(item: unknown): string {\n try {\n return JSON.stringify(item) ?? String(item);\n } catch {\n return String(item);\n }\n}\n\n/** Content signature used to detect in-place data changes of a stable item. */\nexport function reactiveListItemSignature(item: unknown): string {\n return itemValueSignature(item);\n}\n\n/** Stable, identity-only reconciliation key for a reactive-list item. */\nexport function reactiveListItemKey(item: unknown, index: number): string {\n return itemIdentity(item, index);\n}\n\n// ── Base content builder ──────────────────────────────────────────────────────\n\nclass ContentBuilderBase implements ContentDSL {\n constructor(\n protected readonly _node: GraphNode,\n protected readonly _graph: ApplicationGraph,\n ) {}\n\n heading(text: BindableText, options: HeadingOptions = {}): void {\n const props: Props = { level: options.level ?? 1 };\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const node = this._graph.createNode('heading', { parent: this._node, props });\n const resolved = bindValue<TextValue>(this._graph, node, 'text', text);\n node.setProp('text', resolved);\n }\n\n text(content: BindableText, options: TextOptions = {}): void {\n const props: Props = {};\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const node = this._graph.createNode('text', { parent: this._node, props });\n const resolved = bindValue<TextValue>(this._graph, node, 'text', content);\n node.setProp('text', resolved);\n }\n\n button(label: BindableText, options: ButtonOptions = {}): void {\n const props: Props = {};\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const node = this._graph.createNode('button', { parent: this._node, props });\n const resolved = bindValue<TextValue>(this._graph, node, 'label', label);\n node.setProp('label', resolved);\n if (options.disabled !== undefined) {\n const resolvedDisabled = bindValue(this._graph, node, 'disabled', options.disabled);\n node.setProp('disabled', resolvedDisabled);\n }\n if (options.onClick !== undefined) {\n const handlerKey = `click:${node.id}`;\n this._graph.registerHandler(handlerKey, options.onClick as () => unknown);\n node.addEvent({ type: 'click', handlerKey });\n }\n }\n\n input(options: InputOptions = {}): void {\n const props: Props = {};\n props['inputType'] = options.type ?? 'text';\n if (options.placeholder !== undefined) props['placeholder'] = options.placeholder;\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const nodeOpts: { key?: string; props: Props; parent: GraphNode } = {\n props,\n parent: this._node,\n };\n if (options.id !== undefined) nodeOpts.key = options.id;\n const node = this._graph.createNode('input', nodeOpts);\n\n // Two-way `bind` expands to a value binding + an input write-back. The type\n // system (BoundInputOptions vs ControlledInputOptions) guarantees `bind` is\n // never combined with explicit `value`/`onInput`, so there is no ambiguity.\n const bindSignal = options.bind;\n const valueBindable: Bindable<string> | undefined =\n bindSignal !== undefined ? bindSignal : options.value;\n const inputHandler: ((value: string) => void) | undefined =\n bindSignal !== undefined ? (v: string) => bindSignal.set(v) : options.onInput;\n\n if (valueBindable !== undefined) {\n const resolved = bindValue(this._graph, node, 'value', valueBindable);\n node.setProp('value', resolved);\n }\n if (options.disabled !== undefined) {\n const resolved = bindValue(this._graph, node, 'disabled', options.disabled);\n node.setProp('disabled', resolved);\n }\n if (inputHandler !== undefined) {\n const handlerKey = `input:${node.id}`;\n this._graph.registerHandler(handlerKey, inputHandler as () => unknown);\n node.addEvent({ type: 'input', handlerKey });\n }\n if (options.onChange !== undefined) {\n const handlerKey = `change:${node.id}`;\n this._graph.registerHandler(handlerKey, options.onChange as () => unknown);\n node.addEvent({ type: 'change', handlerKey });\n }\n }\n\n image(options: ImageOptions): void {\n const props: Props = {\n src: options.src,\n alt: options.alt,\n };\n if (options.width !== undefined) props['width'] = options.width;\n if (options.height !== undefined) props['height'] = options.height;\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const nodeOpts: { key?: string; props: Props; parent: GraphNode } = {\n props,\n parent: this._node,\n };\n if (options.id !== undefined) nodeOpts.key = options.id;\n this._graph.createNode('image', nodeOpts);\n }\n\n link(label: BindableText, options: LinkOptions): void {\n const props: Props = {\n href: options.href,\n external: options.external ?? false,\n };\n if (options.class !== undefined) props['class'] = options.class;\n if (options.id !== undefined) props['id'] = options.id;\n applyA11yProps(props, options);\n const node = this._graph.createNode('link', { parent: this._node, props });\n const resolved = bindValue<TextValue>(this._graph, node, 'label', label);\n node.setProp('label', resolved);\n if (options.onClick !== undefined) {\n const handlerKey = `click:${node.id}`;\n this._graph.registerHandler(handlerKey, options.onClick as () => unknown);\n node.addEvent({ type: 'click', handlerKey });\n }\n }\n}\n\n// ── Container builder ─────────────────────────────────────────────────────────\n\nclass ContainerBuilderBase extends ContentBuilderBase implements ContainerDSL {\n section(key: string, builder: SectionBuilder, options: SectionOptions = {}): void {\n const node = this._graph.createNode('section', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n builder(new SectionBuilderImpl(node, this._graph));\n }\n\n container(key: string, builder: ContainerBuilderFn, options: ContainerOptions = {}): void {\n const node = this._graph.createNode('container', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n builder(new ContainerBuilderImpl(node, this._graph));\n }\n\n list(key: string, builder: ListBuilder, options: ListOptions = {}): void {\n const node = this._graph.createNode('list', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n builder(new ListBuilderImpl(node, this._graph));\n }\n\n listOf<T>(\n key: string,\n items: Signal<T[]> | ReadonlySignal<T[]>,\n renderItem: (item: T, index: number, content: ContentDSL) => void,\n options: ListOptions = {},\n ): void {\n const graph = this._graph;\n const node = graph.createNode('reactive-list', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n\n // Register the driving signal so the runtime/renderer can subscribe to it.\n const signalId = `${node.id}:items`;\n node.stateRefs.push({ signalId, propKey: 'items' });\n graph.registerHandler(`__signal__${signalId}`, items as unknown as () => unknown);\n\n // Build a single detached list-item subtree for one item. The item's\n // reconciliation `key` is identity-only, and its value signature is stored\n // in the internal `_sig` prop so the renderer can detect (and apply a\n // targeted update for) a data change on an item whose identity is stable.\n const buildItem = (item: T, index: number): GraphNode => {\n const itemKey = reactiveListItemKey(item, index);\n const itemNode = graph.createNode('list-item', {\n key: itemKey,\n // `_item` records the source item *reference* so the reconciler can\n // short-circuit unchanged rows by identity (no signature hashing); `_sig`\n // is the content signature used to detect an in-place data change when the\n // reference differs. Both are internal metadata (leading `_`) and never\n // reach the DOM.\n props: {\n key: itemKey,\n _sig: reactiveListItemSignature(item),\n // The item reference is stored as opaque internal metadata (never\n // rendered); cast through `unknown` since `T` is not a `PropValue`.\n _item: item as unknown as Props[string],\n },\n });\n renderItem(item, index, new ContainerBuilderImpl(itemNode, graph));\n return itemNode;\n };\n\n // Lazy reconciliation plan (spec §15 — the measured keyed-list hot path).\n //\n // Instead of eagerly rebuilding all N item GraphNodes (and hashing every item\n // with JSON.stringify) on *every* emission — the dominant cost of the old\n // `buildAll` path — the renderer receives lightweight descriptors and only\n // materialises a subtree for rows that are genuinely new or whose data\n // actually changed. `key` is cheap (identity only); `sig()` and `build()` are\n // thunks the reconciler calls on demand.\n const buildPlan = (raw: unknown): ListPlanEntry[] => {\n const arr = Array.isArray(raw) ? (raw as T[]) : [];\n const plan: ListPlanEntry[] = new Array(arr.length);\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i]!;\n const index = i;\n plan[i] = {\n key: reactiveListItemKey(item, index),\n item,\n sig: () => reactiveListItemSignature(item),\n build: () => buildItem(item, index),\n };\n }\n return plan;\n };\n graph.registerHandler(`__listplan__${node.id}`, buildPlan as unknown as () => unknown);\n\n // Build the initial children into the graph so the first mount renders them.\n const current = isSignal(items)\n ? (items as ReadonlySignal<T[]>).peek()\n : (items as unknown as T[]);\n const initial = Array.isArray(current) ? current : [];\n initial.forEach((item, i) => {\n node.appendChild(buildItem(item, i));\n });\n }\n\n form(key: string, builder: FormBuilder, options: FormOptions = {}): void {\n const props: Props = containerProps(options);\n const node = this._graph.createNode('form', {\n key,\n parent: this._node,\n props,\n });\n if (options.onSubmit !== undefined) {\n const handlerKey = `submit:${node.id}`;\n this._graph.registerHandler(handlerKey, options.onSubmit as () => unknown);\n node.addEvent({ type: 'submit', handlerKey });\n }\n builder(new FormBuilderImpl(node, this._graph));\n }\n\n when(\n condition: Bindable<boolean>,\n builder: ContainerBuilderFn,\n elseBuilder?: ContainerBuilderFn,\n ): void {\n const graph = this._graph;\n // A dedicated 'conditional' node reuses the reactive-list reconciliation\n // machinery (same signal subscription + keyed reconcile) but renders as a\n // neutral <div> rather than a <ul>. It holds zero or one child branch.\n const node = graph.createNode('conditional', {\n parent: this._node,\n props: containerProps({}),\n });\n\n // Build the active branch as a single keyed container. Distinct keys for the\n // then/else branches make a flip a clean swap under the keyed reconciler.\n const buildBranch = (build: ContainerBuilderFn, tag: 'then' | 'else'): GraphNode => {\n const branchKey = `when-${tag}:${node.id}`;\n const branch = graph.createNode('container', {\n key: branchKey,\n props: { key: branchKey },\n });\n build(new ContainerBuilderImpl(branch, graph));\n return branch;\n };\n\n const buildAll = (raw: unknown): GraphNode[] => {\n if (raw) return [buildBranch(builder, 'then')];\n return elseBuilder !== undefined ? [buildBranch(elseBuilder, 'else')] : [];\n };\n\n if (isSignal(condition)) {\n const signalId = `${node.id}:items`;\n node.stateRefs.push({ signalId, propKey: 'items' });\n graph.registerHandler(`__signal__${signalId}`, condition as unknown as () => unknown);\n graph.registerHandler(`__listbuild__${node.id}`, buildAll as unknown as () => unknown);\n const current = (condition as ReadonlySignal<boolean>).peek();\n for (const child of buildAll(current)) node.appendChild(child);\n } else {\n // Static condition — resolve once at build time, no reactive wiring.\n for (const child of buildAll(condition)) node.appendChild(child);\n }\n }\n\n errorBoundary(\n id: string,\n builder: ContainerBuilderFn,\n options: ErrorBoundaryOptions,\n ): void {\n // Normalise the observed error source(s) into an array.\n const sources: ErrorSource[] =\n options.source === undefined\n ? []\n : Array.isArray(options.source)\n ? [...options.source]\n : [options.source];\n\n // The boundary's own captured error (from a synchronous build throw) and a\n // retry nonce that forces a re-evaluation even when the boolean is unchanged.\n const localError = signal<unknown>(undefined);\n const retryNonce = signal<number>(0);\n\n const readError = (): unknown => {\n const local = localError.peek();\n if (local !== undefined && local !== null) return local;\n for (const s of sources) {\n const e = s.peek();\n if (e !== undefined && e !== null) return e;\n }\n return undefined;\n };\n\n // Reactive condition: true while an error is present. Reads every input so a\n // change in any source (or a retry) re-runs the conditional.\n const hasError = derived<boolean>(() => {\n retryNonce.get();\n localError.get();\n for (const s of sources) s.get();\n return readError() !== undefined;\n });\n\n const retry = (): void => {\n localError.set(undefined);\n options.onRetry?.();\n // Force the body branch to re-attempt even if no observed value changed.\n retryNonce.update((n) => n + 1);\n };\n\n // Wrap in a container so the whole boundary is addressable and disposes as a\n // unit. `when` provides the reactive body↔fallback swap (and its cleanup).\n this.container(id, (c) => {\n c.when(\n hasError,\n // Error state → fallback.\n (fb) => options.fallback(fb, readError(), retry),\n // Healthy state → body, guarded against synchronous build throws.\n (body) => {\n try {\n builder(body);\n } catch (err) {\n // Surface the throw as the boundary's error on the next microtask\n // (deferred to avoid re-entrant reconciliation during this build).\n queueMicrotask(() => localError.set(err));\n }\n },\n );\n }, { id });\n }\n}\n\n// ── Concrete builder implementations ─────────────────────────────────────────\n\nexport class SectionBuilderImpl extends ContainerBuilderBase implements SectionDSL {}\nexport class ContainerBuilderImpl extends ContainerBuilderBase implements ContainerDSL {}\nexport class FormBuilderImpl extends ContainerBuilderBase implements FormDSL {}\n\nexport class ListBuilderImpl extends ContentBuilderBase implements ListDSL {\n item(key: string, builder: ContainerBuilderFn, options: ContainerOptions = {}): void {\n const node = this._graph.createNode('list-item', {\n key,\n parent: this._node,\n props: containerProps(options),\n });\n builder(new ContainerBuilderImpl(node, this._graph));\n }\n}\n\nexport class PageBuilderImpl extends ContainerBuilderBase implements PageDSL {}\n\n// ── App builder ───────────────────────────────────────────────────────────────\n\nexport class AppBuilder implements AppDSL {\n constructor(private readonly _graph: ApplicationGraph) {}\n\n page(key: string, builder: PageBuilder): void {\n const node = this._graph.createNode('page', {\n key,\n parent: this._graph.root,\n props: { key },\n });\n builder(new PageBuilderImpl(node, this._graph));\n }\n}\n","/**\n * StreetUI DSL entry point.\n *\n * Usage:\n * import { streetui } from '@streetui/dsl';\n *\n * const app = streetui.app({ name: 'My App' });\n * app.page('home', page => {\n * page.section('hero', section => {\n * section.heading('Welcome');\n * section.button('Click me', { onClick: () => {} });\n * });\n * });\n *\n * const graph = app.build();\n */\n\nimport { ApplicationGraph } from '@streetui/graph';\nimport { AppBuilder } from './builders.js';\n\nexport interface AppOptions {\n readonly name: string;\n readonly version?: string;\n}\n\nexport class StreetApp {\n private readonly _graph: ApplicationGraph;\n private readonly _builder: AppBuilder;\n\n constructor(options: AppOptions) {\n const graphOpts: { name: string; version?: string } = { name: options.name };\n if (options.version !== undefined) graphOpts.version = options.version;\n this._graph = new ApplicationGraph(graphOpts);\n this._builder = new AppBuilder(this._graph);\n }\n\n page(key: string, builder: Parameters<AppBuilder['page']>[1]): this {\n this._builder.page(key, builder);\n return this;\n }\n\n /** Compile to ApplicationGraph — validates and returns the graph. */\n build(): ApplicationGraph {\n const dc = this._graph.validate();\n dc.throwIfErrors();\n return this._graph;\n }\n\n /** Access graph before building (useful for inspection). */\n get graph(): ApplicationGraph {\n return this._graph;\n }\n}\n\nexport interface StreetUI {\n app(options: AppOptions): StreetApp;\n}\n\nexport const streetui: StreetUI = {\n app(options: AppOptions): StreetApp {\n return new StreetApp(options);\n },\n};\n","/**\n * Compiler-phase validation of the ApplicationGraph.\n *\n * This runs after the DSL has built the graph but before the runtime\n * receives a CompiledApplication. More checks live here than in the\n * graph's own validate() because the compiler has broader context.\n */\n\nimport { DiagnosticCollector } from '@streetui/core';\nimport { ApplicationGraph, GraphNode } from '@streetui/graph';\n\nexport function validateGraph(graph: ApplicationGraph): DiagnosticCollector {\n const dc = new DiagnosticCollector();\n\n // Merge built-in graph validations\n dc.merge(graph.validate());\n\n // Must have at least one page\n const pages = graph.findByType('page');\n if (pages.length === 0) {\n dc.warn(\n 'COMPILER_NO_PAGES',\n 'Application has no pages defined. At least one page is recommended.',\n );\n }\n\n // Walk and validate individual nodes\n graph.walk((node) => {\n validateNode(node, dc);\n });\n\n return dc;\n}\n\nfunction validateNode(node: GraphNode, dc: DiagnosticCollector): void {\n switch (node.type) {\n case 'heading': {\n const text = node.getProp('text');\n if (text === undefined || text === '') {\n dc.warn('COMPILER_EMPTY_HEADING', `Heading node \"${node.id}\" has no text content`, {\n nodeId: node.id,\n });\n }\n break;\n }\n case 'image': {\n const src = node.getProp('src');\n const alt = node.getProp('alt');\n if (!src) {\n dc.error('COMPILER_IMAGE_NO_SRC', `Image node \"${node.id}\" is missing src`, {\n nodeId: node.id,\n });\n }\n if (!alt) {\n dc.warn('COMPILER_IMAGE_NO_ALT', `Image node \"${node.id}\" is missing alt text`, {\n nodeId: node.id,\n });\n }\n break;\n }\n case 'link': {\n const href = node.getProp('href');\n if (!href) {\n dc.error('COMPILER_LINK_NO_HREF', `Link node \"${node.id}\" is missing href`, {\n nodeId: node.id,\n });\n }\n break;\n }\n default:\n break;\n }\n}\n","/**\n * Graph transformation pass.\n *\n * After validation, the transformer prepares the graph for the runtime by:\n * - Resolving implicit defaults (e.g. heading level defaults to 1)\n * - Normalizing prop names\n * - Assigning deterministic render keys where missing\n * - Flattening / hoisting where beneficial\n */\n\nimport { ApplicationGraph, GraphNode } from '@streetui/graph';\n\nexport function transformGraph(graph: ApplicationGraph): void {\n graph.walk((node, depth) => {\n applyDefaults(node);\n ensureRenderKey(node, depth);\n });\n}\n\nfunction applyDefaults(node: GraphNode): void {\n switch (node.type) {\n case 'heading': {\n if (node.getProp('level') === undefined) {\n node.setProp('level', 1);\n }\n break;\n }\n case 'input': {\n if (node.getProp('inputType') === undefined) {\n node.setProp('inputType', 'text');\n }\n break;\n }\n case 'link': {\n if (node.getProp('external') === undefined) {\n node.setProp('external', false);\n }\n break;\n }\n default:\n break;\n }\n}\n\nfunction ensureRenderKey(node: GraphNode, depth: number): void {\n if (node.getProp('_renderKey') === undefined) {\n const key = node.key ?? `${node.type}:${node.id}:${depth}`;\n node.setProp('_renderKey', key);\n }\n}\n","/**\n * StreetUI compiler entry point.\n *\n * Pipeline:\n * StreetApp (DSL)\n * → ApplicationGraph (build)\n * → validate\n * → transform\n * → CompiledApplication\n */\n\nimport { DiagnosticCollector } from '@streetui/core';\nimport { type ApplicationGraph } from '@streetui/graph';\nimport { type StreetApp } from '@streetui/dsl';\nimport { validateGraph } from './validation/validator.js';\nimport { transformGraph } from './transform/transform.js';\n\nexport interface CompiledApplication {\n /** The fully built, validated, and transformed graph. */\n readonly graph: ApplicationGraph;\n /** Diagnostics accumulated during compilation. */\n readonly diagnostics: DiagnosticCollector;\n /** Metadata */\n readonly name: string;\n readonly version: string;\n readonly compiledAt: number;\n}\n\nexport interface CompileOptions {\n /** If true, compilation throws on errors. Defaults to true. */\n readonly strict?: boolean;\n /** If true, also throw on warnings. Defaults to false. */\n readonly strictWarnings?: boolean;\n}\n\n/**\n * Compile a StreetApp DSL definition into a CompiledApplication\n * ready for the runtime to execute.\n */\nexport function compile(\n app: StreetApp,\n options: CompileOptions = {},\n): CompiledApplication {\n const strict = options.strict ?? true;\n const strictWarnings = options.strictWarnings ?? false;\n const dc = new DiagnosticCollector();\n\n // 1. Build the graph from the DSL\n const graph = app.graph;\n\n // 2. Validate\n const validationDc = validateGraph(graph);\n dc.merge(validationDc);\n\n if (strict && dc.hasErrors) {\n dc.throwIfErrors();\n }\n if (strictWarnings && dc.hasWarnings) {\n throw new Error(\n `[StreetUI Compiler] Compilation failed: warnings treated as errors.\\n` +\n dc.diagnostics\n .filter(d => d.severity === 'warning')\n .map(d => ` [${d.code}] ${d.message}`)\n .join('\\n'),\n );\n }\n\n // 3. Transform\n transformGraph(graph);\n\n return {\n graph,\n diagnostics: dc,\n name: graph.name,\n version: graph.version,\n compiledAt: Date.now(),\n };\n}\n\n/**\n * Compile from a pre-built ApplicationGraph (used when the graph\n * was constructed programmatically rather than through the DSL).\n */\nexport function compileGraph(\n graph: ApplicationGraph,\n options: CompileOptions = {},\n): CompiledApplication {\n const strict = options.strict ?? true;\n const dc = new DiagnosticCollector();\n\n const validationDc = validateGraph(graph);\n dc.merge(validationDc);\n\n if (strict && dc.hasErrors) {\n dc.throwIfErrors();\n }\n\n transformGraph(graph);\n\n return {\n graph,\n diagnostics: dc,\n name: graph.name,\n version: graph.version,\n compiledAt: Date.now(),\n };\n}\n","/**\n * RuntimeNodeInstance — the runtime's live representation of a GraphNode.\n *\n * Each GraphNode in the compiled application gets a corresponding\n * RuntimeNodeInstance during mounting. The instance owns:\n * - the DOM node(s) produced for this graph node\n * - all signal subscriptions that drive updates\n * - all DOM event listeners\n * - child instances\n */\n\nimport { CleanupRegistry } from '@streetui/core';\nimport type { GraphNode } from '@streetui/graph';\nimport type { Signal, ReadonlySignal } from '@streetui/state';\n\nexport interface NodeInstanceOptions {\n readonly graphNode: GraphNode;\n readonly domNode: Node;\n}\n\nexport class RuntimeNodeInstance {\n readonly graphNode: GraphNode;\n domNode: Node;\n readonly children: RuntimeNodeInstance[] = [];\n readonly cleanup: CleanupRegistry = new CleanupRegistry();\n private _mounted = false;\n\n constructor(options: NodeInstanceOptions) {\n this.graphNode = options.graphNode;\n this.domNode = options.domNode;\n }\n\n get isMounted(): boolean {\n return this._mounted;\n }\n\n mount(): void {\n this._mounted = true;\n }\n\n unmount(): void {\n if (!this._mounted) return;\n this._mounted = false;\n for (const child of this.children) {\n child.unmount();\n }\n this.cleanup.run();\n }\n\n addChild(instance: RuntimeNodeInstance): void {\n this.children.push(instance);\n }\n\n /** Subscribe to a signal and register the unsubscribe for cleanup. */\n trackSignal<T>(\n signal: Signal<T> | ReadonlySignal<T>,\n handler: (value: T) => void,\n ): void {\n const unsub = signal.subscribe(handler);\n this.cleanup.add(unsub);\n }\n\n /** Register an arbitrary cleanup function (e.g. DOM event removal). */\n trackCleanup(fn: () => void): void {\n this.cleanup.add(fn);\n }\n}\n","/**\n * StreetUI update scheduler.\n *\n * Responsibilities:\n * - Queue update callbacks\n * - Batch synchronous enqueues into a single microtask flush\n * - Guarantee ordering: higher priority jobs flush first\n * - Prevent duplicate work for the same job key\n * - Allow synchronous flush for tests\n */\n\nexport type Priority = 'immediate' | 'normal' | 'idle';\n\nconst PRIORITY_ORDER: Record<Priority, number> = {\n immediate: 0,\n normal: 1,\n idle: 2,\n};\n\nexport interface Job {\n /** Unique key — if another job with the same key is already queued, it is replaced. */\n readonly key: string;\n readonly priority: Priority;\n readonly fn: () => void;\n}\n\n/**\n * Optional error-reporting hook (v0.9 §26/§27). Structurally compatible with\n * `@streetui/core`'s `DiagnosticSink` (the `error` method) so an application can\n * route swallowed scheduler-job failures through its own logger instead of the\n * default `console.error`. Kept as a local structural type so the scheduler\n * stays dependency-free; no network, no telemetry. When unset, behaviour is\n * exactly as before.\n */\nexport interface SchedulerDiagnostics {\n error?(message: string, context?: unknown): void;\n}\n\nexport class Scheduler {\n private readonly _queue: Map<string, Job> = new Map();\n private _flushScheduled = false;\n private _flushing = false;\n private _diagnostics: SchedulerDiagnostics | undefined = undefined;\n\n /**\n * Install an optional diagnostic sink for swallowed job errors. Pass\n * `undefined` to restore the default `console.error` reporting. Additive and\n * opt-in — the scheduler never sends anything anywhere on its own.\n */\n setDiagnostics(sink: SchedulerDiagnostics | undefined): void {\n this._diagnostics = sink;\n }\n\n /** Total jobs currently queued. */\n get size(): number {\n return this._queue.size;\n }\n\n /** True if a flush has been scheduled but not yet executed. */\n get isPending(): boolean {\n return this._flushScheduled;\n }\n\n /**\n * Enqueue a job. If a job with the same key exists, the new one replaces it\n * (allowing callers to coalesce repeated updates for the same node).\n */\n schedule(job: Job): void {\n this._queue.set(job.key, job);\n if (!this._flushScheduled && !this._flushing) {\n this._flushScheduled = true;\n this._scheduleMicrotask();\n }\n }\n\n /** Schedule multiple jobs atomically. */\n scheduleAll(jobs: readonly Job[]): void {\n for (const job of jobs) {\n this._queue.set(job.key, job);\n }\n if (!this._flushScheduled && !this._flushing && this._queue.size > 0) {\n this._flushScheduled = true;\n this._scheduleMicrotask();\n }\n }\n\n /**\n * Cancel a queued job by key. No-op if not queued.\n */\n cancel(key: string): void {\n this._queue.delete(key);\n }\n\n /**\n * Synchronously flush all queued jobs (sorted by priority).\n * Useful in tests and for immediate rendering.\n */\n flush(): void {\n if (this._flushing) return;\n this._flushScheduled = false;\n this._flushing = true;\n\n const jobs = Array.from(this._queue.values()).sort(\n (a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority],\n );\n this._queue.clear();\n\n try {\n for (const job of jobs) {\n try {\n job.fn();\n } catch (err) {\n // Isolate job failures — report and continue so remaining jobs still run.\n if (this._diagnostics?.error) {\n this._diagnostics.error(`Scheduler job \"${job.key}\" threw`, err);\n } else {\n console.error(`[Scheduler] Job \"${job.key}\" threw:`, err);\n }\n }\n }\n } finally {\n this._flushing = false;\n }\n }\n\n /** Clear all pending jobs without executing them. */\n clear(): void {\n this._queue.clear();\n this._flushScheduled = false;\n }\n\n private _scheduleMicrotask(): void {\n Promise.resolve().then(() => {\n if (this._flushScheduled) {\n this.flush();\n }\n });\n }\n}\n\n/** The shared global scheduler instance. */\nexport const scheduler = new Scheduler();\n\n/** Convenience: schedule a normal-priority job. */\nexport function scheduleUpdate(key: string, fn: () => void): void {\n scheduler.schedule({ key, priority: 'normal', fn });\n}\n\n/** Convenience: schedule an immediate-priority job. */\nexport function scheduleImmediate(key: string, fn: () => void): void {\n scheduler.schedule({ key, priority: 'immediate', fn });\n}\n\n/** Convenience: flush the global scheduler synchronously. */\nexport function flushSync(): void {\n scheduler.flush();\n}\n","/**\n * StreetUI Runtime.\n *\n * Owns:\n * - Signal binding — wires signal subscriptions to renderer update calls\n * - Event dispatch — calls registered handlers from graph events\n * - Lifecycle — orchestrates mount, update cycles, unmount\n *\n * The runtime does NOT create DOM nodes. It calls into StreetRenderer\n * for all DOM operations.\n */\n\nimport { CleanupRegistry } from '@streetui/core';\nimport type { GraphNode, ApplicationGraph } from '@streetui/graph';\nimport type { Signal, ReadonlySignal } from '@streetui/state';\nimport { Scheduler } from '@streetui/scheduler';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport type { StreetRenderer, RenderHandle } from './renderer-interface.js';\n\nexport interface RuntimeOptions {\n readonly renderer: StreetRenderer;\n readonly scheduler?: Scheduler;\n}\n\nexport interface MountedApplication {\n readonly renderHandle: RenderHandle;\n readonly runtime: Runtime;\n unmount(): void;\n flush(): void;\n}\n\nexport class Runtime {\n private readonly _renderer: StreetRenderer;\n private readonly _scheduler: Scheduler;\n private readonly _cleanup: CleanupRegistry = new CleanupRegistry();\n private _renderHandle: RenderHandle | null = null;\n private _mounted = false;\n\n constructor(options: RuntimeOptions) {\n this._renderer = options.renderer;\n this._scheduler = options.scheduler ?? new Scheduler();\n }\n\n get isMounted(): boolean {\n return this._mounted;\n }\n\n /**\n * Mount the compiled application into the given DOM container.\n */\n mount(compiled: CompiledApplication, container: Element): MountedApplication {\n if (this._mounted) {\n throw new Error('[Runtime] Already mounted. Call unmount() first.');\n }\n\n // Hand off to renderer — it creates all DOM nodes\n this._renderHandle = this._renderer.mount(compiled, container);\n this._mounted = true;\n\n // Wire signal subscriptions from the graph\n this._bindSignals(compiled.graph);\n\n const self = this;\n return {\n renderHandle: this._renderHandle,\n runtime: this,\n unmount() { self.unmount(); },\n flush() { self._scheduler.flush(); },\n };\n }\n\n unmount(): void {\n if (!this._mounted) return;\n this._mounted = false;\n this._renderHandle?.unmount();\n this._renderHandle = null;\n this._cleanup.run();\n }\n\n /**\n * Hydrate a container that already holds server-rendered HTML for this\n * application. Delegates to the renderer's `hydrate` (adopting the existing\n * DOM instead of recreating it) and falls back to `mount` for renderers that\n * cannot hydrate. Signal binding is identical to `mount`, so the live client\n * lifecycle is established the same way.\n */\n hydrate(compiled: CompiledApplication, container: Element): MountedApplication {\n if (this._mounted) {\n throw new Error('[Runtime] Already mounted. Call unmount() first.');\n }\n\n this._renderHandle = this._renderer.hydrate !== undefined\n ? this._renderer.hydrate(compiled, container)\n : this._renderer.mount(compiled, container);\n this._mounted = true;\n\n this._bindSignals(compiled.graph);\n\n const self = this;\n return {\n renderHandle: this._renderHandle,\n runtime: this,\n unmount() { self.unmount(); },\n flush() { self._scheduler.flush(); },\n };\n }\n\n /**\n * Walk the graph and subscribe to all signal-bound nodes.\n * When a signal changes, schedule a renderer update for that node.\n */\n private _bindSignals(graph: ApplicationGraph): void {\n graph.walk((node) => {\n for (const stateRef of node.stateRefs) {\n const signalKey = `__signal__${stateRef.signalId}`;\n const maybeSignal = graph.getHandler(signalKey) as\n | (Signal<unknown> & ReadonlySignal<unknown>)\n | undefined;\n\n if (maybeSignal === undefined || typeof maybeSignal.subscribe !== 'function') continue;\n\n const unsub = maybeSignal.subscribe(() => {\n // Schedule a re-render update keyed to this node+prop\n this._scheduler.schedule({\n key: `update:${node.id}:${stateRef.propKey}`,\n priority: 'normal',\n fn: () => {\n // The renderer handles the actual DOM update\n this._renderHandle?.flush();\n },\n });\n });\n this._cleanup.add(unsub);\n }\n });\n }\n}\n\n/**\n * Convenience factory — create a runtime, mount, and return the handle.\n */\nexport function createRuntime(options: RuntimeOptions): Runtime {\n return new Runtime(options);\n}\n","/**\n * StreetUI event type catalogue.\n * Framework events are distinct from raw DOM events.\n */\n\nexport type StreetEventType =\n | 'click'\n | 'dblclick'\n | 'input'\n | 'change'\n | 'submit'\n | 'focus'\n | 'blur'\n | 'keydown'\n | 'keyup'\n | 'keypress'\n | 'mouseenter'\n | 'mouseleave'\n | 'mousemove'\n | 'mousedown'\n | 'mouseup'\n | 'pointerdown'\n | 'pointerup'\n | 'pointermove'\n | 'pointerenter'\n | 'pointerleave'\n | 'scroll'\n | 'resize'\n | 'mount'\n | 'unmount'\n | 'update';\n\nexport interface StreetEvent<T = unknown> {\n readonly type: StreetEventType | string;\n readonly target: unknown;\n readonly data: T | undefined;\n readonly originalEvent: Event | undefined;\n readonly timestamp: number;\n defaultPrevented: boolean;\n stopPropagation(): void;\n preventDefault(): void;\n}\n\nexport function createStreetEvent<T = unknown>(\n type: StreetEventType | string,\n target: unknown,\n data?: T,\n originalEvent?: Event,\n): StreetEvent<T> {\n let _stopped = false;\n const ev: StreetEvent<T> = {\n type,\n target,\n data: data as T | undefined,\n originalEvent: originalEvent as Event | undefined,\n timestamp: Date.now(),\n defaultPrevented: false,\n stopPropagation() { _stopped = true; },\n preventDefault() { ev.defaultPrevented = true; },\n };\n return ev;\n}\n\nexport type EventHandler<T = unknown> = (event: StreetEvent<T>) => void;\n","/**\n * Framework-internal event bus.\n * Decouples emitters from handlers across subsystems.\n */\n\nimport type { StreetEvent, EventHandler } from './event-types.js';\n\nexport class EventBus {\n private readonly _handlers: Map<string, Set<EventHandler>> = new Map();\n\n on<T = unknown>(type: string, handler: EventHandler<T>): () => void {\n let set = this._handlers.get(type);\n if (set === undefined) {\n set = new Set();\n this._handlers.set(type, set);\n }\n set.add(handler as EventHandler);\n return () => this.off(type, handler as EventHandler);\n }\n\n off<T = unknown>(type: string, handler: EventHandler<T>): void {\n this._handlers.get(type)?.delete(handler as EventHandler);\n }\n\n once<T = unknown>(type: string, handler: EventHandler<T>): () => void {\n const wrapped: EventHandler<T> = (event) => {\n handler(event);\n this.off(type, wrapped);\n };\n return this.on(type, wrapped);\n }\n\n emit<T = unknown>(event: StreetEvent<T>): void {\n const handlers = this._handlers.get(event.type);\n if (handlers === undefined) return;\n for (const h of handlers) {\n h(event as StreetEvent);\n }\n }\n\n clear(type?: string): void {\n if (type !== undefined) {\n this._handlers.delete(type);\n } else {\n this._handlers.clear();\n }\n }\n\n listenerCount(type: string): number {\n return this._handlers.get(type)?.size ?? 0;\n }\n}\n\nexport const globalEventBus = new EventBus();\n","/**\n * DOM ↔ StreetUI event bridge.\n *\n * Attaches native DOM event listeners and translates them into\n * StreetUI events dispatched to registered handlers.\n * The renderer uses this to wire events without coupling\n * DOM event mechanics into the render pipeline directly.\n */\n\nimport { createStreetEvent, type EventHandler, type StreetEventType } from './event-types.js';\n\nexport interface DomBinding {\n remove(): void;\n}\n\n/**\n * Attach a DOM event listener that fires the given StreetUI handler.\n * Returns a binding whose `remove()` detaches the listener.\n */\nexport function bindDomEvent<T extends Event = Event>(\n element: EventTarget,\n domEventType: StreetEventType | string,\n handler: EventHandler,\n options?: AddEventListenerOptions,\n): DomBinding {\n const listener = (e: T) => {\n const streetEvent = createStreetEvent(domEventType, element, undefined, e as unknown as Event);\n handler(streetEvent);\n };\n\n element.addEventListener(domEventType, listener as EventListener, options);\n\n return {\n remove() {\n element.removeEventListener(domEventType, listener as EventListener, options);\n },\n };\n}\n\n/**\n * A registry that tracks all DOM bindings for a single node,\n * making bulk teardown easy.\n */\nexport class DomEventRegistry {\n private readonly _bindings: DomBinding[] = [];\n\n bind(\n element: EventTarget,\n type: StreetEventType | string,\n handler: EventHandler,\n options?: AddEventListenerOptions,\n ): void {\n this._bindings.push(bindDomEvent(element, type, handler, options));\n }\n\n removeAll(): void {\n for (const b of this._bindings) {\n b.remove();\n }\n this._bindings.length = 0;\n }\n\n get count(): number {\n return this._bindings.length;\n }\n}\n","/**\n * Browser implementation of DOMAdapter — delegates directly to browser APIs.\n */\n\nimport type { DOMAdapter } from './adapter.js';\n\nexport class BrowserDOMAdapter implements DOMAdapter {\n createElement(tag: string, ns?: string): Element {\n if (ns !== undefined) {\n return document.createElementNS(ns, tag);\n }\n return document.createElement(tag);\n }\n\n createTextNode(data: string): Text {\n return document.createTextNode(data);\n }\n\n createComment(data: string): Comment {\n return document.createComment(data);\n }\n\n createFragment(): DocumentFragment {\n return document.createDocumentFragment();\n }\n\n appendChild(parent: Node, child: Node): void {\n parent.appendChild(child);\n }\n\n insertBefore(parent: Node, child: Node, reference: Node | null): void {\n parent.insertBefore(child, reference);\n }\n\n removeChild(parent: Node, child: Node): void {\n parent.removeChild(child);\n }\n\n replaceChild(parent: Node, newChild: Node, oldChild: Node): void {\n parent.replaceChild(newChild, oldChild);\n }\n\n setAttribute(element: Element, name: string, value: string): void {\n element.setAttribute(name, value);\n }\n\n removeAttribute(element: Element, name: string): void {\n element.removeAttribute(name);\n }\n\n getAttribute(element: Element, name: string): string | null {\n return element.getAttribute(name);\n }\n\n setProperty(element: Element, name: string, value: unknown): void {\n (element as unknown as Record<string, unknown>)[name] = value;\n }\n\n setTextContent(node: Node, text: string): void {\n node.textContent = text;\n }\n\n getTextContent(node: Node): string | null {\n return node.textContent;\n }\n\n addEventListener(\n target: EventTarget,\n type: string,\n handler: EventListener,\n options?: AddEventListenerOptions,\n ): void {\n target.addEventListener(type, handler, options);\n }\n\n removeEventListener(\n target: EventTarget,\n type: string,\n handler: EventListener,\n options?: EventListenerOptions,\n ): void {\n target.removeEventListener(type, handler, options);\n }\n\n querySelector(root: Element | Document, selector: string): Element | null {\n return root.querySelector(selector);\n }\n\n querySelectorAll(root: Element | Document, selector: string): NodeListOf<Element> {\n return root.querySelectorAll(selector);\n }\n\n getElementById(id: string): Element | null {\n return document.getElementById(id);\n }\n\n focus(element: Element): void {\n (element as unknown as { focus?: () => void }).focus?.();\n }\n\n isElement(node: Node): node is Element {\n return node.nodeType === Node.ELEMENT_NODE;\n }\n\n isTextNode(node: Node): node is Text {\n return node.nodeType === Node.TEXT_NODE;\n }\n\n tagName(element: Element): string {\n return element.tagName.toLowerCase();\n }\n\n parentNode(node: Node): Node | null {\n return node.parentNode;\n }\n\n nextSibling(node: Node): Node | null {\n return node.nextSibling;\n }\n\n firstChild(node: Node): Node | null {\n return node.firstChild;\n }\n\n childNodes(node: Node): Node[] {\n return Array.from(node.childNodes);\n }\n}\n\nexport const browserDOMAdapter = new BrowserDOMAdapter();\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';\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\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 /** JS properties set via `setProperty` (e.g. input `value`, `checked`). */\n readonly properties = new Map<string, unknown>();\n readonly children: ServerNode[] = [];\n readonly style = new ServerStyle();\n\n constructor(tagName: string) {\n this.tagName = tagName.toLowerCase();\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/** Escape text node content. */\nexport function escapeHtmlText(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\n\n/** Escape a double-quoted attribute value. */\nexport function escapeHtmlAttr(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\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 for (const [name, kind] of Object.entries(SERIALIZED_PROPERTIES)) {\n if (!el.properties.has(name)) continue;\n if (el.attributes.has(name)) continue; // an explicit attribute already won\n const raw = el.properties.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 if (!el.style.isEmpty && !el.attributes.has('style')) {\n parts.push(` style=\"${escapeHtmlAttr(el.style.toCss())}\"`);\n }\n\n return parts.join('');\n}\n\n/** Serialize a single server node (element/text/comment/fragment) 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 '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 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 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 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\nexport const serverDOMAdapter = 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 * 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';\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\nexport function createRenderContext(\n dom: DOMAdapter,\n graph: ApplicationGraph,\n container: Element,\n hydrationDiagnostics?: HydrationDiagnosticSink,\n): RenderContext {\n return {\n dom,\n graph,\n instances: new Map(),\n container,\n ...(hydrationDiagnostics !== undefined ? { hydrationDiagnostics } : {}),\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 * 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};\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 { 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): 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 // New — create and mount\n const inst = mountFn(newNode, parentDom);\n newInstances.push(inst);\n }\n }\n\n // Determine removed instances\n const removed: NodeInstance[] = [];\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n if (!usedKeys.has(key)) {\n removed.push(inst);\n }\n }\n\n // Remove stale DOM nodes\n for (const inst of removed) {\n const parent = ctx.dom.parentNode(inst.domNode);\n if (parent !== null) {\n ctx.dom.removeChild(parent, inst.domNode);\n }\n inst.dispose();\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): 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 const freshNode = entry.build();\n built.push(freshNode);\n const inst = mountFn(freshNode, parentDom);\n newInstances.push(inst);\n }\n }\n\n // Determine + remove stale instances.\n const removed: NodeInstance[] = [];\n for (const inst of oldInstances) {\n const key = inst.graphNode.key ?? inst.graphNode.id;\n if (!usedKeys.has(key)) removed.push(inst);\n }\n for (const inst of removed) {\n const parent = ctx.dom.parentNode(inst.domNode);\n if (parent !== null) ctx.dom.removeChild(parent, inst.domNode);\n inst.dispose();\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 * 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 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';\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 // 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 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);\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 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 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): 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 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));\n } else {\n reconcileReactiveList(ctx, graphNode, instance, el, build!(value));\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): 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 );\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): 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 );\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 * Hydration diagnostics — dev-only, opt-in explanations of hydration mismatches.\n *\n * Hydration is self-repairing: when the server-rendered DOM does not match the\n * graph at a position, the renderer mounts a fresh subtree in place and drops\n * the offending element (see `hydrateChildren` in `hydrate.ts`). That recovery\n * is silent by design — a local mismatch must never tear down the whole app.\n *\n * During development, though, a silent repair hides a real problem (usually a\n * server/client divergence). A `HydrationDiagnosticSink` can be attached to the\n * renderer to *observe* those repairs without changing them: for every mismatch\n * the renderer reports what it expected, what it found, where, and what it did\n * to recover. Nothing is thrown, nothing is mutated differently, and when no\n * sink is attached there is zero additional work on the hydration path.\n */\n\n/** What kind of divergence the hydrator encountered at a position. */\nexport type HydrationMismatchType =\n | 'tag-mismatch' // an element existed but was the wrong tag\n | 'missing-element' // the graph expected a child the DOM did not provide\n | 'surplus-element'; // the DOM had a child the graph no longer expects\n\n/** A single, fully-described hydration divergence and the repair taken. */\nexport interface HydrationDiagnostic {\n /** The category of mismatch. */\n readonly type: HydrationMismatchType;\n /** The tag the graph expected at this position (null for a surplus element). */\n readonly expected: string | null;\n /** The tag actually found in the server DOM (null for a missing element). */\n readonly found: string | null;\n /** A human-readable path to the position, e.g. `app / page[0] / section[1]`. */\n readonly path: string;\n /** The graph node id involved, when one exists (null for surplus DOM). */\n readonly nodeId: string | null;\n /** The semantic node type involved, when one exists (null for surplus DOM). */\n readonly nodeType: string | null;\n /** The recovery action the renderer performed. */\n readonly action: string;\n /** A single-line, developer-facing summary of the whole diagnostic. */\n readonly message: string;\n}\n\n/**\n * Receives hydration diagnostics as they are discovered. Kept intentionally\n * tiny so any logger — `console`, a test collector, a `DiagnosticSink` — can\n * satisfy it. Implementations must not throw.\n */\nexport interface HydrationDiagnosticSink {\n report(diagnostic: HydrationDiagnostic): void;\n}\n\n/** Build the canonical one-line message for a diagnostic. */\nexport function formatHydrationDiagnostic(\n d: Omit<HydrationDiagnostic, 'message'>,\n): string {\n const at = ` at ${d.path}`;\n switch (d.type) {\n case 'tag-mismatch':\n return `Hydration mismatch${at} — Expected: ${d.expected} / Found: ${d.found} / Action: ${d.action}`;\n case 'missing-element':\n return `Hydration mismatch${at} — Expected: ${d.expected} / Found: (nothing) / Action: ${d.action}`;\n case 'surplus-element':\n return `Hydration mismatch${at} — Expected: (nothing) / Found: ${d.found} / Action: ${d.action}`;\n }\n}\n\n/**\n * A ready-made sink that accumulates diagnostics into an array — the shape most\n * useful for tests and for a DevTools panel. The returned `diagnostics` array is\n * appended to in-place as repairs happen.\n */\nexport function createHydrationDiagnosticCollector(): {\n readonly sink: HydrationDiagnosticSink;\n readonly diagnostics: HydrationDiagnostic[];\n} {\n const diagnostics: HydrationDiagnostic[] = [];\n return {\n diagnostics,\n sink: {\n report(d) {\n diagnostics.push(d);\n },\n },\n };\n}\n\n/**\n * A sink that forwards each diagnostic to a `console`-like logger as a single\n * warning line. Handy default when you just want the messages surfaced in dev.\n */\nexport function consoleHydrationDiagnosticSink(\n logger: { warn(message: string): void } = console,\n): HydrationDiagnosticSink {\n return {\n report(d) {\n logger.warn(d.message);\n },\n };\n}\n","/**\n * Hydration — attach a live StreetUI runtime to server-rendered HTML.\n *\n * `hydrate` walks the semantic application graph top-down against the DOM that\n * the server already produced. For every graph node it *adopts* the matching\n * existing element (creating a `NodeInstance` that points at it) and attaches\n * behavior — event listeners and signal subscriptions — using the exact same\n * helpers the browser mount path uses (`wireEvents`, `wireSignalBindings`,\n * `wireReactiveList`, and the per-type update factories). Nothing is recreated\n * when the DOM matches.\n *\n * Matching is positional and works because every non-application graph node\n * maps to exactly one element (see mount.ts). When the element at a position\n * does not match the expected tag (or is missing), only that subtree is\n * repaired: the fresh subtree is mounted and spliced into place, leaving the\n * rest of the hydrated tree untouched. A local mismatch never tears down the\n * whole app.\n */\n\nimport type { GraphNode } from '@streetui/graph';\nimport type { RenderContext } from './render-context.js';\nimport { NodeInstance } from './node-instance.js';\nimport { wireEvents } from './events.js';\nimport { resolveTag } from './tag-map.js';\nimport { formatHydrationDiagnostic } from './hydration-diagnostics.js';\nimport {\n mountNode,\n wireSignalBindings,\n wireReactiveList,\n textUpdate,\n headingUpdate,\n inputUpdate,\n buttonUpdate,\n} from './mount.js';\n\n/** Hydrate the whole application graph against `ctx.container`. */\nexport function hydrateGraph(ctx: RenderContext): NodeInstance {\n const root = ctx.graph.root;\n // The application root maps to the container itself (no element of its own),\n // exactly as in mountNode.\n const instance = new NodeInstance(root, ctx.container);\n ctx.instances.set(root.id, instance);\n hydrateChildren(ctx, root, instance, ctx.container, 'app');\n return instance;\n}\n\n/**\n * Adopt `domNode` as the live element for `graphNode` and attach behavior.\n * The caller has already verified `domNode` matches `graphNode` (right tag).\n * `path` is the human-readable position used only for dev diagnostics.\n */\nfunction hydrateNode(\n ctx: RenderContext,\n graphNode: GraphNode,\n domNode: Element,\n path: string,\n): NodeInstance {\n const { dom, graph } = ctx;\n\n switch (graphNode.type) {\n case 'text': {\n // <span> with an inner text node. Adopt the text node (or create one if\n // the server markup somehow lacks it).\n let textNode = dom.firstChild(domNode);\n if (textNode === null || !dom.isTextNode(textNode)) {\n const created = dom.createTextNode(String(graphNode.getProp('text') ?? ''));\n dom.appendChild(domNode, created);\n textNode = created;\n }\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, domNode, instance);\n // Only build the per-type update closure when the node actually has\n // reactive bindings. wireSignalBindings early-returns on an empty\n // stateRefs list, so for a static node the `textUpdate(...)` closure would\n // be allocated and immediately discarded — pure GC pressure on the hot\n // hydration path, where the vast majority of nodes are static.\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, textUpdate(dom, domNode, textNode as Text));\n }\n return instance;\n }\n\n case 'heading': {\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, domNode, instance);\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, headingUpdate(dom, domNode));\n }\n return instance;\n }\n\n case 'input': {\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n // The controlled value is already present in the server HTML (reflected as\n // the `value` attribute). Re-assert it as a live property so the element's\n // current value matches the bound signal exactly.\n const value = graphNode.getProp('value');\n if (value !== undefined) dom.setProperty(domNode, 'value', String(value));\n wireEvents(dom, graph, graphNode, domNode, instance);\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, inputUpdate(dom, domNode));\n }\n return instance;\n }\n\n case 'button': {\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n wireEvents(dom, graph, graphNode, domNode, instance);\n if (graphNode.stateRefs.length !== 0) {\n wireSignalBindings(ctx, graphNode, instance, buttonUpdate(dom, domNode));\n }\n return instance;\n }\n\n case 'image':\n case 'link': {\n // Leaf elements with no reactive bindings or events beyond what the markup\n // already encodes; links may still carry click handlers.\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n if (graphNode.type === 'link') wireEvents(dom, graph, graphNode, domNode, instance);\n return instance;\n }\n\n case 'reactive-list':\n case 'conditional': {\n // The server rendered the initial children (built into the graph at\n // compile time from the initial signal state). Adopt them positionally,\n // then subscribe for future signal changes — the same keyed reconciler as\n // the browser drives subsequent updates against the adopted instances.\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n hydrateChildren(ctx, graphNode, instance, domNode, path);\n wireReactiveList(ctx, graphNode, instance, domNode);\n return instance;\n }\n\n default: {\n // Structural nodes: container / section / page / form / list / list-item.\n const instance = new NodeInstance(graphNode, domNode);\n ctx.instances.set(graphNode.id, instance);\n if (graphNode.type === 'form') {\n wireEvents(dom, graph, graphNode, domNode, instance);\n }\n // Hydration boundary (a \"slot\" such as the router outlet): adopt the\n // element itself but leave its existing children untouched — neither\n // hydrated by this pass nor removed as surplus. Something else (e.g. the\n // router) owns and will hydrate the content already inside it. Without\n // this, an empty-in-the-graph slot would strip the server-rendered\n // content it is meant to preserve.\n if (graphNode.getProp('_hydrationBoundary') === true) {\n return instance;\n }\n hydrateChildren(ctx, graphNode, instance, domNode, path);\n return instance;\n }\n }\n}\n\n// ── Child matching + local mismatch recovery ───────────────────────────────────\n\n/**\n * Positionally match a parent's expected child graph nodes against the actual\n * child *elements* in the DOM. Matching children are hydrated in place; a\n * mismatch (wrong tag or a missing element) triggers a local repair — the fresh\n * subtree is mounted and spliced into the correct position — without disturbing\n * sibling subtrees. Surplus DOM elements are removed.\n */\nfunction hydrateChildren(\n ctx: RenderContext,\n parentGraphNode: GraphNode,\n parentInstance: NodeInstance,\n parentDom: Element,\n parentPath: string,\n): void {\n const expected = parentGraphNode.children;\n const actual = elementChildren(ctx, parentDom);\n let cursor = 0;\n\n // The human-readable `path` is only ever consumed by hydration diagnostics,\n // which are inert unless a sink is attached. Building the\n // `${parentPath} / ${type}[${i}]` string for every child would allocate one\n // throwaway string per node on the hot path (10k+ on a large tree) for output\n // that is discarded in production. Gate the construction on the sink being\n // present; when it is absent, thread the (meaningless-but-unused) parent path\n // through unchanged so nested calls stay allocation-free too.\n const diag = ctx.hydrationDiagnostics !== undefined;\n\n for (let i = 0; i < expected.length; i++) {\n const childNode = expected[i]!;\n const want = expectedTag(ctx, childNode);\n const childPath = diag ? `${parentPath} / ${childNode.type}[${i}]` : parentPath;\n const actualEl = actual[cursor];\n\n if (\n actualEl !== undefined &&\n ctx.dom.isElement(actualEl) &&\n ctx.dom.tagName(actualEl) === want\n ) {\n // Match — adopt the existing element.\n const inst = hydrateNode(ctx, childNode, actualEl, childPath);\n parentInstance.addChild(inst);\n cursor++;\n } else {\n // Mismatch or missing — repair only this subtree. Mount fresh, then move\n // it into the correct position ahead of the offending/absent node.\n const ref = actualEl ?? null;\n const inst = mountFreshAt(ctx, childNode, parentDom, ref);\n parentInstance.addChild(inst);\n if (actualEl !== undefined) {\n // Drop the mismatched element that the fresh node replaces.\n const found = ctx.dom.isElement(actualEl) ? ctx.dom.tagName(actualEl) : null;\n reportHydrationDiagnostic(ctx, {\n type: 'tag-mismatch',\n expected: want,\n found,\n path: childPath,\n nodeId: childNode.id,\n nodeType: childNode.type,\n action: 'mounted fresh subtree in place',\n });\n ctx.dom.removeChild(parentDom, actualEl);\n cursor++;\n } else {\n reportHydrationDiagnostic(ctx, {\n type: 'missing-element',\n expected: want,\n found: null,\n path: childPath,\n nodeId: childNode.id,\n nodeType: childNode.type,\n action: 'mounted fresh subtree',\n });\n }\n }\n }\n\n // Remove any surplus server elements the graph no longer expects.\n for (let i = cursor; i < actual.length; i++) {\n const surplus = actual[i]!;\n reportHydrationDiagnostic(ctx, {\n type: 'surplus-element',\n expected: null,\n found: ctx.dom.isElement(surplus) ? ctx.dom.tagName(surplus) : null,\n path: `${parentPath} / [surplus ${i}]`,\n nodeId: null,\n nodeType: null,\n action: 'removed surplus server element',\n });\n ctx.dom.removeChild(parentDom, surplus);\n }\n}\n\n/**\n * Emit a hydration diagnostic through the (optional) sink. When no sink is\n * attached this is a single cheap `undefined` check — the production default.\n */\nfunction reportHydrationDiagnostic(\n ctx: RenderContext,\n d: {\n type: 'tag-mismatch' | 'missing-element' | 'surplus-element';\n expected: string | null;\n found: string | null;\n path: string;\n nodeId: string | null;\n nodeType: string | null;\n action: string;\n },\n): void {\n const sink = ctx.hydrationDiagnostics;\n if (sink === undefined) return;\n sink.report({ ...d, message: formatHydrationDiagnostic(d) });\n}\n\n/** Mount a fresh subtree for `node` and splice it before `ref` (or append). */\nfunction mountFreshAt(\n ctx: RenderContext,\n node: GraphNode,\n parentDom: Element,\n ref: Node | null,\n): NodeInstance {\n // mountNode appends the new subtree at the end of parentDom.\n const inst = mountNode(ctx, node, parentDom);\n if (ref !== null) {\n ctx.dom.insertBefore(parentDom, inst.domNode, ref);\n }\n return inst;\n}\n\n/** The element (not text/comment) children of a node, in order. */\nfunction elementChildren(ctx: RenderContext, parent: Element): Element[] {\n const out: Element[] = [];\n for (const node of ctx.dom.childNodes(parent)) {\n if (ctx.dom.isElement(node)) out.push(node);\n }\n return out;\n}\n\n/** The HTML tag a graph node is expected to occupy in the DOM. */\nfunction expectedTag(ctx: RenderContext, graphNode: GraphNode): string {\n switch (graphNode.type) {\n case 'text':\n return 'span';\n case 'heading': {\n const level = (graphNode.getProp('level') as number | undefined) ?? 1;\n return `h${level}`;\n }\n case 'input':\n return 'input';\n case 'image':\n return 'img';\n case 'link':\n return 'a';\n case 'button':\n return 'button';\n default:\n // reactive-list → ul, conditional → div, structural → resolveTag.\n return resolveTag(graphNode.type);\n }\n}\n","/**\n * StreetRenderHandle — the live handle returned by both `mount` and `hydrate`.\n *\n * Owns teardown for a mounted/hydrated application: disposes every NodeInstance\n * (removing event listeners and signal subscriptions) and clears the container\n * through the DOM adapter (never raw browser globals), so the same handle works\n * for browser and — in principle — server-driven teardown.\n */\n\nimport type { RenderHandle } from '@streetui/runtime';\nimport type { RenderContext } from './render-context.js';\nimport type { NodeInstance } from './node-instance.js';\n\nexport class StreetRenderHandle implements RenderHandle {\n private _disposed = false;\n private readonly _ctx: RenderContext;\n private readonly _rootInstance: NodeInstance;\n\n constructor(ctx: RenderContext, rootInstance: NodeInstance) {\n this._ctx = ctx;\n this._rootInstance = rootInstance;\n }\n\n flush(): void {\n if (this._disposed) return;\n // Signal subscriptions fire synchronously in StreetUI's state system;\n // flush() is a no-op at the renderer level — the DOM is already up to date\n // unless the scheduler is batching, in which case the scheduler calls\n // flush() after draining its queue.\n }\n\n unmount(): void {\n if (this._disposed) return;\n this._disposed = true;\n\n // Dispose all node instances (removes event listeners, signal subscriptions).\n this._rootInstance.dispose();\n\n // Remove all children from the container. Routed through the DOM adapter\n // (never `container.firstChild`/`removeChild`) so the teardown path is\n // server-safe.\n const dom = this._ctx.dom;\n const container = this._ctx.container;\n for (const child of dom.childNodes(container)) {\n dom.removeChild(container, child);\n }\n\n this._ctx.instances.clear();\n }\n}\n","/**\n * StreetUI Renderer — framework-owned DOM renderer.\n *\n * No React. No Vue. No virtual-dom. No external rendering library.\n *\n * Pipeline:\n * CompiledApplication\n * → mountGraph (creates all DOM nodes)\n * → signal subscriptions drive patchNode (targeted updates)\n * → flush() propagates any pending scheduler jobs\n * → unmount() disposes everything\n */\n\nimport type { DOMAdapter } from '@streetui/dom';\nimport { BrowserDOMAdapter } from '@streetui/dom';\nimport type { CompiledApplication } from '@streetui/compiler';\nimport type { StreetRenderer, RenderHandle } from '@streetui/runtime';\nimport { createRenderContext } from './render-context.js';\nimport { mountGraph } from './mount.js';\nimport { hydrateGraph } from './hydrate.js';\nimport { StreetRenderHandle } from './render-handle.js';\nimport type { NodeInstance } from './node-instance.js';\nimport type { HydrationDiagnosticSink } from './hydration-diagnostics.js';\n\nexport interface StreetRendererOptions {\n /** Override the DOM adapter (e.g. for testing). Defaults to BrowserDOMAdapter. */\n readonly domAdapter?: DOMAdapter;\n /**\n * Optional dev-only sink that observes hydration mismatch repairs. Attach one\n * to surface server/client divergences during development; leave it unset in\n * production so hydration does no extra work.\n */\n readonly hydrationDiagnostics?: HydrationDiagnosticSink;\n}\n\nexport class StreetRendererImpl implements StreetRenderer {\n private readonly _dom: DOMAdapter;\n private readonly _hydrationDiagnostics?: HydrationDiagnosticSink;\n\n constructor(options: StreetRendererOptions = {}) {\n this._dom = options.domAdapter ?? new BrowserDOMAdapter();\n if (options.hydrationDiagnostics !== undefined) {\n this._hydrationDiagnostics = options.hydrationDiagnostics;\n }\n }\n\n mount(compiled: CompiledApplication, container: Element): RenderHandle {\n const ctx = createRenderContext(this._dom, compiled.graph, container);\n\n // Initial mount — creates the full DOM tree\n const rootInstance = mountGraph(ctx);\n\n // Wire all signal subscriptions so that signal → DOM patches happen automatically\n this._wireSignals(ctx, rootInstance);\n\n return new StreetRenderHandle(ctx, rootInstance);\n }\n\n /**\n * Hydrate a container that already holds server-rendered HTML for this\n * application. Instead of recreating the DOM, it walks the semantic graph\n * against the existing nodes, adopting matching elements and attaching\n * behavior (events + signal subscriptions). Mismatched subtrees are locally\n * replaced. Returns the same handle type as `mount`.\n */\n hydrate(compiled: CompiledApplication, container: Element): RenderHandle {\n const ctx = createRenderContext(\n this._dom,\n compiled.graph,\n container,\n this._hydrationDiagnostics,\n );\n const rootInstance = hydrateGraph(ctx);\n this._wireSignals(ctx, rootInstance);\n return new StreetRenderHandle(ctx, rootInstance);\n }\n\n private _wireSignals(\n ctx: ReturnType<typeof createRenderContext>,\n rootInstance: NodeInstance,\n ): void {\n // Each NodeInstance already wired its own signals in mountNode via wireSignalBindings.\n // This method is a hook for any cross-cutting signal concerns at the renderer level.\n // Currently no-op — individual mount calls handle their own subscriptions.\n void ctx;\n void rootInstance;\n }\n}\n\n/**\n * Create the default StreetUI renderer using the browser's DOM APIs.\n */\nexport function createRenderer(options?: StreetRendererOptions): StreetRendererImpl {\n return new StreetRendererImpl(options);\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 * 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';\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\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 // 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);\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 * Route matching — pure functions, no DOM, no reactivity.\n *\n * A pattern is matched segment-by-segment against a pathname:\n * - a literal segment must equal the path segment,\n * - a `:name` segment captures the path segment into `params.name`,\n * - a `*` segment (or a whole-pattern `*`) is a catch-all that matches the\n * remainder of the path and captures it into `params['*']`.\n *\n * Matching is intentionally small: no optional segments, no regex constraints,\n * no nested route trees. Composition of layouts is done in the DSL, not here.\n */\n\n/** Split a path into non-empty segments. `/` → [], `/a/b` → ['a','b']. */\nfunction segments(path: string): string[] {\n return path.split('/').filter((s) => s.length > 0);\n}\n\n/** Normalize a pathname: ensure a single leading slash, drop a trailing slash. */\nexport function normalizePath(path: string): string {\n let p = path.trim();\n if (p === '') return '/';\n if (!p.startsWith('/')) p = `/${p}`;\n if (p.length > 1 && p.endsWith('/')) p = p.slice(0, -1);\n return p;\n}\n\n/**\n * Try to match a single pattern against a pathname.\n * Returns the captured params on success, or `null` on no match.\n */\nexport function matchPattern(\n pattern: string,\n pathname: string,\n): Record<string, string> | null {\n // Whole-pattern wildcard: matches everything.\n if (pattern === '*') {\n return { '*': normalizePath(pathname).slice(1) };\n }\n\n const patSegs = segments(pattern);\n const pathSegs = segments(normalizePath(pathname));\n const params: Record<string, string> = {};\n\n for (let i = 0; i < patSegs.length; i++) {\n const patSeg = patSegs[i]!;\n\n // Trailing catch-all: capture the rest of the path.\n if (patSeg === '*') {\n params['*'] = pathSegs.slice(i).map((s) => decodeURIComponent(s)).join('/');\n return params;\n }\n\n const pathSeg = pathSegs[i];\n if (pathSeg === undefined) return null; // path ran out of segments\n\n if (patSeg.startsWith(':')) {\n const name = patSeg.slice(1);\n if (name === '') return null; // malformed `:` with no name\n params[name] = decodeURIComponent(pathSeg);\n continue;\n }\n\n if (patSeg !== pathSeg) return null; // literal mismatch\n }\n\n // All pattern segments consumed — the path must be fully consumed too.\n if (pathSegs.length !== patSegs.length) return null;\n return params;\n}\n\nexport interface MatchResult<R> {\n readonly route: R;\n readonly params: Record<string, string>;\n}\n\n/**\n * Match a pathname against an ordered list of routes. The first route whose\n * pattern matches wins (definition order), so more specific routes should be\n * listed before a `*` fallback.\n */\nexport function matchRoutes<R extends { path: string }>(\n routes: readonly R[],\n pathname: string,\n): MatchResult<R> | null {\n for (const route of routes) {\n const params = matchPattern(route.path, pathname);\n if (params !== null) return { route, params };\n }\n return null;\n}\n\n/** Split a `to` target into its pathname and (already-stripped) search string. */\nexport function splitTarget(to: string): { pathname: string; search: string } {\n const hashIndex = to.indexOf('#');\n const withoutHash = hashIndex >= 0 ? to.slice(0, hashIndex) : to;\n const qIndex = withoutHash.indexOf('?');\n if (qIndex < 0) return { pathname: normalizePath(withoutHash), search: '' };\n return {\n pathname: normalizePath(withoutHash.slice(0, qIndex)),\n search: withoutHash.slice(qIndex + 1),\n };\n}\n","/**\n * Router history — a small abstraction over the navigation source so the router\n * can run both in the browser (real `window.history` + `popstate`) and in tests\n * (an in-memory stack, fully deterministic, no globals).\n *\n * Internal navigation never triggers a full-page reload: the browser history\n * uses `pushState`/`replaceState` and notifies listeners synchronously.\n */\n\nexport interface RouterLocation {\n /** Pathname, always normalized with a single leading slash. */\n readonly pathname: string;\n /** Query string without the leading `?`. */\n readonly search: string;\n}\n\nexport interface RouterHistory {\n /** The current location. */\n location(): RouterLocation;\n /** Push a new entry and notify listeners. */\n push(pathname: string, search: string): void;\n /** Replace the current entry and notify listeners. */\n replace(pathname: string, search: string): void;\n /** Go back one entry. */\n back(): void;\n /** Go forward one entry. */\n forward(): void;\n /** Subscribe to location changes. Returns an unsubscribe function. */\n listen(cb: () => void): () => void;\n /** Detach any global listeners (browser only). */\n dispose(): void;\n}\n\nfunction buildLocation(pathname: string, search: string): RouterLocation {\n return { pathname, search };\n}\n\nfunction toUrl(pathname: string, search: string): string {\n return search.length > 0 ? `${pathname}?${search}` : pathname;\n}\n\n/**\n * Browser history backed by `window.history`. `pushState`/`replaceState` do not\n * emit `popstate`, so we notify listeners ourselves after those calls; genuine\n * back/forward navigation arrives via the `popstate` event.\n */\nexport function createBrowserHistory(): RouterHistory {\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const cb of listeners) cb();\n };\n const onPopState = (): void => notify();\n window.addEventListener('popstate', onPopState);\n\n const current = (): RouterLocation => {\n const loc = window.location;\n return buildLocation(loc.pathname, loc.search.replace(/^\\?/, ''));\n };\n\n return {\n location: current,\n push(pathname, search) {\n window.history.pushState({}, '', toUrl(pathname, search));\n notify();\n },\n replace(pathname, search) {\n window.history.replaceState({}, '', toUrl(pathname, search));\n notify();\n },\n back() {\n window.history.back(); // async → emits popstate\n },\n forward() {\n window.history.forward(); // async → emits popstate\n },\n listen(cb) {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n dispose() {\n window.removeEventListener('popstate', onPopState);\n listeners.clear();\n },\n };\n}\n\n/**\n * In-memory history for tests and non-DOM environments. Maintains an explicit\n * stack and cursor so `back()`/`forward()` are deterministic.\n */\nexport function createMemoryHistory(initial = '/'): RouterHistory {\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const cb of listeners) cb();\n };\n\n const parse = (entry: string): RouterLocation => {\n const qIndex = entry.indexOf('?');\n if (qIndex < 0) return buildLocation(entry, '');\n return buildLocation(entry.slice(0, qIndex), entry.slice(qIndex + 1));\n };\n\n const stack: string[] = [initial];\n let index = 0;\n\n return {\n location() {\n return parse(stack[index]!);\n },\n push(pathname, search) {\n // Drop any forward entries, then append.\n stack.splice(index + 1);\n stack.push(toUrl(pathname, search));\n index = stack.length - 1;\n notify();\n },\n replace(pathname, search) {\n stack[index] = toUrl(pathname, search);\n notify();\n },\n back() {\n if (index > 0) {\n index--;\n notify();\n }\n },\n forward() {\n if (index < stack.length - 1) {\n index++;\n notify();\n }\n },\n listen(cb) {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n dispose() {\n listeners.clear();\n },\n };\n}\n","/**\n * StreetUI Router core — renderer-agnostic.\n *\n * Holds the route table, resolves the current location into a `RouteMatch`,\n * and exposes that match as a StreetUI `signal`. Navigation is delegated to a\n * `RouterHistory`; when the location changes (via `navigate`, `back`, `forward`,\n * or a browser `popstate`) the router recomputes the match and updates the\n * signal, which is how every consumer (`isActive`, the mount integration, any\n * `derived` the app builds) stays in sync. No second reactive system.\n */\n\nimport { signal, derived, type ReadonlySignal } from '@streetui/state';\nimport type { RouterHistory } from './history.js';\nimport { createBrowserHistory } from './history.js';\nimport { matchRoutes, normalizePath, splitTarget } from './matching.js';\nimport type { RouteDefinition, RouteMatch } from './types.js';\n\nexport interface RouterOptions {\n /** The route table. Order matters — the first matching pattern wins. */\n readonly routes: readonly RouteDefinition[];\n /**\n * Navigation source. Defaults to a browser history. Pass a memory history\n * for tests or non-DOM environments.\n */\n readonly history?: RouterHistory;\n /**\n * Fallback route used when nothing else matches and no `*` route is present.\n * Defaults to a built-in 404 page (a normal StreetUI tree — no special path).\n */\n readonly notFound?: RouteDefinition;\n}\n\nexport interface NavigateOptions {\n /** Replace the current history entry instead of pushing a new one. */\n readonly replace?: boolean;\n}\n\nexport interface IsActiveOptions {\n /** Require an exact pathname match rather than a prefix match. */\n readonly exact?: boolean;\n}\n\nexport interface Router {\n /** Reactive current match. Consumers subscribe via StreetUI signals. */\n readonly currentRoute: ReadonlySignal<RouteMatch>;\n /** Navigate to a target path (may include a query string). */\n navigate(to: string, options?: NavigateOptions): void;\n /** Go back one history entry. */\n back(): void;\n /** Go forward one history entry. */\n forward(): void;\n /** Reactive predicate: is `path` the active route (or a prefix of it)? */\n isActive(path: string, options?: IsActiveOptions): ReadonlySignal<boolean>;\n /** Tear down history listeners. */\n destroy(): void;\n}\n\n/** Built-in 404 route — a normal StreetUI page tree, overridable via a `*` route. */\nconst DEFAULT_NOT_FOUND: RouteDefinition = {\n path: '*',\n builder: (page) => {\n page.section('not-found', (s) => {\n s.heading('404 — Page not found', { level: 1, id: 'not-found-title' });\n s.text('The page you were looking for does not exist.', { id: 'not-found-text' });\n s.link('Go home', { href: '/', id: 'not-found-home' });\n }, { id: 'not-found' });\n },\n};\n\nexport function createRouter(options: RouterOptions): Router {\n const routes = options.routes;\n const history = options.history ?? createBrowserHistory();\n const fallback = options.notFound ?? DEFAULT_NOT_FOUND;\n\n const resolve = (): RouteMatch => {\n const loc = history.location();\n const pathname = normalizePath(loc.pathname);\n const query = new URLSearchParams(loc.search);\n const matched = matchRoutes(routes, pathname);\n if (matched !== null) {\n return {\n path: pathname,\n pattern: matched.route.path,\n params: matched.params,\n query,\n route: matched.route,\n // A catch-all `*` match is the 404 route whether user-supplied or built-in.\n isFallback: matched.route.path === '*',\n };\n }\n // No explicit route matched — use the fallback (a `*` route if the table\n // has one, otherwise the built-in 404).\n const fallbackParams =\n matchRoutes([fallback], pathname)?.params ?? {};\n return {\n path: pathname,\n pattern: fallback.path,\n params: fallbackParams,\n query,\n route: fallback,\n isFallback: true,\n };\n };\n\n const current = signal<RouteMatch>(resolve());\n const stopListening = history.listen(() => {\n current.set(resolve());\n });\n\n const navigate = (to: string, opts: NavigateOptions = {}): void => {\n const { pathname, search } = splitTarget(to);\n if (opts.replace === true) history.replace(pathname, search);\n else history.push(pathname, search);\n };\n\n const isActive = (path: string, opts: IsActiveOptions = {}): ReadonlySignal<boolean> => {\n const target = normalizePath(path);\n const exact = opts.exact === true;\n return derived(() => {\n const activePath = current.get().path;\n if (activePath === target) return true;\n if (exact || target === '/') return false;\n return activePath.startsWith(`${target}/`);\n });\n };\n\n return {\n currentRoute: current,\n navigate,\n back: () => history.back(),\n forward: () => history.forward(),\n isActive,\n destroy: () => {\n stopListening();\n history.dispose();\n },\n };\n}\n","/**\n * StreetUI Router — DOM integration.\n *\n * `mountRouter` wires a `Router` to real DOM:\n *\n * 1. Mounts an optional persistent shell (layout + navigation) ONCE. The shell\n * declares an outlet element (see `routerOutlet`) into which route content\n * is rendered.\n * 2. Subscribes to `router.currentRoute`. On every change it disposes the\n * previous route (route-scoped `CleanupRegistry.run()` + `runtime.unmount()`)\n * and mounts the new route's compiled application into the outlet.\n * Only the outlet subtree is re-created — the shell persists.\n * 3. Intercepts clicks on internal `<a>` elements for client-side navigation.\n * External links (absolute URLs, `target=\"_blank\"`, `mailto:`/`tel:`) keep\n * their normal browser behaviour, and `link()` is used unchanged.\n *\n * Each route is an ordinary compiled StreetUI application — no special renderer\n * path, no virtual DOM, no full-application rerender on navigation.\n */\n\nimport { streetui, type PageDSL, type ContainerDSL } from '@streetui/dsl';\nimport { compile } from '@streetui/compiler';\nimport { createRuntime, type MountedApplication, type StreetRenderer } from '@streetui/runtime';\nimport { createRenderer } from '@streetui/renderer';\nimport { CleanupRegistry } from '@streetui/core';\nimport type { Router } from './router.js';\nimport type { RouteContext, RouteMatch } from './types.js';\n\n/** Default id used for the route outlet element inside a shell. */\nexport const ROUTER_OUTLET_ID = 'streetui-router-outlet';\n\n/**\n * Declare the route outlet inside a shell builder. The router replaces this\n * element's contents on every navigation.\n */\nexport function routerOutlet(scope: ContainerDSL, id: string = ROUTER_OUTLET_ID): void {\n scope.container('router-outlet', () => { /* filled by the router at runtime */ }, { id });\n}\n\nexport type ShellBuilder = (shell: PageDSL, router: Router) => void;\n\nexport interface MountRouterOptions {\n /** Element to mount into. With a shell, the shell fills this; otherwise routes do. */\n readonly container: Element;\n /** Optional persistent layout. Must include a `routerOutlet(...)`. */\n readonly shell?: ShellBuilder;\n /** Id of the outlet element within the shell. Defaults to `ROUTER_OUTLET_ID`. */\n readonly outletId?: string;\n /** Override the renderer (e.g. a custom DOM adapter for tests). */\n readonly renderer?: StreetRenderer;\n /** Intercept internal `<a>` clicks for client-side navigation. Defaults to true. */\n readonly interceptLinks?: boolean;\n /**\n * Hydrate server-rendered HTML already present in the container instead of\n * mounting fresh. The shell and the *initial* route adopt the existing DOM;\n * subsequent client-side navigations mount normally. Defaults to false.\n */\n readonly hydrate?: boolean;\n}\n\nexport interface MountedRouter {\n /** The element route content is rendered into. */\n readonly outlet: Element;\n /** Tear down the current route, the shell, link interception and the router. */\n unmount(): void;\n}\n\n/** A URL is external when it targets another origin or a non-navigational scheme. */\nfunction isExternalHref(href: string): boolean {\n return (\n /^[a-zA-Z][a-zA-Z\\d+.-]*:/.test(href) || // scheme: http:, https:, mailto:, tel:\n href.startsWith('//') // protocol-relative\n );\n}\n\nexport function mountRouter(router: Router, options: MountRouterOptions): MountedRouter {\n const { container } = options;\n const renderer = options.renderer ?? createRenderer();\n const outletId = options.outletId ?? ROUTER_OUTLET_ID;\n const interceptLinks = options.interceptLinks ?? true;\n const hydrateMode = options.hydrate ?? false;\n\n // ── 1. Mount the shell once (if any) and resolve the outlet ──────────────────\n let shellMounted: MountedApplication | null = null;\n let outlet: Element;\n\n if (options.shell !== undefined) {\n const shellApp = streetui.app({ name: 'router-shell' });\n const shellBuilder = options.shell;\n shellApp.page('shell', (page) => shellBuilder(page, router));\n const shellRuntime = createRuntime({ renderer });\n const shellCompiled = compile(shellApp);\n if (hydrateMode) {\n // The outlet is a slot the router fills. When the shell hydrates, mark the\n // outlet node as a hydration boundary so shell hydration adopts the outlet\n // element itself but preserves the server-rendered route content inside it\n // (instead of stripping it as surplus). The initial route then hydrates\n // that content node-for-node.\n for (const node of shellCompiled.graph.findAll((n) => n.getProp('id') === outletId)) {\n node.setProp('_hydrationBoundary', true);\n }\n }\n shellMounted = hydrateMode\n ? shellRuntime.hydrate(shellCompiled, container)\n : shellRuntime.mount(shellCompiled, container);\n\n const found = container.querySelector(`[id=\"${outletId}\"]`);\n if (found === null) {\n throw new Error(\n `[Router] The shell must contain a route outlet. Call routerOutlet(scope) ` +\n `(or add a container with id=\"${outletId}\") inside your shell builder.`,\n );\n }\n outlet = found;\n } else {\n outlet = container;\n }\n\n // ── 2. Route mounting / disposal ─────────────────────────────────────────────\n interface ActiveRoute {\n readonly registry: CleanupRegistry;\n readonly mounted: MountedApplication;\n }\n let active: ActiveRoute | null = null;\n // Only the very first route render hydrates the server HTML in the outlet;\n // client-side navigations after that mount fresh.\n let firstRender = hydrateMode;\n\n const disposeActive = (): void => {\n if (active === null) return;\n // Run user-registered cleanup (effects, subscriptions) FIRST, then tear down\n // the DOM + runtime signal bindings. Both reuse existing machinery.\n active.registry.run();\n active.mounted.unmount();\n active = null;\n };\n\n const renderRoute = (match: RouteMatch): void => {\n disposeActive();\n\n const registry = new CleanupRegistry();\n const ctx: RouteContext = {\n path: match.path,\n pattern: match.pattern,\n params: match.params,\n query: match.query,\n onCleanup: (fn) => registry.add(fn),\n };\n\n const routeApp = streetui.app({ name: `route:${match.pattern}` });\n routeApp.page('route', (page) => match.route.builder(page, ctx));\n const runtime = createRuntime({ renderer });\n const routeCompiled = compile(routeApp);\n const mounted = firstRender\n ? runtime.hydrate(routeCompiled, outlet)\n : runtime.mount(routeCompiled, outlet);\n firstRender = false;\n\n active = { registry, mounted };\n };\n\n // Initial render, then react to every route change.\n renderRoute(router.currentRoute.peek());\n const stopRouteSub = router.currentRoute.subscribe((match) => renderRoute(match));\n\n // ── 3. Client-side link interception ─────────────────────────────────────────\n const onClick = (event: Event): void => {\n if (event.defaultPrevented) return;\n const mouse = event as MouseEvent;\n if (typeof mouse.button === 'number' && mouse.button !== 0) return;\n if (mouse.metaKey || mouse.ctrlKey || mouse.shiftKey || mouse.altKey) return;\n\n const target = event.target as Element | null;\n const anchor = target?.closest?.('a') ?? null;\n if (anchor === null) return;\n\n const targetAttr = anchor.getAttribute('target');\n if (targetAttr !== null && targetAttr !== '_self') return; // _blank etc.\n\n const href = anchor.getAttribute('href');\n if (href === null || href === '' || href.startsWith('#')) return;\n if (isExternalHref(href)) return;\n\n event.preventDefault();\n router.navigate(href);\n };\n\n if (interceptLinks) {\n container.addEventListener('click', onClick);\n }\n\n // ── Teardown ─────────────────────────────────────────────────────────────────\n return {\n outlet,\n unmount() {\n if (interceptLinks) container.removeEventListener('click', onClick);\n stopRouteSub();\n disposeActive();\n shellMounted?.unmount();\n router.destroy();\n },\n };\n}\n","/**\n * A small, sync validation system.\n *\n * A `Validator` maps a string field value to an error message, or `undefined`\n * when the value is acceptable. This is deliberately tiny — the built-ins cover\n * the common cases (`required`, `minLength`, `maxLength`, `email`, `pattern`)\n * and anything else is just a plain function `(value: string) => string | undefined`.\n *\n * Validators for a field run in order and the FIRST error wins, so list\n * `required` first if a field is mandatory.\n *\n * Async validation is intentionally NOT part of this core. It can be layered on\n * top with `@streetui/state`'s `resource()` (kick off a resource on value\n * change and surface `resource.error` alongside the field error) without\n * destabilising the synchronous validity model here.\n */\n\nexport type Validator = (value: string) => string | undefined;\n\n/** Fails when the trimmed value is empty. */\nexport function required(message = 'This field is required'): Validator {\n return (value) => (value.trim().length === 0 ? message : undefined);\n}\n\n/** Fails when the value is shorter than `length` characters. */\nexport function minLength(length: number, message?: string): Validator {\n return (value) =>\n value.length < length\n ? (message ?? `Must be at least ${length} characters`)\n : undefined;\n}\n\n/** Fails when the value is longer than `length` characters. */\nexport function maxLength(length: number, message?: string): Validator {\n return (value) =>\n value.length > length\n ? (message ?? `Must be at most ${length} characters`)\n : undefined;\n}\n\n// Pragmatic, dependency-free email shape check (not a full RFC 5322 parser).\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** Fails when a non-empty value is not a plausible email address. */\nexport function email(message = 'Enter a valid email address'): Validator {\n return (value) => (value.length === 0 || EMAIL_RE.test(value) ? undefined : message);\n}\n\n/** Fails when a non-empty value does not match `regex`. */\nexport function pattern(regex: RegExp, message = 'Invalid format'): Validator {\n return (value) => (value.length === 0 || regex.test(value) ? undefined : message);\n}\n\n/** Run a validator (or ordered list) and return the first error, if any. */\nexport function runValidators(\n value: string,\n validators: Validator | ReadonlyArray<Validator> | undefined,\n): string | undefined {\n if (validators === undefined) return undefined;\n const list = Array.isArray(validators) ? validators : [validators];\n for (const validate of list) {\n const error = validate(value);\n if (error !== undefined) return error;\n }\n return undefined;\n}\n","/**\n * Reactive form model built entirely on `@streetui/state` signals.\n *\n * There is no second state system here: every piece of form state (`values`,\n * `errors`, `touched`, `dirty`, `valid`, submission status) is a signal or a\n * derived signal, so it composes with the renderer's existing reactive bindings.\n * A field's `value` is a writable `Signal<string>`, which plugs straight into\n * the DSL's `input({ bind })` — typing updates form state and programmatic\n * updates update the input, through the one binding the renderer already wires.\n */\n\nimport {\n signal,\n derived,\n batch,\n DerivedSignal,\n type Signal,\n type ReadonlySignal,\n type Unsubscribe,\n} from '@streetui/state';\nimport { type Validator, runValidators } from './validators.js';\n\n/** Form values are a flat, typed record of string fields (HTML input values). */\nexport type FormValues = Record<string, string>;\n\nexport interface Field {\n readonly name: string;\n /** Writable value signal — pass to `input({ bind: field.value })`. */\n readonly value: Signal<string>;\n /** Current validation error, or `undefined` when the field is valid. */\n readonly error: ReadonlySignal<string | undefined>;\n /** True once the field has received a genuine user interaction. */\n readonly touched: ReadonlySignal<boolean>;\n /** True when the value differs from its initial value. */\n readonly dirty: ReadonlySignal<boolean>;\n /** True when the field has no validation error. */\n readonly valid: ReadonlySignal<boolean>;\n /** Programmatically set the value (does not mark the field touched). */\n setValue(next: string): void;\n /** Force the touched flag (defaults to true). */\n markTouched(touched?: boolean): void;\n /** Restore this field's initial value and clear its touched flag. */\n reset(): void;\n}\n\nexport type FormValidators<T extends FormValues> = {\n readonly [K in keyof T]?: Validator | ReadonlyArray<Validator>;\n};\n\nexport interface FormConfig<T extends FormValues> {\n readonly initialValues: T;\n readonly validators?: FormValidators<T>;\n /** Called by `submit()` once all fields are valid. May be async. */\n readonly onSubmit?: (values: T) => void | Promise<void>;\n}\n\nexport type SubmitStatus = 'idle' | 'submitting' | 'success' | 'error';\n\nexport interface Form<T extends FormValues> {\n readonly values: ReadonlySignal<T>;\n readonly errors: ReadonlySignal<Partial<Record<keyof T, string>>>;\n readonly touched: ReadonlySignal<Partial<Record<keyof T, boolean>>>;\n readonly dirty: ReadonlySignal<boolean>;\n readonly valid: ReadonlySignal<boolean>;\n readonly submitting: ReadonlySignal<boolean>;\n readonly submitted: ReadonlySignal<boolean>;\n readonly status: ReadonlySignal<SubmitStatus>;\n readonly submitError: ReadonlySignal<unknown>;\n /** Access the reactive state + setters for one field. */\n field<K extends keyof T & string>(name: K): Field;\n /** Merge a partial set of values in (does not mark fields touched). */\n setValues(partial: Partial<T>): void;\n /** Validate, mark all fields touched, then run `onSubmit` if valid. */\n submit(): Promise<void>;\n /** Restore initial values and clear errors/touched/dirty/submission state. */\n reset(): void;\n /** Tear down all field subscriptions and derived signals. */\n dispose(): void;\n}\n\ninterface FieldInternal {\n readonly api: Field;\n readonly value: Signal<string>;\n readonly touched: Signal<boolean>;\n readonly error: DerivedSignal<string | undefined>;\n readonly valid: DerivedSignal<boolean>;\n readonly dirty: DerivedSignal<boolean>;\n readonly initial: string;\n readonly unsub: Unsubscribe;\n}\n\n// __FORM_IMPL__\n\nexport function createForm<T extends FormValues>(config: FormConfig<T>): Form<T> {\n const names = Object.keys(config.initialValues) as Array<keyof T & string>;\n const validators = config.validators ?? ({} as FormValidators<T>);\n\n // While true, value changes originate from setValues()/reset() and must NOT\n // mark a field touched. Batch flushes run synchronously inside batch(), i.e.\n // before this flag is reset, so guarding around batch() is sound.\n let programmatic = false;\n\n const fields = new Map<string, FieldInternal>();\n\n for (const name of names) {\n // Keys come from Object.keys(initialValues), so the value is always present;\n // the annotation defeats noUncheckedIndexedAccess widening to `| undefined`.\n const initial: string = config.initialValues[name] as string;\n const value = signal<string>(initial);\n const touched = signal<boolean>(false);\n const error = derived<string | undefined>(() =>\n runValidators(value.get(), validators[name]),\n );\n const valid = derived<boolean>(() => error.get() === undefined);\n const dirty = derived<boolean>(() => value.get() !== initial);\n\n // Mark touched on the first genuine (non-programmatic) value change.\n const unsub = value.subscribe(() => {\n if (!programmatic) touched.set(true);\n });\n\n const api: Field = {\n name,\n value,\n error,\n touched,\n dirty,\n valid,\n setValue(next: string): void {\n value.set(next);\n },\n markTouched(next = true): void {\n touched.set(next);\n },\n reset(): void {\n programmatic = true;\n try {\n batch(() => {\n value.set(initial);\n touched.set(false);\n });\n } finally {\n programmatic = false;\n }\n },\n };\n\n fields.set(name, { api, value, touched, error, valid, dirty, initial, unsub });\n }\n\n const field = (name: string): FieldInternal => {\n const f = fields.get(name);\n if (f === undefined) throw new Error(`Unknown form field: ${name}`);\n return f;\n };\n\n const values = derived<T>(() => {\n const out: Record<string, string> = {};\n for (const name of names) out[name] = field(name).value.get();\n return out as T;\n });\n\n const errors = derived<Partial<Record<keyof T, string>>>(() => {\n const out: Partial<Record<keyof T, string>> = {};\n for (const name of names) {\n const e = field(name).error.get();\n if (e !== undefined) out[name] = e;\n }\n return out;\n });\n\n const touchedMap = derived<Partial<Record<keyof T, boolean>>>(() => {\n const out: Partial<Record<keyof T, boolean>> = {};\n for (const name of names) out[name] = field(name).touched.get();\n return out;\n });\n\n const dirty = derived<boolean>(() => names.some((n) => field(n).dirty.get()));\n const valid = derived<boolean>(() => names.every((n) => field(n).valid.get()));\n\n const status = signal<SubmitStatus>('idle');\n const submitting = derived<boolean>(() => status.get() === 'submitting');\n const submitted = derived<boolean>(() => status.get() === 'success');\n const submitError = signal<unknown>(undefined);\n\n function setValues(partial: Partial<T>): void {\n programmatic = true;\n try {\n batch(() => {\n for (const name of names) {\n const next = partial[name];\n if (next !== undefined) field(name).value.set(next);\n }\n });\n } finally {\n programmatic = false;\n }\n }\n\n function reset(): void {\n programmatic = true;\n try {\n batch(() => {\n for (const name of names) {\n const f = field(name);\n f.value.set(f.initial);\n f.touched.set(false);\n }\n status.set('idle');\n submitError.set(undefined);\n });\n } finally {\n programmatic = false;\n }\n }\n\n async function submit(): Promise<void> {\n // Touch every field so validation errors become visible on submit attempts.\n batch(() => {\n for (const name of names) field(name).touched.set(true);\n });\n if (!valid.peek()) {\n // Invalid — do not enter the submitting lifecycle; field errors now show.\n return;\n }\n submitError.set(undefined);\n status.set('submitting');\n try {\n await config.onSubmit?.(values.peek());\n status.set('success');\n } catch (err) {\n submitError.set(err);\n status.set('error');\n }\n }\n\n function dispose(): void {\n for (const f of fields.values()) {\n f.unsub();\n f.error.dispose();\n f.valid.dispose();\n f.dirty.dispose();\n }\n values.dispose();\n errors.dispose();\n touchedMap.dispose();\n dirty.dispose();\n valid.dispose();\n submitting.dispose();\n submitted.dispose();\n }\n\n return {\n values,\n errors,\n touched: touchedMap,\n dirty,\n valid,\n submitting,\n submitted,\n status,\n submitError,\n field: (name) => field(name).api,\n setValues,\n submit,\n reset,\n dispose,\n };\n}\n\n","/**\n * @streetui/context — build-time provider/consumer scoping.\n *\n * StreetUI builds its semantic tree synchronously, top-down, when the DSL\n * builders run. A `Context` mirrors that shape: `provide(value, run)` pushes a\n * value for the duration of the synchronous `run()` (during which the child\n * DSL builders execute and may `consume()`), then pops it. Consumers resolve\n * the *nearest* enclosing provider, falling back to the context default.\n *\n * This is deliberately NOT a second reactive system. A context value can be a\n * signal (see @streetui/state); reactivity then belongs to that signal and is\n * torn down by the normal node lifecycle when the consuming subtree unmounts —\n * the context itself holds no subscriptions and leaves no refs behind after a\n * `provide()` call returns.\n */\n\nexport interface Context<T> {\n /** Unique identity for this context (useful for debugging/inspection). */\n readonly id: symbol;\n /** The value returned by {@link consume} when no provider is active. */\n readonly defaultValue: T;\n /**\n * Provide `value` to any `consume()` calls made synchronously inside `run`.\n * The value is popped again as soon as `run` returns (even if it throws),\n * so nesting resolves to the nearest active provider.\n */\n provide<R>(value: T, run: () => R): R;\n /** Read the nearest active provider's value, or {@link defaultValue}. */\n consume(): T;\n /** True while at least one provider is active for this context. */\n hasProvider(): boolean;\n}\n\n/**\n * Create a typed context with a required default value, so `consume()` always\n * returns a `T` (never `undefined` unless `T` itself permits it).\n */\nexport function createContext<T>(defaultValue: T, description?: string): Context<T> {\n const id = Symbol(description ?? 'streetui.context');\n const stack: T[] = [];\n\n return {\n id,\n defaultValue,\n provide<R>(value: T, run: () => R): R {\n stack.push(value);\n try {\n return run();\n } finally {\n stack.pop();\n }\n },\n consume(): T {\n return stack.length > 0 ? (stack[stack.length - 1] as T) : defaultValue;\n },\n hasProvider(): boolean {\n return stack.length > 0;\n },\n };\n}\n","/**\n * Minimal, framework-native internationalization for StreetUI.\n *\n * Built entirely on `@streetui/state` signals — there is no second reactive\n * system. The active locale is a writable signal; `t()` returns a derived\n * signal that recomputes when the locale changes, so translations plug\n * straight into the DSL's reactive text bindings (`text(() => i18n.t(...).get())`\n * or `text(i18n.t(...))`).\n *\n * Translation is deterministic: a missing key resolves to the key itself, and\n * the same (locale, key, params) always produces the same string on the server\n * and the client. That determinism is what keeps `renderToString()` and\n * `hydrate()` in agreement — provided the app boots the client with the same\n * initial locale it rendered with on the server.\n */\n\nimport {\n signal,\n derived,\n type ReadonlySignal,\n type DerivedSignal,\n} from '@streetui/state';\n\n/** A flat dictionary of message templates for a single locale. */\nexport type MessageMap = Record<string, string>;\n\n/** Values allowed in interpolation params. */\nexport type InterpolationParams = Record<string, string | number>;\n\nexport interface I18nConfig<M extends MessageMap> {\n /** The initial (and server-rendered) locale. */\n readonly locale: string;\n /** Messages keyed by locale, e.g. `{ en: {...}, fr: {...} }`. */\n readonly messages: Readonly<Record<string, M>>;\n /** Locale consulted when a key is absent from the active locale. */\n readonly fallbackLocale?: string;\n}\n\nexport interface I18n<M extends MessageMap> {\n /** The active locale as a reactive, read-only signal. */\n readonly locale: ReadonlySignal<string>;\n /** Switch the active locale; all `t()`/`plural()` signals recompute. */\n setLocale(locale: string): void;\n /** The locales that have a message map, in declaration order. */\n readonly locales: ReadonlyArray<string>;\n /** Reactive translation. Returns a derived signal — call `.get()` to read. */\n t(key: keyof M & string, params?: InterpolationParams): ReadonlySignal<string>;\n /** Non-reactive translation for the current locale (a one-shot read). */\n translate(key: keyof M & string, params?: InterpolationParams): string;\n /**\n * Reactive pluralization via `Intl.PluralRules`. Selects the message whose\n * key is `${key}.${category}` (e.g. `items.one`), falling back to\n * `${key}.other`. `count` is available to interpolation as `{count}`.\n */\n plural(key: string, count: number, params?: InterpolationParams): ReadonlySignal<string>;\n /** True when the active (or fallback) locale defines `key`. */\n has(key: string): boolean;\n}\n\nconst INTERPOLATION = /\\{(\\w+)\\}/g;\n\n/** Replace `{name}` placeholders using `params`; unknown names are left intact. */\nexport function interpolate(template: string, params?: InterpolationParams): string {\n if (params === undefined) return template;\n return template.replace(INTERPOLATION, (whole, name: string) => {\n const value = params[name];\n return value === undefined ? whole : String(value);\n });\n}\n\nexport function createI18n<M extends MessageMap>(config: I18nConfig<M>): I18n<M> {\n const messages = config.messages;\n const fallback = config.fallbackLocale;\n const localeSignal = signal<string>(config.locale);\n const locales = Object.keys(messages);\n\n /** Resolve a raw template for `key` in `loc`, then the fallback locale. */\n function lookup(loc: string, key: string): string | undefined {\n const active = messages[loc];\n const hit = active === undefined ? undefined : active[key];\n if (hit !== undefined) return hit;\n if (fallback !== undefined && fallback !== loc) {\n const fb = messages[fallback];\n if (fb !== undefined) return fb[key];\n }\n return undefined;\n }\n\n function resolve(loc: string, key: string, params?: InterpolationParams): string {\n const template = lookup(loc, key);\n // Deterministic miss: echo the key so output is stable server/client.\n return template === undefined ? key : interpolate(template, params);\n }\n\n function pluralKey(loc: string, key: string, count: number): string {\n const category = new Intl.PluralRules(loc).select(count);\n if (lookup(loc, `${key}.${category}`) !== undefined) return `${key}.${category}`;\n return `${key}.other`;\n }\n\n return {\n locale: localeSignal,\n locales,\n setLocale(loc: string): void {\n localeSignal.set(loc);\n },\n t(key, params): DerivedSignal<string> {\n return derived<string>(() => resolve(localeSignal.get(), key, params));\n },\n translate(key, params): string {\n return resolve(localeSignal.peek(), key, params);\n },\n plural(key, count, params): DerivedSignal<string> {\n const merged: InterpolationParams = { count, ...(params ?? {}) };\n return derived<string>(() => {\n const loc = localeSignal.get();\n return resolve(loc, pluralKey(loc, key, count), merged);\n });\n },\n has(key: string): boolean {\n return lookup(localeSignal.peek(), key) !== undefined;\n },\n };\n}\n","/**\n * StreetUI DevTools — graph inspector and debug utilities.\n */\n\nimport { formatDiagnostic } from '@streetui/core';\nimport type { ApplicationGraph, GraphNode } from '@streetui/graph';\nimport type { CompiledApplication } from '@streetui/compiler';\n\nexport interface InspectedNode {\n id: string;\n type: string;\n key: string | undefined;\n props: Record<string, unknown>;\n eventTypes: string[];\n stateBindings: string[];\n children: InspectedNode[];\n depth: number;\n}\n\nexport function inspectGraph(graph: ApplicationGraph): InspectedNode {\n return inspectNode(graph.root, 0);\n}\n\nfunction inspectNode(node: GraphNode, depth: number): InspectedNode {\n return {\n id: node.id,\n type: node.type,\n key: node.key,\n props: { ...node.props },\n eventTypes: node.events.map(e => e.type),\n stateBindings: node.stateRefs.map(r => `${r.propKey}→${r.signalId}`),\n depth,\n children: node.children.map(c => inspectNode(c, depth + 1)),\n };\n}\n\n/** Print a human-readable tree of the graph to a string. */\nexport function printGraph(graph: ApplicationGraph): string {\n const lines: string[] = [];\n graph.walk((node, depth) => {\n const indent = ' '.repeat(depth);\n const props = Object.entries(node.props)\n .filter(([k]) => !k.startsWith('_'))\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(', ');\n const events = node.events.length > 0\n ? ` [events: ${node.events.map(e => e.type).join(', ')}]`\n : '';\n const stateRefs = node.stateRefs.length > 0\n ? ` [signals: ${node.stateRefs.map(r => r.propKey).join(', ')}]`\n : '';\n lines.push(`${indent}<${node.type}${props ? ` ${props}` : ''}${events}${stateRefs}>`);\n });\n return lines.join('\\n');\n}\n\n/** Print compilation diagnostics to a string. */\nexport function printDiagnostics(compiled: CompiledApplication): string {\n if (compiled.diagnostics.diagnostics.length === 0) {\n return '(no diagnostics)';\n }\n return compiled.diagnostics.diagnostics.map(formatDiagnostic).join('\\n');\n}\n\n/** Returns node counts per type. */\nexport function nodeTypeStats(graph: ApplicationGraph): Record<string, number> {\n const counts: Record<string, number> = {};\n graph.walk(node => {\n counts[node.type] = (counts[node.type] ?? 0) + 1;\n });\n return counts;\n}\n","/**\n * DevTools foundation (v0.6, Phase 18). A single read-only entry point that\n * aggregates everything an eventual DevTools UI would need — application\n * identity, the graph tree, signal bindings, page/route surface, node\n * statistics, and diagnostics — WITHOUT introducing a second representation of\n * the graph. It reuses `inspectGraph`/`nodeTypeStats` from the inspector and\n * reads `CompiledApplication` metadata directly. This is a foundation, not a\n * UI: it returns plain data so a UI (or a test, or a CLI command) can render it.\n */\n\nimport type { CompiledApplication } from '@streetui/compiler';\nimport { formatDiagnostic } from '@streetui/core';\nimport { inspectGraph, nodeTypeStats, type InspectedNode } from './inspector.js';\n\n/** Stable identity of a compiled application. */\nexport interface ApplicationIdentity {\n readonly name: string;\n readonly version: string;\n /** Epoch millis the application was compiled. */\n readonly compiledAt: number;\n}\n\n/** A page node reachable as a direct child of the application root. */\nexport interface InspectedPage {\n readonly id: string;\n /** The page key when one was supplied in the DSL. */\n readonly key: string | undefined;\n}\n\n/** Compilation diagnostics summarised for display. */\nexport interface DiagnosticsSummary {\n readonly errors: number;\n readonly warnings: number;\n readonly messages: string[];\n}\n\n/**\n * Cheap, count-only performance snapshot (v0.7 §20). These are structural\n * counts derived from a single graph walk — NOT timings and NOT a profiler.\n * They let a DevTools panel or a CI check spot the shapes that correlate with\n * slow apps (very large graphs, deep trees, big lists, many subscriptions)\n * without measuring anything at runtime.\n */\nexport interface PerfSnapshot {\n /** Total GraphNodes in the tree (root included). */\n readonly totalNodes: number;\n /** Maximum nesting depth (root = 0). */\n readonly maxDepth: number;\n /** Total event handler registrations across all nodes. */\n readonly eventHandlers: number;\n /** Total signal→prop bindings across all nodes. */\n readonly stateBindings: number;\n /** Distinct signals referenced anywhere in the graph. */\n readonly distinctSignals: number;\n /** Largest single-node child count (a proxy for the biggest list/section). */\n readonly largestChildCount: number;\n /**\n * Number of reactive keyed-list sites driven by the optimised lazy-plan\n * reconciler (v1.1 §15/§25). Counted from the graph's `__listplan__<id>`\n * handler registrations — one per `listOf(...)` bound to a signal. These are\n * the nodes whose updates take the identity-short-circuit + LIS minimal-move\n * path, so surfacing the count lets a panel or CI check see how much of an app\n * benefits from the keyed-list engine without measuring anything at runtime.\n */\n readonly reactiveLists: number;\n}\n\n/**\n * The complete read-only snapshot of a compiled application. Everything here is\n * derived from the single `CompiledApplication` graph — no state is duplicated.\n */\nexport interface ApplicationInspection {\n readonly identity: ApplicationIdentity;\n readonly graph: InspectedNode;\n /** Count of nodes per DSL type (e.g. `{ section: 2, button: 3 }`). */\n readonly nodeStats: Record<string, number>;\n /** Unique signal ids bound anywhere in the graph, sorted. */\n readonly signals: string[];\n /** Page nodes directly under the root — the app's top-level route surface. */\n readonly pages: InspectedPage[];\n readonly diagnostics: DiagnosticsSummary;\n /** Cheap structural performance counters (v0.7 §20). */\n readonly perf: PerfSnapshot;\n}\n\n/** Walk the inspected tree once, accumulating the count-only perf snapshot. */\nfunction collectPerf(\n node: InspectedNode,\n distinctSignals: number,\n acc: { totalNodes: number; maxDepth: number; eventHandlers: number; stateBindings: number; largestChildCount: number },\n): void {\n acc.totalNodes += 1;\n if (node.depth > acc.maxDepth) acc.maxDepth = node.depth;\n acc.eventHandlers += node.eventTypes.length;\n acc.stateBindings += node.stateBindings.length;\n if (node.children.length > acc.largestChildCount) acc.largestChildCount = node.children.length;\n for (const child of node.children) collectPerf(child, distinctSignals, acc);\n}\n\n/** Collect every distinct signal id referenced by any node in the tree. */\nfunction collectSignals(node: InspectedNode, into: Set<string>): void {\n for (const binding of node.stateBindings) {\n // Bindings are formatted `propKey→signalId` by the inspector.\n const arrow = binding.indexOf('→');\n const signalId = arrow >= 0 ? binding.slice(arrow + 1) : binding;\n if (signalId.length > 0) into.add(signalId);\n }\n for (const child of node.children) collectSignals(child, into);\n}\n\n/**\n * Build the full inspection snapshot for a compiled application. Pure and\n * side-effect free — safe to call in a server, a test, or a DevTools panel.\n */\nexport function inspectApplication(compiled: CompiledApplication): ApplicationInspection {\n const graph = inspectGraph(compiled.graph);\n\n const signals = new Set<string>();\n collectSignals(graph, signals);\n\n const pages: InspectedPage[] = graph.children\n .filter((child) => child.type === 'page')\n .map((child) => ({ id: child.id, key: child.key }));\n\n const diags = compiled.diagnostics.diagnostics;\n const errors = diags.filter((d) => d.severity === 'error').length;\n\n const perfAcc = { totalNodes: 0, maxDepth: 0, eventHandlers: 0, stateBindings: 0, largestChildCount: 0 };\n collectPerf(graph, signals.size, perfAcc);\n\n // Count optimised keyed-list sites from the handler registry (one\n // `__listplan__<id>` per signal-driven `listOf`). Reading the map directly\n // keeps this a pure, count-only derivation — no second graph walk.\n let reactiveLists = 0;\n for (const key of compiled.graph.handlers.keys()) {\n if (key.startsWith('__listplan__')) reactiveLists += 1;\n }\n\n return {\n identity: {\n name: compiled.name,\n version: compiled.version,\n compiledAt: compiled.compiledAt,\n },\n graph,\n nodeStats: nodeTypeStats(compiled.graph),\n signals: [...signals].sort(),\n pages,\n diagnostics: {\n errors,\n warnings: diags.length - errors,\n messages: diags.map(formatDiagnostic),\n },\n perf: {\n totalNodes: perfAcc.totalNodes,\n maxDepth: perfAcc.maxDepth,\n eventHandlers: perfAcc.eventHandlers,\n stateBindings: perfAcc.stateBindings,\n distinctSignals: signals.size,\n largestChildCount: perfAcc.largestChildCount,\n reactiveLists,\n },\n };\n}\n","/**\n * Dev-only performance diagnostics (v0.7 §21).\n *\n * A pure, cheap, count-based check that flags graph *shapes* known to correlate\n * with slow apps — very large graphs, deep trees, oversized lists/sections, and\n * heavy reactive fan-out. It is NOT wired into mount/render and adds ZERO cost\n * to the runtime hot path; a developer (or a CLI command, or a test) calls it\n * explicitly. Thresholds are advisory and overridable.\n *\n * This intentionally reuses the counts already produced by `inspectApplication`\n * — it introduces no second graph walk of its own beyond reading that snapshot.\n */\n\nimport type { CompiledApplication } from '@streetui/compiler';\nimport { inspectApplication } from './application.js';\n\nexport interface PerfThresholds {\n /** Warn when the graph exceeds this many nodes. */\n readonly maxNodes: number;\n /** Warn when nesting depth exceeds this. */\n readonly maxDepth: number;\n /** Warn when any single node has more than this many children (big list). */\n readonly maxChildCount: number;\n /** Warn when distinct signals exceed this (reactive fan-out). */\n readonly maxSignals: number;\n}\n\nexport const DEFAULT_PERF_THRESHOLDS: PerfThresholds = {\n maxNodes: 5000,\n maxDepth: 32,\n maxChildCount: 1000,\n maxSignals: 1000,\n};\n\nexport type PerfDiagnosticCode =\n | 'large-graph'\n | 'deep-tree'\n | 'large-list'\n | 'high-signal-fanout';\n\nexport interface PerfDiagnostic {\n readonly code: PerfDiagnosticCode;\n readonly message: string;\n /** The observed count that tripped the threshold. */\n readonly observed: number;\n /** The threshold it exceeded. */\n readonly threshold: number;\n}\n\n/**\n * Return advisory performance diagnostics for a compiled application. An empty\n * array means nothing tripped a threshold. Never throws; never mutates.\n */\nexport function diagnosePerformance(\n compiled: CompiledApplication,\n thresholds: Partial<PerfThresholds> = {},\n): PerfDiagnostic[] {\n const t = { ...DEFAULT_PERF_THRESHOLDS, ...thresholds };\n const { perf } = inspectApplication(compiled);\n const out: PerfDiagnostic[] = [];\n\n if (perf.totalNodes > t.maxNodes) {\n out.push({\n code: 'large-graph',\n message: `Graph has ${perf.totalNodes} nodes (> ${t.maxNodes}); consider splitting the view or paginating.`,\n observed: perf.totalNodes,\n threshold: t.maxNodes,\n });\n }\n if (perf.maxDepth > t.maxDepth) {\n out.push({\n code: 'deep-tree',\n message: `Graph nests ${perf.maxDepth} levels deep (> ${t.maxDepth}); deep trees slow mount and reconciliation.`,\n observed: perf.maxDepth,\n threshold: t.maxDepth,\n });\n }\n if (perf.largestChildCount > t.maxChildCount) {\n out.push({\n code: 'large-list',\n message: `A single node has ${perf.largestChildCount} children (> ${t.maxChildCount}); large un-windowed lists dominate DOM cost.`,\n observed: perf.largestChildCount,\n threshold: t.maxChildCount,\n });\n }\n if (perf.distinctSignals > t.maxSignals) {\n out.push({\n code: 'high-signal-fanout',\n message: `${perf.distinctSignals} distinct signals are bound (> ${t.maxSignals}); heavy reactive fan-out increases update overhead.`,\n observed: perf.distinctSignals,\n threshold: t.maxSignals,\n });\n }\n\n return out;\n}\n","/**\n * Reactive-surface inspection for DevTools.\n *\n * These functions turn the framework's live objects — signals, resources,\n * router, forms, context, i18n — into plain, read-only snapshots suitable for a\n * DevTools panel. They never mutate anything and never subscribe; each call is a\n * one-shot `peek`. Sensitive-by-default surfaces (resource payloads, form field\n * values) are omitted unless the caller explicitly opts in, so a panel cannot\n * accidentally display tokens, passwords, or private data.\n *\n * Router/forms/context/i18n are described by *structural* interfaces rather than\n * imported types, so DevTools stays decoupled from those packages (no extra\n * dependencies) while still inspecting them when present.\n */\n\nimport {\n type ReadonlySignal,\n type ResourceStatus,\n type SignalKind,\n signalKind,\n observerCount,\n} from '@streetui/state';\n\n// ── Signals ─────────────────────────────────────────────────────────────────\n\nexport interface SignalInspection {\n /** Whether the signal is writable or a derived computation. */\n readonly kind: SignalKind;\n /** The current value (redacted if requested). */\n readonly value: unknown;\n /** Live observer count when the signal exposes it, else undefined. */\n readonly observerCount: number | undefined;\n}\n\nexport interface InspectSignalOptions {\n /**\n * Redact the value: `true` replaces it with `'[redacted]'`; a function maps\n * the raw value to whatever should be shown. Use for signals that may hold\n * sensitive data. Omitted → the value is shown as-is.\n */\n readonly redact?: boolean | ((value: unknown) => unknown);\n}\n\n/** Snapshot a signal's kind, current value, and observer count. Read-only. */\nexport function inspectSignal(\n source: ReadonlySignal<unknown>,\n options: InspectSignalOptions = {},\n): SignalInspection {\n const raw = source.peek();\n let value: unknown = raw;\n if (options.redact === true) value = '[redacted]';\n else if (typeof options.redact === 'function') value = options.redact(raw);\n\n return {\n kind: signalKind(source),\n value,\n observerCount: observerCount(source),\n };\n}\n\n// ── Resources ─────────────────────────────────────────────────────────────\n\n/** The read-only slice of a resource this module needs. */\nexport interface ResourceLike {\n readonly status: ReadonlySignal<ResourceStatus>;\n readonly data: ReadonlySignal<unknown>;\n readonly error: ReadonlySignal<unknown>;\n readonly loading: ReadonlySignal<boolean>;\n readonly isRefetching: ReadonlySignal<boolean>;\n}\n\nexport interface ResourceInspection {\n readonly status: ResourceStatus;\n readonly loading: boolean;\n readonly isRefetching: boolean;\n readonly hasData: boolean;\n readonly hasError: boolean;\n /** The error's constructor name (safe — no message/payload). */\n readonly errorName: string | undefined;\n /** The error message — only present when `includeData` is set. */\n readonly errorMessage?: string;\n /** The loaded value — only present when `includeData` is set. */\n readonly data?: unknown;\n}\n\nexport interface InspectResourceOptions {\n /**\n * Include the loaded `data` and the error `message`. Off by default because a\n * resource payload commonly carries user or secret data.\n */\n readonly includeData?: boolean;\n}\n\n/** Snapshot a resource's lifecycle. Payload/message hidden unless opted in. */\nexport function inspectResource(\n resource: ResourceLike,\n options: InspectResourceOptions = {},\n): ResourceInspection {\n const error = resource.error.peek();\n const hasError = error !== undefined && error !== null;\n const base: ResourceInspection = {\n status: resource.status.peek(),\n loading: resource.loading.peek(),\n isRefetching: resource.isRefetching.peek(),\n hasData: resource.data.peek() !== undefined,\n hasError,\n errorName: hasError ? errorConstructorName(error) : undefined,\n };\n if (options.includeData !== true) return base;\n\n return {\n ...base,\n data: resource.data.peek(),\n ...(hasError ? { errorMessage: errorMessageOf(error) } : {}),\n };\n}\n\nfunction errorConstructorName(error: unknown): string {\n if (error instanceof Error) return error.name;\n return typeof error;\n}\n\nfunction errorMessageOf(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\n// ── Router ──────────────────────────────────────────────────────────────────\n\nexport interface RouteMatchLike {\n readonly path: string;\n readonly pattern: string;\n readonly params: Readonly<Record<string, string>>;\n readonly query: URLSearchParams;\n readonly isFallback?: boolean;\n}\n\nexport interface RouterLike {\n readonly currentRoute: ReadonlySignal<RouteMatchLike>;\n}\n\nexport interface RouterInspection {\n readonly path: string;\n readonly pattern: string;\n readonly params: Record<string, string>;\n readonly query: Record<string, string>;\n readonly isFallback: boolean;\n}\n\n/** Snapshot the router's current route. Read-only. */\nexport function inspectRouter(router: RouterLike): RouterInspection {\n const match = router.currentRoute.peek();\n const query: Record<string, string> = {};\n for (const [k, v] of match.query.entries()) query[k] = v;\n return {\n path: match.path,\n pattern: match.pattern,\n params: { ...match.params },\n query,\n isFallback: match.isFallback === true,\n };\n}\n\n// ── Forms ─────────────────────────────────────────────────────────────────\n\nexport interface FormLike {\n readonly values: ReadonlySignal<Record<string, unknown>>;\n readonly errors: ReadonlySignal<Record<string, string | undefined>>;\n readonly touched: ReadonlySignal<Record<string, boolean | undefined>>;\n readonly dirty: ReadonlySignal<boolean>;\n readonly valid: ReadonlySignal<boolean>;\n readonly status: ReadonlySignal<string>;\n}\n\nexport interface FormInspection {\n readonly fields: string[];\n /** Per-field validation messages (safe — not the entered values). */\n readonly errors: Record<string, string>;\n readonly touched: Record<string, boolean>;\n readonly dirty: boolean;\n readonly valid: boolean;\n readonly status: string;\n /** Entered field values — only present when `includeValues` is set. */\n readonly values?: Record<string, unknown>;\n}\n\nexport interface InspectFormOptions {\n /**\n * Include the entered field `values`. Off by default because form fields\n * frequently hold passwords or other secrets.\n */\n readonly includeValues?: boolean;\n}\n\n/** Snapshot form validation state. Entered values hidden unless opted in. */\nexport function inspectForm(form: FormLike, options: InspectFormOptions = {}): FormInspection {\n const values = form.values.peek();\n const errorsRaw = form.errors.peek();\n const touchedRaw = form.touched.peek();\n\n const errors: Record<string, string> = {};\n for (const [k, v] of Object.entries(errorsRaw)) if (v !== undefined) errors[k] = v;\n const touched: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(touchedRaw)) touched[k] = v === true;\n\n const base: FormInspection = {\n fields: Object.keys(values),\n errors,\n touched,\n dirty: form.dirty.peek(),\n valid: form.valid.peek(),\n status: form.status.peek(),\n };\n if (options.includeValues !== true) return base;\n return { ...base, values: { ...values } };\n}\n\n// ── Context ─────────────────────────────────────────────────────────────────\n\nexport interface ContextLike {\n readonly id: symbol;\n hasProvider(): boolean;\n}\n\nexport interface ContextInspection {\n /** The context's descriptive label (from its Symbol). */\n readonly description: string;\n /** Whether a provider is currently active. */\n readonly hasProvider: boolean;\n}\n\n/** Snapshot a context's identity and provider presence. No value dumped. */\nexport function inspectContext(context: ContextLike): ContextInspection {\n return {\n description: context.id.description ?? 'streetui.context',\n hasProvider: context.hasProvider(),\n };\n}\n\n// ── i18n ──────────────────────────────────────────────────────────────────\n\nexport interface I18nLike {\n readonly locale: ReadonlySignal<string>;\n readonly locales: ReadonlyArray<string>;\n has(key: string): boolean;\n}\n\nexport interface I18nInspection {\n readonly locale: string;\n readonly locales: string[];\n /** Of the probed keys, those with no translation in the active/fallback locale. */\n readonly missingKeys?: string[];\n}\n\nexport interface InspectI18nOptions {\n /** Keys to probe for presence; any absent ones are reported as missing. */\n readonly checkKeys?: readonly string[];\n}\n\n/** Snapshot i18n locale state and (optionally) missing translation keys. */\nexport function inspectI18n(i18n: I18nLike, options: InspectI18nOptions = {}): I18nInspection {\n const base: I18nInspection = {\n locale: i18n.locale.peek(),\n locales: [...i18n.locales],\n };\n if (options.checkKeys === undefined) return base;\n const missingKeys = options.checkKeys.filter((k) => !i18n.has(k));\n return { ...base, missingKeys };\n}\n","/**\n * DevTools session & panels — the first real StreetUI DevTools surface.\n *\n * This is a *headless* DevTools layer: it composes the existing read-only\n * inspection functions (`inspectApplication`, `diagnosePerformance`, and the\n * reactive inspectors) into the panels a DevTools UI shows — Application, Graph,\n * Signals, Router, Resources, Forms, Context, i18n, and Performance — and\n * returns them as plain data plus a text formatter. Any host (a browser panel, a\n * CLI command, a test) can render that data.\n *\n * Design constraints honoured here:\n * - No second graph and no second reactive system — everything is derived from\n * the one `CompiledApplication` and the app's own live signals.\n * - Explicit activation: nothing in the runtime imports this. A session only\n * exists once dev code calls `createDevTools`, so production pays no cost.\n * - Live updates use a simple explicit `refresh()` — DevTools never subscribes\n * to or instruments the reactive graph.\n * - Sensitive surfaces (resource payloads, form values) stay hidden unless the\n * caller opts in per the underlying inspectors.\n */\n\nimport type { CompiledApplication } from '@streetui/compiler';\nimport type { ReadonlySignal } from '@streetui/state';\nimport {\n inspectApplication,\n type ApplicationInspection,\n type ApplicationIdentity,\n type InspectedPage,\n} from './application.js';\nimport type { InspectedNode } from './inspector.js';\nimport { diagnosePerformance, type PerfDiagnostic, type PerfThresholds } from './diagnostics.js';\nimport {\n inspectSignal,\n inspectResource,\n inspectRouter,\n inspectForm,\n inspectContext,\n inspectI18n,\n type SignalInspection,\n type ResourceInspection,\n type RouterInspection,\n type FormInspection,\n type ContextInspection,\n type I18nInspection,\n type ResourceLike,\n type RouterLike,\n type FormLike,\n type ContextLike,\n type I18nLike,\n} from './inspect-reactive.js';\n\n// ── Panel shapes ────────────────────────────────────────────────────────────\n\nexport interface ApplicationPanel {\n readonly identity: ApplicationIdentity;\n readonly nodeCount: number;\n readonly maxDepth: number;\n readonly pages: readonly InspectedPage[];\n readonly signalCount: number;\n readonly eventHandlers: number;\n readonly stateBindings: number;\n readonly errors: number;\n readonly warnings: number;\n}\n\nexport interface SignalsPanel {\n /** Distinct signal ids referenced anywhere in the graph (structural). */\n readonly boundSignalIds: readonly string[];\n /** Live inspections for signals the app registered with DevTools, by label. */\n readonly live: Readonly<Record<string, SignalInspection>>;\n}\n\nexport interface PerformancePanel {\n readonly snapshot: ApplicationInspection['perf'];\n readonly diagnostics: readonly PerfDiagnostic[];\n}\n\n/** All panels captured at one `refresh()`. */\nexport interface DevToolsSnapshot {\n readonly application: ApplicationPanel;\n readonly graph: InspectedNode;\n readonly signals: SignalsPanel;\n readonly performance: PerformancePanel;\n readonly router?: RouterInspection;\n readonly resources?: Readonly<Record<string, ResourceInspection>>;\n readonly forms?: Readonly<Record<string, FormInspection>>;\n readonly contexts?: Readonly<Record<string, ContextInspection>>;\n readonly i18n?: I18nInspection;\n}\n\n// ── Live sources ──────────────────────────────────────────────────────────\n\n/**\n * The app's own live reactive objects, handed to DevTools explicitly so it can\n * inspect them. The compiled graph knows signal *ids* but not the live `Signal`\n * instances, so the app registers whichever surfaces it wants visible. Every\n * field is optional — a session works with none of them (structure-only).\n */\nexport interface DevToolsSources {\n /** Live signals to inspect, keyed by a human label shown in the panel. */\n readonly signals?: Readonly<Record<string, ReadonlySignal<unknown>>>;\n /** Live resources to inspect, keyed by label. */\n readonly resources?: Readonly<Record<string, ResourceLike>>;\n /** The app router, if any. */\n readonly router?: RouterLike;\n /** Live forms to inspect, keyed by label. */\n readonly forms?: Readonly<Record<string, FormLike>>;\n /** Live contexts to inspect, keyed by label. */\n readonly contexts?: Readonly<Record<string, ContextLike>>;\n /** The app i18n instance, if any. */\n readonly i18n?: I18nLike;\n}\n\nexport interface DevToolsOptions {\n /** Thresholds forwarded to `diagnosePerformance`. */\n readonly perfThresholds?: PerfThresholds;\n /**\n * Redact live signal values by default (passed to `inspectSignal`). Use in\n * shared or recorded sessions so values never reach the panel. Off by default.\n */\n readonly redactSignals?: boolean | ((value: unknown) => unknown);\n /** i18n keys to probe for missing translations, forwarded to `inspectI18n`. */\n readonly i18nCheckKeys?: readonly string[];\n}\n\n// ── Session ─────────────────────────────────────────────────────────────────\n\n/**\n * A headless DevTools session over one compiled application.\n *\n * The session holds the compiled app plus the app's registered live sources and\n * produces an immutable {@link DevToolsSnapshot} on demand. Live values are read\n * only when `refresh()` is called (explicit-refresh protocol, §7): the session\n * never subscribes to signals or instruments the reactive graph, so it adds no\n * cost to the running app between refreshes.\n */\nexport interface DevToolsSession {\n /** The most recent snapshot. Recomputed by `refresh()`. */\n readonly snapshot: DevToolsSnapshot;\n /**\n * Recompute every panel from the current live state and return the new\n * snapshot. This is the only way values change — DevTools pulls, it never\n * gets pushed to.\n */\n refresh(): DevToolsSnapshot;\n /**\n * Find a node in the graph by id and return that subtree, or `undefined`.\n * Backs a UI tree inspector's node-selection (§8) without a second graph.\n */\n selectNode(id: string): InspectedNode | undefined;\n /** Render the current snapshot as a plain-text report (for CLI/tests/logs). */\n format(): string;\n}\n\n/**\n * Create a DevTools session. Nothing in the runtime calls this — a session only\n * exists once dev code opts in, so production never pays for it.\n */\nexport function createDevTools(\n compiled: CompiledApplication,\n sources: DevToolsSources = {},\n options: DevToolsOptions = {},\n): DevToolsSession {\n let current = capture(compiled, sources, options);\n\n return {\n get snapshot() {\n return current;\n },\n refresh() {\n current = capture(compiled, sources, options);\n return current;\n },\n selectNode(id: string) {\n return findNode(current.graph, id);\n },\n format() {\n return formatSnapshot(current);\n },\n };\n}\n\n// ── Capture ───────────────────────────────────────────────────────────────\n\nfunction capture(\n compiled: CompiledApplication,\n sources: DevToolsSources,\n options: DevToolsOptions,\n): DevToolsSnapshot {\n const app: ApplicationInspection = inspectApplication(compiled);\n\n const application: ApplicationPanel = {\n identity: app.identity,\n nodeCount: app.perf.totalNodes,\n maxDepth: app.perf.maxDepth,\n pages: app.pages,\n signalCount: app.signals.length,\n eventHandlers: app.perf.eventHandlers,\n stateBindings: app.perf.stateBindings,\n errors: app.diagnostics.errors,\n warnings: app.diagnostics.warnings,\n };\n\n const live: Record<string, SignalInspection> = {};\n if (sources.signals !== undefined) {\n for (const [label, sig] of Object.entries(sources.signals)) {\n live[label] = inspectSignal(\n sig,\n options.redactSignals !== undefined ? { redact: options.redactSignals } : {},\n );\n }\n }\n const signals: SignalsPanel = { boundSignalIds: app.signals, live };\n\n const performance: PerformancePanel = {\n snapshot: app.perf,\n diagnostics: diagnosePerformance(compiled, options.perfThresholds),\n };\n\n const snapshot: DevToolsSnapshot = {\n application,\n graph: app.graph,\n signals,\n performance,\n ...(sources.router !== undefined ? { router: inspectRouter(sources.router) } : {}),\n ...(sources.resources !== undefined\n ? { resources: mapInspect(sources.resources, (r) => inspectResource(r)) }\n : {}),\n ...(sources.forms !== undefined\n ? { forms: mapInspect(sources.forms, (f) => inspectForm(f)) }\n : {}),\n ...(sources.contexts !== undefined\n ? { contexts: mapInspect(sources.contexts, (c) => inspectContext(c)) }\n : {}),\n ...(sources.i18n !== undefined\n ? {\n i18n: inspectI18n(\n sources.i18n,\n options.i18nCheckKeys !== undefined ? { checkKeys: options.i18nCheckKeys } : {},\n ),\n }\n : {}),\n };\n return snapshot;\n}\n\nfunction mapInspect<T, R>(\n source: Readonly<Record<string, T>>,\n inspect: (value: T) => R,\n): Record<string, R> {\n const out: Record<string, R> = {};\n for (const [label, value] of Object.entries(source)) out[label] = inspect(value);\n return out;\n}\n\n// ── Graph node lookup (§8) ──────────────────────────────────────────────────\n\nfunction findNode(node: InspectedNode, id: string): InspectedNode | undefined {\n if (node.id === id) return node;\n for (const child of node.children) {\n const found = findNode(child, id);\n if (found !== undefined) return found;\n }\n return undefined;\n}\n\n// ── Text formatter ────────────────────────────────────────────────────────\n\nfunction formatSnapshot(s: DevToolsSnapshot): string {\n const lines: string[] = [];\n const app = s.application;\n lines.push(`StreetUI DevTools — ${app.identity.name} v${app.identity.version}`);\n lines.push(\n `Application: ${app.nodeCount} nodes, depth ${app.maxDepth}, ${app.pages.length} page(s)`,\n );\n lines.push(\n ` signals ${app.signalCount} · handlers ${app.eventHandlers} · bindings ${app.stateBindings} · errors ${app.errors} · warnings ${app.warnings}`,\n );\n\n lines.push(`Signals: ${s.signals.boundSignalIds.length} bound in graph`);\n for (const [label, sig] of Object.entries(s.signals.live)) {\n lines.push(` ${label} [${sig.kind}] = ${format(sig.value)} · observers ${sig.observerCount ?? '?'}`);\n }\n\n if (s.router !== undefined) {\n lines.push(`Router: ${s.router.path} (${s.router.pattern})${s.router.isFallback ? ' [fallback]' : ''}`);\n }\n\n if (s.resources !== undefined) {\n lines.push('Resources:');\n for (const [label, r] of Object.entries(s.resources)) {\n lines.push(` ${label}: ${r.status}${r.loading ? ' (loading)' : ''}${r.hasError ? ` !${r.errorName}` : ''}`);\n }\n }\n\n if (s.forms !== undefined) {\n lines.push('Forms:');\n for (const [label, f] of Object.entries(s.forms)) {\n lines.push(` ${label}: ${f.valid ? 'valid' : 'invalid'} · ${f.status} · fields ${f.fields.length}`);\n }\n }\n\n if (s.contexts !== undefined) {\n lines.push('Contexts:');\n for (const [label, c] of Object.entries(s.contexts)) {\n lines.push(` ${label} (${c.description}): ${c.hasProvider ? 'provided' : 'no provider'}`);\n }\n }\n\n if (s.i18n !== undefined) {\n const missing = s.i18n.missingKeys;\n lines.push(\n `i18n: ${s.i18n.locale} of [${s.i18n.locales.join(', ')}]${missing !== undefined ? ` · missing ${missing.length}` : ''}`,\n );\n }\n\n lines.push(\n `Performance: ${s.performance.diagnostics.length} diagnostic(s), ${s.performance.snapshot.totalNodes} nodes`,\n );\n for (const d of s.performance.diagnostics) {\n lines.push(` ${d.code}: ${d.message}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction format(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value);\n if (value === null || value === undefined) return String(value);\n if (typeof value === 'object') {\n try {\n return JSON.stringify(value);\n } catch {\n return '[object]';\n }\n }\n return String(value);\n}\n","/**\n * Project-configuration surface for `streetui.config.ts`.\n *\n * The configuration *type* is single-sourced from the internal CLI module (so\n * there is exactly one authoritative `StreetUIConfig` shape). `defineConfig` is\n * the standard one-line identity helper used purely for editor type-inference on\n * the exported config object.\n *\n * This lives in its own tiny module — rather than re-exporting `defineConfig`\n * from the CLI barrel — so that importing `streetui` for application code does\n * **not** drag the CLI's build machinery (and its `esbuild` dependency) into the\n * client runtime bundle. The CLI's own `loadConfig` reads the default export of\n * `streetui.config.ts` regardless of which identity helper wrapped it, so the\n * behaviour is identical to configuring via the CLI directly.\n */\nimport type { StreetUIConfig } from '@streetui/cli';\n\nexport type { StreetUIConfig, ResolvedConfig } from '@streetui/cli';\n\n/** Identity helper that gives `streetui.config.ts` full type-checking + inference. */\nexport function defineConfig(config: StreetUIConfig): StreetUIConfig {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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