-
Notifications
You must be signed in to change notification settings - Fork 0
Cookbook
Cookbook
适用版本:4.0.0。
Applies to 4.0.0.
这里收录可直接改造的小型方案。每个示例只展示一件事;完整 API 语义请回到对象页面确认。
This page collects small patterns that can be adapted directly. Each example demonstrates one concern; return to the object page for complete API semantics.
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
把每次运行独有的数据放入 ScriptObject,脚本通过 $state 读取。不要把每个请求的数据写进 Engine 级全局原型。
Put per-run data in a
ScriptObjectand 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
让每个模块只导出明确的函数或常量,使用相对路径导入。路径的最终解析由 Source Resolver 决定。
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
只对可信且格式正确的文本调用 JSON.parse。输入不合法时先在宿主边界返回错误,或者在脚本中捕获并转换为项目约定的错误结果。
Call
JSON.parseonly 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
循环中使用 StringBuffer,最后一次性读取文本。
Use
StringBufferin 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
在自动生成、热更新或用户编辑脚本的流程中,先调用编译检查,再创建或替换运行 Domain。MCP 客户端可以使用 aurora_check_script 或 aurora_check_file 完成同样的预检。
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_scriptoraurora_check_filefor the same preflight.
await engine.BuildAsync("main.as");
using var domain = engine.CreateDomain();
var result = domain.Execute("MAIN", "run");AuroraScript.JIT 4.0.0 · Documentation Home · Repository · MIT License