xmachines-build 6.0.0

Build-time generator of typed Rust modules for XState v6 machine bundles
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
#![doc = include_str!("../README.md")]

mod names;
mod types;

use std::collections::HashSet;
use std::fmt;
use std::path::{Path, PathBuf};

use serde_json::{Map, Value};
use xmachines_runtime::{Machine, Reference};

use names::{pascal, raw_lit, snake_after, snake_word, string_lit};
use types::{validate, variant_text, Root, Types, VALUE};

/// A problem with a bundle, at a JSON path (`$...` for the definition,
/// `schemas...` for the schemas).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
    pub file: Option<PathBuf>,
    pub path: String,
    pub message: String,
}

impl Error {
    pub(crate) fn new(path: &str, message: impl Into<String>) -> Self {
        Self { file: None, path: path.to_owned(), message: message.into() }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(file) = &self.file {
            write!(f, "{}: ", file.display())?;
        }
        write!(f, "{}: {}", self.path, self.message)
    }
}

impl std::error::Error for Error {}

/// The generated module and any warnings (unused schema entries).
#[derive(Debug, Clone)]
pub struct Generated {
    pub code: String,
    pub warnings: Vec<String>,
}

const SCHEMA_KEYS: &[&str] = &[
    "context",
    "input",
    "output",
    "events",
    "internalEvents",
    "emitted",
    "rejections",
    "actions",
    "guards",
    "children",
    "actors",
];

fn obj(v: Option<&Value>) -> Option<&Map<String, Value>> {
    v.and_then(Value::as_object)
}

/// Every transition of a state, with its path: `on`, `always`, `after`,
/// `onDone`, `onTimeout` and invoke completion transitions.
fn transitions<'a>(state: &'a Map<String, Value>, path: &str) -> Vec<(String, &'a Value)> {
    let mut out = Vec::new();
    let mut add = |p: String, v: &'a Value| match v {
        Value::Array(items) => {
            for (i, t) in items.iter().enumerate() {
                out.push((format!("{p}[{i}]"), t));
            }
        }
        t => out.push((p, t)),
    };
    for key in ["on", "after"] {
        for (k, v) in obj(state.get(key)).into_iter().flatten() {
            add(format!("{path}.{key}.{k}"), v);
        }
    }
    for key in ["always", "onDone", "onTimeout"] {
        if let Some(v) = state.get(key) {
            add(format!("{path}.{key}"), v);
        }
    }
    let invokes: Vec<(String, &Value)> = match state.get("invoke") {
        Some(Value::Array(items)) => {
            items.iter().enumerate().map(|(i, v)| (format!("{path}.invoke[{i}]"), v)).collect()
        }
        Some(v) => vec![(format!("{path}.invoke"), v)],
        None => vec![],
    };
    for (ipath, invoke) in invokes {
        for key in ["onDone", "onError", "onSnapshot", "onTimeout"] {
            if let Some(v) = invoke.get(key) {
                add(format!("{ipath}.{key}"), v);
            }
        }
    }
    out
}

/// Calls `f` for every state node, depth first.
fn each_state<'a>(state: &'a Map<String, Value>, path: &str, f: &mut dyn FnMut(&'a Map<String, Value>, &str)) {
    f(state, path);
    for (k, child) in obj(state.get("states")).into_iter().flatten() {
        if let Some(child) = child.as_object() {
            each_state(child, &format!("{path}.states.{k}"), f);
        }
    }
}

/// Every action object with a built-in `type` in the definition.
fn builtin_actions<'a>(value: &'a Value, path: &str, out: &mut Vec<(String, &'a Map<String, Value>)>) {
    match value {
        Value::Array(items) => {
            for (i, v) in items.iter().enumerate() {
                builtin_actions(v, &format!("{path}[{i}]"), out);
            }
        }
        Value::Object(o) => {
            if o.get("type").and_then(Value::as_str).is_some_and(|t| t.starts_with("@xstate."))
                && o.contains_key("event")
                || o.get("type").and_then(Value::as_str) == Some("@xstate.assign")
            {
                out.push((path.to_owned(), o));
            }
            for (k, v) in o {
                if !matches!(k.as_str(), "meta" | "context" | "output" | "description" | "params" | "event") {
                    builtin_actions(v, &format!("{path}.{k}"), out);
                }
            }
        }
        _ => {}
    }
}

/// Whether a value is an expression (`{"@code": ...}` or `{"@expr": ...}`).
fn is_code(value: &Value) -> bool {
    value.as_object().is_some_and(|o| o.contains_key("@code") || o.contains_key("@expr"))
}

/// Whether a value is or holds an expression.
fn has_code(value: &Value) -> bool {
    match value {
        Value::Object(o) => is_code(value) || o.values().any(has_code),
        Value::Array(items) => items.iter().any(has_code),
        _ => false,
    }
}

/// Checks the static part of a value: all of it without expressions,
/// nothing of an expression, else each property of an object on its own
/// (computed ones are known only at run time, so `required` is not checked).
fn check_static(value: &Value, schema: &Value, root: &Value, path: &str) -> Result<(), Error> {
    if !has_code(value) {
        return validate(value, schema, root, path).map_err(|m| match m.split_once(": ") {
            Some((p, m)) => Error::new(p, m),
            None => Error::new(path, m),
        });
    }
    if is_code(value) {
        return Ok(());
    }
    check_properties(value, schema, root, path)
}

