@illuma-ai/codeviz
v2.0.43
Published
Multi-format code & content preview — Monaco editor, live React/HTML/Markdown/SVG/CSV/JSON rendering, streaming API, zoom/pan, download
Maintainers
Readme
@illuma-ai/codeviz
In-browser preview component for LLM-generated React, HTML, Markdown, SVG, CSV, JSON, Mermaid, Graphviz, LaTeX, and architecture diagrams. Renders single-file model output in a sandboxed iframe with a structured error surface designed for agent self-correction.
Installation
npm install @illuma-ai/codevizPeer dependencies:
{
"react": ">=17.0.0",
"react-dom": ">=17.0.0",
"typescript": ">=5.0.0"
}typescript is optional — required only if you import @illuma-ai/codeviz/typescript.
Quick start
import { CodeViz } from '@illuma-ai/codeviz';
export default function App() {
return (
<CodeViz
code={`export default function Demo() {
return <h1>Hello</h1>;
}`}
template="react-ts"
/>
);
}Templates
<CodeViz template="react-ts" code={tsxSource} />
<CodeViz template="html" code="<div>...</div>" />
<CodeViz template="markdown" code="# Hi" />
<CodeViz template="mermaid" code="graph TD; A-->B" />
<CodeViz template="svg" code="<svg>...</svg>" />
<CodeViz template="csv" code="a,b,c\n1,2,3" />
<CodeViz template="json" code='{"a": 1}' />
<CodeViz template="dot" code="digraph G { A -> B }" />
<CodeViz template="latex" code="\frac{a}{b}" />
<CodeViz template="architecture" code="<mxGraphModel>...</mxGraphModel>" />
<CodeViz template="bpmn" code="<?xml version='1.0'?><bpmn:definitions>...</bpmn:definitions>" />Virtual file system (files prop)
Ship a pre-built component library the model can import using absolute paths. Mirrors the virtual-files shape other browser sandboxes use, so the same map works across them.
<CodeViz
code={modelGeneratedCode}
template="react-ts"
files={{
'/lib/utils.ts': cnSource,
'/components/ui/button.tsx': buttonSource,
'/components/ui/card.tsx': cardSource,
'/styles/globals.css': cssSource,
'/assets/logo.svg': svgSource,
'/data/config.json': jsonSource,
}}
/>Model code:
import { Button } from '/components/ui/button';
import { cn } from '/lib/utils';
import logo from '/assets/logo.svg'; // default-exported data: URL
import config from '/data/config.json'; // parsed JSON default export
import '/styles/globals.css'; // injects <style> on importSupported file kinds
| Extension | Behaviour |
|---|---|
| .tsx, .ts, .jsx, .js | Transpiled with Sucrase, served as data:text/javascript URL |
| .css | Wrapped as ESM module that injects a <style> tag on import |
| .json | Wrapped as export default <parsed> |
| .svg | Default-exported as data:image/svg+xml URL |
| .png, .jpg, .gif, .webp, .avif | Base64 input → data:image/* URL exported by default |
Path resolution
- Extensions optional:
/components/ui/buttonresolves to.tsx - Index files collapse:
/components/ui/index.tsxreachable as/components/ui - Relative imports inside virtual files (
./sibling,../utils) auto-rewrite to absolute paths - The preview iframe uses
srcdocbut injects<base href="${window.location.origin}/">into the generated HTML. This is required becauseabout:srcdoc(andblob:URLs) are opaque per the URL standard — the browser cannot URL-resolve path-style module specifiers against them and the module loader throws "base scheme isn't hierarchical" before consulting the import map. Anchoring the base to the parent page's real origin gives both the map keys and the user code a hierarchical context to normalise against. Nothing is ever fetched from the origin — every import resolves to a data: URL inside the map.
Virtual files in downloaded HTML
The "Download HTML" action (Toolbar → download menu on React templates) bakes the same files map into a self-contained HTML file. Every virtual entry becomes a data: URL inside the downloaded import map, so the file renders identically when opened from disk via file:// — no network, no server.
Styling — Tailwind + shadcn variables
Tailwind CSS is loaded via CDN by default. Inject a theme CSS string using the standard shadcn variable names, tinted to your brand colours:
const THEME_CSS = `
:root {
--background: 0 0% 100%;
--foreground: 220 60% 10%;
--primary: 187 100% 42%;
--card: 0 0% 100%;
--border: 0 0% 89%;
--ring: 187 100% 42%;
--radius: 0.5rem;
}
.dark {
--background: 0 0% 5%;
--foreground: 0 0% 93%;
}
`;
<CodeViz themeCSS={THEME_CSS} code={...} />Model code then uses semantic classes (bg-background, text-foreground, border-border) that resolve to your brand colours.
Imperative API — streaming + control
import { useRef } from 'react';
import { CodeViz, type CodeVizHandle } from '@illuma-ai/codeviz';
const ref = useRef<CodeVizHandle>(null);
<CodeViz ref={ref} template="react-ts" />
// During LLM token streaming — editor updates live, preview rebuild deferred
ref.current?.streamCode(partialSource);
// When the model is done — trigger preview rebuild
ref.current?.commitCode();
// Surgical string replace
ref.current?.editCode('const x = 0', 'const x = 1');
// Full replace
ref.current?.setCode(newSource);
// Restore to the initial `code` prop + clear errors
ref.current?.reset();
// Detect whether the user has edited since the last commit
if (ref.current?.isPristine()) { /* safe to regenerate */ }Full handle:
interface CodeVizHandle {
getCode(): string;
setCode(code: string): void;
streamCode(partialCode: string): void;
commitCode(): void;
editCode(oldStr: string, newStr: string): boolean;
refresh(): void;
reset(): void;
setView(view: 'split' | 'code' | 'preview'): void;
getErrors(): PreviewError[];
clearErrors(): void;
isLoading(): boolean;
isPristine(): boolean;
}verify() — compile-time validation
Pure synchronous function. Runs every static check in one pass and returns errors with inline fix suggestions.
import { verify } from '@illuma-ai/codeviz';
const result = verify({
code: artifactSource,
template: 'react-ts',
filename: 'App.tsx',
files: virtualComponentLibrary, // optional
additionalGlobals: ['cn'], // optional
});
if (!result.valid) {
for (const err of result.errors) {
console.log(err.message);
if (err.suggestion) console.log('Fix:', err.suggestion);
}
}What it catches:
| Class | Example |
|---|---|
| Syntax errors | unclosed JSX, invalid TS |
| Missing default export | function App() {} (no export default) |
| Undeclared identifiers (Levenshtein typo hints) | useStare(0) → suggests useState |
| Unresolved virtual imports | from '/components/ui/buton' → suggests /components/ui/button |
| Hooks in conditionals | if (x) useState() |
| Missing key in .map | items.map(x => <li>) |
| Async function as component | export default async function App |
| Stale-closure useEffect | useEffect(() => use(state), []) |
| setState(state) after mutation | arr.push(x); setArr(arr) |
| key={index} on re-orderable list | .map((item, i) => <li key={i}>) |
| Lowercase JSX (likely typo) | <button2 />, <myComponent /> |
| File truncation | EOF with unclosed brackets + closing-sequence suggestion |
Every error ships { line, sourceContext, location, suggestion? }.
Streaming-aware section verify
For long files, validate each {/* @section: name */} block as it lands — lets the model self-correct mid-stream:
import { verifyStream } from '@illuma-ai/codeviz';
const stream = verifyStream({ template: 'react-ts', files });
for await (const chunk of llmTokenStream) {
const newErrors = stream.append(chunk);
newErrors.forEach(send);
}
const tail = stream.flush();onConsole — capture iframe console
<CodeViz
onConsole={(entry) => {
// entry: { level: 'log' | 'info' | 'warn' | 'error', message, timestamp }
setLogs((l) => [...l, entry]);
}}
/>Built-in limits: 50 messages forwarded per iframe lifetime; each message truncated at 10 000 chars. React dev warnings filtered from the error channel.
parseStack() — structured stack frames
Errors carry a frames array with opaque blob:/data: URLs normalised to <user-code>:
import { parseStack } from '@illuma-ai/codeviz';
const frames = parseStack(error.stack);
// [{ fn: 'App', source: '<user-code>', line: 42, column: 18, isUserCode: true }, ...]generateSystemPrompt() — deterministic LLM prompt
import { generateSystemPrompt } from '@illuma-ai/codeviz';
const prompt = generateSystemPrompt({
productName: 'MyApp',
preambleGlobals: ['cn'],
virtualFiles: ['/components/ui/button', '/lib/utils'],
npmPackages: { 'lucide-react': '0.468.0', recharts: '2.15.0' },
iconLibraries: ['lucide-react'],
tailwind: true,
extraRules: ['Use semantic Tailwind tokens like `bg-card`'],
});Same input → same output. Safe for prompt caching.
Opt-in entries
Heavyweight capabilities ship as separate chunks that tree-shake if unused.
@illuma-ai/codeviz/lint
Adds a browser ESLint pass on top of verify():
import { verifyWithLint } from '@illuma-ai/codeviz/lint';
const result = await verifyWithLint({ code, template: 'react-ts' });Rules: no-unused-vars, no-redeclare, no-self-assign, no-unreachable, no-constant-condition, no-debugger, no-empty. Lazy-loaded (~1.5 MB chunk).
@illuma-ai/codeviz/typescript
Adds TypeScript diagnostics via ts.transpileModule:
import { verifyWithTypes } from '@illuma-ai/codeviz/typescript';
const result = await verifyWithTypes({ code, template: 'react-ts' });Uses the consuming app's own installed typescript (optional peer dep).
Templates registry
Codeviz ships no built-in templates. Register your own:
import { registerTemplates } from '@illuma-ai/codeviz';
registerTemplates([
{
id: 'dashboard',
name: 'Dashboard scaffold',
type: 'react-ts',
language: 'tsx',
code: '...',
keywords: ['dashboard', 'kpi', 'chart'],
},
]);Security
The preview iframe runs user code in a sandbox:
sandbox="allow-forms allow-modals allow-popups allow-presentation
allow-scripts allow-downloads allow-pointer-lock"allow-same-origin is deliberately omitted — iframe code cannot read the host page's localStorage, cookies, or sessionStorage.
postMessage origins are filtered to null (srcdoc) or the host's own origin, with a type: 'codeviz' envelope marker. No eval() or Function() constructor. User code loads via import() of Blob/data: URLs and the blob URL is revoked immediately after import.
See docs/security-audit.md for the full review.
Types
import type {
CodeVizProps,
CodeVizHandle,
PreviewError,
PreviewTemplate,
StackFrame,
ConsoleEntry,
VerifyResult,
} from '@illuma-ai/codeviz';Documentation
docs/architecture.md— module map, data flowdocs/security-audit.md— threat model
License
MIT — see LICENSE.
