Skip to main content

xmachines_runtime_node/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::any::Any;
4use std::cell::{Cell, RefCell};
5use std::collections::{HashMap, HashSet};
6use std::panic::{self, AssertUnwindSafe};
7use std::sync::Arc;
8
9use napi::bindgen_prelude::{
10    Either, FnArgs, FromNapiValue, Function, FunctionRef, JsObjectValue, Object, ToNapiValue, Undefined, Unknown,
11};
12use napi::{sys, Env, JsValue, ValueType};
13use napi_derive::napi;
14use serde_json::{json, Map, Value};
15use xmachines_runtime::host::{apply_error_json, apply_json, parse_json, system_emitted_json, LoadOptions};
16use xmachines_runtime::step::async_logic;
17use xmachines_runtime::work::ApplyError;
18use xmachines_runtime::{Actor as RtActor, HostActions, HostEvaluator, Logic, Machine as RtMachine, Registry};
19
20/// Children may invoke children; a cycle of child definitions is an error.
21const MAX_CHILD_DEPTH: usize = 32;
22
23/// `params` as the callbacks see them: `undefined` when the reference has none.
24fn params_arg(p: &Value) -> Either<String, Undefined> {
25    if p.is_null() {
26        Either::B(())
27    } else {
28        Either::A(p.to_string())
29    }
30}
31
32/// An optional JSON argument: `undefined` when absent.
33fn optional_arg(v: Option<String>) -> Either<String, Undefined> {
34    v.map_or(Either::B(()), Either::A)
35}
36
37// ---------------------------------------------------------------------------
38// Calling JavaScript from the runtime
39
40type GuardRef = FunctionRef<FnArgs<(String, Either<String, Undefined>, String, String)>, Unknown<'static>>;
41type ActionRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
42type DelayRef = FunctionRef<FnArgs<(String, String, String)>, Unknown<'static>>;
43type ExprRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
44type ContextExprRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
45type EvaluateRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
46
47/// The `implementations` callbacks of one actor, each bound to the object it
48/// came from (so they may use `this`). The registry closures share them.
49#[derive(Default)]
50struct Callbacks {
51    guard: Option<GuardRef>,
52    action: Option<ActionRef>,
53    delay: Option<DelayRef>,
54    expr: Option<ExprRef>,
55    context_expr: Option<ContextExprRef>,
56    evaluate: Option<EvaluateRef>,
57}
58
59/// One callback of `implementations`, bound to it: `None` when absent
60/// (`undefined` or `null`), an error when it is not a function.
61fn callback<Args, Return>(object: &Object, key: &str) -> napi::Result<Option<FunctionRef<Args, Return>>>
62where
63    Args: napi::bindgen_prelude::JsValuesTupleIntoVec,
64    Return: napi::bindgen_prelude::FromNapiValue,
65{
66    let Some(value) = object.get::<Unknown>(key)? else { return Ok(None) };
67    match value.get_type()? {
68        ValueType::Undefined | ValueType::Null => Ok(None),
69        ValueType::Function => {
70            // SAFETY: the value was just checked to be a function.
71            let f: Function<Args, Return> = unsafe { value.cast()? };
72            Ok(Some(f.bind(object)?.create_ref()?))
73        }
74        _ => Err(napi::Error::from_reason(format!("implementations.{key} must be a function"))),
75    }
76}
77
78impl Callbacks {
79    fn from_js(implementations: Option<Object>) -> napi::Result<Self> {
80        let Some(o) = implementations else { return Ok(Self::default()) };
81        Ok(Self {
82            guard: callback(&o, "guard")?,
83            action: callback(&o, "action")?,
84            delay: callback(&o, "delay")?,
85            expr: callback(&o, "expr")?,
86            context_expr: callback(&o, "contextExpr")?,
87            evaluate: callback(&o, "evaluate")?,
88        })
89    }
90}
91
92thread_local! {
93    /// The `Env` of the actor call in progress on this thread (calls nest when
94    /// a callback calls another actor).
95    static ENV: Cell<Option<sys::napi_env>> = const { Cell::new(None) };
96}
97
98/// Runs `f` with the current call's `Env`, in a handle scope of its own so that
99/// a long step does not pile up handles. A callback that throws, or returns
100/// what it must not, is the message of that error, which the runtime handles
101/// as XState handles an exception thrown there.
102fn call_js<T>(f: impl FnOnce(&Env) -> napi::Result<T>) -> Result<T, String> {
103    let Some(raw) = ENV.with(Cell::get) else {
104        return Err("an implementation was called outside a call into the actor".into());
105    };
106    let env = Env::from_raw(raw);
107    env.run_in_scope(|| Ok(f(&env).map_err(|e| thrown_message(&env, e)))).unwrap_or_else(|e| Err(e.reason))
108}
109
110/// The message of what a callback threw: an error's `message`, the text of
111/// anything else (as `@xmachines/run`'s `jsEvaluate` reports what code
112/// throws). A failure of the addon's own is its reason.
113fn thrown_message(env: &Env, error: napi::Error) -> String {
114    let reason = error.reason.clone();
115    let message = || -> napi::Result<String> {
116        // SAFETY: `env` is the current call's, and the value is read at once.
117        let value = unsafe { Unknown::from_napi_value(env.raw(), ToNapiValue::to_napi_value(env.raw(), error)?)? };
118        if value.get_type()? == ValueType::Object {
119            // SAFETY: the value was just checked to be an object.
120            let object: Object = unsafe { value.cast()? };
121            if let Some(message) = object.get::<Unknown>("message")? {
122                if message.get_type()? == ValueType::String {
123                    // SAFETY: the value was just checked to be a string.
124                    return unsafe { message.cast::<String>() };
125                }
126            }
127        }
128        value.coerce_to_string()?.into_utf8()?.into_owned()
129    };
130    message().unwrap_or(reason)
131}
132
133/// A callback's JSON text result (`expr`, `contextExpr`): `null` when it does
134/// not parse, as in the WASI component.
135fn json_result(what: &str, name: &str, value: Unknown) -> napi::Result<Value> {
136    if value.get_type()? != ValueType::String {
137        return Err(napi::Error::from_reason(format!("{what} \"{name}\" must return a JSON string")));
138    }
139    // SAFETY: the value was just checked to be a string.
140    let text: String = unsafe { value.cast()? };
141    Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
142}
143
144/// What a callback that a definition needs but `implementations` lacks is
145/// reported as.
146fn missing(kind: &str, name: &str, key: &str) -> String {
147    format!("the definition references {kind} \"{name}\" but implementations.{key} is missing")
148}
149
150/// The child machines of the options, each compiled once (by its source).
151type Compiled = HashMap<String, Arc<dyn Logic>>;
152
153/// Compiles a definition, wiring every name it references to the callbacks and
154/// every invoke source to a child machine or to host async work. A custom
155/// action of `host_actions` is left to the host, so it is bound to no callback.
156fn compile(
157    definition: &Value,
158    children: &Map<String, Value>,
159    host_actions: &HostActions,
160    callbacks: &Arc<Callbacks>,
161    compiled: &mut Compiled,
162    depth: usize,
163) -> Result<RtMachine<Value, Value>, String> {
164    if depth > MAX_CHILD_DEPTH {
165        return Err("child machines are nested too deeply (a child invokes itself?)".into());
166    }
167    let refs = RtMachine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
168    let mut registry: Registry<Value, Value> = Registry::new();
169    registry.host_actions(host_actions.clone());
170    let mut seen = HashSet::new();
171    for r in &refs.guards {
172        if seen.insert(("guard", r.name.clone())) {
173            if callbacks.guard.is_none() {
174                return Err(missing("guard", &r.name, "guard"));
175            }
176            let (name, cb) = (r.name.clone(), callbacks.clone());
177            registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
178                let args = (name.clone(), params_arg(p), args.context.to_string(), args.event.to_json().to_string());
179                call_js(|env| cb.guard.as_ref().unwrap().borrow_back(env)?.call(args.into())?.coerce_to_bool())
180            });
181        }
182    }
183    for r in &refs.actions {
184        // Bound to the callback unless the host does it (with `true`, none
185        // is bound, so every custom action is unimplemented and the host's).
186        if host_actions != &HostActions::Unimplemented
187            && !host_actions.includes(&r.name, false)
188            && seen.insert(("action", r.name.clone()))
189        {
190            if callbacks.action.is_none() {
191                return Err(missing("action", &r.name, "action"));
192            }
193            let (name, cb) = (r.name.clone(), callbacks.clone());
194            registry.try_action_with(r.name.clone(), move |p: &Value| {
195                let args = (name.clone(), params_arg(p));
196                call_js(|env| cb.action.as_ref().unwrap().borrow_back(env)?.call(args.into()).map(drop))
197            });
198        }
199    }
200    for r in &refs.delays {
201        if seen.insert(("delay", r.name.clone())) {
202            if callbacks.delay.is_none() {
203                return Err(missing("delay", &r.name, "delay"));
204            }
205            let (name, cb) = (r.name.clone(), callbacks.clone());
206            registry.try_delay(r.name.clone(), move |context, event| {
207                let args = (name.clone(), context.to_string(), event.to_json().to_string());
208                call_js(|env| {
209                    let result = cb.delay.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
210                    let ms = match result.get_type()? {
211                        // SAFETY: the value was just checked to be a number.
212                        ValueType::Number => unsafe { result.cast::<f64>()? },
213                        _ => f64::NAN,
214                    };
215                    if !(ms.is_finite() && ms >= 0.0) {
216                        return Err(napi::Error::from_reason(format!(
217                            "delay \"{name}\" must return a non-negative number of milliseconds"
218                        )));
219                    }
220                    // Fractional milliseconds round up, like numeric `after` keys.
221                    Ok(ms.ceil() as u64)
222                })
223            });
224        }
225    }
226    for r in &refs.exprs {
227        if callbacks.expr.is_none() {
228            return Err(missing("expression", &r.name, "expr"));
229        }
230        let (name, cb) = (r.name.clone(), callbacks.clone());
231        registry.expr(r.name.clone(), move |args| {
232            let mut scope = json!({ "context": args.context, "event": args.event.to_json() });
233            if let Some(params) = args.params {
234                scope["params"] = params.clone();
235            }
236            let call = (name.clone(), scope.to_string());
237            let result = call_js(|env| {
238                json_result("expr", &name, cb.expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?)
239            });
240            result.unwrap_or_else(|message| {
241                args.fail(message);
242                Value::Null
243            })
244        });
245    }
246    for r in &refs.contexts {
247        if callbacks.context_expr.is_none() {
248            return Err(missing("context expression", &r.name, "contextExpr"));
249        }
250        let (name, cb) = (r.name.clone(), callbacks.clone());
251        registry.context_with(r.name.clone(), move |args| {
252            let call = (name.clone(), optional_arg(args.input.map(Value::to_string)));
253            let result = call_js(|env| {
254                let result = cb.context_expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?;
255                json_result("contextExpr", &name, result)
256            });
257            result.unwrap_or_else(|message| {
258                args.fail(message);
259                Value::Null
260            })
261        });
262    }
263    for r in &refs.languages {
264        if callbacks.evaluate.is_none() {
265            return Err(missing("code in language", &r.name, "evaluate"));
266        }
267        let cb = callbacks.clone();
268        registry.evaluator(
269            r.name.clone(),
270            HostEvaluator(move |code: &str, scope: &str| {
271                let args = (code.to_owned(), scope.to_owned());
272                let result = call_js(|env| {
273                    let result = cb.evaluate.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
274                    if result.get_type()? != ValueType::String {
275                        return Err(napi::Error::from_reason("evaluate must return a JSON string"));
276                    }
277                    // SAFETY: the value was just checked to be a string.
278                    unsafe { result.cast::<String>() }
279                });
280                // What the callback throws is what the code threw.
281                result.unwrap_or_else(|error| json!({ "error": error }).to_string())
282            }),
283        );
284    }
285    for r in &refs.actors {
286        if seen.insert(("actor", r.name.clone())) {
287            let logic: Arc<dyn Logic> = match children.get(&r.name) {
288                Some(child) => compile_child(&r.name, child, children, host_actions, callbacks, compiled, depth + 1)?,
289                None => Arc::new(async_logic(Some(r.name.clone()), None).map_err(|e| e.to_string())?),
290            };
291            registry.actor(r.name.clone(), logic);
292        }
293    }
294    if depth == 0 {
295        // Every child machine is loaded, whether the definition invokes it
296        // or not, and the root may spawn any of them.
297        for (src, child) in children {
298            if seen.insert(("actor", src.clone())) {
299                registry.actor(src.clone(), compile_child(src, child, children, host_actions, callbacks, compiled, 1)?);
300            }
301        }
302    }
303    RtMachine::from_json(definition, &registry).map_err(|e| e.to_string())
304}
305
306/// Loads `definition` with its load options, compiled once. Options that do
307/// not parse are `WORKFLOW_INVALID_INPUT`; a definition that is not JSON or
308/// does not compile, a child's among them, is `WORKFLOW_INVALID_MACHINE`.
309fn load(definition: &str, options: &str, callbacks: &Arc<Callbacks>) -> Result<Machine, ApplyError> {
310    let options = LoadOptions::parse_contract(options, true)?;
311    let definition = parse_json("definition", definition).map_err(ApplyError::invalid_machine)?;
312    let mut compiled = Compiled::new();
313    let machine = compile(&definition, &options.children, &options.host_actions, callbacks, &mut compiled, 0)
314        .map_err(ApplyError::invalid_machine)?;
315    Ok(Machine { machine: Arc::new(machine), options })
316}
317
318/// The child machine for `invoke.src` `src`, compiled the first time.
319fn compile_child(
320    src: &str,
321    child: &Value,
322    children: &Map<String, Value>,
323    host_actions: &HostActions,
324    callbacks: &Arc<Callbacks>,
325    compiled: &mut Compiled,
326    depth: usize,
327) -> Result<Arc<dyn Logic>, String> {
328    if let Some(logic) = compiled.get(src) {
329        return Ok(logic.clone());
330    }
331    let machine = compile(child, children, host_actions, callbacks, compiled, depth)
332        .map_err(|e| format!("child \"{src}\": {e}"))?;
333    let logic: Arc<dyn Logic> = Arc::new(machine);
334    compiled.insert(src.to_owned(), logic.clone());
335    Ok(logic)
336}
337
338/// The largest whole number a JavaScript number holds exactly, `2^53 - 1`.
339const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
340
341/// `now` from JavaScript: a whole number of milliseconds, at most `2^53 - 1`.
342/// A fraction is refused, not dropped, as the contract's time inputs are:
343/// the error is the contract's `WORKFLOW_INVALID_INPUT`, as JSON text.
344fn millis(now: f64) -> Result<u64, String> {
345    if now.is_finite() && now >= 0.0 && now.fract() == 0.0 && now <= MAX_SAFE {
346        Ok(now as u64)
347    } else {
348        Err(apply_error_json(&ApplyError::invalid_input(
349            "now must be a whole number of milliseconds, at most 2^53 - 1",
350        )))
351    }
352}
353
354/// How a call into the runtime went wrong.
355enum Failure {
356    /// The runtime returned an error (a failed step among them); the actor is
357    /// still usable.
358    Error(String),
359    /// The runtime panicked, part way through a step.
360    Fatal(napi::Error),
361}
362
363fn panic_message(payload: &(dyn Any + Send)) -> String {
364    if let Some(s) = payload.downcast_ref::<&str>() {
365        (*s).to_owned()
366    } else if let Some(s) = payload.downcast_ref::<String>() {
367        s.clone()
368    } else {
369        "unknown panic".to_owned()
370    }
371}
372
373/// Runs `f` with `env` reachable to the callbacks, catching any panic, which
374/// must not unwind into Node.
375fn run<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> Result<T, Failure> {
376    struct Restore(Option<sys::napi_env>);
377    impl Drop for Restore {
378        fn drop(&mut self) {
379            ENV.with(|e| e.set(self.0));
380        }
381    }
382    let _restore = Restore(ENV.with(|e| e.replace(Some(env.raw()))));
383    match panic::catch_unwind(AssertUnwindSafe(f)) {
384        Ok(result) => result.map_err(Failure::Error),
385        Err(payload) => {
386            Err(Failure::Fatal(napi::Error::from_reason(format!("internal error: {}", panic_message(&*payload)))))
387        }
388    }
389}
390
391/// For `load`, `start` and `restore`, where a failure leaves nothing behind:
392/// `f` gives the contract's error as JSON text, which throws as
393/// [`contract_error`] makes it.
394fn construct<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> napi::Result<T> {
395    match run(env, || Ok(f())) {
396        Ok(Ok(value)) => Ok(value),
397        Ok(Err(error)) => Err(contract_error(env, &error)),
398        Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
399        Err(Failure::Fatal(e)) => Err(e),
400    }
401}
402
403/// The code of the error a rejected chunk throws, next to its `rejected`.
404pub const REJECTED: &str = "WORKFLOW_REJECTED";
405
406/// The contract's error, as JSON text, as the error JavaScript sees. A fault,
407/// `{ "code", "message" }`, is an `Error` of that `code` and `message`. A
408/// rejection, `{ "rejected": { "message", "data"? } }`, is an `Error` whose
409/// `code` is `WORKFLOW_REJECTED` ([`REJECTED`]), whose `message` is the
410/// rejection's, and whose `rejected` is the rejection itself, its `data`
411/// among it.
412fn contract_error(env: &Env, text: &str) -> napi::Error {
413    let error: Value = serde_json::from_str(text).unwrap_or_default();
414    let field = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_owned();
415    let rejected = error.get("rejected");
416    let (code, message) = match rejected {
417        Some(rejected) => (REJECTED.to_owned(), field(rejected, "message")),
418        None => (field(&error, "code"), field(&error, "message")),
419    };
420    let thrown = || -> napi::Result<napi::Error> {
421        let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
422        object.set_named_property("code", code.as_str())?;
423        if let Some(rejected) = rejected {
424            let json: Object = env.get_global()?.get_named_property("JSON")?;
425            let parse: Function<String, Unknown> = json.get_named_property("parse")?;
426            object.set_named_property("rejected", parse.call(rejected.to_string())?)?;
427        }
428        Ok(napi::Error::from(object.to_unknown()))
429    };
430    thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
431}
432
433/// The interface the addon implements: the WIT package of the WASI component,
434/// whose Node binding the addon is. `@xmachines/run`'s native engine runs an
435/// addon only of the interface it is written against.
436pub const RUNTIME_INTERFACE: &str = "xmachines:runtime@0.4.0";
437
438/// The interface the addon implements, [`RUNTIME_INTERFACE`].
439#[napi]
440pub fn runtime_interface() -> String {
441    RUNTIME_INTERFACE.to_string()
442}
443
444/// A definition compiled once with its load options and the callbacks of its
445/// `implementations` (the WIT `machine` resource). Every actor started or
446/// restored from it shares both; neither a start, a restore nor a refused
447/// chunk compiles it again.
448#[napi]
449pub struct Machine {
450    machine: Arc<RtMachine<Value, Value>>,
451    options: LoadOptions,
452}
453
454#[napi]
455impl Machine {
456    /// Loads `definition` (MachineJSON) and compiles it, with its children,
457    /// once. Load options (JSON, all optional): `{ "children", "maxSteps",
458    /// "maxTimers", "observeSystemEmitted", "hostActions": true | [name] }`.
459    /// A load that fails throws an error whose `code` is the contract's:
460    /// `WORKFLOW_INVALID_MACHINE` of a definition that does not compile,
461    /// `WORKFLOW_INVALID_INPUT` of options that do not parse.
462    #[napi(factory)]
463    pub fn load(env: Env, definition: String, options: String, implementations: Option<Object>) -> napi::Result<Self> {
464        let callbacks = Arc::new(Callbacks::from_js(implementations)?);
465        construct(&env, || load(&definition, &options, &callbacks).map_err(|e| apply_error_json(&e)))
466    }
467
468    /// Starts an actor at `now`, with `{ "input"?, "id"? }`, its root's id
469    /// `root` unless it names one. A start that fails throws an error whose
470    /// `code` is the contract's: `WORKFLOW_MACHINE_FAILED` of a root that
471    /// failed as it started, `WORKFLOW_INVALID_INPUT` of options that do not
472    /// parse.
473    #[napi]
474    pub fn start(&self, env: Env, options: String, now: f64) -> napi::Result<Actor> {
475        let now = millis(now).map_err(|error| contract_error(&env, &error))?;
476        let actor = construct(&env, || self.options.start_json(self.machine.clone(), &options, now))?;
477        Ok(Actor { state: RefCell::new(Ok(actor)) })
478    }
479
480    /// Restores an actor from `persist` output: its `input` and `id` are in
481    /// the snapshot, the rest is the machine's. Runs no actions. A snapshot
482    /// that does not restore throws an error whose `code` is
483    /// `WORKFLOW_INVALID_SNAPSHOT`.
484    #[napi]
485    pub fn restore(&self, env: Env, snapshot: String) -> napi::Result<Actor> {
486        let actor = construct(&env, || self.options.restore_json(self.machine.clone(), &snapshot))?;
487        Ok(Actor { state: RefCell::new(Ok(actor)) })
488    }
489}
490
491/// A running machine and its invoked children (the WIT `actor` resource).
492/// Callbacks run while the actor is borrowed: one that calls back into the
493/// same actor gets an error.
494#[napi]
495pub struct Actor {
496    /// The runtime actor, or why it is no longer usable.
497    state: RefCell<Result<RtActor<Value, Value>, String>>,
498}
499
500impl Actor {
501    fn with<T>(&self, env: &Env, f: impl FnOnce(&mut RtActor<Value, Value>) -> Result<T, String>) -> napi::Result<T> {
502        let Ok(mut state) = self.state.try_borrow_mut() else {
503            return Err(napi::Error::from_reason("the actor is busy: an implementation called back into it"));
504        };
505        let actor = match &mut *state {
506            Ok(actor) => actor,
507            Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
508        };
509        match run(env, || f(actor)) {
510            Ok(v) => Ok(v),
511            Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
512            Err(Failure::Fatal(e)) => {
513                *state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
514                Err(e)
515            }
516        }
517    }
518}
519
520#[napi]
521impl Actor {
522    /// Applies a chunk of inputs, in order, as `Actor::apply` of
523    /// xmachines-runtime: a JSON array of the contract's inputs, or one input
524    /// object. Returns the step's JSON; an empty chunk, `[]`, gives the
525    /// current step. A refused chunk throws, and
526    /// leaves the actor as it was: a rejection, of an event the root failed
527    /// on or one to a run that is over, an error whose `code` is
528    /// `WORKFLOW_REJECTED` and whose `rejected` is `{ "message", "data"? }`,
529    /// after which the run goes on; a fault an error whose `code` is the
530    /// contract's. A time or work input that fails ends the run in `error`
531    /// instead, a step like any other.
532    #[napi]
533    pub fn apply(&self, env: Env, batch: String) -> napi::Result<String> {
534        self.with(&env, |a| Ok(apply_json(a, &batch)))?.map_err(|error| contract_error(&env, &error))
535    }
536
537    /// Whether the root would select a transition for `event` (JSON text)
538    /// now, as kit-workflow's `can`: XState's `!isUnhandled(transition(...))`.
539    /// Any transition counts, an empty one and one that rejects the event
540    /// among them. Guards run; no action
541    /// runs and nothing changes. A guard that throws throws.
542    #[napi]
543    pub fn can(&self, env: Env, event: String) -> napi::Result<bool> {
544        self.with(&env, |a| {
545            let event: Value = serde_json::from_str(&event).map_err(|e| format!("invalid event: {e}"))?;
546            if !event.get("type").is_some_and(Value::is_string) {
547                return Err("an event must have a string \"type\"".into());
548            }
549            a.can_json(&event).map_err(|e| e.to_string())
550        })
551    }
552
553    /// The whole system (XState's `SystemSnapshot` shape), for
554    /// `Machine.restore`.
555    #[napi]
556    pub fn persist(&self, env: Env) -> napi::Result<String> {
557        self.with(&env, |a| Ok(a.persist().to_string()))
558    }
559
560    /// Events every actor emitted since the last call, oldest first, as
561    /// `{ "actor": { "@actor", "incarnation" }, "event": ... }`; always empty
562    /// unless the machine was loaded with `observeSystemEmitted`.
563    #[napi]
564    pub fn take_system_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
565        self.with(&env, |a| Ok(system_emitted_json(a.take_system_emitted())))
566    }
567
568    /// Argument lists of the root's `@xstate.log` actions since the last call.
569    #[napi]
570    pub fn take_logs(&self, env: Env) -> napi::Result<Vec<String>> {
571        self.with(&env, |a| Ok(a.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()))
572    }
573
574    /// Stops the root and its children.
575    #[napi]
576    pub fn stop(&self, env: Env) -> napi::Result<()> {
577        self.with(&env, |a| a.stop().map_err(|e| e.to_string()))
578    }
579}