Trailblazer SDUI Protocol (v1.0)
Overview
The Trailblazer Server-Driven UI (SDUI) Protocol enables fully dynamic, server-controlled user interfaces rendered on the client. The server defines the entire UI structure (templates), computes efficient diffs for updates, and enforces safety through validation and sandboxing. This decouples UI logic from client apps, allowing instant updates without app store releases.
Key Features
- Templates: Declarative JSON trees for UI structure, with data binding.
- Diffing: Efficient tree diffs using operational transforms (inspired by JSON Patch + React reconciliation).
- Safety: Schema validation, input sanitization, no-script execution, and client-side sandboxing.
- Transport: WebSocket (preferred for real-time) or HTTP/2 Server-Sent Events (SSE).
- Assumptions:
- Client: Web (browser), React Native, or native (iOS/Android) with a SDUI renderer.
- Server: Any backend (Node.js, Go, etc.) maintaining per-session UI state.
- No client-side JavaScript execution in UI nodes for security.
Architecture
Client (Renderer) <-> Transport (WS/SSE) <-> Server (State Manager)
↓ ↓
Virtual DOM Tree UI State + Diff Engine
↓
Real DOM/Native Views
- Client connects and requests initial render.
- Server sends full UI tree (template + data).
- Client renders and acks.
- User interacts → Client sends events → Server computes new tree → Sends diff patch.
- Client applies patch atomically and acks.
1. Templates (UI Tree Format)
UI is a hierarchical JSON tree. Each node has:
id: Unique string key (server-generated, stable across diffs for efficient reconciliation).
type: Renderable component (whitelist for safety).
props: Type-specific properties (strings/objects/arrays only; no functions).
children: Array of child nodes (0+).
data: Optional runtime data (bound via mustache-like {{path}} in props).
JSON Schema (Core)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["id", "type"],
"properties": {
"id": {"type": "string", "minLength": 1},
"type": {"enum": ["screen", "container", "row", "column", "text", "button", "image", "input", "list", "modal"]},
"props": {"type": "object"},
"children": {"type": "array", "items": {"$ref": "#"}},
"data": {"type": "object"}
}
}
Supported Types & Props Examples
| Type | Props Example | Render Notes |
|---|
screen | {"title": "App"} | Root; full-screen. |
container | {"padding": 16, "bgColor": "#fff"} | Box with layout. |
row/column | {"gap": 8, "align": "center"} | Flexbox row/col. |
text | {"content": "Hello {{user.name}}", "style": {"fontSize": 18}} | Rich text (Markdown support optional). |
button | {"label": "Click", "variant": "primary", "disabled": false, "action": "increment"} | Touchable; action triggers client event. |
image | {"src": "https://...", "width": 100, "alt": "Logo"} | Remote/local images. |
input | {"placeholder": "Name", "type": "text", "value": "{{user.name}}", "action": "updateName"} | Text/number; two-way binding via events. |
list | {"items": ["{{items}}"], "renderItem": {"type": "text", "props": {"content": "{{item.name}"}}} | Virtualized list. |
modal | {"visible": true, "title": "Alert"} | Overlay. |
Full Initial Tree Example (Server → Client):
{
"id": "screen-1",
"type": "screen",
"props": {"title": "Counter App"},
"data": {"count": 0, "user": {"name": "Sherlock"}},
"children": [
{
"id": "header-1",
"type": "text",
"props": {"content": "Hello {{user.name}}! Count: {{count}}"}
},
{
"id": "btn-inc",
"type": "button",
"props": {"label": "+1", "action": "increment"}
}
]
}
Client renders by recursing the tree, binding data (e.g., mustache templating: {{count}} → 0).
2. Diffing
Server maintains per-session "previous tree". On state change (e.g., event), compute new tree → diff → send minimal Patch.
Diff Operations
Custom operational format (more efficient than JSON Patch for trees). Array of ops, applied sequentially.
Patch Schema:
{
"type": "array",
"items": {
"oneOf": [
{"type": "add", "required": ["path", "node"]},
{"type": "remove", "required": ["path"]},
{"type": "update", "required": ["path", "prop", "value"]},
{"type": "move", "required": ["fromPath", "toPath"]},
{"type": "data", "required": ["path", "data"]}
]
}
}
path: /children/0/props/label or /data/count (JSONPath-like).
- Ops are id-keyed: Use
id for reconciliation (like React keys). Server ensures stable IDs.
Example Patch (count from 0 → 1):
[
{
"type": "update",
"path": "/children/0/props/content",
"prop": "content",
"value": "Hello Sherlock! Count: 1"
},
{
"type": "data",
"path": "/",
"data": {"count": 1}
}
]
Diff Algorithm (Server-Side Pseudocode):
function computeDiff(prevTree, newTree) {
const ops = [];
// Recurse: compare nodes by ID
function diffNode(prev, next, path) {
if (!prev && next) ops.push({type: 'add', path, node: next});
if (prev && !next) ops.push({type: 'remove', path});
if (prev.id === next.id) {
// Update props
for (let [k, v] of Object.entries(next.props || {})) {
if (prev.props?.[k] !== v) {
ops.push({type: 'update', path: `${path}/props/${k}`, prop: k, value: v});
}
}
// Update data
if (JSON.stringify(prev.data) !== JSON.stringify(next.data)) {
ops.push({type: 'data', path, data: next.data});
}
// Recurse children (reconcile by ID)
reconcileChildren(prev.children, next.children, `${path}/children`, ops);
}
}
function reconcileChildren(prevKids, nextKids, path, ops) {
const prevMap = new Map(prevKids.map(k => [k.id, k]));
nextKids.forEach((next, idx) => {
const prev = prevMap.get(next.id);
if (prev) {
diffNode(prev, next, `${path}/${idx}`);
} else {
ops.push({type: 'add', path: `${path}/${idx}`, node: next});
}
});
// Remove extras
prevKids.forEach((prev, idx) => {
if (!nextKids.find(k => k.id === prev.id)) {
ops.push({type: 'remove', path: `${path}/${idx}`});
}
});
}
diffNode(prevTree, newTree, '/');
return ops;
}
Client Apply (Atomic):
- Backup current tree.
- Apply ops in order (validate each).
- Re-render affected subtrees.
- Send ACK if successful, else revert + error.
3. Safety
Client-Side Protections
- Schema Validation: Use JSON Schema (above) + ajv/zod. Reject invalid trees/patches.
- Whitelist Enforcement: Only allow defined
type/props. Block script, onclick, etc.
- Sanitization:
- Escape
{{}} bindings (prevent XSS).
- URL validation for
image.src (CORS, no javascript:).
- Input values truncated/limited.
- Sandbox Rendering: Use Shadow DOM (web) or isolated views (native). No global CSS/JS.
- No Execution: Pure declarative; actions → events only (no inline handlers).
Server-Side Protections
- Session Isolation: Per
session_id, rate-limit events (e.g., 100/sec).
- Input Validation: Sanitize event payloads (e.g., no oversized inputs).
- CSP Headers:
Content-Security-Policy: default-src 'none'; for WS responses.
- Diff Minimization: Limit patch size (<1MB), no deep nesting (>20 levels).
Message Protocol
All messages: {"type": "...", "sessionId": "...", "payload": {...}}
| Type | Direction | Payload | Notes |
|---|
init | C→S | {"capabilities": ["ws"]} | Handshake. |
render | S→C | Full tree (as above). | Initial/full refresh. |
patch | S→C | Patch array. | Update. |
event | C→S | {"action": "increment", "nodeId": "btn-inc", "inputValue": "..."} | User input. |
ack | C→S | {"applied": true} | Confirm. |
error | Both | {"code": "INVALID_TREE"} | With details. |
WebSocket Example Flow:
C: {"type": "init", "sessionId": "abc123"}
S: {"type": "render", "payload": {/* full tree */}}
C: {"type": "ack", "applied": true}
C: {"type": "event", "action": "increment"}
S: {"type": "patch", "payload": [/* ops */]}
C: {"type": "ack", "applied": true}
Implementation Notes
- Libraries: Server:
fast-json-patch + custom tree diff. Client: htmx-like renderer or react-server-components inspired.
- Performance: Virtual DOM on client; batch patches.
- Extensibility: Add types via schema updates.
- Testing: Fuzz trees/patches; audit renderer.
This protocol is production-ready with the provided specs. Source code prototypes available on request! 🚀