VIP-76: TSRX Typed JSX for @effect/ui (.vibex)
Status: accepted by Will, 2026-11-30. Will: "I accept 76 to 81". The implementation is built. (Previously open, 2026-11-28.)
Will's words
"So foldkit and/or effect ui don't use jsx because we lose typesafety in some way. I don't know exact details of how. iwant you to show me how because I suspect we can add the typesafety back supporting jsx because we own the typechecker itself"
"Ok so I want to just optimistically build everything while aI async review. So here are requirements Alright, one requirement is it must use TSRX. Another requirement is it must have the same type safety as the normal TypeScript API. Another requirement is we need to add a VIP for it. Another requirement is it needs to Be fuzz tested and have every form form of testing we have, and be formally verified. Another requirement is we should be able to find the docs for the effect UI and rewrite them using our API. So the demo we want to show is actually just showing the same docs and showing how how everything looks different, switching between the TypeScript API and the ViteLink API."
Motivation
Standard TypeScript JSX (and VIP-39 .vibex, which inherits .tsx checking unchanged) widens every JSX expression to a single global, non-generic JSX.Element (microsoft/TypeScript#14729) and looks up intrinsic tags on one global JSX.IntrinsicElements interface.
@effect/ui carries five type-level channels on every element (Html.Element<out Msg, out R, in out E, in out Node, out Tag>):
- Effect service requirements (
R): Child component requirements bubble through.children(...)into the parentComponent'sRchannel, so omittingComponent.provide(...)at mount time is a compile error. - Component-scoped message safety (
Msg): Every event handler (on("click", msg)) and child node is checked against the enclosing component'sMsgunion. - Exact DOM tag, event map, and node identity (
Tag,E,Node): Headless@effect/ui-kitparts enforce specific elements (e.g.DialogTriggerElementrequires tag"button"/HTMLButtonElement),VoidElementrejects children on<input>,.modal(true)requiresHTMLDialogElement, and.ref(r)checks the ref's exact tag. - Per-view host vocabulary (
HtmlvsOpenTui):Html.componentexposes HTML/SVG tags andHtml.Host, whileOpenTui.componentexposes terminal tags (box,text,span,b) andOpenTui.Host. - Keep-alive capability tracking (
h.keepAlive((s) => ...)):s: KeepAlive<Msg, Ends>enforces literal keys when no termination predicate is supplied.
VIP-76 adopts TSRX (tsrx-org/tsrx) template syntax (@{ ... }, @if/@else, @for/@empty, @switch/@case/@default, @try/@catch/@pending, <>...</>, <style>) inside .vibex files and lowers builder-bound TSRX regions directly to typed @effect/ui builder expressions before typechecking, achieving provably identical type safety to the hand-written TypeScript API with zero runtime wrapper and zero breaking changes to existing VIP-39 React/Solid .vibex files.
Decision
1. TSRX Grammar in .vibex
VIP-76 extends .vibex (ScriptKindTSX + VibeLang dialect) with the core TSRX productions. Ordinary .vibe, .ts, and .tsx files are unaffected. Existing VIP-39 .vibex files without @-prefixed TSRX constructs parse and check identically.
TsrxCodeBlock :
@{ TemplateSetupList? TemplateOutput }
@( Expression ) { TemplateSetupList? TemplateOutput }
TemplateBlock :
{ TemplateChildren? }
{ TemplateSetupList TemplateOutput }
TsrxIfExpression :
@if ( Expression ) TemplateBlock
@if ( Expression ) TemplateBlock @else TemplateBlock
@if ( Expression ) TemplateBlock @else TsrxIfExpression
TsrxForExpression :
@for ( BindingKind BindingPattern of Expression TsrxForOptions? ) TemplateBlock
@for ( BindingKind BindingPattern of Expression TsrxForOptions? ) TemplateBlock @empty TemplateBlock
TsrxForOptions :
; index BindingIdentifier
; key Expression
; index BindingIdentifier ; key Expression
; key Expression ; index BindingIdentifier
TsrxSwitchExpression :
@switch ( Expression ) { TsrxSwitchCaseList? }
TsrxSwitchCase :
@case Expression : TemplateBlock
@default : TemplateBlock
TsrxTryExpression :
@try TemplateBlock @catch ( BindingIdentifier? ) TemplateBlock
@try TemplateBlock @pending TemplateBlock
@try TemplateBlock @pending TemplateBlock @catch ( BindingIdentifier? ) TemplateBlockEntry points
- Function body:
function UploadRow(h: Html.H<Msg>, u: Upload) @{ ... }andexport function Foo(h: Html.H<Msg>) @(h){ ... }. - Arrow body & expression position:
view: (h, model) => @{ ... },const row = @{ ... },return @if (cond) { ... }. - JSX template child position:
@if,@for,@switch,@try, and@{ ... }may appear directly inside any JSX element or fragment children without wrapping{ ... }. Plain text containing@(such asuser@example.comor@effect/ui) remainsJsxText; only@immediately followed by{,(,if,for,switch, ortry(followed by a directive delimiter) starts a TSRX directive.
2. Builder Binding & Zero-Regression Coexistence with VIP-39
A TSRX region operates in either Builder Mode (lowering JSX tags to typed @effect/ui builder calls on a helper H) or Standard JSX Mode (lowering @if/@for/@switch/@try/@{...} to ordinary JSX expressions for React/Solid/Preact/Vue):
- Explicit builder binding (
@(expr){ ... }): Always enters Builder Mode withH = expr(works with any helper name, e.g.,@(h){ ... },@(s){ ... },@(ui){ ... },@(ctx.h){ ... }, regardless of file imports). - Automatic
@effect/uihelper binding (@{ ... }): When the file imports from@effect/ui,@effect/ui/*,@effect/ui-kit,@effect/ui-opentui,@effect/ui-native, or@effect/ui-devtools:- Inside a function or arrow whose first parameter is named
h(e.g.,view: (h, model) => @{ ... },Def.fragment((h, item) => @{ ... }),<M,>(h: Html.H<M>) => @{ ... }),@{ ... }enters Builder Mode withH = h. - Inside a
keepAlive(...)callback whose first parameter is nameds(e.g.,h.keepAlive((s) => @{ <Profile key="profile" /> })),@{ ... }enters Builder Mode withH = s, preservingKeepAlive<Msg, Ends>literal-key checking. The callback must itself be an argument ofkeepAlive(...): a named or generic function bindssas an arrow does, and parentheses around the callback change nothing, while a function nested in another call, array or object inside that argument, a function the argument calls at once (((s) => ...)("text")), or any other function with a first parameter nameds, does not binds. - Nested functions/arrows inside a Builder Mode region inherit the enclosing
H(sofallback={() => <p>Unavailable</p>}anddialog.trigger(<button>Cart</button>)useh), unless the nested callback itself binds a shadowingsinsidekeepAlive(...)or a newhparameter.
- Inside a function or arrow whose first parameter is named
- Standard JSX Mode (
@{ ... }outside@effect/ui): In non-@effect/ui.vibexfiles without@(expr), TSRX control flow lowers to ordinary JSX expressions preserving VIP-39 React/Solid compatibility.
3. Builder Mode Lowering Rules (Exact Type Equivalence)
Let H be the active builder expression. Every lowered AST node carries source-mapped spans from the original TSRX tokens so hover, diagnostics, go-to-definition, and source maps stay accurate.
Intrinsic Elements (<tag ...attrs>children</tag>, <tag ...attrs />)
Lowercase non-member tags lower to a builder chain on H:
- Base expression:
H.<tag>for valid identifier tags (div,button,input,svg,box,text,b, etc.), orH.el("<tag>")for hyphenated custom elements (<my-card>). - Attributes (chained left-to-right):
| TSRX Attribute | Lowered Builder Call |
|---|---|
key={v} / key="s" | .key(v) |
class={v} / class="s" | .class(v) |
style={obj} | .style(obj) |
ref={r} | .ref(r) |
value={v} | .value(v) |
checked={b} | .checked(b) |
selected={b} | .selected(b) |
open={b} | .open(b) |
modal={b} | .modal(b) |
popover={[mode, open]} | .popover(mode, open) |
draggable={data} | .draggable(data) |
dropTarget={opts} | .dropTarget(opts) |
onMount={m} | .onMount(m) |
on:ev={handler} | .on("ev", handler) |
on:ev:prevent={handler} | .on("ev", handler, { preventDefault: true }) |
on:ev:always={handler} | .on("ev", handler, { preventDefault: "always" }) |
on:ev={[handler, opts]} | .on("ev", handler, opts) |
prop:name={v} | .prop("name", v) |
attr:name={v} | .attr("name", v) |
{...obj} | .attrs(obj) |
Any other attribute k={v} / k="s" | .attr("k", v) (bare boolean disabled → .attr("disabled", "")) |
- Children:
- Self-closing
<tag ... />(zero children): emits NO.children(...)call, keepingVoidElement(input,img,br,hr, etc.) intact. - Non-empty
<tag ...>c1 c2</tag>: appends.children(c1, c2). Calling.children(...)on aVoidElement(<input>bad</input>) triggers a TypeScript compile error (Property 'children' does not exist on type 'VoidElement<...>'). - Adjacent JSX text trims insignificant indentation/blank-line whitespace per JSX rules and emits string literals.
- Self-closing
Components, Features & Headless Parts
- Uppercase component or feature member (
<Comp ... />,<NoteActivity.render ... />):- Lowers to
Comp(H, { ...attrs })(orComp(H)when zero attributes). - If children are present (
<Button onPress={msg}>Save</Button>), lowers toButton(H, { onPress: msg }).children("Save").
- Lowers to
- Lowercase member expression (
<dialog.trigger><button .../></dialog.trigger>):- Lowers to
dialog.trigger(child)(ordialog.trigger(child, ...extra)). A member part takes no attributes (EK7611); put them on the child element. Inline{dialog.trigger(<button ...>Cart</button>)}also works directly because<button ...>has the exactHtml.Element<Msg, R, EventsOf<"button">, HTMLButtonElement, "button">type.
- Lowers to
Fragments (<>c1 c2</>)
- Lowers to an array literal
[c1, c2](which@effect/uiflattens natively while unioningRacross all elements).
Control Flow Directives
@if (cond) { A } @else if (cond2) { B } @else { C }: Lowers tocond ? [[A]] : cond2 ? [[B]] : [[C]](with: nullif@elseis omitted). Full TypeScript control-flow narrowing and unionRinference apply.@for (const item of items; index i; key k) { body } @empty { emptyBody }:- Without
@empty:Array.from(items, (item, i) => [[body]]). - With
@empty:((__tsrxItems) => __tsrxItems.length === 0 ? [[emptyBody]] : __tsrxItems.map((item, i) => [[body]]))(Array.from(items)). - When
key kis specified andbodylowers to a single element builder without an explicitkey=attribute,.key(String(k))(or.key(k)whenkis already string-typed via helper / explicit.key(k)) is attached automatically.
- Without
@switch (expr) { @case v1: { B1 } @default: { BD } }: Lowers to(() => { switch (expr) { case v1: return [[B1]]; default: return [[BD]]; } })().@try { B } @catch (e) { C }: Lowers to(() => { try { return [[B]]; } catch (e) { return [[C]]; } })().@try { B } @pending { P }: Lowers to(() => { try { return [[B]]; } catch { return [[P]]; } })()(or when combined with@catch, preserves both branches cleanly).
Scoped <style> Blocks
- Inside a TSRX template block,
<style> ...css... </style>computes a deterministic compile-time hash classtsrx-<8hex>, injects.class("tsrx-<8hex>")onto sibling and descendant intrinsic elements in that scope, and emits a static CSS scope record (or omits runtime style DOM clutter when only class scoping is needed). - Assigned style themes (
const theme = <style> .card { ... } </style>) lower to a typed frozen class map{ readonly $class: "tsrx-...", readonly card: "card tsrx-..." } as constwith full autocomplete. <style apply={theme} />appliestheme.$classto sibling elements in scope.
4. Static Rules & Diagnostics (EK76xx)
| Mistake | Code |
|---|---|
Empty TSRX code block @{ } with no template output | EK7601 |
Missing ( or condition in @if / @for / @switch | EK7602 |
Missing template block { ... } after @if, @else, @for, @empty, @switch case, or @try | EK7603 |
Invalid @for option (only index <id> and key <expr> are allowed) | EK7604 |
@try without at least one @catch or @pending clause | EK7605 |
Invalid on: event modifier (only :prevent and :always are supported) | EK7606 |
@import inside a scoped <style> block (TSRX3012) | EK7607 |
Declaring .$class inside an assigned <style> theme (TSRX3006) | EK7608 |
Invalid apply attribute on <style> (must be {theme} or {[a, b]}) | EK7609 |
TSRX directive used in non-JSX .vibe file (rename to .vibex) | EK7610 |
Attribute on a lowercase member part (<dialog.trigger key={k}>): the part call takes children only, so the attribute would be dropped | EK7611 |
5. Formal Verification & Type Equivalence Theorem
Because Builder Mode lowering maps every TSRX construct syntactically to its canonical @effect/ui TypeScript expression before typechecking:
$$\forall \Gamma, e, \tau:\quad \Gamma \vdash_{\text{TSRX}} e : \tau \iff \Gamma \vdash_{\text{TS}} \llbracket e \rrbracket : \tau$$
The formal SMT-LIB2 model in docs/design/formal/vip76-tsrx-soundness.smt2 proves (via Z3 unsat counterexample elimination):
- Requirement Soundness: $R(\llbracket e \rrbracket) = \bigcup_{c \in \text{children}(e)} R(c)$ across elements, fragments,
@if,@for,@switch, and nested components. - Message Confinement: Every
on:ev={h}handler inside a component with message type $M$ satisfies $h \sqsubseteq \text{Handler}(M, \text{EventPayload}(\text{Tag}, ev))$. - Tag & Void Preservation: $\text{Tag}(\llbracket \langle t \rangle \rrbracket) = t$ and $\text{isVoid}(t) \implies \text{children}(e) = \emptyset$.
- Host Vocabulary Isolation: $\text{Host}(H) = \text{OpenTui} \implies \text{div} \notin \text{ValidTags}(H)$ and $\text{Host}(H) = \text{Html} \implies \text{box} \notin \text{ValidTags}(H)$.
- Keep-Alive Literal-Key Soundness: Non-literal keys in predicate-free
keepAliveare rejected identically to the TypeScript API. - Zero Soundness Gap vs. TypeScript API: No ill-typed UI program rejected by the TypeScript API is accepted by TSRX Builder Mode.