/// Checks each property of an object against its schema, if it has one.
fn check_properties(value: &Value, schema: &Value, root: &Value, path: &str) -> Result<(), Error> {
    let (Some(object), Some(props)) = (value.as_object(), schema.get("properties").and_then(Value::as_object)) else {
        return Ok(());
    };
    if is_code(value) {
        return Ok(());
    }
    for (k, v) in object {
        match props.get(k) {
            Some(s) => check_static(v, s, root, &format!("{path}.{k}"))?,
            None if schema.get("additionalProperties") == Some(&Value::Bool(false)) => {
                return Err(Error::new(&format!("{path}.{k}"), format!("unknown property `{k}`")))
            }
            None => {}
        }
    }
    Ok(())
}

struct Checker<'a> {
    schemas: &'a Map<String, Value>,
    declared_events: Option<HashSet<&'a str>>,
}

impl Checker<'_> {
    fn check(value: &Value, schema: &Value, path: &str) -> Result<(), Error> {
        validate(value, schema, schema, path).map_err(|m| match m.split_once(": ") {
            Some((p, m)) => Error::new(p, m),
            None => Error::new(path, m),
        })
    }

    fn event_schema(&self, ty: &str) -> Option<&Value> {
        ["events", "internalEvents"].iter().find_map(|k| self.schemas.get(*k)?.get(ty))
    }

    /// Checks a rejecting branch's reasons against `schemas.rejections`, as
    /// XState checks a rejection against its rejection schemas: when there
    /// are any, a reason's `type` must be one of them and its static payload
    /// must fit. A computed reason or type is known only at run time.
    fn rejections(&self, reasons: &[Value], path: &str) -> Result<(), Error> {
        let Some(schemas) = obj(self.schemas.get("rejections")) else { return Ok(()) };
        for (i, reason) in reasons.iter().enumerate() {
            let rpath = format!("{path}[{i}]");
            let Some(reason) = reason.as_object() else { continue };
            let Some(ty) = reason.get("type").and_then(Value::as_str) else { continue };
            let schema = schemas
                .get(ty)
                .ok_or_else(|| Error::new(&rpath, format!("rejection `{ty}` is not declared in schemas.rejections")))?;
            if has_code(&Value::Object(reason.clone())) {
                check_properties(&Value::Object(reason.clone()), schema, schema, &rpath)?;
            } else {
                Self::payload(reason, schema, &rpath)?;
            }
        }
        Ok(())
    }

    /// Checks an event object's payload (everything but `type`).
    fn payload(event: &Map<String, Value>, schema: &Value, path: &str) -> Result<(), Error> {
        let mut payload = event.clone();
        payload.remove("type");
        let mut schema = schema.clone();
        if let Some(props) = schema.get_mut("properties").and_then(Value::as_object_mut) {
            props.remove("type");
        }
        if let Some(req) = schema.get_mut("required").and_then(Value::as_array_mut) {
            req.retain(|r| r != "type");
        }
        Self::check(&Value::Object(payload), &schema, path)
    }

    fn references(&self, kind: &str, refs: &[Reference], warnings: &mut Vec<String>) -> Result<(), Error> {
        let empty = Map::new();
        let declared = obj(self.schemas.get(kind)).unwrap_or(&empty);
        for r in refs {
            let def = declared.get(&r.name).ok_or_else(|| {
                Error::new(&r.path, format!("`{}` has no entry in schemas.{kind}; declare its params there", r.name))
            })?;
            let params = r.params.clone().unwrap_or(Value::Null);
            match def.get("params") {
                Some(schema) => check_static(&params, schema, schema, &format!("{}.params", r.path))?,
                None if !params.is_null() => {
                    return Err(Error::new(
                        &format!("{}.params", r.path),
                        format!("`{}` takes no params (schemas.{kind}.{} declares none)", r.name, r.name),
                    ))
                }
                None => {}
            }
        }
        for name in declared.keys() {
            if !refs.iter().any(|r| r.name == *name) {
                warnings.push(format!("schemas.{kind}.{name} is declared but never referenced"));
            }
        }
        Ok(())
    }

    fn definition(&self, machine: &Map<String, Value>) -> Result<(), Error> {
        let context_schema = self.schemas.get("context");
        let initial = machine.get("context").cloned();
        // A computed initial context: patches are checked property by property.
        let initial_computed = initial.as_ref().is_some_and(has_code);
        match (&initial, context_schema) {
            (Some(ctx), Some(schema)) => check_static(ctx, schema, schema, "$.context")?,
            (Some(_), None) => {
                return Err(Error::new("schemas.context", "the machine has context but no context schema"))
            }
            _ => {}
        }
        let patch = |path: &str, patch: &Value, initial: &Option<Value>| -> Result<(), Error> {
            let (Some(schema), Some(patch_object)) = (context_schema, patch.as_object()) else { return Ok(()) };
            if initial_computed || has_code(patch) {
                return check_properties(patch, schema, schema, path);
            }
            let patch = patch_object;
            let mut merged = initial.clone().and_then(|v| v.as_object().cloned()).unwrap_or_default();
            for (k, v) in patch {
                merged.insert(k.clone(), v.clone());
            }
            Self::check(&Value::Object(merged), schema, path)
        };

        let mut result = Ok(());
        each_state(machine, "$", &mut |state, path| {
            if result.is_err() {
                return;
            }
            result = (|| {
                if let Some(declared) = &self.declared_events {
                    for key in obj(state.get("on")).into_iter().flatten().map(|(k, _)| k) {
                        if !key.contains('*') && !key.starts_with("xstate.") && !declared.contains(key.as_str()) {
                            return Err(Error::new(
                                &format!("{path}.on.{key}"),
                                format!("event `{key}` is not declared in schemas.events or schemas.internalEvents"),
                            ));
                        }
                    }
                }
                for (tpath, t) in transitions(state, path) {
                    if let Some(ctx) = t.get("context") {
                        patch(&format!("{tpath}.context"), ctx, &initial)?;
                    }
                    if let Some(reasons) = t.get("reject").and_then(Value::as_array) {
                        self.rejections(reasons, &format!("{tpath}.reject"))?;
                    }
                }
                Ok(())
            })();
        });
        result?;

        let mut actions = Vec::new();
        let whole = Value::Object(machine.clone());
        builtin_actions(&whole, "$", &mut actions);
        for (path, action) in actions {
            let ty = action.get("type").and_then(Value::as_str).unwrap_or_default();
            if ty == "@xstate.assign" {
                if let Some(ctx) = action.get("context") {
                    patch(&format!("{path}.context"), ctx, &initial)?;
                }
                continue;
            }
            let Some(event) = action.get("event").and_then(Value::as_object) else { continue };
            // A computed event or event type is known only at run time.
            let Some(event_type) = event.get("type").and_then(Value::as_str) else { continue };
            let epath = format!("{path}.event");
            let payload = |event: &Map<String, Value>, schema: &Value| {
                if has_code(&Value::Object(event.clone())) {
                    check_properties(&Value::Object(event.clone()), schema, schema, &epath)
                } else {
                    Self::payload(event, schema, &epath)
                }
            };
            match ty {
                "@xstate.raise" if !event_type.starts_with("xstate.") => {
                    if let Some(declared) = &self.declared_events {
                        if !declared.contains(event_type) {
                            return Err(Error::new(&epath, format!("raised event `{event_type}` is not declared in schemas.events or schemas.internalEvents")));
                        }
                        payload(event, self.event_schema(event_type).unwrap())?;
                    }
                }
                "@xstate.emit" => {
                    let schema = self.schemas.get("emitted").and_then(|e| e.get(event_type)).ok_or_else(|| {
                        Error::new(&epath, format!("emitted event `{event_type}` is not declared in schemas.emitted"))
                    })?;
                    payload(event, schema)?;
                }
                _ => {}
            }
        }

        if let Some(schema) = self.schemas.get("output") {
            if let Some(output) = machine.get("output") {
                check_static(output, schema, schema, "$.output")?;
            } else {
                for (k, child) in obj(machine.get("states")).into_iter().flatten() {
                    if child.get("type").and_then(Value::as_str) == Some("final") {
                        if let Some(output) = child.get("output") {
                            check_static(output, schema, schema, &format!("$.states.{k}.output"))?;
                        }
                    }
                }
            }
        }
        Ok(())
    }
}

