js_engine

    Pure MoonBit cross-target embedded JavaScript engine

    javascript
    interpreter
    embedded
    scripting
    Download zip
    Author
    Version
    0.6.0
    License
    Apache-2.0
    Last updated
    4 months ago
    Downloads
    5K

    #js_engine

    A pure MoonBit, cross-target embedded JavaScript engine. It uses a tree-walking interpreter and runs on MoonBit's native, JavaScript, Wasm, and Wasm-GC targets.

    • Conformance on test262: each file is run in strict and non-strict modes and reported per mode. Do not sum the modes. Generate current numbers from CI artifacts with make test262-report; see docs/TEST262.md.
    • Cross-target embedding: the same stateful Engine API is tested on native, JavaScript, Wasm, and Wasm-GC.
    • Benchmark dashboard: https://dowdiness.github.io/js_engine/benchmarks/

    #Quick Start

    #CLI

    moon run cmd/main -- 'console.log(1 + 2)' # 3

    moon run cmd/main -- ' function fib(n) { if (n <= 1) { return n; } return fib(n - 1) + fib(n - 2); } console.log(fib(10)); ' # 55

    More sample programs live in example/.

    #As a Library

    ///|
    test "README stateful rule engine" {
    let engine = @js_engine.Engine()
    let source =
    #|let evaluations = 0;
    #|function allow(request) {
    #| evaluations += 1;
    #| return { allowed: request.role === "admin", evaluations };
    #|}
    engine.eval(source)
    let admin = Json::object({ "role": Json::string("admin") })
    let member_request = Json::object({ "role": Json::string("member") })
    json_inspect(engine.call_json("allow", [admin]), content={
    "allowed": true,
    "evaluations": 1,
    })
    json_inspect(engine.call_json("allow", [member_request]), content={
    "allowed": false,
    "evaluations": 2,
    })
    }

    Engine keeps one global realm alive across calls. Its strict JSON boundary copies plain data directly: it does not consult a mutable global JSON, call getters or toJSON, or execute Proxy traps. Promise results and non-JSON values are rejected. This API is intended for trusted application scripts, not as a security sandbox. See example/rule_engine/ for the runnable example.

    For one-shot evaluation, the existing facade remains available:

    ///|
    test "README one-shot facade" {
    let (output, _) = @js_engine.run("console.log(1 + 2)")
    json_inspect(output, content=["3"])
    }

    The public entry points are defined in js_engine.mbt:

    • Engine, Engine::eval, Engine::call_json, Engine::take_output — persistent JSON-oriented embedding
    • Engine::run_microtask_checkpoint, Engine::run_timer_checkpoint — explicit job-queue control; eval and call_json do not drain queues automatically
    • run — evaluate a script; drains microtasks and timers before returning
    • run_compiled — evaluate the supported script subset through the opt-in closure-conversion prototype
    • run_module / run_modules — evaluate one or more ES modules and collect exports
    • run_with_event_loop, run_microtask_checkpoint, run_timer_checkpoint, has_pending_microtasks, has_pending_timers — for hosts that want to drive the event loop themselves

    #Embedding (custom host objects)

    For DOM-style globals and native methods, create a wired interpreter and inject bindings — do not reverse-engineer Interpreter::new / setup_builtins unless you need to replace builtin installation itself:

    let interp = @interpreter.new_interpreter()
    // Build query_selector with realm_state=Some(interp.realm_state) — see guide.
    let document = @runtime.make_host_object(
    name="Document",
    proto=@runtime.get_obj_proto(realm_state=Some(interp.realm_state)),
    methods={ "querySelector": query_selector },
    )
    interp.global.def_builtin("document", document)
    // Then parse, interp.run, interp.run_microtasks(), interp.run_timers().

    Full cookbook (make_*_func + realm_state, errors, host slots, globalThis, custom setup_builtins): docs/embedding.md.

    #Supported Language

    Core ES5 plus selected ES6+ features: let / const / var, arrow functions, closures, classes, for / while / for-in / for-of, try / catch / finally, template literals, destructuring, spread / rest, ES Modules, Promises + microtasks, setTimeout / setInterval, ES6 Proxy (13 traps) + Reflect API (13 methods), TypedArrays (9 types), ArrayBuffer, DataView, RegExp, JSON, Map / Set / WeakMap / WeakSet, generators, Symbols.

    For the full per-category breakdown, see docs/supported-features.md.

    #Conformance

    Test262 conformance by edition — CI run 29141665989, tip 74d84e5, 2026-07-11. P/E = passed ÷ executed (excludes skipped tests). Refresh: make test262-report ARGS="--format=readme".

    #strict

    EditionDiscoveredSkippedExecutedPassedFailedTimeout/ErrPassed / ExecutedPassed / Discovered
    Pre-ES2015 (baseline)13,281013,27812,986292397.8%97.8%
    ES201510,30016110,1319,935196898.1%96.5%
    ES20161000999901100.0%99.0%
    ES20177363443923893099.2%52.9%
    ES20184,7257273,9983,811187095.3%80.7%
    ES2019128012810622082.8%82.8%
    ES20201,7841,5372472443098.8%13.7%
    ES202146812834032515095.6%69.4%
    ES20225,0654,3247417365099.3%14.5%
    ES2023254332212183098.6%85.8%
    ES20241,07286620610898052.4%10.1%
    ES20251,14877936929673080.2%25.8%
    Annex B3654432126754083.2%73.2%
    Stage 35,5315,5191266050.0%0.1%
    Total44,98614,49130,48329,5269571296.9%65.6%

    Fully-skipped buckets (no tests executed) folded into Total: Unmapped (29).

    #non-strict

    EditionDiscoveredSkippedExecutedPassedFailedTimeout/ErrPassed / ExecutedPassed / Discovered
    Pre-ES2015 (baseline)13,917013,91113,460451696.8%96.7%
    ES201510,78816010,62010,393227897.9%96.3%
    ES20161000999901100.0%99.0%
    ES20177753444314283099.3%55.2%
    ES20184,7817354,0463,859187095.4%80.7%
    ES2019127012710522082.7%82.7%
    ES20201,9841,6043803773099.2%19.0%
    ES202144412831630115095.3%67.8%
    ES20225,3614,6007617556099.2%14.1%
    ES2023277562212183098.6%78.7%
    ES20241,07787020710998052.7%10.1%
    ES20251,18081336729473080.1%24.9%
    Annex B1,156441,110933177284.1%80.7%
    Stage 35,6965,593103109309.7%0.2%
    Total47,69214,97632,69931,3411,3581795.8%65.7%

    Fully-skipped buckets (no tests executed) folded into Total: Unmapped (29).

    #Package Structure

    token/ Token types and source locations errors/ JavaScript error variants and formatting helpers lexer/ Tokenizer ast/ AST node definitions parser/ Recursive descent parser with Pratt precedence static_semantics/ Early-error and declaration-fact analysis compiler/ Opt-in closure-conversion prototype interpreter/ Wiring layer for runtime + standard library interpreter/runtime/ Tree-walking evaluator, value model, host state interpreter/stdlib/ JavaScript built-ins cmd/main/ CLI entry point cmd/test262_runner/ Native test262 runner cmd/report_test262/ CI artifact report generator benchmarks/ Benchmark workloads and runner example/rule_engine/ Canonical stateful JSON rule-engine embedding

    #Development

    moon check # Type check moon test # Run unit tests moon fmt # Format code moon info # Update .mbti interface files moon build # Build

    Run the test262 conformance suite with make test262. See docs/TEST262.md for prerequisites, filtering, and options.

    #Documentation

    #License

    Apache-2.0

    EngineError

    pub(all) suberror EngineError {
    ParseError(String)
    JavaScriptException(String)
    MissingGlobal(String)
    NotCallable(String)
    JsonConversionError(String)
    InternalError(String)
    } derive(
    Debug
    )

    Stable errors raised by the stateful Engine facade.
    impl Show for EngineError

    Engine

    A persistent JavaScript realm for repeated evaluation and JSON calls.

    Engine::Engine

    fn Engine::Engine(annex_b? : Bool) -> Engine

    Engine::call_json

    fn Engine::call_json(self : Engine, name : String, args : Array[Json]) -> Json raise EngineError

    Engine::eval

    fn Engine::eval(self : Engine, source : String) -> Unit raise EngineError

    Engine::has_pending_microtasks

    fn Engine::has_pending_microtasks(self : Engine) -> Bool

    Engine::has_pending_timers

    fn Engine::has_pending_timers(self : Engine) -> Bool

    Engine::run_microtask_checkpoint

    fn Engine::run_microtask_checkpoint(self : Engine) -> Bool raise EngineError

    Engine::run_timer_checkpoint

    fn Engine::run_timer_checkpoint(self : Engine) -> Unit raise EngineError

    Engine::take_output

    fn Engine::take_output(self : Engine) -> Array[String]

    has_pending_microtasks

    fn has_pending_microtasks(interp :
    Interpreter
    ) -> Bool

    Check if there are pending microtasks in the queue

    has_pending_timers

    Check if there are pending timers in the queue

    run

    fn run(source : String, annex_b? : Bool) -> (Array[String], String) raise

    run_compiled

    fn run_compiled(source : String, annex_b? : Bool) -> (Array[String], String) raise

    Run JavaScript source through the opt-in closure-conversion prototype.

    The normal run facade remains the default interpreter path. This entry point parses once, compiles the supported script subset to executable closures, then runs it with the same event-loop drain behavior as run.

    run_microtask_checkpoint

    fn run_microtask_checkpoint(interp :
    Interpreter
    ) -> Bool raise

    Run a single microtask checkpoint Returns true if there are more microtasks to process

    run_module

    fn run_module(source : String, annex_b? : Bool) -> (Array[String], Map[String,
    Value
    ]) raise

    Run a JavaScript module source and return its exports The module is executed in strict mode and its exports are collected

    run_modules

    fn run_modules(modules : Array[(String, String)], annex_b? : Bool) -> (Array[String], Map[String,
    Value
    ]) raise

    Run multiple modules with dependency resolution. The runtime graph runner pre-registers every module specifier before instantiation/evaluation, so callers do not need to order modules by dependency. Returns the exports of the last module.

    run_timer_checkpoint

    fn run_timer_checkpoint(interp :
    Interpreter
    ) -> Unit raise

    Run all pending timers with microtask draining between each

    run_with_event_loop

    Run JavaScript source with event loop support This version allows the host to control microtask and timer execution timing

    Source Files