xmachines-runtime-node 2.0.0

Node.js native addon (napi-rs), and its library, that runs XState v6 machine definitions, with guards and actions from JavaScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#![doc = include_str!("../README.md")]

use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;

use napi::bindgen_prelude::{
    Either, FnArgs, FromNapiValue, Function, FunctionRef, Object, ToNapiValue, Undefined, Unknown,
};
use napi::{sys, Env, JsValue, ValueType};
use napi_derive::napi;
use serde_json::{json, Map, Value};
use xmachines_runtime::host::{parse_event, parse_json, system_emitted_json, HostOptions, OptionsFor};
use xmachines_runtime::step::async_logic;
use xmachines_runtime::{Actor as RtActor, HostEvaluator, Logic, Machine, Registry, Status};

/// Children may invoke children; a cycle of child definitions is an error.
const MAX_CHILD_DEPTH: usize = 32;

/// `params` as the callbacks see them: `undefined` when the reference has none.
fn params_arg(p: &Value) -> Either<String, Undefined> {
    if p.is_null() {
        Either::B(())
    } else {
        Either::A(p.to_string())
    }
}

/// An optional JSON argument: `undefined` when absent.
fn optional_arg(v: Option<String>) -> Either<String, Undefined> {
    v.map_or(Either::B(()), Either::A)
}

// ---------------------------------------------------------------------------
// Calling JavaScript from the runtime

type GuardRef = FunctionRef<FnArgs<(String, Either<String, Undefined>, String, String)>, Unknown<'static>>;
type ActionRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
type DelayRef = FunctionRef<FnArgs<(String, String, String)>, Unknown<'static>>;
type ExprRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
type ContextExprRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
type EvaluateRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;

/// The `implementations` callbacks of one actor, each bound to the object it
/// came from (so they may use `this`). The registry closures share them.
#[derive(Default)]
struct Callbacks {
    guard: Option<GuardRef>,
    action: Option<ActionRef>,
    delay: Option<DelayRef>,
    expr: Option<ExprRef>,
    context_expr: Option<ContextExprRef>,
    evaluate: Option<EvaluateRef>,
}

/// One callback of `implementations`, bound to it: `None` when absent
/// (`undefined` or `null`), an error when it is not a function.
fn callback<Args, Return>(object: &Object, key: &str) -> napi::Result<Option<FunctionRef<Args, Return>>>
where
    Args: napi::bindgen_prelude::JsValuesTupleIntoVec,
    Return: napi::bindgen_prelude::FromNapiValue,
{
    let Some(value) = object.get::<Unknown>(key)? else { return Ok(None) };
    match value.get_type()? {
        ValueType::Undefined | ValueType::Null => Ok(None),
        ValueType::Function => {
            // SAFETY: the value was just checked to be a function.
            let f: Function<Args, Return> = unsafe { value.cast()? };
            Ok(Some(f.bind(object)?.create_ref()?))
        }
        _ => Err(napi::Error::from_reason(format!("implementations.{key} must be a function"))),
    }
}

impl Callbacks {
    fn from_js(implementations: Option<Object>) -> napi::Result<Self> {
        let Some(o) = implementations else { return Ok(Self::default()) };
        Ok(Self {
            guard: callback(&o, "guard")?,
            action: callback(&o, "action")?,
            delay: callback(&o, "delay")?,
            expr: callback(&o, "expr")?,
            context_expr: callback(&o, "contextExpr")?,
            evaluate: callback(&o, "evaluate")?,
        })
    }
}

thread_local! {
    /// The `Env` of the actor call in progress on this thread (calls nest when
    /// a callback calls another actor).
    static ENV: Cell<Option<sys::napi_env>> = const { Cell::new(None) };
}

/// Runs `f` with the current call's `Env`, in a handle scope of its own so that
/// a long step does not pile up handles. A callback that throws, or returns
/// what it must not, is the message of that error, which the runtime handles
/// as XState handles an exception thrown there.
fn call_js<T>(f: impl FnOnce(&Env) -> napi::Result<T>) -> Result<T, String> {
    let Some(raw) = ENV.with(Cell::get) else {
        return Err("an implementation was called outside a call into the actor".into());
    };
    let env = Env::from_raw(raw);
    env.run_in_scope(|| Ok(f(&env).map_err(|e| thrown_message(&env, e)))).unwrap_or_else(|e| Err(e.reason))
}

