docs/SDK.md
TypeScript SDK & Browser Runtime Reference
Version 0.6.0 programmatic SDK signatures, two-tier error handling, createSession() SSE lifecycle, and sandboxed DOMPatchApplier integration.
This reference covers the TypeScript exports from leveonas, leveonas/sdk, leveonas/runtime, and the standalone CDN bundles (/leveonas-runtime.js and /leveonas.js).
For HTTP REST endpoints (/api/v1/chat/completions, /api/generate, /api/compile, /api/patch, /api/models), see the Public REST API Reference.
Package Entry Points (leveonas@0.6.0)
| Import / Script URL | Environment | Exports |
|---|---|---|
import { ... } from "leveonas" | Node.js / Bundlers | compile (async), parse, lower, inspect, format, diagnose, types |
import { createSession } from "leveonas/sdk" | Node.js / Browser | createSession, LeveonasSession, StreamingEvent, LeveonasError |
import { DOMPatchApplier } from "leveonas/runtime" | Bundlers (Vite, Next.js) | DOMPatchApplier, CSSPatchApplier, JSPatchApplier, validatePatches |
https://leveonas.ainot.site/leveonas-runtime.js | Standalone <iframe sandbox="allow-scripts"> | window.LeveonasRuntime (DOMPatchApplier, validatePatches, PatchSerializer) |
https://leveonas.ainot.site/leveonas.js | Standalone HTML host page | window.Leveonas.Engine + window.LeveonasRuntime |
1. Compiler SDK (leveonas)
import {
compile,
parse,
lower,
inspect,
format,
diagnose,
VERSION,
type LMFramework,
type CompileOptions,
type CompileResult,
type ParseOptions,
type ParsedAST,
type UIIRProgramNode,
type DocumentInspection,
type LSPDiagnostic,
} from 'leveonas';Synchronous Offline vs. Asynchronous Server Functions
| Function | Execution | Network / Key Required | Returns | ||||
|---|---|---|---|---|---|---|---|
compile(source, options?) | Async (Promise) | Yes (POST /api/compile + lv_live_...) | Promise<CompileResult> (code, html, document, sections, ast, uiIR) | ||||
parse(source, options?) | Sync (Offline) | No | ParsedAST (`RootNode \ | ReactProgramNode \ | VueProgramNode \ | SvelteProgramNode \ | AngularProgramNode`) |
lower(astOrSource, framework?) | Sync (Offline) | No | UIIRProgramNode (framework-neutral Common UI IR) | ||||
inspect(source) | Sync (Offline) | No | DocumentInspection (AST, UI IR, Runtime IR, Reactivity Graph, patchOperations) | ||||
format(source, options?) | Sync (Offline) | No | Canonical formatted LM string (tag(attr(value) child)) | ||||
diagnose(source, options?) | Sync (Offline) | No | LSPDiagnostic[] |
CompileOptions, ParseOptions & Error Handling
export type LMFramework =
| 'html'
| 'react'
| 'nextjs'
| 'tailwind'
| 'vue'
| 'svelte'
| 'angular'
| 'auto'
| (string & {});
export interface ParseOptions {
framework?: LMFramework;
}
export interface CompileOptions {
apiKey?: string;
serverUrl?: string;
/** Target language/framework dialect override */
framework?: LMFramework;
/** Representation hint (`'all' | 'ui-ir' | 'dom' | 'patches'`) */
target?: 'all' | 'ui-ir' | 'dom' | 'patches';
allowIncomplete?: boolean;
documentMode?: boolean;
}compile() has two distinct failure modes depending on where the failure happens:
- HTTP / Auth / Network failures (
401 LM-AUTH-001,413oversized body, missing API key, offline timeout): Rejects the Promise with anError. - LM Syntax / Compiler Diagnostics (malformed LM such as legacy Lisp
(di cs:"x")->LM-DIALECT-001, unclosed parens): Resolves withresult.success === false, populatedresult.diagnostics, andresult.error.
Always handle both:
import { compile } from 'leveonas';
try {
const result = await compile('<REACT>component(Card)(di(h2(Pro)))</REACT>', {
apiKey: process.env.LEVEONAS_API_KEY,
serverUrl: 'https://leveonas.ainot.site',
framework: 'react',
documentMode: true,
});
if (!result.success) {
console.error('LM diagnostics:', result.diagnostics);
throw new Error(result.error ?? 'Compilation failed');
}
console.log(result.detectedTarget); // "react"
console.log(result.code); // React TSX source
} catch (error) {
console.error('Leveonas request failed:', error);
}Offline parse(), lower(), inspect(), format(), diagnose()
const lm = '<SVELTE>component(Counter)(state(count, 0) bo(oc(count++) {count}))</SVELTE>';
const formatted = format(lm);
const diagnostics = diagnose(formatted, { streaming: false });
const ast = parse(formatted, { framework: 'svelte' });
const uiIR = lower(ast, 'svelte');
const report = inspect(formatted);
console.log(report.reactivityGraph.nodes);
console.log(report.patchOperations);2. Streaming Session SDK (leveonas/sdk)
createSession() connects to POST /api/generate and translates raw SSE frames (session, patch, text, error, telemetry, [DONE]) into a typed StreamingEvent async iterable.
Complete TypeScript Interfaces
export type StreamingEvent =
| { type: 'generation:start'; timestamp: number }
| { type: 'generation:chunk'; text: string; delta: string; timestamp: number }
| { type: 'generation:patch'; patch: PatchOperation[]; timestamp: number }
| { type: 'generation:diagnostic'; diagnostic: LSPDiagnostic | unknown; timestamp: number }
| { type: 'generation:error'; error: Error; code?: string; timestamp: number }
| { type: 'generation:complete'; metrics: GenerationMetrics; timestamp: number };SSE Wire Event (/api/generate) | createSession() Event | When Emitted |
|---|---|---|
| Stream opened | generation:start | Immediately when session.generate() starts |
data: {"text":"..."} | generation:chunk | When emitDebugText: true is passed; delta has incremental text, text has full buffer |
data: {"patch":[...]} | generation:patch | Whenever LM tokens reconcile into a PatchOperation[] batch |
data: {"error":"..."} | generation:error | Emitted on error before throwing LeveonasError (non-abort failures) |
data: [DONE] | generation:complete | Translated into generation:complete carrying metrics: GenerationMetrics |
PatchOperation Schema
Every event.patch emitted in generation:patch is a PatchOperation[] array ready for validatePatches() and DOMPatchApplier.apply():
export interface PatchOperation {
operation: PatchOperationType; // e.g. 'CREATE_NODE' | 'INSERT_CHILD' | 'UPDATE_TEXT' | 'SET_ATTRIBUTE' | ...
nodeId: string;
parentId?: string;
index?: number;
payload?: any;
timestamp?: number;
}3. End-to-End Tutorial: Progressive React Pricing Card
This verified bridge connects createSession() (leveonas/sdk) on your server/API route (or proxy) directly to DOMPatchApplier (window.LeveonasRuntime) inside a sandboxed <iframe sandbox="allow-scripts"> — streaming a React pricing card generated by Gemini into the browser without exposing keys.
Step A — Server Route (app/api/stream-ui/route.ts)
Forward the authenticated /api/generate SSE stream from your backend so LEVEONAS_API_KEY and GEMINI_API_KEY stay strictly on the server:
import { NextRequest } from 'next/server';
export async function POST(req: NextRequest) {
const { prompt } = await req.json();
const upstream = await fetch('https://leveonas.ainot.site/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Leveonas-Key': process.env.LEVEONAS_API_KEY!,
'x-gemini-key': process.env.GEMINI_API_KEY!,
},
body: JSON.stringify({
provider: 'gemini',
model: 'gemini-4-carbon',
prompt,
maxTokens: 4096,
telemetry: true,
}),
signal: req.signal,
});
return new Response(upstream.body, {
status: upstream.status,
headers: { 'Content-Type': 'text/event-stream' },
});
}Step B — Client Stream + Sandboxed DOMPatchApplier Bridge
Because event.patch from createSession() already matches PatchOperation[] expected by DOMPatchApplier.apply(), you can stream straight into the sandboxed iframe:
'use client';
import React, { useRef, useState } from 'react';
import { createSession } from 'leveonas/sdk';
const SANDBOX_HTML = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://leveonas.ainot.site/leveonas-runtime.js"></script>
</head>
<body style="margin:0;padding:16px;font-family:system-ui,sans-serif;">
<div id="leveonas-root" data-ast-id="leveonas-root"></div>
<script>
var root = document.getElementById('leveonas-root');
var applier = null;
window.addEventListener('message', function (event) {
if (event.source !== window.parent) return;
if (!event.data || event.data.type !== 'leveonas:patch') return;
var rt = window.LeveonasRuntime;
if (!rt) return;
if (!applier) {
applier = new rt.DOMPatchApplier(root, document);
applier.registerNode('leveonas-root', root);
}
var validPatches = rt.validatePatches(event.data.patches);
applier.apply(validPatches);
});
</script>
</body>
</html>`;
export function PricingCardGenerator() {
const iframeRef = useRef<HTMLIFrameElement>(null);
const [error, setError] = useState<string | null>(null);
async function runGeneration() {
setError(null);
const session = createSession({
endpoint: '/api/stream-ui', // Calls your own backend route — no keys in browser!
provider: 'gemini',
model: 'gemini-4-carbon',
});
try {
for await (const event of session.generate('Build a React pricing card with Pro tier at $29/mo')) {
if (event.type === 'generation:patch') {
iframeRef.current?.contentWindow?.postMessage(
{ type: 'leveonas:patch', patches: event.patch },
'*'
);
} else if (event.type === 'generation:error') {
setError(event.error.message);
}
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Generation failed');
} finally {
session.destroy();
}
}
return (
<div>
<button onClick={runGeneration}>Generate React Pricing Card</button>
{error && <p role="alert">{error}</p>}
<iframe
ref={iframeRef}
title="Progressive Preview"
sandbox="allow-scripts"
srcDoc={SANDBOX_HTML}
style={{ width: '100%', minHeight: 420, border: '1px solid #DADCE0' }}
/>
</div>
);
}4. Browser Runtime Distributions & Security Architecture
Three Browser Runtime Distributions
| Distribution | Intended Use | Main API |
|---|---|---|
leveonas/runtime | TypeScript / bundler apps applying patches directly in controlled containers | DOMPatchApplier, CSSPatchApplier, JSPatchApplier, validatePatches, isPatchBatchValid |
/leveonas-runtime.js | Standalone CDN bundle loaded inside <iframe sandbox="allow-scripts"> | window.LeveonasRuntime (identical exports as leveonas/runtime) |
/leveonas.js | Full zero-build client engine that handles SSE fetch, validatePatches, and iframe creation automatically | new window.Leveonas.Engine({ apiUrl, apiKey }) |
Browser Security Guarantees & Boundaries
- Opaque Origin Isolation:
<iframe sandbox="allow-scripts">omitsallow-same-origin, giving the iframeorigin: "null". Untrusted generated scripts cannot read hostdocument.cookie,localStorage,sessionStorage, or DOM. - Directional
postMessageValidation: Because an opaque iframe has origin"null", message authenticity relies onevent.source === window.parentinside the iframe andevent.source === iframe.contentWindowin the host window. Unknown messagetypevalues and__proto__/constructor/prototypekeys are dropped immediately. - Patch & Attribute Hardening (
validatePatches): Rejects unknown operation names, batches > 500 ops, node IDs > 256 chars or with control characters, anyon*inline HTML event attributes (onclick,onerror, etc.), dangerous URL schemes (javascript:,vbscript:,file:,about:), and CSSexpression()/-moz-binding. Invalid schemas throwPatchValidationErrorbefore touching the DOM. - Known Limitation: Dynamic event handlers bound via
ATTACH_EVENT_HANDLERexecute inside the iframe's sandboxed JS realm (JSPatchApplier); do not pass secrets intosrcDocor post sensitive user data viapostMessageinto the preview iframe.