The ERD Platform
A complete stack: compile TypeScript, generate bytecode, execute on microcontrollers, desktops, and browsers.
Runtime
The ERD TypeScript Virtual Machine (ERD-TSVM) compiles TypeScript source into compact bytecode, then executes it on a register-based VM with up to 256 general-purpose registers per stack frame, automatic spilling, and super instruction fusion. Targets include ESP32 (C3, C6, S3, H2, P4), desktop (Linux/macOS/Windows), and WebAssembly.
The platform targets full ES2026 semantics and the complete TypeScript type system โ including generics, union/intersection types, decorators, enums, mapped types, and conditional types. The bytecode format is designed for minimal memory footprint while maintaining full type fidelity.
ES2026 Compliance
ERD-TSVM implements 254+ tracked language features spanning TypeScript 6.0
and ES2026. Every TypeScript syntax construct is accepted โ type annotations, interfaces,
generics, classes, decorators, namespaces, using declarations, and auto-accessors.
Type annotations are checked at compile time and erased during bytecode generation,
consistent with standard TypeScript behavior.
ES2022 Features
Top-level await, class fields (public, private #fields,
static), class static blocks, Array.prototype.at(),
Object.hasOwn(), RegExp match indices (/d flag),
Error cause, and structuredClone().
ES2023 Features
Change Array by Copy (toSorted, toReversed,
toSpliced, with),
Array.prototype.findLast() / findLastIndex(),
Hashbang grammar (#!), and
Symbols as WeakMap keys.
ES2024 Features
Explicit Resource Management (using / await using),
ArrayBuffer.prototype.resize(),
ArrayBuffer.prototype.transfer(),
Object.groupBy() / Map.groupBy(),
Promise.withResolvers(), and
String.prototype.isWellFormed().
ES2025 Features
Set methods (union, intersection, difference,
symmetricDifference, isSubsetOf, isSupersetOf,
isDisjointFrom), Iterator Helpers,
Promise.try(), Float16Array,
and RegExp modifiers.
ES2026 Features
Temporal API (PlainDate, PlainTime, ZonedDateTime, Duration, Instant),
RegExp.escape(),
JSON.rawJSON() / JSON.isRawJSON(),
Math.sumPrecise(),
Error.isError(),
DisposableStack / AsyncDisposableStack,
and Uint8Array Base64/Hex encoding.
Intentionally Excluded
eval() and new Function() are excluded by design โ no
runtime code compilation in a bytecode VM. The with statement is
excluded as it is deprecated in strict mode. These are the same restrictions
applied by most TypeScript runtimes targeting constrained platforms.
Built-in Objects
The runtime natively implements 150+ built-in objects and functions, covering the full ES2026 specification. All built-ins execute as native code in the runtime for maximum performance.
| Category | Objects |
|---|---|
| Fundamental | Object, Function, Boolean, Symbol |
| Numbers & Dates | Number, BigInt, Math, Date |
| Text Processing | String, RegExp |
| Collections | Array, Map, Set, WeakMap, WeakSet, WeakRef |
| TypedArrays | Int8Array โฆ BigUint64Array, Float16Array, with Base64/Hex encoding |
| Structured Data | ArrayBuffer, SharedArrayBuffer, DataView, Atomics, JSON |
| Async | Promise, async/await, generators, AsyncGenerator, Iterator helpers |
| Error Types | Error, TypeError, RangeError, SuppressedError, Error.isError() |
| Temporal (ES2026) | Temporal.Now, PlainDate, PlainTime, PlainDateTime, ZonedDateTime, Duration, Instant |
| Resource Management | DisposableStack, AsyncDisposableStack, FinalizationRegistry |
| Reflection | Proxy, Reflect |
| Internationalization | Intl.Collator, DateTimeFormat, NumberFormat, PluralRules, Segmenter, ListFormat, RelativeTimeFormat, DisplayNames, Locale |
| Web APIs | fetch, Headers, Request, Response, EventTarget, EventEmitter, AbortController, ReadableStream, WritableStream, Blob, FormData |
| Encoding | TextEncoder, TextDecoder, URL, URLSearchParams, atob, btoa |
| Global | console, process, performance, setTimeout, setInterval, setImmediate, requestAnimationFrame |
Storage โ DocStore
DocStore is a lightweight, MongoDB-compatible embedded document database that runs directly on-device. It provides durable storage with crash recovery on all platforms โ persistent storage on ESP32 (flash or SD card), local filesystem on desktop, and in-memory storage on WASM โ with the same TypeScript API everywhere.
CRUD Operations
Full document lifecycle: insertOne, insertMany,
findOne, find (cursor-based), updateOne,
updateMany, deleteOne, deleteMany,
replaceOne, and countDocuments.
Secondary Indexes
Create indexes on any document field for fast lookups.
Supports createIndex, dropIndex, and
listIndexes. The query engine automatically selects
the best index for each query.
Aggregation Pipelines
MongoDB-compatible aggregation with pipeline stages for grouping, filtering, projecting, and transforming documents. Run complex analytics directly on-device without external databases.
TypeScript API
import { DocStore } from '@erdtsvm/std/modules/docstore';
// Open a database and get a typed collection
const db = DocStore.open('mydb');
const users = db.collection<User>('users');
// Insert documents
await users.insertOne({ name: 'Alice', age: 30, role: 'admin' });
// Query with MongoDB-compatible filters
const admins = await users.find({ role: 'admin' }).toArray();
// Aggregation pipeline
const stats = await users.aggregate([
{ $group: { _id: '$role', count: { $sum: 1 } } }
]);
Security
Security is built into every layer โ from encrypted storage to signed firmware updates and a hardware-rooted secure boot chain.
Encrypted Storage
All data at rest โ DocStore documents, configuration, credentials โ is encrypted. Encryption keys are derived from device-specific material and never stored in plain text.
Signed Updates & Integrity
Firmware and bytecode updates are cryptographically signed before distribution. The device verifies signatures and checksums before staging. Rollback is automatic if health checks fail after installation. Corruption or tampering is detected before execution.
Secure Boot Chain
Each boot stage verifies the next, ensuring only trusted, signed firmware executes on the device. Unauthorized code is rejected before it can run.
OTA Lifecycle
Over-the-air updates follow a safe, staged rollout designed for production environments where reliability is critical.
If the new firmware fails health checks within a configurable window, the device automatically rolls back to the previous known-good version. The OTA system supports both full firmware updates and bytecode-only hot swaps โ allowing application logic to be updated without reflashing the entire runtime.
Debugging
The runtime implements the Debug Adapter Protocol (DAP), providing a professional debugging experience across all platforms โ VS Code (desktop), on-device (ESP32 via network), and in the browser (WASM playground).
Breakpoints
Set breakpoints by line number, conditional breakpoints that pause only when an expression evaluates to true, and hit-count breakpoints. Breakpoints are resolved against source maps for TypeScript-level debugging.
Step-Through Execution
Step over, step into, and step out of function calls. The debugger correctly handles async/await boundaries, showing the logical execution flow rather than the fiber-level mechanics.
Variable Inspection
Inspect local variables, closure captures, and global state. Objects, arrays, maps, and sets are expanded with their full contents. Evaluate expressions in the current scope.
Getting Started
ERD-TSVM lets you write TypeScript that runs on microcontrollers, desktops, and browsers. The compiler produces compact bytecode, and the runtime executes it on your chosen platform with full ES2026 semantics.
Hello World
// hello.ts
console.log('Hello from ERD-TSVM!');
# Compile to bytecode
erdtsvm build hello.ts -o hello.erd1
# Execute on the desktop runtime
erdtsvm run hello.erd1
Sensor Reading (ESP32)
import { GPIO, ADC } from '@erdtsvm/std/modules/gpio';
// Read an analog sensor every second
const sensor = ADC.open(34); // GPIO34
setInterval(() => {
const value = sensor.read();
console.log(`Sensor reading: ${value}`);
}, 1000);
HTTP Server
import { HttpServer } from '@erdtsvm/std/modules/http';
const server = new HttpServer({ port: 8080 });
server.on('request', (req, res) => {
res.json({ status: 'ok', uptime: performance.now() });
});
server.listen();
console.log('Server running on :8080');
Project Configuration
Create an erdtsconfig.json in your project root to configure the compiler,
set manifest metadata, and enable features like heap snapshots. The compiler automatically
discovers it โ no flags needed.
{
"compilerOptions": {
"optimizationLevel": 2,
"strict": true,
"snapshot": true,
"target": "esp32"
},
"manifest": {
"moduleName": "sensor-hub",
"version": "1.0.0",
"heapBudget": 65536,
"capabilities": ["gpio", "bus", "mqtt", "timer"]
}
}
Path aliases let you organize multi-package projects โ like pnpm workspaces โ with clean imports:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@myproject/sensors/*": ["packages/sensors/src/*"],
"@myproject/utils/*": ["packages/utils/src/*"]
}
}
}
import { readTemperature } from '@myproject/sensors/temperature';
import { formatValue } from '@myproject/utils/format';
CLI flags always override config file values. See the full erdtsconfig reference for all options.
Heap Snapshots
Heap snapshots capture the runtime's memory state after module initialization and embed it in the bytecode. On cold start, the runtime restores the snapshot instead of re-executing top-level code โ up to 82ร faster startup with zero behavioral change.
How It Works
The compiler runs your program's $bundled_init (all top-level module
code) in a sandbox, serializes the resulting heap to a binary snapshot, and
splices it into the .erd file as a SNAPSHOT section. At runtime, the
VM detects the section and restores the heap directly โ skipping all imports,
class definitions, and constant initialization.
Performance Impact
The self-hosted compiler starts in 336 ms with a snapshot vs 27.6 s without (82ร faster). Snapshot restore is a single memcpy โ no parsing, no execution, no prototype chain construction. Every program benefits, from simple scripts to complex multi-module applications.
Enabling Snapshots
Add "snapshot": true to your erdtsconfig.json, or pass
--snapshot on the command line. Your program must use the
setMain() pattern to separate setup from per-invocation work:
import { setMain } from '@erdtsvm/std/modules/runtime';
// Top-level: runs once, captured in snapshot
const config = loadConfig();
const db = new DocStore('sensors');
// Per-invocation: runs on every cold start
setMain(() => {
const reading = readSensor();
db.insert({ timestamp: Date.now(), value: reading });
console.log(`Stored: ${reading}`);
});
Syscall Reference
Syscalls bridge TypeScript code and native platform capabilities. The compiler emits a syscall instruction, the VM dispatches to a registered handler, and the platform adapter executes the native implementation. All I/O syscalls support both synchronous and asynchronous modes โ async operations suspend the calling fiber and resume it when the operation completes.
| Category | Capabilities | Platforms |
|---|---|---|
| Console | console.log, console.warn, console.error, console.debug | All |
| Timers | setTimeout, setInterval, clearTimeout, clearInterval | All |
| DocStore | CRUD, cursors, indexes, aggregation, TTL expiry | All |
| Filesystem | Read, write, stat, mkdir, readdir, rename, delete | All |
| HTTP | fetch(), HTTP client, HTTP server (sync + async) | All |
| WebSocket | WebSocket client and server (sync + async) | All |
| MQTT | Publish, subscribe, connection management | All |
| Network | TCP/UDP sockets, DNS resolution | All |
| GPIO | Digital I/O, touch, rotary encoder, IR, stepper | ESP32 |
| UART | Serial port read/write, baud configuration | All |
| I2C / SPI | Bus read/write, device enumeration | ESP32 |
| ADC / DAC / PWM | Analog input, analog output, PWM generation | ESP32 |
| Camera / Display | Camera capture, LCD/OLED display output | ESP32 |
| USB | USB device communication | ESP32 |
| Crypto | SHA-256, AES-256, HMAC, secure random bytes | All |
| OTA | Firmware update, staging, rollback, health check | ESP32 |
| Events | Subscribe, unsubscribe, wait, event-driven I/O | All |
| Data Formats | JSON5, CBOR, MessagePack, Protocol Buffers, TOON | All |
| AI Inference | On-device model loading and inference (TFLite, ONNX) | All |
Platform adapters implement only the syscalls relevant to their target โ unsupported syscalls return a clear error at runtime. This allows the same TypeScript source to compile once and run on any platform, with platform-specific capabilities gracefully degrading where not available.
Standard Library
The standard library provides TypeScript modules that map to native syscalls at
compile time. Import modules from @erdtsvm/std/modules/โฆ.
console
Formatted output via console.log, console.warn, console.error, and console.debug. Works on all platforms.
docstore
On-device document database with CRUD operations, secondary indexes, aggregation pipelines, TTL-based expiry, and crash recovery.
crypto
Cryptographic hashing (SHA-256), encryption/decryption (AES-256), HMAC, and secure random byte generation.
timers
setTimeout, setInterval, setImmediate, and requestAnimationFrame with cooperative scheduling. No OS threads required.
events
EventTarget and EventEmitter for publish-subscribe patterns and DOM-compatible event handling.
http
fetch, Headers, Request, Response, HttpServer, and AbortController. Standards-aligned HTTP for all platforms.
gpio
Digital pin read/write, PWM output, analog-to-digital conversion, touch input, rotary encoders, and stepper motor control. ESP32 only.
filesystem
File and directory operations: read, write, append, stat, mkdir, readdir, rename, and delete. Available on all platforms (SPIFFS/LittleFS on ESP32, std::filesystem on desktop, OPFS on WASM).
uart
Serial port communication with configurable baud rate, data bits, and flow control. Available on all platforms (hardware UART on ESP32, termios/Win32 on desktop, Web Serial API on WASM).
websocket
WebSocket client and server with connection lifecycle management, message framing, and ping/pong keepalive.
mqtt
MQTT publish/subscribe messaging with QoS levels, retained messages, and automatic reconnection. Ideal for IoT telemetry.
network
Low-level TCP and UDP socket communication with async I/O support. For protocols not covered by the HTTP or WebSocket modules.
streams
ReadableStream, WritableStream, and TransformStream following the WHATWG Streams Standard. Pipe data between producers and consumers.
ai
On-device AI/ML inference with TFLite and ONNX Runtime backends. Supports GPU acceleration via CUDA/DirectML on desktop and WebGPU on WASM. Available on all platforms.
zlib
Native zlib, DEFLATE, and gzip compression. Supports one-shot deflate/inflate, compress/decompress, gzip/gunzip, and streaming via TransformStream. The standard compression behind HTTP, PNG, and ZIP.
crc
CRC-8, CRC-16, and CRC-32 checksum computation with configurable polynomials. Essential for Modbus, CAN bus, 1-Wire, Ethernet, and embedded protocol integrity checks.
zip
ZIP archive creation and extraction with DEFLATE compression. Create archives, add files and directories, list contents, and extract entries โ all in native code.
msgpack
MessagePack binary serialization โ a compact, fast alternative to JSON. Encode and decode structured data with native performance, ideal for IoT protocols and inter-device communication.
cbor
CBOR (Concise Binary Object Representation) encoding and decoding. An IETF standard binary format designed for constrained environments and IoT data exchange.
protobuf
Protocol Buffers encoding and decoding. Serialize structured data using Google's efficient binary format for cross-platform communication and storage.
jwt
JSON Web Token creation and verification. Sign and validate JWTs for authentication, API authorization, and secure token exchange.
uuid
UUID generation and parsing for versions 1 through 7. Generate unique identifiers for documents, devices, sessions, and distributed systems.
zstd
Zstandard compression and decompression with streaming support. High-ratio, fast compression for data storage, network transfer, and bytecode payload optimization.
tar
TAR archive creation and extraction with .tar.gz (gzip) support. Bundle and unbundle files using the standard tape archive format for firmware packaging and data distribution.
cron
CRON expression parsing and scheduling. Define recurring tasks with standard cron syntax and execute callbacks on schedule.
json5
JSON5 parsing and serialization โ a superset of JSON that allows comments, trailing commas, unquoted keys, and more. Native implementation for fast parsing on all platforms.
totp
TOTP/HOTP one-time password generation and verification (RFC 6238/4226). Supports configurable digits, time periods, and hash algorithms for two-factor authentication.
glob
Glob pattern matching for strings and file paths. Supports wildcards (*), recursive matching (**), character classes (?), and brace expansion.
ini
INI configuration file parser and serializer. Parses sectioned key-value configuration files into nested objects and back.
csv
RFC 4180 compliant CSV parser and serializer. Supports custom delimiters, quoting, escaping, and row-level operations for data processing.
baseEncoding
Base32, Base45, Base58, Base62, and Base85 encoding and decoding. Useful for TOTP secrets, cryptocurrency addresses, compact binary encoding, and URL-safe identifiers.
mcpServer
Model Context Protocol server โ expose device sensors, actuators, and data as MCP tools and resources that AI assistants can discover and invoke. Supports HTTP+SSE and WebSocket transports.
mcpClient
Model Context Protocol client โ connect to remote MCP servers to list tools, call functions, read resources, and get prompts. Enables AI-powered edge device interactions.
mime
MIME type database with file extension lookups and reverse lookups. Map file paths to content types and content types back to extensions.
semver
Semantic versioning 2.0.0 parsing, comparison, and range matching. Validate, compare, and test version strings against semver ranges.
toon
TOON (Token-Oriented Object Notation) encoding and decoding โ a compact, human-readable data format optimized for token-efficient LLM prompt construction.
time
Async timing utilities including delay and sleep for promise-based waiting in cooperative scheduling environments.
compiler
On-device TypeScript compilation API. Dispatch parallel module compilations to a worker thread pool and receive compiled bytecode results.
tcp
Event-driven TCP client and server with async I/O. Create persistent connections, listen for incoming connections, and stream data with zero-copy performance.
udp
Event-driven UDP datagram sockets for connectionless communication with broadcast and multicast group support.
bytecodeManager
Zero-downtime bytecode deployment with A/B slot scheme. Hot-swap running programs, warm-restart with state preservation, and automatic rollback on health check failure.