/// The message of what a callback threw: an error's `message`, the text of
/// anything else (as `@xmachines/run`'s `jsEvaluate` reports what code
/// throws). A failure of the addon's own is its reason.
fn thrown_message(env: &Env, error: napi::Error) -> String {
    let reason = error.reason.clone();
    let message = || -> napi::Result<String> {
        // SAFETY: `env` is the current call's, and the value is read at once.
        let value = unsafe { Unknown::from_napi_value(env.raw(), ToNapiValue::to_napi_value(env.raw(), error)?)? };
        if value.get_type()? == ValueType::Object {
            // SAFETY: the value was just checked to be an object.
            let object: Object = unsafe { value.cast()? };
            if let Some(message) = object.get::<Unknown>("message")? {
                if message.get_type()? == ValueType::String {
                    // SAFETY: the value was just checked to be a string.
                    return unsafe { message.cast::<String>() };
                }
            }
        }
        value.coerce_to_string()?.into_utf8()?.into_owned()
    };
    message().unwrap_or(reason)
}

/// A callback's JSON text result (`expr`, `contextExpr`): `null` when it does
/// not parse, as in the WASI component.
fn json_result(what: &str, name: &str, value: Unknown) -> napi::Result<Value> {
    if value.get_type()? != ValueType::String {
        return Err(napi::Error::from_reason(format!("{what} \"{name}\" must return a JSON string")));
    }
    // SAFETY: the value was just checked to be a string.
    let text: String = unsafe { value.cast()? };
    Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
}

/// What a callback that a definition needs but `implementations` lacks is
/// reported as.
fn missing(kind: &str, name: &str, key: &str) -> String {
    format!("the definition references {kind} \"{name}\" but implementations.{key} is missing")
}

/// The child machines of the options, each compiled once (by its source).
type Compiled = HashMap<String, Arc<dyn Logic>>;

