Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

3.6 KB
Raw Blame
//! raea's native-call registry: every name TypeScript can reach Rust by (`__raea_call(name, json) -> json`), registered
//! once with the TypeScript types of its arguments and answer by whichever crate implements it. `typescript()` writes
//! the types the SDK imports, so a call that doesn't exist, or takes the wrong arguments, fails to type-check. It needs
//! no JS engine: raea-native binds it into JavaScriptCore and seeds it with the shell's own calls.

use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock, RwLock};

use serde_json::Value;

pub type R<T> = Result<T, String>;

/// A native call's handler: JSON arguments in, a JSON answer or a message out.
pub type Handler = Arc<dyn Fn(&Value) -> R<Value> + Send + Sync>;

/// One registered call.
#[derive(Clone)]
pub struct Call {
    pub name: String,
    /// TypeScript type of the arguments object
    pub args: String,
    /// TypeScript type of the answer
    pub answer: String,
    /// one line for the generated types
    pub doc: String,
    pub f: Handler,
}

impl Call {
    pub fn new(name: &str, args: &str, answer: &str, doc: &str, f: Handler) -> Call {
        Call { name: name.into(), args: args.into(), answer: answer.into(), doc: doc.into(), f }
    }
}


fn table() -> &'static RwLock<BTreeMap<String, Call>> {
    static T: OnceLock<RwLock<BTreeMap<String, Call>>> = OnceLock::new();
    T.get_or_init(|| RwLock::new(BTreeMap::new()))
}

/// Registers every call in `all` (replacing any of the same name).
pub fn register_all(all: impl IntoIterator<Item = Call>) {
    let mut t = table().write().unwrap();
    for c in all {
        t.insert(c.name.clone(), c);
    }
}

/// Registers (or replaces) a call.
pub fn register(name: &str, args: &str, answer: &str, doc: &str, f: impl Fn(&Value) -> R<Value> + Send + Sync + 'static) {
    table().write().unwrap().insert(name.into(), Call::new(name, args, answer, doc, Arc::new(f)));
}

/// Whether `name` is registered.
pub fn has(name: &str) -> bool {
    table().read().unwrap().contains_key(name)
}

/// Runs a call; an unknown name says so.
pub fn call(name: &str, args: &Value) -> R<Value> {
    let f = table().read().unwrap().get(name).map(|c| c.f.clone());
    match f {
        Some(f) => f(args),
        None => Err(format!("no native call \"{name}\" in this host")),
    }
}

/// Every registered call, by name.
pub fn calls() -> Vec<Call> {
    table().read().unwrap().values().cloned().collect()
}

/// The TypeScript the SDK imports (sdk/raea/src/native-calls.ts): one entry per call, its arguments and answer.
pub fn typescript() -> String {
    let mut out = String::from(
        "// Generated by `raea types` from raea's native-call registry (every host's calls); don't edit by hand.\n\
         // native(name, args) is typed by this table: a call that isn't registered, or wrong arguments, fails to check.\n\n\
         export interface NativeCalls {\n",
    );
    for c in calls() {
        if !c.doc.is_empty() {
            out += &format!("  /** {} */\n", c.doc);
        }
        out += &format!("  {:?}: {{ args: {}; answer: {} }};\n", c.name, c.args, c.answer);
    }
    out += "}\n\nexport type NativeName = keyof NativeCalls;\n";
    out
}

/// A string argument.
pub fn s<'a>(v: &'a Value, k: &str) -> R<&'a str> {
    v.get(k).and_then(Value::as_str).ok_or_else(|| format!("{k}: a string"))
}

/// Bytes as standard base64, and back.
pub fn enc64(b: &[u8]) -> String {
    use base64::Engine as _;
    base64::engine::general_purpose::STANDARD.encode(b)
}
pub fn dec64(t: &str) -> R<Vec<u8>> {
    use base64::Engine as _;
    base64::engine::general_purpose::STANDARD.decode(t).map_err(|e| e.to_string())
}