@llui/dom 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/binding-registry.d.ts +10 -0
  2. package/dist/binding-registry.d.ts.map +1 -0
  3. package/dist/binding-registry.js +96 -0
  4. package/dist/binding-registry.js.map +1 -0
  5. package/dist/binding.d.ts +22 -0
  6. package/dist/binding.d.ts.map +1 -1
  7. package/dist/binding.js +56 -5
  8. package/dist/binding.js.map +1 -1
  9. package/dist/build-flags.d.ts +25 -0
  10. package/dist/build-flags.d.ts.map +1 -0
  11. package/dist/build-flags.js +18 -0
  12. package/dist/build-flags.js.map +1 -0
  13. package/dist/el-split.d.ts.map +1 -1
  14. package/dist/el-split.js +8 -4
  15. package/dist/el-split.js.map +1 -1
  16. package/dist/el-template.d.ts.map +1 -1
  17. package/dist/el-template.js +15 -18
  18. package/dist/el-template.js.map +1 -1
  19. package/dist/elements.d.ts.map +1 -1
  20. package/dist/elements.js +12 -4
  21. package/dist/elements.js.map +1 -1
  22. package/dist/hmr.js +9 -4
  23. package/dist/hmr.js.map +1 -1
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +2 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/internal/test-component-builder.d.ts +21 -0
  29. package/dist/internal/test-component-builder.d.ts.map +1 -0
  30. package/dist/internal/test-component-builder.js +65 -0
  31. package/dist/internal/test-component-builder.js.map +1 -0
  32. package/dist/internal.d.ts +1 -0
  33. package/dist/internal.d.ts.map +1 -1
  34. package/dist/internal.js +1 -0
  35. package/dist/internal.js.map +1 -1
  36. package/dist/lifetime.d.ts.map +1 -1
  37. package/dist/lifetime.js +16 -3
  38. package/dist/lifetime.js.map +1 -1
  39. package/dist/mount.d.ts +1 -0
  40. package/dist/mount.d.ts.map +1 -1
  41. package/dist/mount.js +32 -22
  42. package/dist/mount.js.map +1 -1
  43. package/dist/primitives/branch.d.ts.map +1 -1
  44. package/dist/primitives/branch.js +29 -16
  45. package/dist/primitives/branch.js.map +1 -1
  46. package/dist/primitives/client-only.d.ts +1 -1
  47. package/dist/primitives/client-only.d.ts.map +1 -1
  48. package/dist/primitives/client-only.js +3 -3
  49. package/dist/primitives/client-only.js.map +1 -1
  50. package/dist/primitives/context.d.ts.map +1 -1
  51. package/dist/primitives/context.js +6 -3
  52. package/dist/primitives/context.js.map +1 -1
  53. package/dist/primitives/each.d.ts.map +1 -1
  54. package/dist/primitives/each.js +121 -74
  55. package/dist/primitives/each.js.map +1 -1
  56. package/dist/primitives/foreign.js +2 -1
  57. package/dist/primitives/foreign.js.map +1 -1
  58. package/dist/primitives/lazy.d.ts +1 -1
  59. package/dist/primitives/lazy.d.ts.map +1 -1
  60. package/dist/primitives/lazy.js +11 -5
  61. package/dist/primitives/lazy.js.map +1 -1
  62. package/dist/primitives/portal.js +2 -1
  63. package/dist/primitives/portal.js.map +1 -1
  64. package/dist/primitives/sample.d.ts.map +1 -1
  65. package/dist/primitives/sample.js +22 -16
  66. package/dist/primitives/sample.js.map +1 -1
  67. package/dist/primitives/track.d.ts +54 -0
  68. package/dist/primitives/track.d.ts.map +1 -0
  69. package/dist/primitives/track.js +54 -0
  70. package/dist/primitives/track.js.map +1 -0
  71. package/dist/primitives/virtual-each.js +4 -2
  72. package/dist/primitives/virtual-each.js.map +1 -1
  73. package/dist/render-context.d.ts +27 -1
  74. package/dist/render-context.d.ts.map +1 -1
  75. package/dist/render-context.js +82 -33
  76. package/dist/render-context.js.map +1 -1
  77. package/dist/ssr.d.ts.map +1 -1
  78. package/dist/ssr.js +5 -3
  79. package/dist/ssr.js.map +1 -1
  80. package/dist/types.d.ts +2 -2
  81. package/dist/types.d.ts.map +1 -1
  82. package/dist/types.js.map +1 -1
  83. package/dist/update-loop.d.ts +1 -0
  84. package/dist/update-loop.d.ts.map +1 -1
  85. package/dist/update-loop.js +115 -50
  86. package/dist/update-loop.js.map +1 -1
  87. package/package.json +1 -1
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,qEAAqE","sourcesContent":["// ── Component Definition ──────────────────────────────────────────\n\nimport type { View } from './view-helpers.js'\nimport type { StructuralBlock } from './structural.js'\nimport type { ComponentInstance } from './update-loop.js'\nimport type { DisposerEvent } from './tracking/disposer-log.js'\n\nexport interface ComponentDef<S, M, E = never, D = void> {\n name: string\n init: (data: D) => [S, E[]]\n update: (state: S, msg: M) => [S, E[]]\n view: (h: View<S, M>) => Node[]\n onEffect?: (ctx: { effect: E; send: Send<M>; signal: AbortSignal }) => void\n\n /**\n * @internal Compiler-injected — **path-keyed reactivity** prefix table.\n *\n * Each entry is a stable closure `(s: S) => unknown` that the compiler\n * hoists at module scope, one per distinct *minimal reference-stable\n * prefix* read across this component's accessors. The position of\n * each entry in this array IS its bit position: positions 0..30 map\n * to the low-word `mask`, positions 31..61 map to the high-word\n * `maskHi`. The runtime computes `combinedDirty` (and\n * `combinedDirtyHi` for >31-prefix components) by reference-comparing\n * `prefix(prev)` vs `prefix(next)` for each entry.\n *\n * Hand-authoring this is supported but unusual — `@llui/vite-plugin`\n * emits it automatically from accessor analysis. The previous\n * `__dirty` bitmask emission was removed; user-supplied `__dirty`\n * functions throw at mount.\n */\n __prefixes?: ReadonlyArray<(state: S) => unknown>\n /** @internal Compiler-injected */\n __renderToString?: (state: S) => string\n /** @internal Compiler-injected */\n __msgSchema?: object\n /** @internal Compiler-injected; keyed by Msg discriminant → annotations. See agent spec §5.1. */\n __msgAnnotations?: Record<\n string,\n {\n intent: string | null\n alwaysAffordable: boolean\n requiresConfirm: boolean\n humanOnly: boolean\n }\n >\n /** @internal Compiler-emitted; one entry per send() call site in view(). See agent spec §5.2. */\n __bindingDescriptors?: Array<{ variant: string }>\n /** @internal Compiler-injected; 32-char hex SHA-256 of schemas + annotations. See agent spec §12.3. */\n __schemaHash?: string\n /** @internal Compiler-injected — maps top-level state field → dirty-mask bit(s) */\n __maskLegend?: Record<string, number>\n /** @internal Compiler-injected — source-file location of the component() call */\n __componentMeta?: { file: string; line: number }\n /** @internal Compiler-injected — shape of the State type (for introspection) */\n __stateSchema?: object\n /** @internal Compiler-injected — Effect union schema (for introspection) */\n __effectSchema?: object\n /**\n * @internal Compiler-injected — replaces generic Phase 1 + Phase 2 loop.\n *\n * The trailing `dirtyHi` is the high-word dirty mask used by\n * 32..61-prefix components. Appended (not inserted) so old compiled\n * bundles emitted with a 5-param signature remain callable — the\n * runtime always passes 6 args; old bundles ignore the extra one\n * and ≤31-prefix components have `dirtyHi === 0` anyway.\n */\n __update?: (\n state: S,\n dirty: number,\n bindings: Binding[],\n blocks: StructuralBlock[],\n bindingsBeforePhase1: number,\n dirtyHi?: number,\n ) => void\n /** @internal Compiler-injected — per-message-type specialized handlers.\n * Bypass the entire processMessages pipeline for single-message updates. */\n __handlers?: Record<string, (inst: object, msg: unknown) => [S, E[]]>\n}\n\nexport type Send<M> = (msg: M) => void\n\n/**\n * Type-erased component definition for use at module boundaries where\n * the consumer's `S`, `M`, `E` are internal and invisible to the caller.\n *\n * Why this exists: `ComponentDef<S, M, E, D>` uses property syntax for\n * its callable fields (`init: (data: D) => ...`), and TypeScript\n * checks property syntax with strict (contravariant) variance. That's\n * the right call for user-facing type safety when authoring a\n * component (a narrower `Msg` type can't accidentally satisfy the\n * `update`'s param), but it means `ComponentDef<MyState, MyMsg, MyEffect, MyData>`\n * is NOT structurally assignable to `ComponentDef<unknown, unknown, unknown, unknown>`\n * — the `init: (data: MyData) => ...` field is contravariant in `MyData`,\n * so widening to `unknown` is rejected.\n *\n * `AnyComponentDef` (and `LazyDef<D>` below) declare the same fields\n * using **method syntax** (`init(data: D): ...`), which TypeScript\n * checks bivariantly. Concrete `ComponentDef<S, M, E, D>` assigns into\n * these structurally without any `widenDef` helper at the callsite.\n *\n * Used by every API that accepts an opaque component definition at a\n * module boundary:\n *\n * - `subApp({ def })`\n * - `lazy({ loader })` — returns `LazyDef<D>` so the loader's `D` survives\n * - `createOnRenderClient({ Layout })` (from `@llui/vike`)\n * - `createOnRenderHtml({ Layout })` (from `@llui/vike`)\n *\n * The `D` parameter is `unknown` here — the boundary doesn't carry init\n * data through (`subApp` passes its own `data` separately, and `Layout`\n * callers pass route-supplied data whose shape is unknown at the\n * type-erased boundary). Use `LazyDef<D>` when you need to preserve the\n * init data shape (the lazy loader case).\n */\nexport interface AnyComponentDef {\n name: string\n init(data: unknown): [unknown, unknown[]]\n update(state: unknown, msg: unknown): [unknown, unknown[]]\n view(h: unknown): Node[]\n onEffect?: unknown\n __dirty?: unknown\n __prefixes?: unknown\n __renderToString?: unknown\n __msgSchema?: unknown\n __msgAnnotations?: unknown\n __bindingDescriptors?: unknown\n __schemaHash?: unknown\n __maskLegend?: unknown\n __componentMeta?: unknown\n __stateSchema?: unknown\n __effectSchema?: unknown\n __update?: unknown\n __handlers?: unknown\n}\n\n/**\n * Type-erased component definition for use at module boundaries where the\n * loaded component's S, M, E are internal and invisible to the caller.\n * Only `D` (init data) survives because the caller provides it.\n *\n * `ComponentDef<S, M, E, D>` is structurally assignable to `LazyDef<D>`\n * for any S, M, E — `view: (h: unknown) => Node[]` accepts any View via\n * contravariance, and all other fields widen to `unknown` return types.\n *\n * Used by `lazy()` as the loader's return type. Use `AnyComponentDef`\n * (above) when D is also opaque — most other adapter-layer APIs.\n */\nexport interface LazyDef<D = void> {\n name: string\n // Method syntax — TypeScript checks methods bivariantly, so\n // ComponentDef<S, M, E, D>'s concrete (state: S, msg: M) => ...\n // assigns here even though S/M ≠ unknown. Property syntax would\n // be contravariant and reject the assignment.\n init(data: D): [unknown, unknown[]]\n update(state: unknown, msg: unknown): [unknown, unknown[]]\n view(h: unknown): Node[]\n onEffect?: unknown\n __dirty?: unknown\n __prefixes?: unknown\n __renderToString?: unknown\n __msgSchema?: unknown\n __msgAnnotations?: unknown\n __bindingDescriptors?: unknown\n __schemaHash?: unknown\n __maskLegend?: unknown\n __componentMeta?: unknown\n __stateSchema?: unknown\n __effectSchema?: unknown\n __update?: unknown\n __handlers?: unknown\n}\n\n/**\n * Maps a value shape to a reactive-props shape: every field becomes an accessor\n * `(s: S) => V`. Use for Level-1 view function signatures.\n *\n * ```ts\n * type ToolbarData = { tools: Tool[]; theme: 'light' | 'dark' }\n *\n * export function toolbar<S>(props: Props<ToolbarData, S>, send: Send<Msg>) {\n * return [div({ class: props.theme }, [each({ items: props.tools, ... })])]\n * }\n *\n * // Caller — TypeScript enforces per-field accessors; passing a raw value errors:\n * toolbar({ tools: (s: State) => s.tools, theme: (s) => s.theme }, send)\n * ```\n */\nexport type Props<T, S> = {\n [K in keyof T]: (s: S) => T[K]\n}\n\n// ── App Handle ────────────────────────────────────────────────────\n\nexport interface AppHandle {\n dispose(): void\n flush(): void\n /**\n * Dispatch a message into the mounted instance from outside its\n * normal view-bound `send` channel. Useful for adapter layers that\n * need to push updates into a long-lived instance — e.g.\n * `@llui/vike`'s persistent-layout chain pushes layout-data updates\n * into surviving layer instances on client navigation through the\n * user-supplied `onLayerDataChange` callback, which then calls\n * `handle.send(msg)` with the layout's chosen state-update message.\n *\n * Messages are queued through the same path as `view`-side `send`\n * calls — they batch into the next microtask and process via the\n * normal update loop. Calling `send` after `dispose` is a no-op.\n */\n send(msg: unknown): void\n /**\n * Read the current state snapshot. Safe to call from anywhere —\n * event handlers, async callbacks, adapter `send` wrappers, or any\n * imperative context where the render context is not live.\n *\n * Unlike `sample()` (a view primitive that requires an active\n * render context and throws outside of `view()`), `getState` is\n * the sanctioned escape hatch for \"I need to know the current\n * state to decide what to dispatch.\" Typical shape:\n *\n * ```ts\n * const handle = mountApp(root, MyApp)\n * container.addEventListener('drop', () => {\n * const { mode } = handle.getState() as AppState\n * if (mode === 'drag') handle.send({ type: 'commit' })\n * })\n * ```\n *\n * Throws after `dispose()` — stale reads are silent bugs; a thrown\n * error pinpoints the callsite that forgot to detach.\n *\n * The return type is `unknown` because `AppHandle` is state-type\n * erased at this boundary; cast to your app's state type at the\n * call site.\n */\n getState(): unknown\n /**\n * Register a listener called synchronously after every update cycle\n * completes. The listener receives the new state. Returns an\n * unsubscribe function. Safe after dispose (no-op; returns a no-op\n * unsubscribe). See agent spec §10.5 (state-update frames).\n */\n subscribe(listener: (state: unknown) => void): () => void\n /**\n * Snapshot the Msg variants currently dispatchable from rendered UI.\n * Each entry corresponds to one or more event-handler bindings the\n * compiler tagged with literal `send({type: '<variant>'})` calls;\n * the registry tracks live mounts via lifetime refcounts so the\n * snapshot reflects what the user can click *right now*, not the\n * static catalogue of every variant the app could ever accept.\n *\n * Used by `@llui/agent` to populate `list_actions`. Apps that don't\n * use the LLui compiler tagger pass (or whose views contain no\n * literal sends) get an empty array — agents fall back to the Msg\n * schema for affordance discovery.\n */\n getBindingDescriptors(): Array<{ variant: string }>\n /**\n * Hot-swap the component's `update` function (and optionally\n * `onEffect`) without rebuilding the DOM. Pending messages are\n * drained against the OLD `update` first so a half-applied\n * transition can't leave the state ill-formed; subsequent\n * dispatches go through the new function.\n *\n * This is the lightweight HMR escape hatch for cases where the\n * full `replaceComponent` flow (in `@llui/dom/hmr`) is overkill —\n * pure `update.ts` edits don't change the view, so disposing the\n * root lifetime and re-running the view just to install a new\n * function is wasteful and loses focus / scroll / transient DOM\n * state. Wire it via `import.meta.hot`:\n *\n * ```ts\n * // main.ts\n * const handle = mountApp(root, App)\n * if (import.meta.hot) {\n * import.meta.hot.accept('./app/update', (mod) => {\n * if (mod) handle.swapUpdate(mod.update)\n * })\n * }\n * ```\n *\n * Caveats:\n * - Doesn't compensate for State shape changes — if the new\n * `update` reads a field the old state doesn't have, you'll\n * see runtime errors. Hard-reload after structural state\n * changes.\n * - Doesn't swap `view` or compiler-emitted `__update`/`__dirty`\n * — for those, prefer the auto-injected component-level HMR\n * accept callback (which routes through `replaceComponent`).\n */\n swapUpdate(\n newUpdate: (state: unknown, msg: unknown) => [unknown, unknown[]],\n newOnEffect?: unknown,\n ): void\n /**\n * Run the reducer in isolation against the current state. Returns\n * `[newState, effects]` — the reducer's literal output without any\n * commit, flush, or effect-handler invocation. Used by the agent's\n * `would_dispatch` tool to predict what a candidate dispatch would\n * do before committing to it.\n *\n * Pure-reducer assumption: TEA mandates `update` be pure. LLui's\n * runtime treats it that way too (no speculative re-runs for any\n * other reason). Apps whose reducers branch on `Date.now()` or\n * read `localStorage` will see prediction drift from real dispatch\n * by exactly that amount of impurity — surface as documented at\n * the agent's call site, not silently corrected here.\n *\n * **No effects fire.** Effect descriptors are returned for the\n * agent to inspect; `onEffect` is not called. This is the entire\n * point of the API.\n */\n runReducer(msg: unknown): { state: unknown; effects: unknown[] } | null\n /**\n * Install a hook called whenever a binding's accessor throws during\n * the update cycle. The runtime catches the throw, leaves the\n * binding's `lastValue` unchanged (DOM stays at its previous value\n * rather than blanking), continues with sibling bindings, and\n * notifies this hook with `{kind, key?, message, stack?}`.\n *\n * Used by `@llui/agent` to fold binding-evaluation throws into the\n * dispatch envelope's `drain.errors` — so an LLM dispatching a Msg\n * that breaks scoring doesn't get HTTP 500 + a frozen UI; instead\n * the dispatch reports as `{status: 'dispatched', drain: {errors:\n * [...]}}` with the rest of the page rendering normally.\n *\n * Pass `null` to remove the hook. Without a hook, throws fall back\n * to `console.error` (dev mode) or `console.warn` (prod) so they\n * aren't silently swallowed.\n */\n setOnBindingError(\n hook: ((info: { kind: string; key?: string; message: string; stack?: string }) => void) | null,\n ): void\n}\n\n// ── Lifetime ─────────────────────────────────────────────────────────\n\nexport interface Lifetime {\n id: number\n parent: Lifetime | null\n children: Lifetime[]\n disposers: Array<() => void>\n bindings: Binding[]\n /** Per-item updaters — called directly by each() when item changes, bypassing Phase 2 */\n itemUpdaters: Array<() => void>\n /**\n * @internal dev-only back-reference to the owning ComponentInstance.\n * Populated on the root scope by `installDevTools` so `disposeLifetime`\n * can walk up the scope chain and emit DisposerEvents into the\n * instance's `_disposerLog`. Undefined in production.\n */\n instance?: ComponentInstance\n /**\n * @internal dev-only cause hint. Structural primitives (branch, each,\n * child, mountApp teardown) set this field immediately before calling\n * `disposeLifetime`; the dispose path reads it once to stamp the emitted\n * DisposerEvent. Left undefined, `disposeLifetime` falls back to\n * `'component-unmount'`. Undefined in production.\n */\n disposalCause?: DisposerEvent['cause']\n /** @internal dev-only — populated by structural primitives for scope-tree classification */\n _kind?: 'root' | 'show' | 'each' | 'branch' | 'scope' | 'child' | 'portal' | 'foreign'\n}\n\nexport interface LifetimeNode {\n scopeId: string\n kind: 'root' | 'show' | 'each' | 'branch' | 'scope' | 'child' | 'portal' | 'foreign'\n active: boolean\n children: LifetimeNode[]\n}\n\n// ── Binding ───────────────────────────────────────────────────────\n\n/**\n * Binding output kinds.\n *\n * `'text' | 'prop' | 'attr' | 'class' | 'style'` write their accessor's\n * return value to the DOM. `'effect'` is a side-effect-only watcher:\n * the accessor is invoked every Phase 2 tick its mask is hit, but its\n * return value is discarded and `applyBinding` is a no-op. Reserved\n * for primitives that need to fire a side-effect on each binding\n * evaluation without writing to the DOM.\n */\nexport type BindingKind = 'text' | 'prop' | 'attr' | 'class' | 'style' | 'effect'\n\nexport interface Binding {\n /**\n * Bits 0..30 of the binding's dirty mask. For components with ≤31\n * reactive prefixes this is the entire mask; for components with\n * 32..61 prefixes, the bits beyond 30 live in {@link maskHi}.\n */\n mask: number\n /**\n * Bits 31..61 of the binding's dirty mask, encoded with `1 <<\n * (pos - 31)`. Zero for ≤31-path components — the runtime gates\n * still AND against it, but `0 & dirtyHi` is always 0 so the gate\n * collapses to the single-word check. Compiler-emitted only when\n * the component actually reads paths past bit 30.\n */\n maskHi: number\n accessor: (state: unknown) => unknown\n lastValue: unknown\n kind: BindingKind\n node: Node\n key?: string\n ownerLifetime: Lifetime\n perItem: boolean\n dead: boolean\n}\n\n// ── Structural Primitives ─────────────────────────────────────────\n\nexport interface TransitionOptions {\n enter?: (nodes: Node[]) => void | Promise<void>\n leave?: (nodes: Node[]) => void | Promise<void>\n onTransition?: (ctx: { entering: Node[]; leaving: Node[]; parent: Node }) => void | Promise<void>\n}\n\ninterface BranchOptionsBase extends TransitionOptions {\n /**\n * @internal Set by `show()` / `scope()` sugar when delegating to\n * `branch()`, so the dev-only disposer log can report `'show-hide'` /\n * `'scope-rebuild'` instead of the default `'branch-swap'` for the\n * leaving arm. User code should not set this directly.\n */\n __disposalCause?: DisposerEvent['cause']\n /** @internal Compiler-injected mask of paths read by `on`. */\n __mask?: number\n}\n\n/**\n * Discriminant accessor — reads a string-keyed value either from the\n * current state (`(s) => …`) or from a closed-over item accessor /\n * memo (`() => item.kind()`). Both forms re-evaluate on every commit.\n * The zero-arg form is the canonical shape for branching on per-row\n * fields inside an `each.render` callback.\n */\ntype Discriminant<S, K extends string> = ((s: S) => K) | (() => K)\n\n/**\n * All cases covered by `cases` — no default allowed (would be dead code).\n */\ntype BranchOptionsExhaustive<S, M, K extends string> = BranchOptionsBase & {\n on: Discriminant<S, K>\n cases: { [P in K]: (h: View<S, M>) => Node[] }\n default?: never\n}\n\n/**\n * `cases` may cover some but not all keys; `default` handles the rest.\n */\ntype BranchOptionsNonExhaustive<S, M, K extends string> = BranchOptionsBase & {\n on: Discriminant<S, K>\n cases?: { [P in K]?: (h: View<S, M>) => Node[] }\n default: (h: View<S, M>) => Node[]\n}\n\n/**\n * `on` returns a wide `string` — exhaustiveness cannot be verified at\n * compile time (the key domain is infinite). Lenient: `default` is\n * optional so existing call sites that predate exhaustiveness typing\n * continue to compile. Authors who want the gate opt in by narrowing\n * `on`'s return type to a literal union.\n */\ntype BranchOptionsWide<S, M> = BranchOptionsBase & {\n on: Discriminant<S, string>\n cases?: Record<string, (h: View<S, M>) => Node[]>\n default?: (h: View<S, M>) => Node[]\n}\n\n/**\n * Options for `branch()`.\n *\n * When `on` returns a literal string union (e.g. `'idle' | 'loading'\n * | 'done'`), TypeScript enforces exhaustiveness: either every union\n * member has a case (and `default` is disallowed as unreachable), or\n * `default` is required to cover the remainder. When `on` returns a\n * wide `string`, `default` stays optional — exhaustiveness isn't\n * meaningful for an unbounded domain.\n *\n * `cases` is optional when `default` is present; `branch({ on, default })`\n * is the canonical dynamic-rebuild shape — `scope()` sugar wraps\n * exactly this form.\n */\nexport type BranchOptions<S, M = unknown, K extends string = string> = string extends K\n ? BranchOptionsWide<S, M>\n : BranchOptionsExhaustive<S, M, K> | BranchOptionsNonExhaustive<S, M, K>\n\nexport interface ShowOptions<S, M = unknown> extends TransitionOptions {\n /**\n * Predicate evaluated on every commit. `(s) => …` reads from\n * component state; `() => …` (zero-arg) reads from a closed-over\n * source — typically `item.field()` inside an `each.render`\n * callback. Both forms are reactive: the predicate runs against\n * each new state and the rendered subtree mounts/unmounts on the\n * boolean transition.\n */\n when: ((s: S) => boolean) | (() => boolean)\n render: (h: View<S, M>) => Node[]\n fallback?: (h: View<S, M>) => Node[]\n}\n\n/**\n * Options for `scope()` — rebuilds a subtree when `on(state)` changes.\n *\n * Sugar over `branch({ on, cases: {}, default: render, __disposalCause: 'scope-rebuild' })`.\n * Use when the key is dynamic (e.g. an epoch counter bumped from the\n * outside) and you want a fresh arm — fresh lifetime, fresh bindings —\n * each time it changes. Combine with `sample()` inside `render` for a\n * one-shot current-state read.\n */\nexport interface ScopeOptions<S, M = unknown> extends TransitionOptions {\n /**\n * Key accessor evaluated on every commit. `(s) => …` reads from\n * component state; `() => …` (zero-arg) reads from a closed-over\n * source. The render callback rebuilds whenever the returned key\n * changes — fresh lifetime, fresh bindings.\n */\n on: ((s: S) => string) | (() => string)\n render: (h: View<S, M>) => Node[]\n /** @internal Compiler-injected mask of paths read by `on`. */\n __mask?: number\n}\n\n/**\n * Options for `each()`. The inherited `enter` / `leave` callbacks fire **per item**:\n * `enter(nodes)` runs after an item's DOM is inserted (including initial mount);\n * `leave(nodes)` runs before an item's DOM is removed and may return a Promise\n * to hold the DOM until the animation resolves. Setting `leave` disables the\n * bulk-clear / full-replace fast paths.\n */\n/**\n * Per-item accessor. Two access forms:\n * - `item.field` — shorthand, returns accessor for `item.current[field]`\n * - `item(t => t.expr)` — computed expressions\n *\n * In both cases the returned value is a `() => V` accessor.\n * Invoke it (`item.field()`) to read the current value imperatively.\n */\nexport type ItemAccessor<T> = {\n <R>(selector: (t: T) => R): () => R\n} & {\n [K in keyof T]-?: () => T[K]\n} & {\n /**\n * Read the whole current item. Needed when T is a primitive (where the\n * field-map branch collapses to method names like `toString`) or when\n * you want to sample the entire record rather than a single field.\n *\n * Shadows any literal `current` field on T — if T has such a field,\n * use `item(r => r.current)` to disambiguate.\n */\n current(): T\n}\n\nexport interface EachOptions<S, T, M = unknown> extends TransitionOptions {\n items: (s: S) => T[]\n key: (item: T) => string | number\n render: (opts: {\n send: Send<M>\n item: ItemAccessor<T>\n /**\n * Plain (non-Proxy) accessor factory. Compiler-output path; avoid in user code\n * (use `item.field` / `item(fn)` — more ergonomic and bypasses Proxy when compiled).\n */\n acc: <R>(selector: (t: T) => R) => () => R\n index: () => number\n /**\n * The component's View bag (`h.text`, `h.show`, `h.branch`,\n * `h.scope`, `h.sample`, …). Each-render callers used to reach\n * for the top-level imports; the bag form is symmetric with how\n * `branch.cases[k]`, `show.render`, and `scope.render` receive it.\n * Both still work — destructure whichever is more convenient.\n */\n h: View<S, M>\n /** @internal Compiler-injected — entry reference for row factory */\n entry?: Record<string, unknown>\n }) => Node[]\n}\n\nexport interface PortalOptions {\n target: HTMLElement | string\n render: () => Node[]\n}\n\nexport interface ForeignOptions<S, M, T extends Record<string, unknown>, Instance> {\n /**\n * Construct the imperative instance. Can be async — return a\n * `Promise<Instance>` to defer construction until e.g. a dynamic\n * `import()` resolves. While the promise is pending:\n *\n * - The container element is in the DOM immediately (so layout\n * doesn't shift when the instance arrives).\n * - `sync` is NOT called. State changes are tracked by the\n * primitive and the latest props are applied as the initial\n * sync right after the promise resolves.\n * - If the owning scope disposes before the promise resolves,\n * `destroy(instance)` runs on resolution — no matter how long\n * the promise takes.\n */\n mount: (ctx: { container: HTMLElement; send: Send<M> }) => Instance | Promise<Instance>\n props: (s: S) => T\n sync:\n | ((ctx: { instance: Instance; props: T; prev: T | undefined }) => void)\n | {\n [K in keyof T]?: (ctx: { instance: Instance; value: T[K]; prev: T[K] | undefined }) => void\n }\n destroy: (instance: Instance) => void\n container?: { tag?: string; attrs?: Record<string, string> }\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,qEAAqE","sourcesContent":["// ── Component Definition ──────────────────────────────────────────\n\nimport type { View } from './view-helpers.js'\nimport type { ComponentInstance } from './update-loop.js'\nimport type { DisposerEvent } from './tracking/disposer-log.js'\n\nexport interface ComponentDef<S, M, E = never, D = void> {\n name: string\n init: (data: D) => [S, E[]]\n update: (state: S, msg: M) => [S, E[]]\n view: (h: View<S, M>) => Node[]\n onEffect?: (ctx: { effect: E; send: Send<M>; signal: AbortSignal }) => void\n\n /**\n * @internal Compiler-injected — **path-keyed reactivity** prefix table.\n *\n * Each entry is a stable closure `(s: S) => unknown` that the compiler\n * hoists at module scope, one per distinct *minimal reference-stable\n * prefix* read across this component's accessors. The position of\n * each entry in this array IS its bit position: positions 0..30 map\n * to the low-word `mask`, positions 31..61 map to the high-word\n * `maskHi`. The runtime computes `combinedDirty` (and\n * `combinedDirtyHi` for >31-prefix components) by reference-comparing\n * `prefix(prev)` vs `prefix(next)` for each entry.\n *\n * Hand-authoring this is supported but unusual — `@llui/vite-plugin`\n * emits it automatically from accessor analysis. The previous\n * `__dirty` bitmask emission was removed; user-supplied `__dirty`\n * functions throw at mount.\n */\n __prefixes?: ReadonlyArray<(state: S) => unknown>\n /** @internal Compiler-injected */\n __renderToString?: (state: S) => string\n /** @internal Compiler-injected */\n __msgSchema?: object\n /** @internal Compiler-injected; keyed by Msg discriminant → annotations. See agent spec §5.1. */\n __msgAnnotations?: Record<\n string,\n {\n intent: string | null\n alwaysAffordable: boolean\n requiresConfirm: boolean\n humanOnly: boolean\n }\n >\n /** @internal Compiler-emitted; one entry per send() call site in view(). See agent spec §5.2. */\n __bindingDescriptors?: Array<{ variant: string }>\n /** @internal Compiler-injected; 32-char hex SHA-256 of schemas + annotations. See agent spec §12.3. */\n __schemaHash?: string\n /** @internal Compiler-injected — maps top-level state field → dirty-mask bit(s) */\n __maskLegend?: Record<string, number>\n /** @internal Compiler-injected — source-file location of the component() call */\n __componentMeta?: { file: string; line: number }\n /** @internal Compiler-injected — shape of the State type (for introspection) */\n __stateSchema?: object\n /** @internal Compiler-injected — Effect union schema (for introspection) */\n __effectSchema?: object\n // `__update` removed in v0.4 Tier 2.4 — empirical perf benefit (~3% on a\n // 200-binding sparse-update microbench) didn't justify the per-component\n // bytes cost (200-400 bytes plus the dispatch branch). Every component\n // goes through genericUpdate now.\n /** @internal Compiler-injected — per-message-type specialized handlers.\n * Bypass the entire processMessages pipeline for single-message updates.\n *\n * Tier 5 (drop __handlers) was attempted in the v0.4 size-cut work and\n * REVERTED — see benchmarks/bundle-baseline.json#/abandoned. The bytes\n * win (~1.4 kB) cost 23-89% perf on keyed-each operations (swap/remove/\n * update/select) that dispatched specialized reconcile methods here.\n */\n __handlers?: Record<string, (inst: object, msg: unknown) => [S, E[]]>\n /**\n * @internal Compiler-injected — minimal view-bag factory.\n *\n * Returns an object containing ONLY the primitives this component's\n * view callback destructures (e.g. `{ send, text, each }`). The\n * runtime prefers `def.__view(send)` over `createView(send)` for\n * compiled components, so the file-level `createView` import chain\n * (which references all primitives) is dead in the produced bundle.\n *\n * For uncompiled defs (tests, hand-authored fixtures) the runtime\n * falls back to `createView`, which is the full bag and stays\n * available in the bundle only when something references it.\n */\n __view?: (send: Send<M>) => unknown\n /**\n * @internal Compiler-injected — semver of the @llui/compiler that\n * emitted this def. Read by the runtime's `createInstance` to detect\n * uncompiled (`undefined`) and version-mismatched (`< RUNTIME_MIN_COMPILER_VERSION`)\n * defs. The sentinel `'__test__'` short-circuits the gate for fixtures\n * built via `defineTestComponent()`. v2b §5.\n */\n __compilerVersion?: string\n}\n\nexport type Send<M> = (msg: M) => void\n\n/**\n * Type-erased component definition for use at module boundaries where\n * the consumer's `S`, `M`, `E` are internal and invisible to the caller.\n *\n * Why this exists: `ComponentDef<S, M, E, D>` uses property syntax for\n * its callable fields (`init: (data: D) => ...`), and TypeScript\n * checks property syntax with strict (contravariant) variance. That's\n * the right call for user-facing type safety when authoring a\n * component (a narrower `Msg` type can't accidentally satisfy the\n * `update`'s param), but it means `ComponentDef<MyState, MyMsg, MyEffect, MyData>`\n * is NOT structurally assignable to `ComponentDef<unknown, unknown, unknown, unknown>`\n * — the `init: (data: MyData) => ...` field is contravariant in `MyData`,\n * so widening to `unknown` is rejected.\n *\n * `AnyComponentDef` (and `LazyDef<D>` below) declare the same fields\n * using **method syntax** (`init(data: D): ...`), which TypeScript\n * checks bivariantly. Concrete `ComponentDef<S, M, E, D>` assigns into\n * these structurally without any `widenDef` helper at the callsite.\n *\n * Used by every API that accepts an opaque component definition at a\n * module boundary:\n *\n * - `subApp({ def })`\n * - `lazy({ loader })` — returns `LazyDef<D>` so the loader's `D` survives\n * - `createOnRenderClient({ Layout })` (from `@llui/vike`)\n * - `createOnRenderHtml({ Layout })` (from `@llui/vike`)\n *\n * The `D` parameter is `unknown` here — the boundary doesn't carry init\n * data through (`subApp` passes its own `data` separately, and `Layout`\n * callers pass route-supplied data whose shape is unknown at the\n * type-erased boundary). Use `LazyDef<D>` when you need to preserve the\n * init data shape (the lazy loader case).\n */\nexport interface AnyComponentDef {\n name: string\n init(data: unknown): [unknown, unknown[]]\n update(state: unknown, msg: unknown): [unknown, unknown[]]\n view(h: unknown): Node[]\n onEffect?: unknown\n __dirty?: unknown\n __prefixes?: unknown\n __renderToString?: unknown\n __msgSchema?: unknown\n __msgAnnotations?: unknown\n __bindingDescriptors?: unknown\n __schemaHash?: unknown\n __maskLegend?: unknown\n __componentMeta?: unknown\n __stateSchema?: unknown\n __effectSchema?: unknown\n __handlers?: unknown\n __compilerVersion?: unknown\n}\n\n/**\n * Type-erased component definition for use at module boundaries where the\n * loaded component's S, M, E are internal and invisible to the caller.\n * Only `D` (init data) survives because the caller provides it.\n *\n * `ComponentDef<S, M, E, D>` is structurally assignable to `LazyDef<D>`\n * for any S, M, E — `view: (h: unknown) => Node[]` accepts any View via\n * contravariance, and all other fields widen to `unknown` return types.\n *\n * Used by `lazy()` as the loader's return type. Use `AnyComponentDef`\n * (above) when D is also opaque — most other adapter-layer APIs.\n */\nexport interface LazyDef<D = void> {\n name: string\n // Method syntax — TypeScript checks methods bivariantly, so\n // ComponentDef<S, M, E, D>'s concrete (state: S, msg: M) => ...\n // assigns here even though S/M ≠ unknown. Property syntax would\n // be contravariant and reject the assignment.\n init(data: D): [unknown, unknown[]]\n update(state: unknown, msg: unknown): [unknown, unknown[]]\n view(h: unknown): Node[]\n onEffect?: unknown\n __dirty?: unknown\n __prefixes?: unknown\n __renderToString?: unknown\n __msgSchema?: unknown\n __msgAnnotations?: unknown\n __bindingDescriptors?: unknown\n __schemaHash?: unknown\n __maskLegend?: unknown\n __componentMeta?: unknown\n __stateSchema?: unknown\n __effectSchema?: unknown\n __handlers?: unknown\n __compilerVersion?: unknown\n}\n\n/**\n * Maps a value shape to a reactive-props shape: every field becomes an accessor\n * `(s: S) => V`. Use for Level-1 view function signatures.\n *\n * ```ts\n * type ToolbarData = { tools: Tool[]; theme: 'light' | 'dark' }\n *\n * export function toolbar<S>(props: Props<ToolbarData, S>, send: Send<Msg>) {\n * return [div({ class: props.theme }, [each({ items: props.tools, ... })])]\n * }\n *\n * // Caller — TypeScript enforces per-field accessors; passing a raw value errors:\n * toolbar({ tools: (s: State) => s.tools, theme: (s) => s.theme }, send)\n * ```\n */\nexport type Props<T, S> = {\n [K in keyof T]: (s: S) => T[K]\n}\n\n// ── App Handle ────────────────────────────────────────────────────\n\nexport interface AppHandle {\n dispose(): void\n flush(): void\n /**\n * Dispatch a message into the mounted instance from outside its\n * normal view-bound `send` channel. Useful for adapter layers that\n * need to push updates into a long-lived instance — e.g.\n * `@llui/vike`'s persistent-layout chain pushes layout-data updates\n * into surviving layer instances on client navigation through the\n * user-supplied `onLayerDataChange` callback, which then calls\n * `handle.send(msg)` with the layout's chosen state-update message.\n *\n * Messages are queued through the same path as `view`-side `send`\n * calls — they batch into the next microtask and process via the\n * normal update loop. Calling `send` after `dispose` is a no-op.\n */\n send(msg: unknown): void\n /**\n * Read the current state snapshot. Safe to call from anywhere —\n * event handlers, async callbacks, adapter `send` wrappers, or any\n * imperative context where the render context is not live.\n *\n * Unlike `sample()` (a view primitive that requires an active\n * render context and throws outside of `view()`), `getState` is\n * the sanctioned escape hatch for \"I need to know the current\n * state to decide what to dispatch.\" Typical shape:\n *\n * ```ts\n * const handle = mountApp(root, MyApp)\n * container.addEventListener('drop', () => {\n * const { mode } = handle.getState() as AppState\n * if (mode === 'drag') handle.send({ type: 'commit' })\n * })\n * ```\n *\n * Throws after `dispose()` — stale reads are silent bugs; a thrown\n * error pinpoints the callsite that forgot to detach.\n *\n * The return type is `unknown` because `AppHandle` is state-type\n * erased at this boundary; cast to your app's state type at the\n * call site.\n */\n getState(): unknown\n /**\n * Register a listener called synchronously after every update cycle\n * completes. The listener receives the new state. Returns an\n * unsubscribe function. Safe after dispose (no-op; returns a no-op\n * unsubscribe). See agent spec §10.5 (state-update frames).\n */\n subscribe(listener: (state: unknown) => void): () => void\n /**\n * Snapshot the Msg variants currently dispatchable from rendered UI.\n * Each entry corresponds to one or more event-handler bindings the\n * compiler tagged with literal `send({type: '<variant>'})` calls;\n * the registry tracks live mounts via lifetime refcounts so the\n * snapshot reflects what the user can click *right now*, not the\n * static catalogue of every variant the app could ever accept.\n *\n * Used by `@llui/agent` to populate `list_actions`. Apps that don't\n * use the LLui compiler tagger pass (or whose views contain no\n * literal sends) get an empty array — agents fall back to the Msg\n * schema for affordance discovery.\n */\n getBindingDescriptors(): Array<{ variant: string }>\n /**\n * Hot-swap the component's `update` function (and optionally\n * `onEffect`) without rebuilding the DOM. Pending messages are\n * drained against the OLD `update` first so a half-applied\n * transition can't leave the state ill-formed; subsequent\n * dispatches go through the new function.\n *\n * This is the lightweight HMR escape hatch for cases where the\n * full `replaceComponent` flow (in `@llui/dom/hmr`) is overkill —\n * pure `update.ts` edits don't change the view, so disposing the\n * root lifetime and re-running the view just to install a new\n * function is wasteful and loses focus / scroll / transient DOM\n * state. Wire it via `import.meta.hot`:\n *\n * ```ts\n * // main.ts\n * const handle = mountApp(root, App)\n * if (import.meta.hot) {\n * import.meta.hot.accept('./app/update', (mod) => {\n * if (mod) handle.swapUpdate(mod.update)\n * })\n * }\n * ```\n *\n * Caveats:\n * - Doesn't compensate for State shape changes — if the new\n * `update` reads a field the old state doesn't have, you'll\n * see runtime errors. Hard-reload after structural state\n * changes.\n * - Doesn't swap `view` or compiler-emitted `__update`/`__dirty`\n * — for those, prefer the auto-injected component-level HMR\n * accept callback (which routes through `replaceComponent`).\n */\n swapUpdate(\n newUpdate: (state: unknown, msg: unknown) => [unknown, unknown[]],\n newOnEffect?: unknown,\n ): void\n /**\n * Run the reducer in isolation against the current state. Returns\n * `[newState, effects]` — the reducer's literal output without any\n * commit, flush, or effect-handler invocation. Used by the agent's\n * `would_dispatch` tool to predict what a candidate dispatch would\n * do before committing to it.\n *\n * Pure-reducer assumption: TEA mandates `update` be pure. LLui's\n * runtime treats it that way too (no speculative re-runs for any\n * other reason). Apps whose reducers branch on `Date.now()` or\n * read `localStorage` will see prediction drift from real dispatch\n * by exactly that amount of impurity — surface as documented at\n * the agent's call site, not silently corrected here.\n *\n * **No effects fire.** Effect descriptors are returned for the\n * agent to inspect; `onEffect` is not called. This is the entire\n * point of the API.\n */\n runReducer(msg: unknown): { state: unknown; effects: unknown[] } | null\n /**\n * Install a hook called whenever a binding's accessor throws during\n * the update cycle. The runtime catches the throw, leaves the\n * binding's `lastValue` unchanged (DOM stays at its previous value\n * rather than blanking), continues with sibling bindings, and\n * notifies this hook with `{kind, key?, message, stack?}`.\n *\n * Used by `@llui/agent` to fold binding-evaluation throws into the\n * dispatch envelope's `drain.errors` — so an LLM dispatching a Msg\n * that breaks scoring doesn't get HTTP 500 + a frozen UI; instead\n * the dispatch reports as `{status: 'dispatched', drain: {errors:\n * [...]}}` with the rest of the page rendering normally.\n *\n * Pass `null` to remove the hook. Without a hook, throws fall back\n * to `console.error` (dev mode) or `console.warn` (prod) so they\n * aren't silently swallowed.\n */\n setOnBindingError(\n hook: ((info: { kind: string; key?: string; message: string; stack?: string }) => void) | null,\n ): void\n}\n\n// ── Lifetime ─────────────────────────────────────────────────────────\n\nexport interface Lifetime {\n id: number\n parent: Lifetime | null\n children: Lifetime[]\n disposers: Array<() => void>\n bindings: Binding[]\n /** Per-item updaters — called directly by each() when item changes, bypassing Phase 2 */\n itemUpdaters: Array<() => void>\n /**\n * @internal dev-only back-reference to the owning ComponentInstance.\n * Populated on the root scope by `installDevTools` so `disposeLifetime`\n * can walk up the scope chain and emit DisposerEvents into the\n * instance's `_disposerLog`. Undefined in production.\n */\n instance?: ComponentInstance\n /**\n * @internal dev-only cause hint. Structural primitives (branch, each,\n * child, mountApp teardown) set this field immediately before calling\n * `disposeLifetime`; the dispose path reads it once to stamp the emitted\n * DisposerEvent. Left undefined, `disposeLifetime` falls back to\n * `'component-unmount'`. Undefined in production.\n */\n disposalCause?: DisposerEvent['cause']\n /** @internal dev-only — populated by structural primitives for scope-tree classification */\n _kind?: 'root' | 'show' | 'each' | 'branch' | 'scope' | 'child' | 'portal' | 'foreign'\n}\n\nexport interface LifetimeNode {\n scopeId: string\n kind: 'root' | 'show' | 'each' | 'branch' | 'scope' | 'child' | 'portal' | 'foreign'\n active: boolean\n children: LifetimeNode[]\n}\n\n// ── Binding ───────────────────────────────────────────────────────\n\n/**\n * Binding output kinds.\n *\n * `'text' | 'prop' | 'attr' | 'class' | 'style'` write their accessor's\n * return value to the DOM. `'effect'` is a side-effect-only watcher:\n * the accessor is invoked every Phase 2 tick its mask is hit, but its\n * return value is discarded and `applyBinding` is a no-op. Reserved\n * for primitives that need to fire a side-effect on each binding\n * evaluation without writing to the DOM.\n */\nexport type BindingKind = 'text' | 'prop' | 'attr' | 'class' | 'style' | 'effect'\n\nexport interface Binding {\n /**\n * Bits 0..30 of the binding's dirty mask. For components with ≤31\n * reactive prefixes this is the entire mask; for components with\n * 32..61 prefixes, the bits beyond 30 live in {@link maskHi}.\n */\n mask: number\n /**\n * Bits 31..61 of the binding's dirty mask, encoded with `1 <<\n * (pos - 31)`. Zero for ≤31-path components — the runtime gates\n * still AND against it, but `0 & dirtyHi` is always 0 so the gate\n * collapses to the single-word check. Compiler-emitted only when\n * the component actually reads paths past bit 30.\n */\n maskHi: number\n accessor: (state: unknown) => unknown\n lastValue: unknown\n kind: BindingKind\n node: Node\n key?: string\n ownerLifetime: Lifetime\n perItem: boolean\n dead: boolean\n}\n\n// ── Structural Primitives ─────────────────────────────────────────\n\nexport interface TransitionOptions {\n enter?: (nodes: Node[]) => void | Promise<void>\n leave?: (nodes: Node[]) => void | Promise<void>\n onTransition?: (ctx: { entering: Node[]; leaving: Node[]; parent: Node }) => void | Promise<void>\n}\n\ninterface BranchOptionsBase extends TransitionOptions {\n /**\n * @internal Set by `show()` / `scope()` sugar when delegating to\n * `branch()`, so the dev-only disposer log can report `'show-hide'` /\n * `'scope-rebuild'` instead of the default `'branch-swap'` for the\n * leaving arm. User code should not set this directly.\n */\n __disposalCause?: DisposerEvent['cause']\n /** @internal Compiler-injected mask of paths read by `on`. */\n __mask?: number\n}\n\n/**\n * Discriminant accessor — reads a string-keyed value either from the\n * current state (`(s) => …`) or from a closed-over item accessor /\n * memo (`() => item.kind()`). Both forms re-evaluate on every commit.\n * The zero-arg form is the canonical shape for branching on per-row\n * fields inside an `each.render` callback.\n */\ntype Discriminant<S, K extends string> = ((s: S) => K) | (() => K)\n\n/**\n * All cases covered by `cases` — no default allowed (would be dead code).\n */\ntype BranchOptionsExhaustive<S, M, K extends string> = BranchOptionsBase & {\n on: Discriminant<S, K>\n cases: { [P in K]: (h: View<S, M>) => Node[] }\n default?: never\n}\n\n/**\n * `cases` may cover some but not all keys; `default` handles the rest.\n */\ntype BranchOptionsNonExhaustive<S, M, K extends string> = BranchOptionsBase & {\n on: Discriminant<S, K>\n cases?: { [P in K]?: (h: View<S, M>) => Node[] }\n default: (h: View<S, M>) => Node[]\n}\n\n/**\n * `on` returns a wide `string` — exhaustiveness cannot be verified at\n * compile time (the key domain is infinite). Lenient: `default` is\n * optional so existing call sites that predate exhaustiveness typing\n * continue to compile. Authors who want the gate opt in by narrowing\n * `on`'s return type to a literal union.\n */\ntype BranchOptionsWide<S, M> = BranchOptionsBase & {\n on: Discriminant<S, string>\n cases?: Record<string, (h: View<S, M>) => Node[]>\n default?: (h: View<S, M>) => Node[]\n}\n\n/**\n * Options for `branch()`.\n *\n * When `on` returns a literal string union (e.g. `'idle' | 'loading'\n * | 'done'`), TypeScript enforces exhaustiveness: either every union\n * member has a case (and `default` is disallowed as unreachable), or\n * `default` is required to cover the remainder. When `on` returns a\n * wide `string`, `default` stays optional — exhaustiveness isn't\n * meaningful for an unbounded domain.\n *\n * `cases` is optional when `default` is present; `branch({ on, default })`\n * is the canonical dynamic-rebuild shape — `scope()` sugar wraps\n * exactly this form.\n */\nexport type BranchOptions<S, M = unknown, K extends string = string> = string extends K\n ? BranchOptionsWide<S, M>\n : BranchOptionsExhaustive<S, M, K> | BranchOptionsNonExhaustive<S, M, K>\n\nexport interface ShowOptions<S, M = unknown> extends TransitionOptions {\n /**\n * Predicate evaluated on every commit. `(s) => …` reads from\n * component state; `() => …` (zero-arg) reads from a closed-over\n * source — typically `item.field()` inside an `each.render`\n * callback. Both forms are reactive: the predicate runs against\n * each new state and the rendered subtree mounts/unmounts on the\n * boolean transition.\n */\n when: ((s: S) => boolean) | (() => boolean)\n render: (h: View<S, M>) => Node[]\n fallback?: (h: View<S, M>) => Node[]\n}\n\n/**\n * Options for `scope()` — rebuilds a subtree when `on(state)` changes.\n *\n * Sugar over `branch({ on, cases: {}, default: render, __disposalCause: 'scope-rebuild' })`.\n * Use when the key is dynamic (e.g. an epoch counter bumped from the\n * outside) and you want a fresh arm — fresh lifetime, fresh bindings —\n * each time it changes. Combine with `sample()` inside `render` for a\n * one-shot current-state read.\n */\nexport interface ScopeOptions<S, M = unknown> extends TransitionOptions {\n /**\n * Key accessor evaluated on every commit. `(s) => …` reads from\n * component state; `() => …` (zero-arg) reads from a closed-over\n * source. The render callback rebuilds whenever the returned key\n * changes — fresh lifetime, fresh bindings.\n */\n on: ((s: S) => string) | (() => string)\n render: (h: View<S, M>) => Node[]\n /** @internal Compiler-injected mask of paths read by `on`. */\n __mask?: number\n}\n\n/**\n * Options for `each()`. The inherited `enter` / `leave` callbacks fire **per item**:\n * `enter(nodes)` runs after an item's DOM is inserted (including initial mount);\n * `leave(nodes)` runs before an item's DOM is removed and may return a Promise\n * to hold the DOM until the animation resolves. Setting `leave` disables the\n * bulk-clear / full-replace fast paths.\n */\n/**\n * Per-item accessor. Two access forms:\n * - `item.field` — shorthand, returns accessor for `item.current[field]`\n * - `item(t => t.expr)` — computed expressions\n *\n * In both cases the returned value is a `() => V` accessor.\n * Invoke it (`item.field()`) to read the current value imperatively.\n */\nexport type ItemAccessor<T> = {\n <R>(selector: (t: T) => R): () => R\n} & {\n [K in keyof T]-?: () => T[K]\n} & {\n /**\n * Read the whole current item. Needed when T is a primitive (where the\n * field-map branch collapses to method names like `toString`) or when\n * you want to sample the entire record rather than a single field.\n *\n * Shadows any literal `current` field on T — if T has such a field,\n * use `item(r => r.current)` to disambiguate.\n */\n current(): T\n}\n\nexport interface EachOptions<S, T, M = unknown> extends TransitionOptions {\n items: (s: S) => T[]\n key: (item: T) => string | number\n render: (opts: {\n send: Send<M>\n item: ItemAccessor<T>\n /**\n * Plain (non-Proxy) accessor factory. Compiler-output path; avoid in user code\n * (use `item.field` / `item(fn)` — more ergonomic and bypasses Proxy when compiled).\n */\n acc: <R>(selector: (t: T) => R) => () => R\n index: () => number\n /**\n * The component's View bag (`h.text`, `h.show`, `h.branch`,\n * `h.scope`, `h.sample`, …). Each-render callers used to reach\n * for the top-level imports; the bag form is symmetric with how\n * `branch.cases[k]`, `show.render`, and `scope.render` receive it.\n * Both still work — destructure whichever is more convenient.\n */\n h: View<S, M>\n /** @internal Compiler-injected — entry reference for row factory */\n entry?: Record<string, unknown>\n }) => Node[]\n}\n\nexport interface PortalOptions {\n target: HTMLElement | string\n render: () => Node[]\n}\n\nexport interface ForeignOptions<S, M, T extends Record<string, unknown>, Instance> {\n /**\n * Construct the imperative instance. Can be async — return a\n * `Promise<Instance>` to defer construction until e.g. a dynamic\n * `import()` resolves. While the promise is pending:\n *\n * - The container element is in the DOM immediately (so layout\n * doesn't shift when the instance arrives).\n * - `sync` is NOT called. State changes are tracked by the\n * primitive and the latest props are applied as the initial\n * sync right after the promise resolves.\n * - If the owning scope disposes before the promise resolves,\n * `destroy(instance)` runs on resolution — no matter how long\n * the promise takes.\n */\n mount: (ctx: { container: HTMLElement; send: Send<M> }) => Instance | Promise<Instance>\n props: (s: S) => T\n sync:\n | ((ctx: { instance: Instance; props: T; prev: T | undefined }) => void)\n | {\n [K in keyof T]?: (ctx: { instance: Instance; value: T[K]; prev: T[K] | undefined }) => void\n }\n destroy: (instance: Instance) => void\n container?: { tag?: string; attrs?: Record<string, string> }\n}\n"]}
@@ -2,6 +2,7 @@ import type { ComponentDef, Lifetime, Binding } from './types.js';
2
2
  import type { StructuralBlock } from './structural.js';
