Skip to content

Cookbook

Liu.Yandong.Hanks edited this page Aug 21, 2026 · 3 revisions

Cookbook

Adapt focused examples for common module-loading, host-state, data, and execution workflows.

Applies to 4.0.0.

Home · Language Guide · Host Integration

On this page

Loading Modules from Memory

Use this for tests, rule editors, or cases where scripts should not be written to disk.

var resolver = ScriptSources.Memory("mem://rules/")
    .Add("main.as", """
        @module(RULES);
        export func score(value) { return value * 2; }
        """);

var options = EngineOptions.Default.WithCompiler(c =>
{
    c.SourceResolver = resolver;
    c.Mode = CompilationMode.Dynamic;
});

var engine = new AuroraEngine(options);
await engine.BuildAsync("main.as");
using var domain = engine.CreateDomain();
var score = domain.Execute("RULES", "score", ScriptDatum.FromNumber(21));

Passing Host State

Put per-run data in a ScriptObject and read it through $state. Do not write per-request data into the engine-level global prototype.

var state = new ScriptObject();
state.Define("Tenant", "acme");
using var domain = engine.CreateDomain(userState: state);
@module(MAIN);

export func tenantMessage() {
    return "hello " + $state.Tenant;
}

Composing Modules

Let each module export explicit functions or constants and import by relative path. Final path resolution is controlled by the Source Resolver.

// lib/format.as
@module(FORMAT);

export func label(name) {
    return "[" + name.trim() + "]";
}
// main.as
@module(MAIN);
import format from "./lib/format";

export func run(name) {
    return format.label(name);
}

Safely Handling JSON

Call JSON.parse only on trusted, well-formed text. For invalid input, return an error at the host boundary or catch and translate it to the project's agreed error result.

func readEnabled(text) {
    var config = JSON.parse(text);
    return Boolean(config.enabled);
}

return readEnabled('{"enabled":true}');

Building Long Text

Use StringBuffer in a loop and read the text once at the end.

var buffer = new StringBuffer();
for (var i = 0; i < 3; i++) {
    buffer.appendLine("item=" + i);
}
return buffer.toString();

Pre-execution Checks

In generated, hot-patched, or user-edited script flows, compile-check first and only then create or replace a running domain. MCP clients can use aurora_check_script or aurora_check_file for the same preflight.

await engine.BuildAsync("main.as");
using var domain = engine.CreateDomain();
var result = domain.Execute("MAIN", "run");

Next steps

Clone this wiki locally