Fradualv2.0.0
GitHub

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.

Terminal
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:

embed_example.ts
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);  // 520

02. Executive Architecture & Design Tenets

Embedding dynamic script evaluation in enterprise software traditionally forces an unacceptable compromise:

UNSAFE APPROACH
Native eval() / new Function()

Directly shares the host V8 engine context. Vulnerable to prototype pollution, arbitrary code execution, event loop freezing via infinite loops, and unconstrained memory exhaustion.

HEAVYWEIGHT APPROACH
V8 Worker Isolates / Docker

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.

THE FRADUAL ARCHITECTURAL GUARANTEE

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:

StageComponentResponsibilityOutput Artifact
01LexerTokenizes character stream; tracks line, column, and token kindsToken[] stream
02ParserRecursive descent parsing; constructs typed AST nodesStmt.Stmt[] syntax tree
03CompilerSingle-pass emitter; resolves locals, calculates jump offsets, upvaluesObjFunction bytecode chunk
04Stack VMDispatches opcodes against value stack; enforces instruction quotaRunResult + 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:

infinite_loop_trap.ts
// 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."
SECURITY SPECIFICATION: ZERO PROTOTYPE POLLUTION

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

TypeSyntax / LiteralDescription
Number42, 3.14159, -10.5Double-precision IEEE 754 floating point numbers
String"hello world"Immutable UTF-8 strings with escape sequences
Booleantrue, falseExact booleans with short-circuiting and / or
NilnilAbsence of value (corresponds to JS null)
Array[1, 2, 3]Ordered dynamic collections with index subscripting
Map{ "key": "value" }Key-value dictionary tables
Functionfun 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:

closures.fu
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 / TypeScriptDirectionFradual 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:

abort_controller.ts
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:

OPCODES 00 – 05
Constants & Literals

OP_CONSTANT, OP_NIL, OP_TRUE, OP_FALSE, OP_POP

OPCODES 06 – 11
Variables & Scopes

OP_GET_LOCAL, OP_SET_LOCAL, OP_GET_GLOBAL, OP_DEFINE_GLOBAL, OP_SET_GLOBAL

OPCODES 12 – 20
Arithmetic & Logic

OP_EQUAL, OP_GREATER, OP_LESS, OP_ADD, OP_SUBTRACT, OP_MULTIPLY, OP_DIVIDE, OP_NOT

OPCODES 21 – 36
Jumps, Closures & Objects

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 MetricValueEnterprise Verification
External Dependencies0 dependencies100% clean npm audit; immune to supply-chain attacks
Bundle Size< 42 KB minifiedNegligible bundle impact in web and serverless bundles
Cold Start Latency0.04 msSub-millisecond instant evaluation without thread spinup
TypeScript Definitions100% strict typingComplete .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:

CLI Usage
# 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