npm package: @minuiruntime/minui_rt
Description: Ultra-fast Rust/WASM runtime for rendering AI-generated JSON → HTML. Built for streaming SSR, deterministic UI shaping, and safe client-side or server-side rendering.
Latest version: 0.4.0

# @minuiruntime/minui_rt

> **⚠️ Security Notice:** Versions prior to 0.3.0 may be vulnerable to XSS attacks from AI-generated content. It is strongly recommended to upgrade to 0.3.0 or later.

Ultra-fast **Rust + WebAssembly runtime** for rendering **AI-generated JSON → HTML**.  
Designed for **streaming SSR**, **deterministic UI shaping**, and **extremely safe client-side or server-side rendering**.

MinUI Runtime is the lightweight core that powers the next generation of AI-powered UI rendering pipelines.

---

## 🚀 Why MinUIRuntime?

Modern LLMs output JSON structures describing UI fragments.  
MinUI Runtime takes those JSON structures and renders **real HTML**, safely and deterministically.

- ✔️ Pure Rust + WASM — incredibly fast  
- ✔️ Safe renderer — blocks scripts, invalid tags, malformed structures  
- ✔️ Works in browsers *and* Node.js SSR  
- ✔️ Supports streaming — render partial UI as JSON chunks arrive  
- ✔️ Perfect for AI chatbots, dashboards, documents, and dynamic UI  
- ✔️ Zero JS dependencies — all the heavy lifting happens in WASM  

This library lets you bring **AI-driven UI** into production with confidence.

---

## 🎮 Try the Demo

