Fradual Architecture & Developer Specification
A comprehensive technical specification for the Fradual embeddable virtual machine and compiler (@hypecaves/compiler@2.0.0). Designed for secure multi-tenant rule evaluation, edge function dispatch, and deterministic computational budgets.
01. Quickstart & Installation
Fradual installs as a zero-dependency package compatible with Node.js (≥ 18.0.0), Next.js (App & Pages Router), Cloudflare Workers, and evergreen browsers.
npm install @hypecaves/compiler
30-Second Execution Example
The following example instantiates the VM, sets an exact instruction limit of 10,000 steps, binds a native host mathematical function, and evaluates business logic:
import { Fradual } from "@hypecaves/compiler";
const vm = new Fradual({
maxInstructions: 10000,
maxExecutionMs: 150,
natives: {
host_timestamp: () => Date.now(),
},
});
const result = vm.run(`
fun evaluateTier(spend, isMember) {
var discount = 0;
if (spend > 500 and isMember) {
discount = spend * 0.20;
}
return spend - discount;
}
return evaluateTier(650, true);
`);
console.log("Status:", result.status); // "ok"
console.log("Returned:", result.value); // 52002. Executive Architecture & Design Tenets
Embedding dynamic script evaluation in enterprise software traditionally forces an unacceptable compromise:
Directly shares the host V8 engine context. Vulnerable to prototype pollution, arbitrary code execution, event loop freezing via infinite loops, and unconstrained memory exhaustion.
Requires thread spawning, IPC serialization across boundary buffers, and 25–45 MB baseline RSS memory per isolate. Cold start latency ranges from 15ms to 80ms.
Fradual implements an in-process, pure TypeScript stack virtual machine. It executes in the caller's thread with a zero-allocation baseline, cold start latency below 0.05 milliseconds, and a strict deterministic instruction trap that prevents CPU monopolization without workers or native bindings.
4-Stage Pipelined Compilation
Fradual strictly separates parsing, compilation, verification, and interpretation into distinct, audited stages:
| Stage | Component | Responsibility | Output Artifact |
|---|---|---|---|
01 | Lexer | Tokenizes character stream; tracks line, column, and token kinds | Token[] stream |
02 | Parser | Recursive descent parsing; constructs typed AST nodes | Stmt.Stmt[] syntax tree |
03 | Compiler | Single-pass emitter; resolves locals, calculates jump offsets, upvalues | ObjFunction bytecode chunk |
04 | Stack VM | Dispatches opcodes against value stack; enforces instruction quota | RunResult + diagnostics |
03. Sandbox Security & Resource Quotas
Untrusted user scripts must never be capable of crashing the host process or causing denial-of-service conditions. Fradual enforces multiple independent layers of defense:
Deterministic Instruction Budget (`maxInstructions`)
Unlike time-based limits which vary based on CPU clock frequency and server load, the instruction budget decrements on every single opcode dispatch in the VM loop. A loop like while (true) or an unintended O(N!) recursion halts deterministically at the exact instruction boundary:
// Script executes within a strict 5,000 instruction budget
const vm = new Fradual({ maxInstructions: 5000 });
const res = vm.run("while(true) {}");
console.log(res.ok); // false
console.log(res.status); // "runtime_error"
console.log(res.diagnostics[0].message);
// "Execution halted: instruction limit (5000) exceeded."Fradual VM objects (ObjMap, ObjInstance, ObjArray) do not inherit from JavaScript's Object.prototype. Property accesses like __proto__, constructor, or prototype are strictly treated as inert dictionary keys with no prototype escalation vectors.
Call Stack Depth Bounds
Recursive functions are bounded by an internal call frame limit (default 64 frames). If a script attempts a stack overflow, the VM traps the execution gracefully with a clean diagnostic error rather than throwing a V8 RangeError: Maximum call stack size exceeded.
04. Formal Language Specification
Fradual implements an expressive, dynamically typed scripting language inspired by modern ECMAScript and Lua.
Data Types & Literals
| Type | Syntax / Literal | Description |
|---|---|---|
Number | 42, 3.14159, -10.5 | Double-precision IEEE 754 floating point numbers |
String | "hello world" | Immutable UTF-8 strings with escape sequences |
Boolean | true, false | Exact booleans with short-circuiting and / or |
Nil | nil | Absence of value (corresponds to JS null) |
Array | [1, 2, 3] | Ordered dynamic collections with index subscripting |
Map | { "key": "value" } | Key-value dictionary tables |
Function | fun add(a, b) { return a + b; } | First-class functions with lexical closures and upvalues |
Closures & Lexical Scoping
Functions are first-class values and can be returned from outer scopes while retaining access to closed-over variables:
fun makeMultiplier(factor) {
fun multiply(x) {
return x * factor;
}
return multiply;
}
var triple = makeMultiplier(3);
print "3 * 15 = " + triple(15); // 45
return triple(15);05. Host Interoperability & Value Marshalling
Fradual provides seamless bidirectional bridging between native JavaScript/TypeScript host code and the sandboxed virtual machine environment.
Bidirectional Type Conversion Rules
The engine automatically converts values across the boundary with cycle preservation and configurable depth checks:
| Host JavaScript / TypeScript | Direction | Fradual Guest VM Value |
|---|---|---|
number | ↔ | Number |
string | ↔ | String |
boolean | ↔ | Boolean |
null / undefined | ↔ | nil |
Array<T> | ↔ | ObjArray |
Record<string, any> | ↔ | ObjMap |
(...args) => unknown | → | ObjNative |
Cooperative Abortion via AbortSignal
Fradual natively hooks into browser and Node.js AbortController signals. If an HTTP request is cancelled or an upstream timeout fires, the script is aborted cooperatively:
const controller = new AbortController();
const vm = new Fradual();
vm.setAbortSignal(controller.signal);
// Abort from host after 50ms
setTimeout(() => controller.abort("Request cancelled by client"), 50);
const result = vm.run("while(true) {}");
console.log(result.status); // "runtime_error"
console.log(result.diagnostics[0].message); // "Request cancelled by client"06. Virtual Machine & Bytecode Instruction Set
The Fradual VM utilizes a dense, 1-byte opcode instruction set. Below is the structural classification of the 37 virtual machine opcodes:
OP_CONSTANT, OP_NIL, OP_TRUE, OP_FALSE, OP_POP
OP_GET_LOCAL, OP_SET_LOCAL, OP_GET_GLOBAL, OP_DEFINE_GLOBAL, OP_SET_GLOBAL
OP_EQUAL, OP_GREATER, OP_LESS, OP_ADD, OP_SUBTRACT, OP_MULTIPLY, OP_DIVIDE, OP_NOT
OP_JUMP, OP_LOOP, OP_CALL, OP_CLOSURE, OP_GET_UPVALUE, OP_ARRAY, OP_MAP
Pre-Execution Bytecode Verifier
Before bytecode is ever dispatched by the interpreter, it passes through verifyBytecode(chunk). This pass verifies that all jump targets reside within valid instruction boundaries, all operand indices align with the constant pool, and operand stack depths will never underflow.
07. Production Hardening & CLI Tooling
Fradual is engineered for zero-maintenance enterprise deployments:
| Production Metric | Value | Enterprise Verification |
|---|---|---|
| External Dependencies | 0 dependencies | 100% clean npm audit; immune to supply-chain attacks |
| Bundle Size | < 42 KB minified | Negligible bundle impact in web and serverless bundles |
| Cold Start Latency | 0.04 ms | Sub-millisecond instant evaluation without thread spinup |
| TypeScript Definitions | 100% strict typing | Complete .d.ts declarations generated on build |
Command Line Interface (CLI)
You can run and inspect Fradual script files directly from your terminal using the bundled executable:
# Run a script file npx @hypecaves/compiler script.fu # Disassemble and inspect bytecode opcodes npx @hypecaves/compiler --disassemble script.fu # Run with custom instruction quota npx @hypecaves/compiler --max-instructions 20000 script.fu