3
3
  import { type DomEnv } from './dom-env.js';
4
4
  export declare const FULL_MASK: number;
5
+ export declare const RUNTIME_MIN_COMPILER_VERSION = "0.3.0";
5
6
  export interface ComponentInstance<S = unknown, M = unknown, E = unknown> {
6
7
  def: ComponentDef<S, M, E>;
7
8
  state: S;
@@ -1 +1 @@
1
- {"version":3,"file":"update-loop.d.ts","sourceRoot":"","sources":["../src/update-loop.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAItD,OAAO,EAAE,KAAK,MAAM,EAAc,MAAM,cAAc,CAAA;AAoBtD,eAAO,MAAM,SAAS,QAAiB,CAAA;AA6CvC,MAAM,WAAW,iBAAiB,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO;IACtE,GAAG,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;IAC1B,KAAK,EAAE,CAAC,CAAA;IACR,cAAc,EAAE,CAAC,EAAE,CAAA;IACnB,YAAY,EAAE,QAAQ,CAAA;IACtB,GAAG,EAAE,MAAM,CAAA;IACX,WAAW,EAAE,OAAO,EAAE,CAAA;IACtB,gBAAgB,EAAE,eAAe,EAAE,CAAA;IACnC,KAAK,EAAE,CAAC,EAAE,CAAA;IACV,kBAAkB,EAAE,OAAO,CAAA;IAC3B,aAAa,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,CAAC,EAAE,CAAA;IAChB,IAAI,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI,CAAA;IACtB,MAAM,EAAE,WAAW,CAAA;IACnB,eAAe,EAAE,eAAe,CAAA;CAkEjC;AAED,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,IAAI,EACvD,GAAG,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAC7B,IAAI,CAAC,EAAE,CAAC,EACR,cAAc,GAAE,QAAQ,GAAG,IAAW,EACtC,GAAG,CAAC,EAAE,MAAM,GACX,iBAAiB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAkE5B;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,IAAI,CAI7E;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,CAqExF;AA8ND;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CACxB,IAAI,EAAE,iBAAiB,EACvB,GAAG,EAAE,OAAO,EACZ,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,MAAU,GAClB,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC,CAqEtB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CACxB,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,OAAO,EAAE,EACnB,oBAAoB,EAAE,MAAM,EAC5B,aAAa,CAAC,EAAE,MAAM,EAMtB,cAAc,CAAC,EAAE,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,KAAK,IAAI,GAC/F,IAAI,CAiEN"}
1
+ {"version":3,"file":"update-loop.d.ts","sourceRoot":"","sources":["../src/update-loop.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAItD,OAAO,EAAE,KAAK,MAAM,EAAc,MAAM,cAAc,CAAA;AAoBtD,eAAO,MAAM,SAAS,QAAiB,CAAA;AAgBvC,eAAO,MAAM,4BAA4B,UAAU,CAAA;AA+FnD,MAAM,WAAW,iBAAiB,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO;IACtE,GAAG,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;IAC1B,KAAK,EAAE,CAAC,CAAA;IACR,cAAc,EAAE,CAAC,EAAE,CAAA;IACnB,YAAY,EAAE,QAAQ,CAAA;IACtB,GAAG,EAAE,MAAM,CAAA;IACX,WAAW,EAAE,OAAO,EAAE,CAAA;IACtB,gBAAgB,EAAE,eAAe,EAAE,CAAA;IACnC,KAAK,EAAE,CAAC,EAAE,CAAA;IACV,kBAAkB,EAAE,OAAO,CAAA;IAC3B,aAAa,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,CAAC,EAAE,CAAA;IAChB,IAAI,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI,CAAA;IACtB,MAAM,EAAE,WAAW,CAAA;IACnB,eAAe,EAAE,eAAe,CAAA;CA6EjC;AAED,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,IAAI,EACvD,GAAG,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAC7B,IAAI,CAAC,EAAE,CAAC,EACR,cAAc,GAAE,QAAQ,GAAG,IAAW,EACtC,GAAG,CAAC,EAAE,MAAM,GACX,iBAAiB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAoE5B;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,IAAI,CAI7E;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,CAqExF;AAkND;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CACxB,IAAI,EAAE,iBAAiB,EACvB,GAAG,EAAE,OAAO,EACZ,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,MAAU,GAClB,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC,CAqEtB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CACxB,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,OAAO,EAAE,EACnB,oBAAoB,EAAE,MAAM,EAC5B,aAAa,CAAC,EAAE,MAAM,EAMtB,cAAc,CAAC,EAAE,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,KAAK,IAAI,GAC/F,IAAI,CAiEN"}
@@ -13,6 +13,67 @@ import { applyBinding } from './binding.js';
13
13
  import { setCurrentDirtyMask } from './primitives/memo.js';
14
14
  import { enterAccessor, exitAccessor } from './render-context.js';
15
15
  export const FULL_MASK = 0xffffffff | 0;
16
+ // ── Compiler/runtime version gate (v2b §5) ──────────────────────────
17
+ //
18
+ // `__compilerVersion` is the field every compiled `ComponentDef` carries
19
+ // at v2b+ runtime. `createInstance` consults it to detect components
20
+ // that bypassed the compiler (hand-rolled defs, builds that skipped the
21
+ // plugin) and either falls back to `genericUpdate` (with a one-time
22
+ // warn per def.name) or rejects an incompatible compiled bundle.
23
+ //
24
+ // The minimum compatible compiler version: at v2b ship this is 0.3.0.
25
+ // A def's `__compilerVersion >= RUNTIME_MIN_COMPILER_VERSION` is accepted;
26
+ // older versions throw in dev and warn in prod.
27
+ //
28
+ // The sentinel `'__test__'` is reserved for test fixtures built via
29
+ // `defineTestComponent()` — see v2b §6.3.
30
+ export const RUNTIME_MIN_COMPILER_VERSION = '0.3.0';
31
+ const _uncompiledWarned = new Set();
32
+ function warnUncompiledOnce(defName) {
33
+ if (_uncompiledWarned.has(defName))
34
+ return;
35
+ _uncompiledWarned.add(defName);
36
+ if (import.meta.env?.DEV) {
37
+ console.warn(`[llui] Component "${defName}" has no \`__compilerVersion\` — falling back to ` +
38
+ `\`genericUpdate\` (FULL_MASK on every update; no bitmask gating). Either the ` +
39
+ `file was authored as a raw \`ComponentDef\` literal (use \`defineTestComponent()\` ` +
40
+ `in tests, or compile via @llui/vite-plugin in app code), or the build pipeline ` +
41
+ `skipped the LLui transform. See docs/proposals/v2-compiler/v2b.md §5.`);
42
+ }
43
+ }
44
+ function compareVersions(a, b) {
45
+ const pa = a.split('.').map((p) => parseInt(p, 10) || 0);
46
+ const pb = b.split('.').map((p) => parseInt(p, 10) || 0);
47
+ const n = Math.max(pa.length, pb.length);
48
+ for (let i = 0; i < n; i++) {
49
+ const av = pa[i] ?? 0;
50
+ const bv = pb[i] ?? 0;
51
+ if (av !== bv)
52
+ return av - bv;
53
+ }
54
+ return 0;
55
+ }
56
+ function assertCompilerCompatibility(defName, version) {
57
+ if (version === undefined) {
58
+ warnUncompiledOnce(defName);
59
+ return;
60
+ }
61
+ if (version === '__test__')
62
+ return; // defineTestComponent sentinel
63
+ // Strip pre-release tags (e.g. '0.3.0-alpha.0' → '0.3.0') so alpha builds
64
+ // are accepted alongside the stable minimum. Conservative pre-release
65
+ // policy: an alpha satisfies any equal-or-lower stable minimum.
66
+ const stable = version.split('-', 1)[0];
67
+ if (compareVersions(stable, RUNTIME_MIN_COMPILER_VERSION) < 0) {
68
+ const msg = `[llui] Component "${defName}" was compiled by @llui/compiler v${version}, ` +
69
+ `but this runtime requires ≥ v${RUNTIME_MIN_COMPILER_VERSION}. Upgrade the compiler ` +
70
+ `(\`pnpm up @llui/vite-plugin\`) and rebuild. See v2-compiler/v2b.md §5.`;
71
+ if (import.meta.env?.DEV) {
72
+ throw new Error(msg);
73
+ }
74
+ console.warn(msg);
75
+ }
76
+ }
16
77
  /**
17
78
  * Path-keyed dirty mask computation. Walks the prefix table; each entry
18
79
  * whose `prefix(prev) !== prefix(next)` contributes its bit to the dirty
@@ -56,21 +117,23 @@ export function computeDirtyFromPrefixes(prefixes, prev, next) {
56
117
  return [lo, hi];
57
118
  }
58
119
  export function createComponentInstance(def, data, parentLifetime = null, dom) {
59
- // Hand-authored `__dirty` is no longer supported — the path-keyed
60
- // `__prefixes` emission supersedes it (62-prefix capacity, precise
61
- // per-prefix gating). Compiler-emitted `__dirty` was removed in
62
- // 2026-05 alongside this throw; any `__dirty` field at runtime must
63
- // be user code, and silently ignoring it would hide a stale pattern.
64
- // Migrate by deleting the `__dirty` field — the compiler emits
65
- // `__prefixes` automatically from accessor analysis, and uncompiled
66
- // components correctly fall back to FULL_MASK.
67
- if (def.__dirty !== undefined) {
68
- throw new Error(`[llui] Component "${def.name}" defines \`__dirty\` directly. ` +
69
- `This field is no longer accepted — the compiler emits \`__prefixes\` ` +
70
- `(path-keyed reactivity) automatically. Remove \`__dirty\` from the ` +
71
- `ComponentDef; either the compiler will regenerate the correct ` +
72
- `prefix table, or uncompiled components will fall back to FULL_MASK. ` +
73
- `See docs/proposals/unified-composition-model.md.`);
120
+ // v0.4 size-cut (Tier 7): the `__dirty` rejection and the compiler-
121
+ // version compatibility check are dev-aids they catch authoring
122
+ // mistakes that the build pipeline already prevents in well-configured
123
+ // projects. Gating them behind `import.meta.env?.DEV` lets Vite fold
124
+ // the calls away from production bundles. The functions themselves
125
+ // (`compareVersions`, `assertCompilerCompatibility`, `warnUncompiledOnce`)
126
+ // are reachable only through this site, so they tree-shake along with it.
127
+ if (import.meta.env?.DEV) {
128
+ if (def.__dirty !== undefined) {
129
+ throw new Error(`[llui] Component "${def.name}" defines \`__dirty\` directly. ` +
130
+ `This field is no longer accepted — the compiler emits \`__prefixes\` ` +
131
+ `(path-keyed reactivity) automatically. Remove \`__dirty\` from the ` +
132
+ `ComponentDef; either the compiler will regenerate the correct ` +
133
+ `prefix table, or uncompiled components will fall back to FULL_MASK. ` +
134
+ `See docs/proposals/unified-composition-model.md.`);
135
+ }
136
+ assertCompilerCompatibility(def.name, def.__compilerVersion);
74
137
  }
75
138
  const [initialState, initialEffects] = def.init(data);
76
139
  const controller = new AbortController();
@@ -112,7 +175,8 @@ export function createComponentInstance(def, data, parentLifetime = null, dom) {
112
175
  }
113
176
  },
114
177
  };
115
- inst.rootLifetime._kind = 'root';
178
+ if (import.meta.env?.DEV)
179
+ inst.rootLifetime._kind = 'root';
116
180
  return inst;
117
181
  }
118
182
  export function flushInstance(inst) {
@@ -264,6 +328,11 @@ function processMessages(inst) {
264
328
  const queue = inst.queue;
265
329
  // Single-message fast path: dispatch directly to per-message-type handler
266
330
  // if available. Skips dirty computation, Phase 1/2 entirely.
331
+ //
332
+ // Tier 5 (drop __handlers) was attempted in the v0.4 size-cut work and
333
+ // REVERTED — see benchmarks/bundle-baseline.json#/abandoned. The bytes
334
+ // win (~1.4 kB) cost 23-89% perf on the jfb keyed-each operations that
335
+ // dispatched here (swap, remove, update-10th, select). __handlers stays.
267
336
  if (queue.length === 1 && inst.def.__handlers) {
268
337
  const msg = queue[0];
269
338
  const handler = inst.def.__handlers[msg.type];
@@ -289,26 +358,23 @@ function processMessages(inst) {
289
358
  let combinedDirtyHi = 0;
290
359
  const allEffects = [];
291
360
  const defUpdate = inst.def.update;
292
- // Path-keyed reactivity: when the compiler emits `__prefixes`, dirty
293
- // bits correspond to entries in the prefix table (one bit per minimal
294
- // reference-stable prefix read across the component's accessors). The
295
- // runtime computes the dirty mask by reference-comparing `prefix(prev)
296
- // !== prefix(next)` for each table entry precise per-prefix and
297
- // supports two-word emission for up to 62 prefixes. Components compiled
298
- // without `__llui/vite-plugin` (or with no reactive accessors) have no
299
- // `__prefixes` table; they fall back to `FULL_MASK` and pay the cost
300
- // of re-evaluating every binding every cycle. User-authored `__dirty`
301
- // is no longer accepted — see types.ts for the rationale.
361
+ // v0.4 size-cut (Tier 3.4): every compiled component carries `__prefixes`,
362
+ // so the production path skips the FULL_MASK fallback for components
363
+ // missing the table. The fallback is gated by `import.meta.env.MODE`
364
+ // Vite dead-code-eliminates it from production builds. Tests
365
+ // (vitest, MODE='test') construct ComponentDef literals by hand without
366
+ // a prefix table and rely on the FULL_MASK behaviour to fire all
367
+ // bindings on every update.
302
368
  const prefixes = inst.def.__prefixes;
303
369
  for (let qi = 0; qi < queue.length; qi++) {
304
370
  const msg = queue[qi];
305
371
  const [newState, effects] = defUpdate(state, msg);
306
372
  let dirty;
307
- if (prefixes !== undefined) {
308
- dirty = computeDirtyFromPrefixes(prefixes, state, newState);
373
+ if (import.meta.env?.MODE !== 'production' && prefixes === undefined) {
374
+ dirty = FULL_MASK;
309
375
  }
310
376
  else {
311
- dirty = FULL_MASK;
377
+ dirty = computeDirtyFromPrefixes(prefixes, state, newState);
312
378
  }
313
379
  if (typeof dirty === 'number') {
314
380
  combinedDirty |= dirty;
@@ -339,19 +405,11 @@ function processMessages(inst) {
339
405
  // Set current dirty mask BEFORE Phase 1 so memo() accessors used in
340
406
  // structural primitives (e.g. each.items) can use the bitmask fast path.
341
407
  setCurrentDirtyMask(combinedDirty, combinedDirtyHi);
342
- if (inst.def.__update) {
343
- // Compiler-generated fast path replaces generic Phase 1 + Phase 2.
344
- // `combinedDirtyHi` is passed as the trailing positional arg so
345
- // stale 5-param compiled bundles continue to gate correctly: they
346
- // ignore the extra arg, and for ≤31-prefix components `dirtyHi`
347
- // is always 0 anyway. Fresh compiled bundles use the 6th param
348
- // for precise two-word Phase 1 gating on 32..61-prefix components.
349
- inst.def.__update(state, combinedDirty, bindings, inst.structuralBlocks, bindingsBeforePhase1, combinedDirtyHi);
350
- }
351
- else {
352
- // Generic Phase 1 + Phase 2 fallback (uncompiled components)
353
- genericUpdate(inst, state, combinedDirty, combinedDirtyHi, bindings, bindingsBeforePhase1);
354
- }
408
+ // v0.4 size-cut (Tier 2.4): the compiler-emitted __update fast path was
409
+ // removed. Empirical perf was ~3% on the 200-binding sparse-update
410
+ // microbench the bytes win outweighs the throughput loss. Every
411
+ // component now goes through genericUpdate.
412
+ genericUpdate(inst, state, combinedDirty, combinedDirtyHi, bindings, bindingsBeforePhase1);
355
413
  // Dispatch effects after DOM updates
356
414
  for (let i = 0; i < allEffects.length; i++) {
357
415
  dispatchEffect(inst, allEffects[i]);
@@ -567,10 +625,14 @@ onBindingError) {
567
625
  function handleBindingThrow(onBindingError, binding, e, componentName) {
568
626
  // Dev mode: build the rich wrapped error (with accessor source,
569
627
  // node descriptor, undefined-hint detection). Prod skips the
570
- // bookkeeping. Either way the report flows through `_onBindingError`
571
- // when wired (agent setups), else falls back to console.error so
572
- // operators see the cause.
573
- const wrapped = componentName !== null && e instanceof Error
628
+ // bookkeeping the `import.meta.env?.DEV` gate is also what lets
629
+ // the bundler tree-shake `enhanceBindingError` out of production
630
+ // bundles (otherwise its accessor-source / node-descriptor / hint
631
+ // helpers stay reachable through this one call site). Either way
632
+ // the report flows through `_onBindingError` when wired (agent
633
+ // setups), else falls back to console.error so operators see the
634
+ // cause.
635
+ const wrapped = import.meta.env?.DEV && componentName !== null && e instanceof Error
574
636
  ? enhanceBindingError(e, binding, componentName)
575
637
  : null;
576
638
  const err = wrapped ?? (e instanceof Error ? e : new Error(String(e)));
@@ -653,10 +715,13 @@ function dispatchEffect(inst, effect) {
653
715
  return;
654
716
  }
655
717
  // Dev-only: record on the timeline / consult the mock registry.
656
- // Short-circuits real dispatch when a mock matches. Zero cost in
657
- // production the guard on `_effectTimeline` is undefined unless
658
- // `installDevTools` populated the trackers.
659
- if (inst._effectTimeline !== undefined && dispatchEffectDev(inst, effect))
718
+ // Short-circuits real dispatch when a mock matches. Gated by
719
+ // `import.meta.env?.DEV` so the bundler tree-shakes
720
+ // `dispatchEffectDev` (and its mock-matching, timeline-push, and
721
+ // `newEffectId` dependencies) out of production builds. The
722
+ // historical `inst._effectTimeline !== undefined` runtime guard was
723
+ // correct but not bundler-visible.
724
+ if (import.meta.env?.DEV && inst._effectTimeline !== undefined && dispatchEffectDev(inst, effect))
660
725
  return;
661
726
  // User onEffect handler
662
727
  if (inst.def.onEffect) {