/// The `id`s of every invoke in the definition, with their paths.
fn invoke_ids(machine: &Map<String, Value>) -> Vec<(String, String)> {
    let mut ids = Vec::new();
    each_state(machine, "$", &mut |state, path| {
        let invokes: Vec<(String, &Value)> = match state.get("invoke") {
            Some(Value::Array(items)) => {
                items.iter().enumerate().map(|(i, v)| (format!("{path}.invoke[{i}]"), v)).collect()
            }
            Some(v) => vec![(format!("{path}.invoke"), v)],
            None => vec![],
        };
        for (ipath, invoke) in invokes {
            if let Some(id) = invoke.get("id").and_then(Value::as_str) {
                ids.push((id.to_owned(), ipath));
            }
        }
    });
    ids
}

/// Types, a handle and an output reader for each declared child.
fn children(types: &mut Types, machine: &Map<String, Value>, schemas: &Map<String, Value>) -> Result<String, Error> {
    let Some(declared) = schemas.get("children") else { return Ok(String::new()) };
    let declared = declared.as_object().ok_or_else(|| Error::new("schemas.children", "expected an object"))?;
    let ids = invoke_ids(machine);
    let mut code = String::new();
    for (id, def) in declared {
        let path = format!("schemas.children.{id}");
        let def = def.as_object().ok_or_else(|| Error::new(&path, "expected `{ events?, output? }`"))?;
        if let Some(k) = def.keys().find(|k| !matches!(k.as_str(), "events" | "output")) {
            return Err(Error::new(&format!("{path}.{k}"), "unknown key (expected `events` or `output`)"));
        }
        let Some((_, invoke_path)) = ids.iter().find(|(i, _)| i == id) else {
            return Err(Error::new(&path, format!("no invoke in the machine has `id: \"{id}\"`")));
        };
        let p = pascal(id);
        let (handle, event, output) = (format!("{p}Child"), format!("{p}ChildEvent"), format!("{p}ChildOutput"));
        types.claim(&handle, &path)?;
        match def.get("events") {
            Some(Value::Object(events)) => {
                event_enum(types, &event, &event, &[(&format!("children.{id}.events"), events)])?
            }
            Some(_) => return Err(Error::new(&format!("{path}.events"), "expected an object of event schemas")),
            None => {
                types.claim(&event, &path)?;
                types.out.push(format!("pub type {event} = {VALUE};\n"));
            }
        }
        match def.get("output") {
            Some(schema) => types.named(schema, &output, &format!("{path}.output"))?,
            None => {
                types.claim(&output, &path)?;
                types.out.push(format!("pub type {output} = {VALUE};\n"));
            }
        }
        let snake_id = snake_word(id);
        let lit = string_lit(id);
        code.push_str(&format!(
            r#"/// The running child invoked with `id: {lit}` (at `{invoke_path}`).
pub struct {handle}<'a> {{
    actor: &'a mut Actor,
    address: String,
}}

impl {handle}<'_> {{
    /// The invoke `id`.
    pub const ID: &'static str = {lit};

    /// The child's address in the actor's system.
    pub fn address(&self) -> &str {{
        &self.address
    }}

    /// The child's status.
    pub fn status(&self) -> __rt::Status {{
        self.actor.system().snapshot(&self.address).map_or(__rt::Status::Stopped, |s| s.status())
    }}

    /// Sends an event to the child at `now_ms` (see `Actor::send_to`).
    pub fn send(&mut self, event: {event}, now_ms: u64) -> Result<(), __rt::SystemError> {{
        let event = __rt::EventType::to_json(&event);
        self.actor.send_to(&self.address, event, now_ms)
    }}
}}