/// Compiles a definition, wiring every name it references to the callbacks and
/// every invoke source to a child machine or to host async work.
fn compile(
    definition: &Value,
    children: &Map<String, Value>,
    callbacks: &Arc<Callbacks>,
    compiled: &mut Compiled,
    depth: usize,
) -> Result<Machine<Value, Value>, String> {
    if depth > MAX_CHILD_DEPTH {
        return Err("child machines are nested too deeply (a child invokes itself?)".into());
    }
    let refs = Machine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
    let mut registry: Registry<Value, Value> = Registry::new();
    let mut seen = HashSet::new();
    for r in &refs.guards {
        if seen.insert(("guard", r.name.clone())) {
            if callbacks.guard.is_none() {
                return Err(missing("guard", &r.name, "guard"));
            }
            let (name, cb) = (r.name.clone(), callbacks.clone());
            registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
                let args = (name.clone(), params_arg(p), args.context.to_string(), args.event.to_json().to_string());
                call_js(|env| cb.guard.as_ref().unwrap().borrow_back(env)?.call(args.into())?.coerce_to_bool())
            });
        }
    }
    for r in &refs.actions {
        if seen.insert(("action", r.name.clone())) {
            if callbacks.action.is_none() {
                return Err(missing("action", &r.name, "action"));
            }
            let (name, cb) = (r.name.clone(), callbacks.clone());
            registry.try_action_with(r.name.clone(), move |p: &Value| {
                let args = (name.clone(), params_arg(p));
                call_js(|env| cb.action.as_ref().unwrap().borrow_back(env)?.call(args.into()).map(drop))
            });
        }
    }
    for r in &refs.delays {
        if seen.insert(("delay", r.name.clone())) {
            if callbacks.delay.is_none() {
                return Err(missing("delay", &r.name, "delay"));
            }
            let (name, cb) = (r.name.clone(), callbacks.clone());
            registry.try_delay(r.name.clone(), move |context, event| {
                let args = (name.clone(), context.to_string(), event.to_json().to_string());
                call_js(|env| {
                    let result = cb.delay.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
                    let ms = match result.get_type()? {
                        // SAFETY: the value was just checked to be a number.
                        ValueType::Number => unsafe { result.cast::<f64>()? },
                        _ => f64::NAN,
                    };
                    if !(ms.is_finite() && ms >= 0.0) {
                        return Err(napi::Error::from_reason(format!(
                            "delay \"{name}\" must return a non-negative number of milliseconds"
                        )));
                    }
                    // Fractional milliseconds round up, like numeric `after` keys.
                    Ok(ms.ceil() as u64)
                })
            });
        }
    }
    for r in &refs.exprs {
        if callbacks.expr.is_none() {
            return Err(missing("expression", &r.name, "expr"));
        }
        let (name, cb) = (r.name.clone(), callbacks.clone());
        registry.expr(r.name.clone(), move |args| {
            let mut scope = json!({ "context": args.context, "event": args.event.to_json() });
            if let Some(params) = args.params {
                scope["params"] = params.clone();
            }
            let call = (name.clone(), scope.to_string());
            let result = call_js(|env| {
                json_result("expr", &name, cb.expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?)
            });
            result.unwrap_or_else(|message| {
                args.fail(message);
                Value::Null
            })
        });
    }
    for r in &refs.contexts {
        if callbacks.context_expr.is_none() {
            return Err(missing("context expression", &r.name, "contextExpr"));
        }
        let (name, cb) = (r.name.clone(), callbacks.clone());
        registry.context_with(r.name.clone(), move |args| {
            let call = (name.clone(), optional_arg(args.input.map(Value::to_string)));
            let result = call_js(|env| {
                let result = cb.context_expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?;
                json_result("contextExpr", &name, result)
            });
            result.unwrap_or_else(|message| {
                args.fail(message);
                Value::Null
            })
        });
    }
    for r in &refs.languages {
        if callbacks.evaluate.is_none() {
            return Err(missing("code in language", &r.name, "evaluate"));
        }
        let cb = callbacks.clone();
        registry.evaluator(
            r.name.clone(),
            HostEvaluator(move |code: &str, scope: &str| {
                let args = (code.to_owned(), scope.to_owned());
                let result = call_js(|env| {
                    let result = cb.evaluate.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
                    if result.get_type()? != ValueType::String {
                        return Err(napi::Error::from_reason("evaluate must return a JSON string"));
                    }
                    // SAFETY: the value was just checked to be a string.
                    unsafe { result.cast::<String>() }
                });
                // What the callback throws is what the code threw.
                result.unwrap_or_else(|error| json!({ "error": error }).to_string())
            }),
        );
    }
    for r in &refs.actors {
        if seen.insert(("actor", r.name.clone())) {
            let logic: Arc<dyn Logic> = match children.get(&r.name) {
                Some(child) => compile_child(&r.name, child, children, callbacks, compiled, depth + 1)?,
                None => Arc::new(async_logic(Some(r.name.clone()), None).map_err(|e| e.to_string())?),
            };
            registry.actor(r.name.clone(), logic);
        }
    }
    if depth == 0 {
        // Every child machine is loaded, whether the definition invokes it
        // or not, and the root may spawn any of them.
        for (src, child) in children {
            if seen.insert(("actor", src.clone())) {
                registry.actor(src.clone(), compile_child(src, child, children, callbacks, compiled, 1)?);
            }
        }
    }
    Machine::from_json(definition, &registry).map_err(|e| e.to_string())
}

fn load(
    definition: &str,
    options: &str,
    callbacks: &Arc<Callbacks>,
    call: OptionsFor,
) -> Result<(Arc<Machine<Value, Value>>, HostOptions), String> {
    let options = HostOptions::parse(options, call, true)?;
    let definition = parse_json("definition", definition)?;
    let mut compiled = Compiled::new();
    let machine = compile(&definition, &options.children, callbacks, &mut compiled, 0)?;
    Ok((Arc::new(machine), options))
}

/// The child machine for `invoke.src` `src`, compiled the first time.
fn compile_child(
    src: &str,
    child: &Value,
    children: &Map<String, Value>,
    callbacks: &Arc<Callbacks>,
    compiled: &mut Compiled,
    depth: usize,
) -> Result<Arc<dyn Logic>, String> {
    if let Some(logic) = compiled.get(src) {
        return Ok(logic.clone());
    }
    let machine = compile(child, children, callbacks, compiled, depth).map_err(|e| format!("child \"{src}\": {e}"))?;
    let logic: Arc<dyn Logic> = Arc::new(machine);
    compiled.insert(src.to_owned(), logic.clone());
    Ok(logic)
}

fn status_str(status: Status) -> &'static str {
    match status {
        Status::Active => "active",
        Status::Done => "done",
        Status::Error => "error",
        Status::Stopped => "stopped",
    }
}