Check out the live demo: [https://minuiruntime.github.io/minuiruntime-demo-angular/](https://minuiruntime.github.io/minuiruntime-demo-angular/)

---

# 📦 Installation

```sh
npm install @minuiruntime/minui_rt
```

---

# 📥 Importing the Runtime

```ts
import init, { MinUiRuntime } from "@minuiruntime/minui_rt";
```

---

# 🖼️ Basic Usage — Render JSON → HTML

```ts
import init, { MinUiRuntime } from "@minuiruntime/minui_rt";

// Initialize WASM first (required before using the runtime)
await init("/assets/wasm/minui_rt_bg.wasm");
// OR just: await init(); for auto-loading from default path

// This can also be a pure string from the LLM
const jsonString = JSON.stringify({
  version: "1.0",
  type: "element",
  tag: "div",
  attrs: { class: "message" },
  children: [
    { type: "text", value: "Hello from MinUI Runtime!" }
  ]
});

// Render directly — returns Frame object
const frame = MinUiRuntime.render(jsonString);

console.log(frame.html);
// → <div class="message">Hello from MinUI Runtime!</div>
```

---

# 🌊 Streaming Usage — Incremental Updates

For AI-powered applications that stream JSON chunks incrementally:

```ts
import init, { MinUiRuntime } from "@minuiruntime/minui_rt";

// Initialize WASM first (required before using the runtime)
await init("/assets/wasm/minui_rt_bg.wasm");

console.log("Creating streaming session...");

// Create a streaming session with options
const session = MinUiRuntime.createStreamingSession({ mode: "auto" });

// Update session with chunks as they arrive
const chunk = '{"type":"element","tag":"div","children":[{"type":"text","value":"Hello"}]}';
const frame = session.update(chunk);

// Log frame fields to inspect the response
console.log("Frame fields:", {
  html: frame.html,
  patchesApplied: frame.patchesApplied,
  diagnostics: frame.diagnostics
});

// Access the rendered HTML
console.log(frame.html);
// → <div>Hello</div>

// Access diagnostics
const delta = frame.diagnostics?.patchCountDelta ?? 0;
console.log(`Applied ${delta} patches in this update`);

// Continue updating as more chunks arrive
const chunk2 = '{"type":"element","tag":"div","children":[{"type":"text","value":"Hello, World!"}]}';
const frame2 = session.update(chunk2);
console.log(frame2.html);
// → <div>Hello, World!</div>

// Get current HTML at any time
const currentHtml = session.html();
```

### Options

- **`mode`** (optional): `"auto"` (default), `"json"`, or `"ai"`
  - `"auto"`: Automatically detects JSON vs AI-generated text
  - `"json"`: Strict JSON mode (must conform to schema)
  - `"ai"`: AI-generated text mode (more lenient parsing)

- **`debug`** (optional): `boolean` (default: `false`)
  - Enable debug logging to console

### Migration Guide (v0.2.x → v0.3.0)

**Breaking Changes:**

1. **`session.reset()` method removed** — To reset a session, create a new session instance:
   ```ts
   // ❌ Old (no longer supported)
   session.reset();
   
   // ✅ New (0.3.0+)
   session = MinUiRuntime.createStreamingSession({ mode: "auto" });
   ```

2. **`model` field no longer accepted in VNode JSON** — Remove any `model` fields from your JSON structures:
   ```ts
   // ❌ Old (causes schema error in 0.3.0)
   {"model":"gpt-4","type":"element","tag":"div"}
   
   // ✅ New (0.3.0+)
   {"type":"element","tag":"div"}
   ```

### Frame Structure

Each `update()` call returns a `Frame` object:

```ts
{
  html: string,              // Current rendered HTML
  patchesApplied: number,    // Total patches applied so far
  diagnostics: {
    patchCountDelta: number, // Patches applied in this update
    error?: {                // Error information (if any)
      kind: string,          // "parse" | "schema" | "diff" | "runtime"
      message: string,       // Human-readable error message
      offendingChunk?: string, // The chunk that caused the error
      recoverable: boolean   // Whether streaming can continue
    }
  }
}
```

---

# 🔒 Security & Safety

MinUI Runtime enforces strict safety guarantees:

- **No script injection** — `<script>` tags are blocked
- **No event handlers** — `onclick`, `onerror`, etc. are stripped
- **Tag whitelist** — only safe HTML tags are allowed
- **Attribute sanitization** — dangerous attributes are filtered
- **Schema validation** — JSON input is validated against a strict schema

---

# 🌐 Browser & Node.js Support

MinUI Runtime works seamlessly in both environments:

```ts
// Browser
import init, { MinUiRuntime } from "@minuiruntime/minui_rt";
await init("/assets/wasm/minui_rt_bg.wasm");

// Node.js (SSR)
import init, { MinUiRuntime } from "@minuiruntime/minui_rt";
import { readFile } from "fs/promises";
const wasmBytes = await readFile("./node_modules/@minuiruntime/minui_rt/minui_rt_bg.wasm");
await init(wasmBytes);
```

---

# 📚 API Reference

## `init(path?: string | BufferSource): Promise<void>`

Initialize the WASM module. Must be called before using any other APIs.

- **Browser**: Pass the path to the `.wasm` file, or omit for auto-loading
- **Node.js**: Pass the raw bytes from `fs.readFile()`

## `MinUiRuntime.render(json: string): Frame`

Render JSON to HTML in a single call. Returns a Frame object with `html`, `patchesApplied`, and `diagnostics` properties.

## `MinUiRuntime.createStreamingSession(options?): StreamingSession`

Create a new streaming session for incremental updates.

### `StreamingSession` Methods

- **`update(chunk: string): Frame`** — Add a new chunk and get the updated frame
- **`html(): string`** — Get the current HTML

---

# 🛠️ Development

This package is built from the [MinUIRuntime](https://github.com/rod-z/minuiruntime) monorepo.

```bash
# Build the WASM package
npm run build:release

# Run tests
npm test
```

---

# 📄 License

MIT — see [LICENSE](./LICENSE)

---

# 🔗 Links

- [GitHub Repository](https://github.com/rod-z/minuiruntime)
- [npm Package](https://www.npmjs.com/package/@minuiruntime/minui_rt)
- [Documentation](https://github.com/rod-z/minuiruntime#readme)

---

**Built with ❤️ using Rust + WebAssembly**