/// The child invoked with `id: {lit}`, while the machine's active states invoke it.
pub fn child_{snake_id}(actor: &mut Actor) -> Option<{handle}<'_>> {{
    let address = actor.children().into_iter().find(|(id, _)| *id == {lit})?.1.to_owned();
    Some({handle} {{ actor, address }})
}}

/// The output of the child invoked with `id: {lit}`, when `event` is its
/// `xstate.done.actor` event (`None` for other events, or an output that
/// does not fit `{output}`).
pub fn child_{snake_id}_output(event: &__rt::Ev<Event>) -> Option<{output}> {{
    if event.event_type() != "xstate.done.actor" || event.field("actorId")?.as_str() != Some({lit}) {{
        return None;
    }}
    __rt::serde_json::from_value(event.field("output").unwrap_or(__rt::serde_json::Value::Null)).ok()
}}

"#
        ));
    }
    Ok(code)
}

/// Distinct names in reference order.
fn distinct(refs: &[Reference]) -> Vec<&Reference> {
    let mut seen = HashSet::new();
    refs.iter().filter(|r| seen.insert(r.name.as_str())).collect()
}

/// An event enum (`Event`, `Emitted` or `Rejection`) from `type -> schema` maps.
fn event_enum(
    types: &mut Types,
    name: &str,
    nested_prefix: &str,
    maps: &[(&str, &Map<String, Value>)],
) -> Result<(), Error> {
    types.claim(name, &format!("schemas.{}", maps[0].0))?;
    let mut item = format!(
        "{}\n#[serde(crate = \"__rt::serde\", tag = \"type\")]\npub enum {name} {{\n",
        "#[derive(Debug, Clone, PartialEq, __rt::serde::Serialize, __rt::serde::Deserialize)]"
    );
    let mut arms = String::new();
    let mut seen = HashSet::new();
    for (key, map) in maps {
        for (ty, schema) in *map {
            let path = format!("schemas.{key}.{ty}");
            let variant = pascal(ty);
            if !seen.insert(variant.clone()) {
                return Err(Error::new(&path, format!("event types map to the same variant `{variant}`")));
            }
            let hint = format!("{nested_prefix}{variant}");
            let root = Root { schema, name: &hint };
            let resolved = match schema.get("$ref").and_then(Value::as_str) {
                Some(r) => r.strip_prefix("#/$defs/").and_then(|n| schema.get("$defs")?.get(n)).unwrap_or(schema),
                None => schema,
            };
            let o = resolved
                .as_object()
                .filter(|o| o.get("type").and_then(Value::as_str) == Some("object"))
                .ok_or_else(|| Error::new(&path, "an event schema must be an object (z.object)"))?;
            let fields = types.fields(o, &hint, &path, root, &["type"], "")?;
            item.push_str(&variant_text(&variant, ty, &fields, o));
            arms.push_str(&format!("            Self::{variant} {{ .. }} => {},\n", string_lit(ty)));
        }
    }
    item.push_str("}\n\n");
    item.push_str(&format!(
        "impl __rt::EventType for {name} {{\n    fn event_type(&self) -> &str {{\n        match self {{\n{arms}        }}\n    }}\n}}\n"
    ));
    types.out.push(item);
    Ok(())
}

/// The bundle's `hostActions`: the custom actions the host does, each one the
/// definition references. None of a bundle that names none.
fn host_actions(bundle: &Value, refs: &xmachines_runtime::References) -> Result<Vec<String>, Error> {
    let Some(names) = bundle.get("hostActions") else { return Ok(Vec::new()) };
    let names = names.as_array().ok_or_else(|| Error::new("hostActions", "expected an array of action names"))?;
    let mut out = Vec::new();
    for (i, name) in names.iter().enumerate() {
        let path = format!("hostActions[{i}]");
        let name = name.as_str().ok_or_else(|| Error::new(&path, "expected an action name"))?;
        if !refs.actions.iter().any(|r| r.name == name) {
            return Err(Error::new(&path, format!("the definition references no custom action `{name}`")));
        }
        if out.iter().any(|n| n == name) {
            return Err(Error::new(&path, format!("`{name}` is named twice")));
        }
        out.push(name.to_owned());
    }
    Ok(out)
}