/// `now` from JavaScript: whole milliseconds (fractions are dropped).
fn millis(now: f64) -> napi::Result<u64> {
    if now.is_finite() && now >= 0.0 {
        Ok(now as u64)
    } else {
        Err(napi::Error::from_reason("now must be a non-negative number of milliseconds"))
    }
}

/// How a call into the runtime went wrong.
enum Failure {
    /// The runtime returned an error (a failed step among them); the actor is
    /// still usable.
    Error(String),
    /// The runtime panicked, part way through a step.
    Fatal(napi::Error),
}

fn panic_message(payload: &(dyn Any + Send)) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        (*s).to_owned()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic".to_owned()
    }
}

/// Runs `f` with `env` reachable to the callbacks, catching any panic, which
/// must not unwind into Node.
fn run<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> Result<T, Failure> {
    struct Restore(Option<sys::napi_env>);
    impl Drop for Restore {
        fn drop(&mut self) {
            ENV.with(|e| e.set(self.0));
        }
    }
    let _restore = Restore(ENV.with(|e| e.replace(Some(env.raw()))));
    match panic::catch_unwind(AssertUnwindSafe(f)) {
        Ok(result) => result.map_err(Failure::Error),
        Err(payload) => {
            Err(Failure::Fatal(napi::Error::from_reason(format!("internal error: {}", panic_message(&*payload)))))
        }
    }
}

/// For `start` and `restore`, where a failure leaves no actor behind.
fn construct(env: &Env, f: impl FnOnce() -> Result<RtActor<Value, Value>, String>) -> napi::Result<Actor> {
    match run(env, f) {
        Ok(actor) => Ok(Actor { state: RefCell::new(Ok(actor)) }),
        Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
        Err(Failure::Fatal(e)) => Err(e),
    }
}

/// The interface the addon implements: the WIT package of the WASI component,
/// whose Node binding the addon is. `@xmachines/run`'s native engine runs an
/// addon only of the interface it is written against.
pub const RUNTIME_INTERFACE: &str = "xmachines:runtime@0.3.0";

/// The interface the addon implements, [`RUNTIME_INTERFACE`].
#[napi]
pub fn runtime_interface() -> String {
    RUNTIME_INTERFACE.to_string()
}

/// A running machine and its invoked children (the WIT `actor` resource).
/// Callbacks run while the actor is borrowed: one that calls back into the
/// same actor gets an error.
#[napi]
pub struct Actor {
    /// The runtime actor, or why it is no longer usable.
    state: RefCell<Result<RtActor<Value, Value>, String>>,
}

impl Actor {
    fn with<T>(&self, env: &Env, f: impl FnOnce(&mut RtActor<Value, Value>) -> Result<T, String>) -> napi::Result<T> {
        let Ok(mut state) = self.state.try_borrow_mut() else {
            return Err(napi::Error::from_reason("the actor is busy: an implementation called back into it"));
        };
        let actor = match &mut *state {
            Ok(actor) => actor,
            Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
        };
        match run(env, || f(actor)) {
            Ok(v) => Ok(v),
            Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
            Err(Failure::Fatal(e)) => {
                *state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
                Err(e)
            }
        }
    }
}

#[napi]
impl Actor {
    /// Loads `definition` (MachineJSON) and starts it at `now`.
    #[napi(factory)]
    pub fn start(
        env: Env,
        definition: String,
        options: String,
        now: f64,
        implementations: Option<Object>,
    ) -> napi::Result<Self> {
        let now = millis(now)?;
        let callbacks = Arc::new(Callbacks::from_js(implementations)?);
        construct(&env, || {
            let (machine, options) = load(&definition, &options, &callbacks, OptionsFor::Start)?;
            options.start(machine, now)
        })
    }

    /// Restores an actor from `persist` output with `children`, `maxSteps`
    /// and `observeSystemEmitted` from the options; `input` and `id` are in
    /// the snapshot and are an error here. Runs no actions.
    #[napi(factory)]
    pub fn restore(
        env: Env,
        definition: String,
        options: String,
        snapshot: String,
        implementations: Option<Object>,
    ) -> napi::Result<Self> {
        let callbacks = Arc::new(Callbacks::from_js(implementations)?);
        construct(&env, || {
            let (machine, options) = load(&definition, &options, &callbacks, OptionsFor::Restore)?;
            let snapshot = parse_json("snapshot", &snapshot)?;
            options.restore(machine, &snapshot)
        })
    }

