use crate::{describe, install_console, Logs};
use boa_engine::builtins::promise::PromiseState;
use boa_engine::module::{ModuleLoader, Referrer};
use boa_engine::object::builtins::{JsFunction, JsPromise};
use boa_engine::{js_string, Context, JsError, JsNativeError, JsResult, JsValue, Module, NativeFunction, Source};
use serde_json::{json, Value};
use std::cell::RefCell;
use std::collections::HashMap;
#[cfg(not(target_arch = "wasm32"))]
use std::io::{BufRead, Write};
use std::rc::Rc;
struct NoImports;
impl ModuleLoader for NoImports {
async fn load_imported_module(
self: Rc<Self>,
_referrer: Referrer,
request: boa_engine::module::ModuleRequest,
_context: &RefCell<&mut Context>,
) -> JsResult<Module> {
let spec = request.specifier().to_std_string_escaped();
Err(JsNativeError::typ().with_message(format!("cannot import `{spec}`: a program imports nothing; `sdk` is a global")).into())
}
}
pub const MAIN_OPEN: &str = "export default async function main() { ";
pub fn module_source(body: &str) -> String {
format!("{MAIN_OPEN}{body}\n}}")
}
pub fn strip_sdk_import(source: &str) -> String {
let mut offset = 0;
for line in source.split_inclusive('\n') {
let trimmed = line.trim_start();
if trimmed.trim_end().is_empty() || trimmed.starts_with("//") {
offset += line.len();
continue;
}
let start = offset + (line.len() - trimmed.len());
let Some(rest) = trimmed.strip_prefix("import") else { break };
if !rest.starts_with(|c: char| c.is_whitespace() || matches!(c, '{' | '*' | '"' | '\'')) {
break;
}
let Some((at, quoted)) = ["\"@brep/cad\"", "'@brep/cad'"].iter().filter_map(|q| rest.find(q).map(|at| (at, *q))).min() else { break };
let clause = rest[..at].trim();
if !(clause.is_empty() || (clause.ends_with("from") && !clause.contains(['"', '\'', ';', '(', '=']))) {
break;
}
let mut end = "import".len() + at + quoted.len();
let tail = &trimmed[end..];
let spaces = tail.len() - tail.trim_start_matches([' ', '\t']).len();
if tail[spaces..].starts_with(';') {
end += spaces + 1;
}
let blank = " ".repeat(trimmed[..end].chars().count());
return format!("{}{blank}{}", &source[..start], &source[start + end..]);
}
source.to_string()
}
const BOOTSTRAP: &str = r#"(() => {
const host = globalThis.__brep_host;
const names = JSON.parse(globalThis.__brep_names);
delete globalThis.__brep_host;
delete globalThis.__brep_names;
const failure = (error) => {
const e = new Error(error && error.message ? error.message : "API failure");
e.name = "ApiFailure";
e.error = error === undefined ? null : error;
return e;
};
const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
const tree = {};
for (const name of names) {
const dot = name.indexOf(".");
if (dot <= 0 || dot === name.length - 1) continue;
const namespace = name.slice(0, dot);
const action = name.slice(dot + 1);
if (!own(tree, namespace)) tree[namespace] = {};
tree[namespace][action] = async (body) => {
const text = JSON.stringify(body === undefined ? {} : body);
if (text === undefined) throw new TypeError("sdk." + name + " takes one JSON value (an object of arguments)");
const reply = JSON.parse(await host(name, text));
if (reply && reply.ok === true) return reply.value;
throw failure(reply ? reply.error : null);
};
}
const passThrough = new Set(["then", "toJSON", "constructor", "valueOf", "toString", "inspect", "prototype", "__proto__", "length", "name"]);
const squash = (k) => k.toLowerCase().replace(/[^a-z0-9]/g, "");
function distance(a, b) {
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let prev = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
prev = row[j];
row[j] = next;
}
}
return row[b.length];
}
// The members of `target` closest to `key`: one spelled another way
// (`massProperties`) first, then by edit distance.
function near(target, key) {
const wanted = squash(key);
return Object.keys(target)
.map((k) => [squash(k) === wanted ? -1 : distance(squash(k), wanted), k])
.filter(([d]) => d <= Math.max(2, Math.floor(key.length / 3)))
.sort((a, b) => a[0] - b[0])
.slice(0, 3)
.map(([, k]) => k);
}
function unknown(namespace, key) {
const hints = [];
const add = (path) => { if (hints.length < 4 && !hints.includes(path)) hints.push(path); };
if (namespace === null) {
for (const k of near(tree, key)) add("sdk." + k);
// A bare action name: say which namespaces hold it.
for (const g of Object.keys(tree)) if (own(tree[g], key)) add("sdk." + g + "." + key);
} else {
const members = tree[namespace];
// The registry's own spelling (`scene_entities`) of `sdk.scene.entities`.
const prefix = namespace + "_";
if (key.startsWith(prefix) && own(members, key.slice(prefix.length))) add("sdk." + namespace + "." + key.slice(prefix.length));
for (const g of Object.keys(tree)) {
if (g !== namespace) for (const m of Object.keys(tree[g])) if (squash(m) === squash(key)) add("sdk." + g + "." + m);
}
for (const k of near(members, key)) add("sdk." + namespace + "." + k);
}
const path = namespace === null ? "sdk." + key : "sdk." + namespace + "." + key;
const listing = namespace === null ? "the `sdk` tool lists the namespaces: sdk({})" : "the `sdk` tool lists this namespace: sdk({topic: \"" + namespace + "\"})";
return path + " does not exist, or is not granted to this program" + (hints.length ? "; did you mean " + hints.join(" or ") + "?" : "") + " (" + listing + ")";
}
const guard = (target, namespace) => new Proxy(target, {
get(t, key, receiver) {
if (typeof key !== "string" || key in t || passThrough.has(key)) return Reflect.get(t, key, receiver);
throw new TypeError(unknown(namespace, key));
},
});
const guarded = {};
for (const namespace of Object.keys(tree)) guarded[namespace] = guard(tree[namespace], namespace);
Object.defineProperty(globalThis, "sdk", { value: guard(guarded, null), writable: false, enumerable: true, configurable: false });
})();
"#;
thread_local! {
static PENDING: RefCell<HashMap<u64, (JsFunction, JsFunction)>> = RefCell::new(HashMap::new());
static NEXT: RefCell<u64> = const { RefCell::new(0) };
static SINK: RefCell<Option<Box<dyn Fn(&Value)>>> = RefCell::new(None);
}
fn emit(line: &Value) {
SINK.with(|s| {
if let Some(sink) = s.borrow().as_ref() {
sink(line);
}
});
}
fn done_error(code: &str, message: String) -> Value {
json!({ "done": { "error": { "code": code, "message": message } } })
}
fn host_call(_: &JsValue, args: &[JsValue], cx: &mut Context) -> JsResult<JsValue> {
let text = |i: usize| args.get(i).and_then(JsValue::as_string).map(|s| s.to_std_string_escaped()).unwrap_or_default();
let method = text(0);
let body: Value = serde_json::from_str(&text(1)).map_err(|e| JsNativeError::typ().with_message(format!("sdk.{method}: the argument is not JSON: {e}")))?;
let (promise, resolvers) = JsPromise::new_pending(cx);
let id = NEXT.with(|n| {
*n.borrow_mut() += 1;
*n.borrow()
});
PENDING.with(|p| p.borrow_mut().insert(id, (resolvers.resolve, resolvers.reject)));
emit(&json!({ "call": id, "method": method, "body": body }));
Ok(promise.into())
}
fn fail(code: &str, e: JsError, cx: &mut Context) -> Value {
let limit = e.as_engine().is_some();
let message = describe(e, cx);
done_error(if limit || message.contains("RuntimeLimitError") { "resource_limit" } else { code }, message)
}
pub fn syntax_help(source: &str, message: &str, first_row_shift: usize) -> String {
let mut out = message.to_string();
let unterminated = message.to_ascii_lowercase().contains("unterminated string literal");
let named = position(message).map(|(row, col)| (row, if row == 1 { col.saturating_sub(first_row_shift) } else { col }));
let (row, col) = named.or_else(|| if unterminated { open_quote(source) } else { None }).unwrap_or((0, 0));
let lines: Vec<&str> = source.lines().collect();
if (1..=lines.len()).contains(&row) {
out.push_str("\n");
for n in row.saturating_sub(1).max(1)..=(row + 1).min(lines.len()) {
let text: String = lines[n - 1].chars().take(160).collect();
out.push_str(&format!("\n{n:>4} | {text}"));
if n == row && col > 0 && col <= 161 {
out.push_str(&format!("\n | {}^", " ".repeat(col - 1)));
}
}
}
if !source.contains('\n') && source.contains("\\n") {
out.push_str("\n\nhint: the program arrived as ONE line holding literal \\n sequences: it was escaped twice. Send real line breaks (one JSON string escape, not two).");
} else if unterminated {
out.push_str("\n\nhint: a '...' or \"...\" string cannot span lines. A program sent inside JSON turns each \\n into a real line break: write \\\\n in the JSON for the two-character escape, or use a template literal `...` for multi-line text (an expressions_set script, say).");
if lines.iter().any(|l| l.contains("n't") || l.contains("'s ")) {
out.push_str(" An apostrophe also ends a '...' string early: use \"...\" or `...` for text containing one.");
}
} else if lines.iter().any(|l| l.starts_with("export ") || l.starts_with("import ")) {
out.push_str("\n\nhint: a program is a script body, not a module: write its statements at the top level with `await` and `return` (the returned value is the result). `sdk` is a global, nothing is imported, and `export` is not valid.");
}
out
}
fn open_quote(source: &str) -> Option<(usize, usize)> {
let (mut row, mut col) = (1usize, 0usize);
let mut quote: Option<(char, usize, usize)> = None;
let (mut template, mut line_comment, mut block_comment, mut escaped) = (false, false, false, false);
let mut prev = '\0';
for ch in source.chars() {
col += 1;
if ch == '\n' {
if quote.is_some() && !escaped { return quote.map(|(_, r, c)| (r, c)); }
row += 1;
col = 0;
line_comment = false;
escaped = false;
prev = ch;
continue;
}
if line_comment {
} else if block_comment {
if prev == '*' && ch == '/' { block_comment = false; }
} else if let Some((q, _, _)) = quote {
if escaped { escaped = false } else if ch == '\\' { escaped = true } else if ch == q { quote = None }
} else if template {
if escaped { escaped = false } else if ch == '\\' { escaped = true } else if ch == '`' { template = false }
} else if prev == '/' && ch == '/' {
line_comment = true;
} else if prev == '/' && ch == '*' {
block_comment = true;
} else if ch == '\'' || ch == '"' {
quote = Some((ch, row, col));
} else if ch == '`' {
template = true;
}
prev = if block_comment && prev == '/' && ch == '*' { '\0' } else { ch };
}
quote.map(|(_, r, c)| (r, c))
}
fn position(message: &str) -> Option<(usize, usize)> {
let digits = |s: &str| -> Option<(usize, usize)> {
let n: String = s.chars().take_while(char::is_ascii_digit).collect();
Some((n.parse().ok()?, n.len()))
};
for (at, _) in message.match_indices("line ") {
let rest = &message[at + 5..];
let Some((row, used)) = digits(rest) else { continue };
let col = rest[used..].find("col").and_then(|c| digits(rest[used + c..].trim_start_matches(|ch: char| !ch.is_ascii_digit()))).map_or(0, |(c, _)| c);
return Some((row, col));
}
None
}
pub struct Realm {
cx: Context,
logs: Logs,
sent: usize,
main: JsPromise,
}
impl Realm {
pub fn begin(start: &str, sink: Box<dyn Fn(&Value)>) -> Option<Realm> {
SINK.with(|s| *s.borrow_mut() = Some(sink));
let start: Value = match serde_json::from_str(start) {
Ok(v) => v,
Err(e) => {
emit(&done_error("internal_error", format!("bad start message: {e}")));
return None;
}
};
let source = strip_sdk_import(start.get("source").and_then(Value::as_str).unwrap_or_default());
let names: Vec<&str> = start.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
let names = Value::from(names).to_string();
let mut cx = match Context::builder().module_loader(Rc::new(NoImports)).build() {
Ok(cx) => cx,
Err(e) => {
emit(&done_error("internal_error", e.to_string()));
return None;
}
};
cx.runtime_limits_mut().set_loop_iteration_limit(crate::LOOP_ITERATION_LIMIT);
cx.runtime_limits_mut().set_recursion_limit(crate::RECURSION_LIMIT);
let logs: Logs = Rc::new(RefCell::new(Vec::new()));
let setup = (|| -> JsResult<()> {
install_console(&mut cx, &logs)?;
cx.register_global_property(js_string!("__brep_names"), js_string!(names), boa_engine::property::Attribute::all())?;
cx.register_global_builtin_callable(js_string!("__brep_host"), 2, NativeFunction::from_fn_ptr(host_call))?;
cx.eval(Source::from_bytes(BOOTSTRAP).with_path(std::path::Path::new("sdk")))?;
Ok(())
})();
if let Err(e) = setup {
let line = done_error("internal_error", describe(e, &mut cx));
return Self::end(&logs, &mut 0, line);
}
let mut sent = 0;
match Self::start_main(&source, &mut cx) {
Ok(main) => {
let mut realm = Realm { cx, logs, sent, main };
if realm.progress() {
None
} else {
Some(realm)
}
}
Err(line) => Self::end(&logs, &mut sent, line),
}
}
fn start_main(source: &str, cx: &mut Context) -> Result<JsPromise, Value> {
let wrapped = module_source(source);
let module = Module::parse(Source::from_bytes(&wrapped).with_path(std::path::Path::new("main.js")), None, cx).map_err(|e| {
let mut line = fail("compile_failed", e, cx);
if let Some(message) = line["done"]["error"]["message"].as_str() {
line["done"]["error"]["message"] = Value::String(syntax_help(source, message, MAIN_OPEN.len()));
}
line
})?;
let evaluated = module.load_link_evaluate(cx);
cx.run_jobs().map_err(|e| fail("job_failed", e, cx))?;
match evaluated.state() {
PromiseState::Fulfilled(_) => {}
PromiseState::Rejected(v) => {
let message = describe(JsError::from_opaque(v), cx);
let code = if message.contains("SyntaxError") { "compile_failed" } else { "script_failed" };
return Err(done_error(code, message));
}
PromiseState::Pending => return Err(done_error("internal_error", "the program's module did not evaluate".into())),
}
let main = module.namespace(cx).get(js_string!("default"), cx).map_err(|e| fail("script_failed", e, cx))?;
let Some(main) = main.as_callable() else {
return Err(done_error("compile_failed", "the program is not a script body (check for an unbalanced `}`)".into()));
};
let returned = main.call(&JsValue::undefined(), &[], cx).map_err(|e| fail("script_failed", e, cx))?;
returned
.as_object()
.and_then(|o| JsPromise::from_object(o.clone()).ok())
.ok_or_else(|| done_error("invalid_arguments", "main() must be async (return a Promise)".into()))
}
pub fn answer(&mut self, message: &str) -> bool {
let Ok(mut msg) = serde_json::from_str::<Value>(message) else { return false };
let Some(id) = msg.get("call").and_then(Value::as_u64) else { return false };
if !msg.get("ok").is_some_and(Value::is_boolean) { return false }
if let Some(reply) = msg.as_object_mut() {
reply.remove("call");
}
let body = msg.to_string();
if let Some((resolve, _)) = PENDING.with(|p| p.borrow_mut().remove(&id)) {
if let Err(e) = resolve.call(&JsValue::undefined(), &[js_string!(body).into()], &mut self.cx) {
let line = fail("job_failed", e, &mut self.cx);
Self::end(&self.logs, &mut self.sent, line);
return true;
}
}
self.progress()
}
pub fn abandon(&mut self) {
Self::end(&self.logs, &mut self.sent, done_error("internal_error", "the host closed the bridge".into()));
}
fn progress(&mut self) -> bool {
if let Err(e) = self.cx.run_jobs() {
let line = fail("job_failed", e, &mut self.cx);
Self::end(&self.logs, &mut self.sent, line);
return true;
}
flush_logs(&self.logs, &mut self.sent);
let line = match self.main.state() {
PromiseState::Fulfilled(v) => match v.to_json(&mut self.cx) {
Ok(json) => json!({ "done": { "ok": json.unwrap_or(Value::Null) } }),
Err(e) => done_error("invalid_arguments", format!("the program's result is not JSON: {}", describe(e, &mut self.cx))),
},
PromiseState::Rejected(v) => {
let message = describe(JsError::from_opaque(v), &mut self.cx);
done_error(if message.contains("RuntimeLimitError") { "resource_limit" } else { "script_failed" }, message)
}
PromiseState::Pending if PENDING.with(|p| p.borrow().is_empty()) => {
done_error("invalid_arguments", "the program is pending without progress: no host call is outstanding and no job can run".into())
}
PromiseState::Pending => return false,
};
Self::end(&self.logs, &mut self.sent, line);
true
}
fn end(logs: &Logs, sent: &mut usize, line: Value) -> Option<Realm> {
flush_logs(logs, sent);
emit(&line);
PENDING.with(|p| p.borrow_mut().clear());
None
}
}
fn flush_logs(logs: &Logs, sent: &mut usize) {
let lines = logs.borrow();
for line in &lines[*sent..] {
emit(&json!({ "log": line }));
}
*sent = lines.len();
}
#[cfg(not(target_arch = "wasm32"))]
pub fn main() {
let stdin = std::io::stdin();
let mut lines = stdin.lock().lines();
let Some(Ok(first)) = lines.next() else { return };
let sink = Box::new(|line: &Value| {
let mut out = std::io::stdout().lock();
let _ = writeln!(out, "{line}");
let _ = out.flush();
});
let Some(mut realm) = Realm::begin(&first, sink) else { return };
loop {
let Some(Ok(line)) = lines.next() else {
realm.abandon();
return;
};
if realm.answer(&line) {
return;
}
}
}