/// The bundle's `schemas.actors`: by `src`, what the invoked logic takes,
/// gives and fails with, `{ input?, output?, error? }`, each `src` one the
/// definition invokes.
fn actors<'a>(
    schemas: &'a Map<String, Value>,
    refs: &xmachines_runtime::References,
) -> Result<Option<&'a Map<String, Value>>, Error> {
    let Some(actors) = schemas.get("actors") else { return Ok(None) };
    let actors = actors.as_object().ok_or_else(|| Error::new("schemas.actors", "expected an object by `src`"))?;
    for (src, def) in actors {
        let path = format!("schemas.actors.{src}");
        let def = def.as_object().ok_or_else(|| Error::new(&path, "expected `{ input?, output?, error? }`"))?;
        if let Some(k) = def.keys().find(|k| !matches!(k.as_str(), "input" | "output" | "error")) {
            return Err(Error::new(&format!("{path}.{k}"), "unknown key (expected `input`, `output` or `error`)"));
        }
        if !refs.actors.iter().any(|r| r.name == *src) {
            return Err(Error::new(&path, format!("no invoke in the machine has `src: \"{src}\"`")));
        }
    }
    Ok(Some(actors))
}

/// The types of the work of the record protocol (`xmachines-workflow`), of
/// `schemas.actors` and `hostActions`: `Invoke`, by `src`, with the types of
/// each one's input, output and error; `HostAction`, by `type`, with its
/// params; and the protocol's types of this machine, `Work`,
/// `WorkflowInput`, `Snapshot` and `Record`. A child the machine runs itself
/// is a variant of `Invoke` too: nothing in the bundle tells it apart from
/// the host's work, and a run never asks the host for it.
fn workflow_types(
    types: &mut Types,
    schemas: &Map<String, Value>,
    actors: Option<&Map<String, Value>>,
    sources: &[&Reference],
    host_actions: &[String],
) -> Result<(), Error> {
    let derive = "#[derive(Debug, Clone, PartialEq, __rt::serde::Serialize, __rt::serde::Deserialize)]";
    // An optional value keeps `null` apart from none, as the record protocol's own types do.
    let optional = "#[serde(default, skip_serializing_if = \"Option::is_none\", deserialize_with = \"::xmachines_workflow::present\")]";
    let empty = Map::new();
    let mut invoke = format!("/// Invoked work, by `src`: what the host does.\n{derive}\n#[serde(crate = \"__rt::serde\", tag = \"src\")]\npub enum Invoke {{\n");
    let mut invoke_ids = String::new();
    types.claim("Invoke", "schemas.actors")?;
    // One variant for each `src` the definition invokes: one of no schema takes and gives JSON, as
    // a child the trait's implementation runs may be invoked work of the host's all the same.
    for src in sources.iter().map(|r| r.name.as_str()) {
        let def = actors.unwrap_or(&empty).get(src).and_then(Value::as_object).unwrap_or(&empty);
        let path = format!("schemas.actors.{src}");
        let p = pascal(src);
        let mut input = VALUE.to_owned();
        for (key, suffix) in [("input", "Input"), ("output", "Output"), ("error", "Error")] {
            let name = format!("{p}{suffix}");
            match def.get(key) {
                Some(schema) => types.named(schema, &name, &format!("{path}.{key}"))?,
                None => {
                    types.claim(&name, &path)?;
                    types.out.push(format!("pub type {name} = {VALUE};\n"));
                }
            }
            if key == "input" {
                input = name;
            }
        }
        invoke.push_str(&format!(
            "    /// The invoked logic `{src}`.\n    #[serde(rename = {lit})]\n    {p} {{\n        id: String,\n        actor: String,\n        {optional}\n        input: Option<{input}>,\n    }},\n",
            lit = string_lit(src)
        ));
        invoke_ids.push_str(&format!("            Self::{p} {{ id, .. }} => id,\n"));
    }
    invoke.push_str("}\n\n");
    let body = if invoke_ids.is_empty() {
        "        match *self {}\n".to_owned()
    } else {
        format!("        match self {{\n{invoke_ids}        }}\n")
    };
    invoke.push_str(&format!(
        "impl ::xmachines_workflow::WorkId for Invoke {{\n    fn id(&self) -> &str {{\n{body}    }}\n}}\n"
    ));
    types.out.push(invoke);

    let mut action = format!("/// A host action, by `type`: what the host does, then settles `done`.\n{derive}\n#[serde(crate = \"__rt::serde\", tag = \"type\")]\npub enum HostAction {{\n");
    let mut action_ids = String::new();
    types.claim("HostAction", "hostActions")?;
    for name in host_actions {
        let p = pascal(name);
        let params = match schemas.get("actions").and_then(|a| a.get(name)).and_then(|d| d.get("params")) {
            Some(schema) => {
                let params = format!("{p}Params");
                types.named(schema, &params, &format!("schemas.actions.{name}.params"))?;
                params
            }
            None => VALUE.to_owned(),
        };
        action.push_str(&format!(
            "    /// The host action `{name}`.\n    #[serde(rename = {lit})]\n    {p} {{\n        id: String,\n        actor: String,\n        {optional}\n        params: Option<{params}>,\n    }},\n",
            lit = string_lit(name)
        ));
        action_ids.push_str(&format!("            Self::{p} {{ id, .. }} => id,\n"));
    }
    action.push_str("}\n\n");
    let body = if action_ids.is_empty() {
        "        match *self {}\n".to_owned()
    } else {
        format!("        match self {{\n{action_ids}        }}\n")
    };
    action.push_str(&format!(
        "impl ::xmachines_workflow::WorkId for HostAction {{\n    fn id(&self) -> &str {{\n{body}    }}\n}}\n"
    ));
    types.out.push(action);

    for name in ["Work", "WorkflowInput", "Snapshot", "Record"] {
        types.claim(name, "schemas")?;
    }
    let output = if schemas.contains_key("output") { "Output" } else { VALUE };
    let emitted = if schemas.contains_key("emitted") { "Emitted" } else { VALUE };
    types.out.push(format!(
        "/// The work a run of the machine waits for (the record protocol's).\npub type Work = ::xmachines_workflow::Work<Invoke, HostAction>;\n\n/// An input of a run of the machine: an event of it, or a control input.\npub type WorkflowInput = ::xmachines_workflow::Input<Event>;\n\n/// A snapshot of a run of the machine.\npub type Snapshot = ::xmachines_workflow::Snapshot<Context, {VALUE}, Work, {output}>;\n\n/// A record of a run of the machine.\npub type Record = ::xmachines_workflow::Record<{emitted}, Snapshot, WorkflowInput>;\n"
    ));
    Ok(())
}