    /// Sends an event (`{ "type": ..., ... }`) to the root at `now`. When time
    /// moved forward, due timers fire first.
    #[napi]
    pub fn send(&self, env: Env, event: String, now: f64) -> napi::Result<()> {
        let now = millis(now)?;
        self.with(&env, |a| a.send_json(parse_event(&event)?, now).map_err(|e| e.to_string()))
    }

    /// Sends an event to any actor in the system by address: the root's is its
    /// id, an invoked child's is `<parent address>/<invoke id>`.
    #[napi]
    pub fn send_to(&self, env: Env, address: String, event: String, now: f64) -> napi::Result<()> {
        let now = millis(now)?;
        self.with(&env, |a| a.send_to(&address, parse_event(&event)?, now).map_err(|e| e.to_string()))
    }

    /// Fires every timer due at or before `now`.
    #[napi]
    pub fn advance(&self, env: Env, now: f64) -> napi::Result<()> {
        let now = millis(now)?;
        self.with(&env, |a| a.advance(now).map_err(|e| e.to_string()))
    }

    /// When the next timer is due.
    #[napi]
    pub fn next_deadline(&self, env: Env) -> napi::Result<Option<f64>> {
        self.with(&env, |a| Ok(a.next_deadline().map(|t| t as f64)))
    }

    /// The root's snapshot: `{ "status", "value", "context", "output"?, "error"? }`.
    #[napi]
    pub fn snapshot(&self, env: Env) -> napi::Result<String> {
        self.with(&env, |a| {
            let mut s = json!({ "status": status_str(a.status()) });
            // A root whose start threw has only its error, as XState's live actor.
            if let (Some(value), Some(context)) = (a.value(), a.context()) {
                s["value"] = value;
                s["context"] = context.clone();
            }
            if let Some(output) = a.output() {
                s["output"] = output.clone();
            }
            if let Some(error) = a.error() {
                s["error"] = error.clone();
            }
            Ok(s.to_string())
        })
    }

    /// The whole system (XState's `SystemSnapshot` shape), for `restore`.
    #[napi]
    pub fn persist(&self, env: Env) -> napi::Result<String> {
        self.with(&env, |a| Ok(a.persist().to_string()))
    }

    /// Events the root emitted since the last call, oldest first.
    #[napi]
    pub fn take_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
        self.with(&env, |a| Ok(a.take_emitted().iter().map(Value::to_string).collect()))
    }

    /// Collects the events every actor in the system emits from now on, as
    /// XState's `system.onEmitted`.
    #[napi]
    pub fn observe_system_emitted(&self, env: Env) -> napi::Result<()> {
        self.with(&env, |a| {
            a.observe_system_emitted();
            Ok(())
        })
    }

    /// Stops collecting them and drops those not taken.
    #[napi]
    pub fn unobserve_system_emitted(&self, env: Env) -> napi::Result<()> {
        self.with(&env, |a| {
            a.unobserve_system_emitted();
            Ok(())
        })
    }

    /// Events every actor emitted since the last call, oldest first, as
    /// `{ "actor": { "@actor", "incarnation" }, "event": ... }`.
    #[napi]
    pub fn take_system_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
        self.with(&env, |a| Ok(system_emitted_json(a.take_system_emitted())))
    }

    /// Argument lists of the root's `@xstate.log` actions since the last call.
    #[napi]
    pub fn take_logs(&self, env: Env) -> napi::Result<Vec<String>> {
        self.with(&env, |a| Ok(a.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()))
    }

    /// External work waiting for the host (XState's external effect data).
    #[napi]
    pub fn pending_effects(&self, env: Env) -> napi::Result<Vec<String>> {
        self.with(&env, |a| Ok(a.pending_effects().iter().map(|e| e.to_json().to_string()).collect()))
    }

    /// Completes a pending effect, optionally with a result event.
    #[napi]
    pub fn resolve_effect(&self, env: Env, id: String, event: Option<String>) -> napi::Result<()> {
        self.with(&env, |a| {
            let event = event.as_deref().map(parse_event).transpose()?;
            a.resolve_effect(&id, event).map_err(|e| e.to_string())
        })
    }

    /// Stops the root and its children.
    #[napi]
    pub fn stop(&self, env: Env) -> napi::Result<()> {
        self.with(&env, |a| a.stop().map_err(|e| e.to_string()))
    }
}