1use crate::{describe, install_console, Logs};
41use boa_engine::builtins::promise::PromiseState;
42use boa_engine::module::{ModuleLoader, Referrer};
43use boa_engine::object::builtins::{JsFunction, JsPromise};
44use boa_engine::{js_string, Context, JsError, JsNativeError, JsResult, JsValue, Module, NativeFunction, Source};
45use serde_json::{json, Value};
46use std::cell::RefCell;
47use std::collections::HashMap;
48#[cfg(not(target_arch = "wasm32"))]
49use std::io::{BufRead, Write};
50use std::rc::Rc;
51
52struct NoImports;
55
56impl ModuleLoader for NoImports {
57 async fn load_imported_module(
58 self: Rc<Self>,
59 _referrer: Referrer,
60 request: boa_engine::module::ModuleRequest,
61 _context: &RefCell<&mut Context>,
62 ) -> JsResult<Module> {
63 let spec = request.specifier().to_std_string_escaped();
64 Err(JsNativeError::typ().with_message(format!("cannot import `{spec}`: a program imports nothing; `sdk` is a global")).into())
65 }
66}
67
68pub const MAIN_OPEN: &str = "export default async function main() { ";
71
72pub fn module_source(body: &str) -> String {
76 format!("{MAIN_OPEN}{body}\n}}")
77}
78
79pub fn strip_sdk_import(source: &str) -> String {
84 let mut offset = 0;
85 for line in source.split_inclusive('\n') {
86 let trimmed = line.trim_start();
87 if trimmed.trim_end().is_empty() || trimmed.starts_with("//") {
88 offset += line.len();
89 continue;
90 }
91 let start = offset + (line.len() - trimmed.len());
92 let Some(rest) = trimmed.strip_prefix("import") else { break };
93 if !rest.starts_with(|c: char| c.is_whitespace() || matches!(c, '{' | '*' | '"' | '\'')) {
94 break;
95 }
96 let Some((at, quoted)) = ["\"@brep/cad\"", "'@brep/cad'"].iter().filter_map(|q| rest.find(q).map(|at| (at, *q))).min() else { break };
97 let clause = rest[..at].trim();
99 if !(clause.is_empty() || (clause.ends_with("from") && !clause.contains(['"', '\'', ';', '(', '=']))) {
100 break;
101 }
102 let mut end = "import".len() + at + quoted.len();
103 let tail = &trimmed[end..];
104 let spaces = tail.len() - tail.trim_start_matches([' ', '\t']).len();
105 if tail[spaces..].starts_with(';') {
106 end += spaces + 1;
107 }
108 let blank = " ".repeat(trimmed[..end].chars().count());
109 return format!("{}{blank}{}", &source[..start], &source[start + end..]);
110 }
111 source.to_string()
112}
113
114const BOOTSTRAP: &str = r#"(() => {
121 const host = globalThis.__brep_host;
122 const names = JSON.parse(globalThis.__brep_names);
123 delete globalThis.__brep_host;
124 delete globalThis.__brep_names;
125 const failure = (error) => {
126 const e = new Error(error && error.message ? error.message : "API failure");
127 e.name = "ApiFailure";
128 e.error = error === undefined ? null : error;
129 return e;
130 };
131 const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
132 const tree = {};
133 for (const name of names) {
134 const dot = name.indexOf(".");
135 if (dot <= 0 || dot === name.length - 1) continue;
136 const namespace = name.slice(0, dot);
137 const action = name.slice(dot + 1);
138 if (!own(tree, namespace)) tree[namespace] = {};
139 tree[namespace][action] = async (body) => {
140 const text = JSON.stringify(body === undefined ? {} : body);
141 if (text === undefined) throw new TypeError("sdk." + name + " takes one JSON value (an object of arguments)");
142 const reply = JSON.parse(await host(name, text));
143 if (reply && reply.ok === true) return reply.value;
144 throw failure(reply ? reply.error : null);
145 };
146 }
147 const passThrough = new Set(["then", "toJSON", "constructor", "valueOf", "toString", "inspect", "prototype", "__proto__", "length", "name"]);
148 const squash = (k) => k.toLowerCase().replace(/[^a-z0-9]/g, "");
149 function distance(a, b) {
150 const row = Array.from({ length: b.length + 1 }, (_, j) => j);
151 for (let i = 1; i <= a.length; i++) {
152 let prev = row[0];
153 row[0] = i;
154 for (let j = 1; j <= b.length; j++) {
155 const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
156 prev = row[j];
157 row[j] = next;
158 }
159 }
160 return row[b.length];
161 }
162 // The members of `target` closest to `key`: one spelled another way
163 // (`massProperties`) first, then by edit distance.
164 function near(target, key) {
165 const wanted = squash(key);
166 return Object.keys(target)
167 .map((k) => [squash(k) === wanted ? -1 : distance(squash(k), wanted), k])
168 .filter(([d]) => d <= Math.max(2, Math.floor(key.length / 3)))
169 .sort((a, b) => a[0] - b[0])
170 .slice(0, 3)
171 .map(([, k]) => k);
172 }
173 function unknown(namespace, key) {
174 const hints = [];
175 const add = (path) => { if (hints.length < 4 && !hints.includes(path)) hints.push(path); };
176 if (namespace === null) {
177 for (const k of near(tree, key)) add("sdk." + k);
178 // A bare action name: say which namespaces hold it.
179 for (const g of Object.keys(tree)) if (own(tree[g], key)) add("sdk." + g + "." + key);
180 } else {
181 const members = tree[namespace];
182 // The registry's own spelling (`scene_entities`) of `sdk.scene.entities`.
183 const prefix = namespace + "_";
184 if (key.startsWith(prefix) && own(members, key.slice(prefix.length))) add("sdk." + namespace + "." + key.slice(prefix.length));
185 for (const g of Object.keys(tree)) {
186 if (g !== namespace) for (const m of Object.keys(tree[g])) if (squash(m) === squash(key)) add("sdk." + g + "." + m);
187 }
188 for (const k of near(members, key)) add("sdk." + namespace + "." + k);
189 }
190 const path = namespace === null ? "sdk." + key : "sdk." + namespace + "." + key;
191 const listing = namespace === null ? "the `sdk` tool lists the namespaces: sdk({})" : "the `sdk` tool lists this namespace: sdk({topic: \"" + namespace + "\"})";
192 return path + " does not exist, or is not granted to this program" + (hints.length ? "; did you mean " + hints.join(" or ") + "?" : "") + " (" + listing + ")";
193 }
194 const guard = (target, namespace) => new Proxy(target, {
195 get(t, key, receiver) {
196 if (typeof key !== "string" || key in t || passThrough.has(key)) return Reflect.get(t, key, receiver);
197 throw new TypeError(unknown(namespace, key));
198 },
199 });
200 const guarded = {};
201 for (const namespace of Object.keys(tree)) guarded[namespace] = guard(tree[namespace], namespace);
202 Object.defineProperty(globalThis, "sdk", { value: guard(guarded, null), writable: false, enumerable: true, configurable: false });
203})();
204"#;
205
206thread_local! {
207 static PENDING: RefCell<HashMap<u64, (JsFunction, JsFunction)>> = RefCell::new(HashMap::new());
208 static NEXT: RefCell<u64> = const { RefCell::new(0) };
209 static SINK: RefCell<Option<Box<dyn Fn(&Value)>>> = RefCell::new(None);
212}
213
214fn emit(line: &Value) {
215 SINK.with(|s| {
216 if let Some(sink) = s.borrow().as_ref() {
217 sink(line);
218 }
219 });
220}
221
222fn done_error(code: &str, message: String) -> Value {
223 json!({ "done": { "error": { "code": code, "message": message } } })
224}
225
226fn host_call(_: &JsValue, args: &[JsValue], cx: &mut Context) -> JsResult<JsValue> {
230 let text = |i: usize| args.get(i).and_then(JsValue::as_string).map(|s| s.to_std_string_escaped()).unwrap_or_default();
231 let method = text(0);
232 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}")))?;
233 let (promise, resolvers) = JsPromise::new_pending(cx);
234 let id = NEXT.with(|n| {
235 *n.borrow_mut() += 1;
236 *n.borrow()
237 });
238 PENDING.with(|p| p.borrow_mut().insert(id, (resolvers.resolve, resolvers.reject)));
239 emit(&json!({ "call": id, "method": method, "body": body }));
240 Ok(promise.into())
241}
242
243fn fail(code: &str, e: JsError, cx: &mut Context) -> Value {
246 let limit = e.as_engine().is_some();
247 let message = describe(e, cx);
248 done_error(if limit || message.contains("RuntimeLimitError") { "resource_limit" } else { code }, message)
249}
250
251pub fn syntax_help(source: &str, message: &str, first_row_shift: usize) -> String {
259 let mut out = message.to_string();
260 let unterminated = message.to_ascii_lowercase().contains("unterminated string literal");
261 let named = position(message).map(|(row, col)| (row, if row == 1 { col.saturating_sub(first_row_shift) } else { col }));
264 let (row, col) = named.or_else(|| if unterminated { open_quote(source) } else { None }).unwrap_or((0, 0));
265 let lines: Vec<&str> = source.lines().collect();
266 if (1..=lines.len()).contains(&row) {
267 out.push_str("\n");
268 for n in row.saturating_sub(1).max(1)..=(row + 1).min(lines.len()) {
269 let text: String = lines[n - 1].chars().take(160).collect();
270 out.push_str(&format!("\n{n:>4} | {text}"));
271 if n == row && col > 0 && col <= 161 {
272 out.push_str(&format!("\n | {}^", " ".repeat(col - 1)));
273 }
274 }
275 }
276 if !source.contains('\n') && source.contains("\\n") {
277 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).");
278 } else if unterminated {
279 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).");
280 if lines.iter().any(|l| l.contains("n't") || l.contains("'s ")) {
281 out.push_str(" An apostrophe also ends a '...' string early: use \"...\" or `...` for text containing one.");
282 }
283 } else if lines.iter().any(|l| l.starts_with("export ") || l.starts_with("import ")) {
284 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.");
285 }
286 out
287}
288
289fn open_quote(source: &str) -> Option<(usize, usize)> {
294 let (mut row, mut col) = (1usize, 0usize);
295 let mut quote: Option<(char, usize, usize)> = None;
296 let (mut template, mut line_comment, mut block_comment, mut escaped) = (false, false, false, false);
297 let mut prev = '\0';
298 for ch in source.chars() {
299 col += 1;
300 if ch == '\n' {
301 if quote.is_some() && !escaped { return quote.map(|(_, r, c)| (r, c)); }
302 row += 1;
303 col = 0;
304 line_comment = false;
305 escaped = false;
306 prev = ch;
307 continue;
308 }
309 if line_comment {
310 } else if block_comment {
311 if prev == '*' && ch == '/' { block_comment = false; }
312 } else if let Some((q, _, _)) = quote {
313 if escaped { escaped = false } else if ch == '\\' { escaped = true } else if ch == q { quote = None }
314 } else if template {
315 if escaped { escaped = false } else if ch == '\\' { escaped = true } else if ch == '`' { template = false }
316 } else if prev == '/' && ch == '/' {
317 line_comment = true;
318 } else if prev == '/' && ch == '*' {
319 block_comment = true;
320 } else if ch == '\'' || ch == '"' {
321 quote = Some((ch, row, col));
322 } else if ch == '`' {
323 template = true;
324 }
325 prev = if block_comment && prev == '/' && ch == '*' { '\0' } else { ch };
326 }
327 quote.map(|(_, r, c)| (r, c))
328}
329
330fn position(message: &str) -> Option<(usize, usize)> {
332 let digits = |s: &str| -> Option<(usize, usize)> {
333 let n: String = s.chars().take_while(char::is_ascii_digit).collect();
334 Some((n.parse().ok()?, n.len()))
335 };
336 for (at, _) in message.match_indices("line ") {
337 let rest = &message[at + 5..];
338 let Some((row, used)) = digits(rest) else { continue };
339 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);
340 return Some((row, col));
341 }
342 None
343}
344
345pub struct Realm {
347 cx: Context,
348 logs: Logs,
349 sent: usize,
350 main: JsPromise,
351}
352
353impl Realm {
354 pub fn begin(start: &str, sink: Box<dyn Fn(&Value)>) -> Option<Realm> {
358 SINK.with(|s| *s.borrow_mut() = Some(sink));
359 let start: Value = match serde_json::from_str(start) {
360 Ok(v) => v,
361 Err(e) => {
362 emit(&done_error("internal_error", format!("bad start message: {e}")));
363 return None;
364 }
365 };
366 let source = strip_sdk_import(start.get("source").and_then(Value::as_str).unwrap_or_default());
367 let names: Vec<&str> = start.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
370 let names = Value::from(names).to_string();
371 let mut cx = match Context::builder().module_loader(Rc::new(NoImports)).build() {
372 Ok(cx) => cx,
373 Err(e) => {
374 emit(&done_error("internal_error", e.to_string()));
375 return None;
376 }
377 };
378 cx.runtime_limits_mut().set_loop_iteration_limit(crate::LOOP_ITERATION_LIMIT);
379 cx.runtime_limits_mut().set_recursion_limit(crate::RECURSION_LIMIT);
380 let logs: Logs = Rc::new(RefCell::new(Vec::new()));
381 let setup = (|| -> JsResult<()> {
382 install_console(&mut cx, &logs)?;
383 cx.register_global_property(js_string!("__brep_names"), js_string!(names), boa_engine::property::Attribute::all())?;
384 cx.register_global_builtin_callable(js_string!("__brep_host"), 2, NativeFunction::from_fn_ptr(host_call))?;
385 cx.eval(Source::from_bytes(BOOTSTRAP).with_path(std::path::Path::new("sdk")))?;
386 Ok(())
387 })();
388 if let Err(e) = setup {
389 let line = done_error("internal_error", describe(e, &mut cx));
390 return Self::end(&logs, &mut 0, line);
391 }
392 let mut sent = 0;
393 match Self::start_main(&source, &mut cx) {
394 Ok(main) => {
395 let mut realm = Realm { cx, logs, sent, main };
396 if realm.progress() {
397 None
398 } else {
399 Some(realm)
400 }
401 }
402 Err(line) => Self::end(&logs, &mut sent, line),
403 }
404 }
405
406 fn start_main(source: &str, cx: &mut Context) -> Result<JsPromise, Value> {
409 let wrapped = module_source(source);
410 let module = Module::parse(Source::from_bytes(&wrapped).with_path(std::path::Path::new("main.js")), None, cx).map_err(|e| {
411 let mut line = fail("compile_failed", e, cx);
412 if let Some(message) = line["done"]["error"]["message"].as_str() {
413 line["done"]["error"]["message"] = Value::String(syntax_help(source, message, MAIN_OPEN.len()));
414 }
415 line
416 })?;
417 let evaluated = module.load_link_evaluate(cx);
418 cx.run_jobs().map_err(|e| fail("job_failed", e, cx))?;
419 match evaluated.state() {
420 PromiseState::Fulfilled(_) => {}
421 PromiseState::Rejected(v) => {
422 let message = describe(JsError::from_opaque(v), cx);
424 let code = if message.contains("SyntaxError") { "compile_failed" } else { "script_failed" };
425 return Err(done_error(code, message));
426 }
427 PromiseState::Pending => return Err(done_error("internal_error", "the program's module did not evaluate".into())),
428 }
429 let main = module.namespace(cx).get(js_string!("default"), cx).map_err(|e| fail("script_failed", e, cx))?;
430 let Some(main) = main.as_callable() else {
433 return Err(done_error("compile_failed", "the program is not a script body (check for an unbalanced `}`)".into()));
434 };
435 let returned = main.call(&JsValue::undefined(), &[], cx).map_err(|e| fail("script_failed", e, cx))?;
436 returned
437 .as_object()
438 .and_then(|o| JsPromise::from_object(o.clone()).ok())
439 .ok_or_else(|| done_error("invalid_arguments", "main() must be async (return a Promise)".into()))
440 }
441
442 pub fn answer(&mut self, message: &str) -> bool {
447 let Ok(mut msg) = serde_json::from_str::<Value>(message) else { return false };
448 let Some(id) = msg.get("call").and_then(Value::as_u64) else { return false };
449 if !msg.get("ok").is_some_and(Value::is_boolean) { return false }
450 if let Some(reply) = msg.as_object_mut() {
451 reply.remove("call");
452 }
453 let body = msg.to_string();
454 if let Some((resolve, _)) = PENDING.with(|p| p.borrow_mut().remove(&id)) {
455 if let Err(e) = resolve.call(&JsValue::undefined(), &[js_string!(body).into()], &mut self.cx) {
456 let line = fail("job_failed", e, &mut self.cx);
457 Self::end(&self.logs, &mut self.sent, line);
458 return true;
459 }
460 }
461 self.progress()
462 }
463
464 pub fn abandon(&mut self) {
466 Self::end(&self.logs, &mut self.sent, done_error("internal_error", "the host closed the bridge".into()));
467 }
468
469 fn progress(&mut self) -> bool {
472 if let Err(e) = self.cx.run_jobs() {
473 let line = fail("job_failed", e, &mut self.cx);
474 Self::end(&self.logs, &mut self.sent, line);
475 return true;
476 }
477 flush_logs(&self.logs, &mut self.sent);
478 let line = match self.main.state() {
479 PromiseState::Fulfilled(v) => match v.to_json(&mut self.cx) {
480 Ok(json) => json!({ "done": { "ok": json.unwrap_or(Value::Null) } }),
481 Err(e) => done_error("invalid_arguments", format!("the program's result is not JSON: {}", describe(e, &mut self.cx))),
482 },
483 PromiseState::Rejected(v) => {
484 let message = describe(JsError::from_opaque(v), &mut self.cx);
485 done_error(if message.contains("RuntimeLimitError") { "resource_limit" } else { "script_failed" }, message)
486 }
487 PromiseState::Pending if PENDING.with(|p| p.borrow().is_empty()) => {
488 done_error("invalid_arguments", "the program is pending without progress: no host call is outstanding and no job can run".into())
489 }
490 PromiseState::Pending => return false,
492 };
493 Self::end(&self.logs, &mut self.sent, line);
494 true
495 }
496
497 fn end(logs: &Logs, sent: &mut usize, line: Value) -> Option<Realm> {
500 flush_logs(logs, sent);
501 emit(&line);
502 PENDING.with(|p| p.borrow_mut().clear());
503 None
504 }
505}
506
507fn flush_logs(logs: &Logs, sent: &mut usize) {
508 let lines = logs.borrow();
509 for line in &lines[*sent..] {
510 emit(&json!({ "log": line }));
511 }
512 *sent = lines.len();
513}
514
515#[cfg(not(target_arch = "wasm32"))]
518pub fn main() {
519 let stdin = std::io::stdin();
520 let mut lines = stdin.lock().lines();
521 let Some(Ok(first)) = lines.next() else { return };
522 let sink = Box::new(|line: &Value| {
523 let mut out = std::io::stdout().lock();
524 let _ = writeln!(out, "{line}");
525 let _ = out.flush();
526 });
527 let Some(mut realm) = Realm::begin(&first, sink) else { return };
528 loop {
529 let Some(Ok(line)) = lines.next() else {
530 realm.abandon();
531 return;
532 };
533 if realm.answer(&line) {
534 return;
535 }
536 }
537}
538