/// Generates the module for a bundle. `module` names it in comments and is
/// the trait's name when the machine has no `id`.
pub fn generate(bundle: &Value, module: &str) -> Result<Generated, Error> {
    if let Some(key) =
        obj(Some(bundle)).and_then(|b| b.keys().find(|k| !matches!(k.as_str(), "machine" | "schemas" | "hostActions")))
    {
        return Err(Error::new(key, "unknown bundle key (a bundle has `machine`, `schemas` and `hostActions`)"));
    }
    let machine =
        obj(bundle.get("machine")).ok_or_else(|| Error::new("machine", "the bundle has no `machine` object"))?;
    let empty = Map::new();
    let schemas = match bundle.get("schemas") {
        None => &empty,
        Some(Value::Object(s)) => s,
        Some(_) => return Err(Error::new("schemas", "expected an object")),
    };
    for k in schemas.keys() {
        if !SCHEMA_KEYS.contains(&k.as_str()) {
            return Err(Error::new(&format!("schemas.{k}"), "unknown schema key"));
        }
    }
    let machine_value = Value::Object(machine.clone());
    let refs = Machine::<Value, Value>::references(&machine_value).map_err(|e| Error::new(&e.path, e.message))?;

    let host_actions = host_actions(bundle, &refs)?;
    let actors = actors(schemas, &refs)?;

    let events = obj(schemas.get("events"));
    let internal = obj(schemas.get("internalEvents"));
    let declared_events = (events.is_some() || internal.is_some())
        .then(|| events.into_iter().chain(internal).flat_map(|m| m.keys().map(String::as_str)).collect::<HashSet<_>>());
    let checker = Checker { schemas, declared_events };
    let mut warnings = Vec::new();
    checker.references("guards", &refs.guards, &mut warnings)?;
    checker.references("actions", &refs.actions, &mut warnings)?;
    checker.definition(machine)?;

    let id = machine.get("id").and_then(Value::as_str).unwrap_or("");
    let trait_name = format!("{}Impl", pascal(if id.is_empty() { module } else { id }));
    let mut types = Types::default();
    for name in ["Actor", "ID", "DEFINITION", trait_name.as_str()] {
        types.claim(name, "$")?;
    }

    match schemas.get("context") {
        Some(schema) => types.named(schema, "Context", "schemas.context")?,
        None => {
            types.named(&serde_json::json!({ "type": "object", "properties": {} }), "Context", "schemas.context")?
        }
    }
    let mut maps = Vec::new();
    if let Some(e) = events {
        maps.push(("events", e));
    }
    if let Some(e) = internal {
        maps.push(("internalEvents", e));
    }
    if maps.is_empty() {
        types.claim("Event", "schemas.events")?;
        types.out.push(format!("pub type Event = {VALUE};\n"));
    } else {
        event_enum(&mut types, "Event", "", &maps)?;
    }
    if let Some(e) = obj(schemas.get("emitted")) {
        event_enum(&mut types, "Emitted", "Emitted", &[("emitted", e)])?;
    }
    if let Some(e) = obj(schemas.get("rejections")) {
        event_enum(&mut types, "Rejection", "Rejection", &[("rejections", e)])?;
    }
    for (key, name) in [("input", "Input"), ("output", "Output")] {
        if let Some(schema) = schemas.get(key) {
            types.named(schema, name, &format!("schemas.{key}"))?;
        }
    }

    let children_code = children(&mut types, machine, schemas)?;

    // The implementation trait and the registry wiring.
    let mut methods = Vec::new();
    let mut wiring = Vec::new();
    let mut method_names = HashSet::new();
    let mut method = |name: String, path: &str| -> Result<String, Error> {
        if !method_names.insert(name.clone()) {
            return Err(Error::new(path, format!("two sources map to the method `{name}`; rename one")));
        }
        Ok(name)
    };
    let params_type = |types: &mut Types, kind: &str, r: &Reference| -> Result<Option<String>, Error> {
        let Some(schema) = schemas.get(kind).and_then(|d| d.get(&r.name)).and_then(|d| d.get("params")) else {
            return Ok(None);
        };
        let name = format!("{}Params", pascal(&r.name));
        types.named(schema, &name, &format!("schemas.{kind}.{}.params", r.name))?;
        Ok(Some(name))
    };
    for r in distinct(&refs.guards) {
        let m = method(snake_after("guard", &r.name), &r.path)?;
        let doc = format!("    /// Guard `{}` (referenced at `{}`).\n", r.name, r.path);
        let lit = string_lit(&r.name);
        match params_type(&mut types, "guards", r)? {
            Some(p) => {
                methods.push(format!(
                    "{doc}    fn {m}(&self, args: &__rt::GuardArgs<'_, Context, Event>, params: &{p}) -> bool;\n"
                ));
                wiring.push(format!(
                    "    let i = imp.clone();\n    r.guard_with({lit}, move |args, p: &{p}| i.{m}(args, p));\n"
                ));
            }
            None => {
                methods.push(format!("{doc}    fn {m}(&self, args: &__rt::GuardArgs<'_, Context, Event>) -> bool;\n"));
                wiring.push(format!("    let i = imp.clone();\n    r.guard({lit}, move |args| i.{m}(args));\n"));
            }
        }
    }
    if !host_actions.is_empty() {
        let names: Vec<String> = host_actions.iter().map(|n| format!("{}.to_owned()", string_lit(n))).collect();
        wiring.push(format!("    r.host_actions(__rt::HostActions::Named(::std::vec![{}]));\n", names.join(", ")));
    }
    for r in distinct(&refs.actions).into_iter().filter(|r| !host_actions.contains(&r.name)) {
        let m = method(snake_after("action", &r.name), &r.path)?;
        let doc = format!(
            "    /// Action `{}` (referenced at `{}`). Runs as an effect after the step that enqueued it.\n",
            r.name, r.path
        );
        let lit = string_lit(&r.name);
        match params_type(&mut types, "actions", r)? {
            Some(p) => {
                methods.push(format!("{doc}    fn {m}(&self, params: &{p});\n"));
                wiring.push(format!("    let i = imp.clone();\n    r.action_with({lit}, move |p: &{p}| i.{m}(p));\n"));
            }
            None => {
                methods.push(format!("{doc}    fn {m}(&self);\n"));
                wiring.push(format!("    let i = imp.clone();\n    r.action({lit}, move || i.{m}());\n"));
            }
        }
    }
    for r in distinct(&refs.delays) {
        let m = method(snake_after("delay", &r.name), &r.path)?;
        methods.push(format!(
            "    /// Delay `{}` in milliseconds (referenced at `{}`), computed when the timer is scheduled.\n    fn {m}(&self, context: &Context, event: &__rt::Ev<Event>) -> u64;\n",
            r.name, r.path
        ));
        wiring.push(format!(
            "    let i = imp.clone();\n    r.delay({}, move |c, e| i.{m}(c, e));\n",
            string_lit(&r.name)
        ));
    }
    for r in distinct(&refs.actors) {
        let m = method(snake_after("actor", &r.name), &r.path)?;
        methods.push(format!(
            "    /// Actor logic for `src: {}` (referenced at `{}`).\n    fn {m}(&self) -> ::std::sync::Arc<dyn __rt::Logic>;\n",
            r.name, r.path
        ));
        wiring.push(format!("    r.actor({}, imp.{m}());\n", string_lit(&r.name)));
    }

    for r in distinct(&refs.exprs) {
        let m = method(snake_after("expr", &r.name), &r.path)?;
        methods.push(format!(
            "    /// Expression `{}` (first used at `{}`): the value of each `{{\"@code\": {}, \"@lang\": \"rust\"}}`.\n    fn {m}(&self, args: &__rt::ExprArgs<'_, Context, Event>) -> __rt::serde_json::Value;\n",
            r.name,
            r.path,
            string_lit(&r.name)
        ));
        wiring.push(format!("    let i = imp.clone();\n    r.expr({}, move |a| i.{m}(a));\n", string_lit(&r.name)));
    }
    for r in distinct(&refs.contexts) {
        let m = method(snake_after("context", &r.name), &r.path)?;
        // The whole root context is typed; a part of it is JSON.
        let (ty, wrap) = if r.path == "$.context" {
            ("Context", "__rt::serde_json::to_value(i.{m}(input)).expect(\"the context serializes\")")
        } else {
            ("__rt::serde_json::Value", "i.{m}(input)")
        };
        methods.push(format!(
            "    /// The root context expression `{}` (at `{}`), computed from the actor's input when it starts.\n    fn {m}(&self, input: Option<&__rt::serde_json::Value>) -> {ty};\n",
            r.name, r.path
        ));
        wiring.push(format!(
            "    let i = imp.clone();\n    r.context({}, move |input| {});\n",
            string_lit(&r.name),
            wrap.replace("{m}", &m)
        ));
    }

    for r in &refs.languages {
        let m = method(snake_after("evaluator", &r.name), &r.path)?;
        methods.push(format!(
            "    /// The evaluator of the code nodes in language `{}` (first used at `{}`).\n    fn {m}(&self) -> ::std::sync::Arc<dyn __rt::Evaluator<Context, Event>>;\n",
            r.name, r.path
        ));
        wiring.push(format!("    r.evaluator({}, imp.{m}());\n", string_lit(&r.name)));
    }

    if actors.is_some() || bundle.get("hostActions").is_some() {
        workflow_types(&mut types, schemas, actors, &distinct(&refs.actors), &host_actions)?;
    }

    let mut code = String::new();
    code.push_str(&format!("// @generated by xmachines-build from `{module}`. Do not edit.\n\n"));
    code.push_str("#[allow(unused_imports)]\nuse ::xmachines_runtime::__codegen as __rt;\n\n");
    code.push_str(&format!("/// The machine's `id`.\npub const ID: &str = {};\n\n", string_lit(id)));
    code.push_str(&format!(
        "/// The `MachineJSON` definition.\npub const DEFINITION: &str = {};\n\n",
        raw_lit(&serde_json::to_string(&machine_value).expect("JSON"))
    ));
    code.push_str(&format!(
        "/// The bundle's JSON Schemas (`schemas`: context, events, emitted, ...).\npub const SCHEMAS: &str = {};\n\n",
        raw_lit(&serde_json::to_string(schemas).expect("JSON"))
    ));
    for item in &types.out {
        code.push_str(item);
        code.push('\n');
    }
    code.push_str(&format!(
        "/// The guards, actions, delays, actors and expressions `{module}` needs from Rust.\npub trait {trait_name}: Send + Sync + 'static {{\n{}}}\n\n",
        methods.join("\n")
    ));
    code.push_str(&format!(
        "/// A registry that calls `imp`.\npub fn registry<I: {trait_name}>(imp: ::std::sync::Arc<I>) -> __rt::Registry<Context, Event> {{\n    #[allow(unused_mut)]\n    let mut r = __rt::Registry::new();\n{}    let _ = imp;\n    r\n}}\n\n",
        wiring.concat()
    ));
    code.push_str(&format!(
        "/// Compiles the definition with `imp`.\npub fn machine<I: {trait_name}>(imp: ::std::sync::Arc<I>) -> Result<__rt::Machine<Context, Event>, __rt::LoadError> {{\n    __rt::Machine::from_json_str(DEFINITION, &registry(imp))\n}}\n\n"
    ));
    code.push_str("/// An actor running this machine.\npub type Actor = __rt::Actor<Context, Event>;\n");
    if !children_code.is_empty() {
        code.push('\n');
        code.push_str(&children_code);
    }
    Ok(Generated { code, warnings })
}

/// Generates modules for bundles from `build.rs`.
#[derive(Debug, Default)]
pub struct Builder {
    machines: Vec<PathBuf>,
    out_dir: Option<PathBuf>,
}

impl Builder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a bundle (`<name>.machine.json`). The module is named `<name>`.
    pub fn machine(mut self, path: impl AsRef<Path>) -> Self {
        self.machines.push(path.as_ref().to_owned());
        self
    }

    /// Where to write the modules. Defaults to `$OUT_DIR/xstate`, where
    /// `include_machine!` looks.
    pub fn out_dir(mut self, dir: impl AsRef<Path>) -> Self {
        self.out_dir = Some(dir.as_ref().to_owned());
        self
    }

    /// Writes one module per bundle, prints `cargo:rerun-if-changed` for each
    /// bundle and `cargo:warning` for each warning, and returns the files.
    pub fn build(self) -> Result<Vec<PathBuf>, Error> {
        let io = |file: &Path, e: std::io::Error| Error {
            file: Some(file.to_owned()),
            path: String::new(),
            message: e.to_string(),
        };
        let out_dir = match self.out_dir {
            Some(d) => d,
            None => PathBuf::from(
                std::env::var_os("OUT_DIR")
                    .ok_or_else(|| Error::new("", "OUT_DIR is not set; call build() from build.rs or set out_dir"))?,
            )
            .join("xstate"),
        };
        std::fs::create_dir_all(&out_dir).map_err(|e| io(&out_dir, e))?;
        let mut written = Vec::new();
        for path in self.machines {
            println!("cargo:rerun-if-changed={}", path.display());
            let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
            let module = file_name
                .strip_suffix(".machine.json")
                .or_else(|| file_name.strip_suffix(".json"))
                .unwrap_or(file_name);
            let text = std::fs::read_to_string(&path).map_err(|e| io(&path, e))?;
            let bundle: Value = serde_json::from_str(&text).map_err(|e| Error {
                file: Some(path.clone()),
                path: String::new(),
                message: e.to_string(),
            })?;
            let generated = generate(&bundle, module).map_err(|e| Error { file: Some(path.clone()), ..e })?;
            for w in generated.warnings {
                println!("cargo:warning={}: {w}", path.display());
            }
            let out = out_dir.join(format!("{module}.rs"));
            std::fs::write(&out, generated.code).map_err(|e| io(&out, e))?;
            written.push(out);
        }
        Ok(written)
    }
}