onemessagebus 0.1.0

A typed NDJSON message bus: one envelope, one filter grammar, payload bounds and redaction, a schema registry, and an emitter and reader over streams — generic over the vocabulary a consumer declares.
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
//! The Rust-owned schema bundle the language SDKs are generated from, and the
//! per-language rendering of one registered document.
//!
//! Keeping every shared contract root here gives every SDK one generation
//! source: the capability manifest, the envelope and filter roots, the schema
//! id, the registry document, each verb's option contract, and every message
//! the registry holds. Language packages may add client behaviour, but must
//! not restate these wire shapes by hand.

use std::collections::BTreeMap;
use std::fmt::Write as _;

use schemars::{schema_for, JsonSchema, Schema};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::capability::{Capability, CAPABILITIES};
use crate::envelope::Envelope;
use crate::filter::{Filter, Matcher};
use crate::schema::{Registry, SchemaId};
use crate::vocabulary::{Reserved, Vocabulary};

/// How a reading verb renders what it read.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Format {
    /// One JSON document (or one per line), the machine-readable contract.
    #[default]
    Json,
    /// A deterministic rendering of the same content for a person.
    Text,
}

/// The language `schema gen` renders a document for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Lang {
    /// The registered JSON Schema document, byte for byte.
    Json,
    /// A Rust declaration that regenerates the document through schemars.
    Rust,
    /// A Python declaration — generated by the SDK package, not this build.
    Python,
    /// A TypeScript declaration — generated by the SDK package, not this build.
    Typescript,
}

impl Lang {
    /// The word `--lang` takes for this language.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Lang::Json => "json",
            Lang::Rust => "rust",
            Lang::Python => "python",
            Lang::Typescript => "typescript",
        }
    }
}

/// The options of `schema list`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SchemaListOptions {
    /// The registry directory, or the `ONEMESSAGEBUS_REGISTRY` environment
    /// variable when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry: Option<String>,
    /// How the list is rendered.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<Format>,
}

/// The options of `schema check`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SchemaCheckOptions {
    /// The id to check against.
    pub id: SchemaId,
    /// The payload file; stdin when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
    /// The registry directory.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry: Option<String>,
}

/// The options of `schema gen`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SchemaGenOptions {
    /// The id to render.
    pub id: SchemaId,
    /// The language to render it for.
    pub lang: Lang,
    /// The registry directory.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry: Option<String>,
}

/// The options of `schema register`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SchemaRegisterOptions {
    /// The id to register under.
    pub id: SchemaId,
    /// The file holding the JSON Schema document.
    pub file: String,
    /// The registry directory.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry: Option<String>,
}

/// The options of `events merge`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EventsMergeOptions {
    /// The stream files to merge.
    pub files: Vec<String>,
    /// A filter spec: inline JSON, or a path to a YAML document.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter: Option<String>,
    /// The profile whose vocabulary the streams are read through.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    // llmlint: ignore[invalid_states_unrepresentable] the core names no agent word and knows no profile: the binary in crates/onemessagebus-cli links the profiles and owns their names, and the SDK node reads the set from the manifest, so a closed type here would put the profile's words in the core.
    pub profile: Option<String>,
    /// How the merged stream is rendered.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<Format>,
}

/// The options of `events emit`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EventsEmitOptions {
    /// The stream file to append to.
    pub path: String,
    /// The kind of the event.
    // llmlint: ignore[invalid_states_unrepresentable] these options are the argv an SDK client hands `events emit`, which refuses a kind that is not kebab-case by name at that boundary; `Kind` is an open newtype by contract, because a relay carries a sibling's kinds, so there is no closed kind type in the core to use here.
    pub kind: String,
    /// The stream id to stamp.
    pub stream: String,
    /// The source word; the profile's default when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    // llmlint: ignore[invalid_states_unrepresentable] the source words are the chosen profile's, and the core knows no profile: the binary refuses a word outside the profile it runs by name, and a closed type here would put a vocabulary's words in the core.
    pub source: Option<String>,
    /// The profile whose vocabulary the envelope is written over.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    // llmlint: ignore[invalid_states_unrepresentable] the core names no agent word and knows no profile: the binary in crates/onemessagebus-cli links the profiles and owns their names, and the SDK node reads the set from the manifest, so a closed type here would put the profile's words in the core.
    pub profile: Option<String>,
    /// Labels to stamp, by key.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub labels: BTreeMap<String, String>,
    /// The payload file; stdin when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
    /// How the written envelope is rendered.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<Format>,
}

/// One entry of `schema list`.
///
/// `family` and `version` restate `id` for a reader that does not parse ids, so
/// an entry whose restatement contradicts its id is refused on read rather than
/// handed back with two answers to the same question.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(try_from = "SchemaEntryWire")]
pub struct SchemaEntry {
    /// The full id.
    pub id: SchemaId,
    /// The id without its version.
    pub family: String,
    /// The version.
    pub version: u32,
}

/// A `schema list` entry as it arrives, before its restatement is checked.
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(rename = "SchemaEntry")]
struct SchemaEntryWire {
    /// The full id.
    id: SchemaId,
    /// The id without its version.
    family: String,
    /// The version.
    version: u32,
}

impl TryFrom<SchemaEntryWire> for SchemaEntry {
    type Error = String;

    fn try_from(wire: SchemaEntryWire) -> Result<Self, Self::Error> {
        let entry = Self::from(&wire.id);
        if wire.family != entry.family || wire.version != entry.version {
            return Err(format!(
                "the schema entry for {} restates it as family {} at version {}, which its id contradicts",
                wire.id, wire.family, wire.version
            ));
        }
        Ok(entry)
    }
}

impl From<&SchemaId> for SchemaEntry {
    fn from(id: &SchemaId) -> Self {
        Self {
            id: id.clone(),
            family: id.family(),
            version: id.version(),
        }
    }
}

/// One file of a `--registry` directory: a document and the id it is under.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RegistryDocument {
    /// The id the document is registered under.
    pub id: SchemaId,
    /// The JSON Schema document.
    pub schema: Value,
}

/// What one vocabulary declares, as the SDK manifest carries it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct VocabularyManifest {
    /// The profile name.
    pub name: &'static str,
    /// The reserved label keys.
    pub reserved: &'static [Reserved],
    /// The top-level dimensions.
    pub dimensions: &'static [Reserved],
    /// The source word an emitter stamps when its caller names none.
    pub default_source: &'static str,
}

/// Every shared contract root, and the capability manifest beside them.
#[derive(Debug, Serialize)]
pub struct Bundle {
    /// The declared capability surface: what each SDK must expose, and which
    /// CLI flag each of its options renders to.
    pub capabilities: &'static [Capability],
    /// The vocabulary the roots below are generated over.
    pub vocabulary: VocabularyManifest,
    /// The envelope over that vocabulary.
    pub envelope: Schema,
    /// The filter over that vocabulary.
    pub filter: Schema,
    /// One matcher of that filter.
    pub matcher: Schema,
    /// `<namespace>.<name>@<version>`.
    pub schema_id: Schema,
    /// One file of a `--registry` directory.
    pub registry_document: Schema,
    /// The output of `schema list`.
    pub schema_list: Schema,
    /// The option contracts, by the root each capability names.
    pub options: BTreeMap<&'static str, Schema>,
    /// Every message the registry holds, by id.
    pub messages: BTreeMap<String, Value>,
}

/// The bundle for vocabulary `V`, carrying every message `registry` holds.
#[must_use]
pub fn bundle<V: Vocabulary>(registry: &Registry) -> Bundle {
    let mut options = BTreeMap::new();
    options.insert("schema_list_options", schema_for!(SchemaListOptions));
    options.insert("schema_check_options", schema_for!(SchemaCheckOptions));
    options.insert("schema_gen_options", schema_for!(SchemaGenOptions));
    options.insert(
        "schema_register_options",
        schema_for!(SchemaRegisterOptions),
    );
    options.insert("events_merge_options", schema_for!(EventsMergeOptions));
    options.insert("events_emit_options", schema_for!(EventsEmitOptions));
    Bundle {
        capabilities: CAPABILITIES,
        vocabulary: VocabularyManifest {
            name: V::NAME,
            reserved: V::RESERVED,
            dimensions: V::DIMENSIONS,
            default_source: V::DEFAULT_SOURCE,
        },
        envelope: schema_for!(Envelope<V>),
        filter: schema_for!(Filter<V>),
        matcher: schema_for!(Matcher<V>),
        schema_id: schema_for!(SchemaId),
        registry_document: schema_for!(RegistryDocument),
        schema_list: schema_for!(Vec<SchemaEntry>),
        options,
        messages: registry
            .ids()
            .into_iter()
            .filter_map(|id| {
                registry
                    .schema(&id)
                    .map(|document| (id.to_string(), document.clone()))
            })
            .collect(),
    }
}

/// Why a document could not be rendered for a language.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum GenerateError {
    /// This build renders no declaration for the language.
    #[error("{id}: `{lang}` declarations are generated by the {lang} SDK package, not by this build; ask for `json` or `rust`")]
    Unsupported {
        /// The id asked for.
        id: SchemaId,
        /// The language.
        lang: &'static str,
    },
    /// The document uses a construct the Rust renderer does not cover.
    #[error("{id}: cannot render {at} as Rust: {why}")]
    Unrenderable {
        /// The id asked for.
        id: SchemaId,
        /// Where in the document.
        at: String,
        /// What is there.
        why: String,
    },
}

/// The document registered under `id`, rendered for `lang`.
///
/// `json` is the document itself, pretty-printed; `rust` is a declaration
/// that compiles with serde and schemars and regenerates the document.
///
/// # Errors
///
/// [`GenerateError`] for a language this build does not render, or a
/// document the Rust renderer cannot express.
pub fn generate(lang: Lang, id: &SchemaId, document: &Value) -> Result<String, GenerateError> {
    match lang {
        Lang::Json => Ok(format!(
            "{}\n",
            serde_json::to_string_pretty(document).unwrap_or_default()
        )),
        Lang::Rust => rust::render(id, document),
        Lang::Python | Lang::Typescript => Err(GenerateError::Unsupported {
            id: id.clone(),
            lang: lang.as_str(),
        }),
    }
}

/// The Rust rendering of a JSON Schema document, in the subset schemars
/// generates for plain data: objects with typed properties, arrays, string
/// enums, nullable fields, and `$defs` references.
mod rust {
    use super::{GenerateError, Map, SchemaId, Value};
    use std::collections::BTreeMap;
    use std::fmt::Write as _;

    /// Every declaration the document needs, root first, then its `$defs` in
    /// order.
    pub(super) fn render(id: &SchemaId, document: &Value) -> Result<String, GenerateError> {
        let mut out = String::new();
        let _ = writeln!(
            out,
            "// Generated by `onemessagebus schema gen --lang rust {id}`; regenerates the same document."
        );
        let _ = writeln!(out, "// Do not edit by hand.");
        let title = document
            .get("title")
            .and_then(Value::as_str)
            .ok_or_else(|| unrenderable(id, "", "the document has no title to name the type by"))?;
        // Every type name is checked before any declaration is rendered, so a
        // `$ref` naming a declared type always names one that renders.
        let mut types = Names::new("type");
        let ident = types.admit(id, "/title", "title", title, title.to_owned())?;
        let mut declarations = vec![(title, ident, String::new(), document)];
        if let Some(defs) = document.get("$defs").and_then(Value::as_object) {
            for (name, def) in defs {
                let at = format!("/$defs/{}", pointer_token(name));
                let ident = types.admit(id, &at, "$defs name", name, name.clone())?;
                declarations.push((name, ident, at, def));
            }
        }
        for (name, ident, at, schema) in declarations {
            out.push('\n');
            declaration(id, name, &ident, &at, schema, &mut out)?;
        }
        Ok(out)
    }

    /// Keywords Rust accepts as raw identifiers: strict, reserved, and those of
    /// later editions, so a declaration compiles under any of them.
    const RAW_KEYWORDS: &[&str] = &[
        "abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "do",
        "dyn", "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if", "impl", "in",
        "let", "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref",
        "return", "static", "struct", "trait", "true", "try", "type", "typeof", "unsafe",
        "unsized", "use", "virtual", "where", "while", "yield",
    ];

    /// Keywords Rust refuses even as raw identifiers.
    const UNRAW_KEYWORDS: &[&str] = &["crate", "self", "Self", "super"];

    /// The identifiers one namespace of the generated source has handed out —
    /// the types of the module, the fields of a struct, the variants of an
    /// enum — so two names from the document cannot become the same one.
    struct Names<'a> {
        /// What an identifier here declares, for a refusal.
        declares: &'static str,
        /// Each identifier, by what named it and the name it was derived from;
        /// `None` for one the renderer declares itself.
        taken: BTreeMap<String, Option<(&'a str, &'a str)>>,
    }

    impl<'a> Names<'a> {
        fn new(declares: &'static str) -> Self {
            Self {
                declares,
                taken: BTreeMap::new(),
            }
        }

        /// Hold `ident` for the renderer's own use.
        fn reserve(&mut self, ident: &str) {
            self.taken.insert(ident.to_owned(), None);
        }

        /// `derived`, the identifier the renderer spells `name` as, once it is
        /// known to be one Rust accepts and no other name here became it.
        fn admit(
            &mut self,
            id: &SchemaId,
            at: &str,
            what: &'a str,
            name: &'a str,
            derived: String,
        ) -> Result<String, GenerateError> {
            let ident = identifier(id, at, what, name, derived)?;
            match self.taken.get(&ident) {
                Some(Some((named, earlier))) => Err(unrenderable(
                    id,
                    at,
                    &format!(
                        "the {named} {earlier:?} and the {what} {name:?} both become the {} `{ident}`",
                        self.declares
                    ),
                )),
                Some(None) => Err(unrenderable(
                    id,
                    at,
                    &format!(
                        "the {what} {name:?} becomes `{ident}`, the {} the renderer declares for every other key",
                        self.declares
                    ),
                )),
                None => {
                    self.taken.insert(ident.clone(), Some((what, name)));
                    Ok(ident)
                }
            }
        }
    }

    /// `derived`, the identifier the renderer spells `name` as, checked to be
    /// one Rust accepts: a keyword is written raw where Rust allows that, since
    /// a name from the document is spliced into source verbatim.
    fn identifier(
        id: &SchemaId,
        at: &str,
        what: &str,
        name: &str,
        derived: String,
    ) -> Result<String, GenerateError> {
        let Some(defect) = defect_of(name, &derived) else {
            return Ok(if RAW_KEYWORDS.contains(&derived.as_str()) {
                format!("r#{derived}")
            } else {
                derived
            });
        };
        let spelled = if derived == name || derived.is_empty() {
            String::new()
        } else {
            format!(" (as `{derived}`)")
        };
        Err(unrenderable(
            id,
            at,
            &format!("the {what} {name:?}{spelled} is not a Rust identifier: {defect}"),
        ))
    }

    /// What keeps `ident`, derived from `name`, from being a Rust identifier.
    fn defect_of(name: &str, ident: &str) -> Option<String> {
        let Some(first) = ident.chars().next() else {
            return Some(if name.is_empty() {
                "it is empty".to_owned()
            } else {
                "nothing of it is left once mapped".to_owned()
            });
        };
        if first.is_ascii_digit() {
            return Some("it starts with a digit".to_owned());
        }
        if let Some(ch) = ident
            .chars()
            .find(|ch| !ch.is_ascii_alphanumeric() && *ch != '_')
        {
            return Some(format!(
                "{ch:?} is not an ASCII letter, digit or underscore"
            ));
        }
        if ident == "_" {
            return Some("a lone `_` is a pattern, not a name".to_owned());
        }
        if UNRAW_KEYWORDS.contains(&ident) {
            return Some(format!(
                "`{ident}` is a keyword Rust does not take even as a raw identifier"
            ));
        }
        None
    }

    /// `name` escaped as one reference token of a JSON pointer.
    fn pointer_token(name: &str) -> String {
        name.replace('~', "~0").replace('/', "~1")
    }

    fn unrenderable(id: &SchemaId, at: &str, why: &str) -> GenerateError {
        GenerateError::Unrenderable {
            id: id.clone(),
            at: if at.is_empty() {
                "the document".to_owned()
            } else {
                at.to_owned()
            },
            why: why.to_owned(),
        }
    }

    fn doc(description: Option<&Value>, indent: &str, out: &mut String) {
        if let Some(text) = description.and_then(Value::as_str) {
            for line in text.lines() {
                let _ = writeln!(
                    out,
                    "{indent}///{}{line}",
                    if line.is_empty() { "" } else { " " }
                );
            }
        }
    }

    /// The declaration of `schema`, which the document names `name` and which
    /// sits at the JSON pointer `at`, as the type `ident`.
    fn declaration(
        id: &SchemaId,
        name: &str,
        ident: &str,
        at: &str,
        schema: &Value,
        out: &mut String,
    ) -> Result<(), GenerateError> {
        doc(schema.get("description"), "", out);
        if let Some(variants) = words_of(schema) {
            let _ = writeln!(
                out,
                "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]"
            );
            let _ = writeln!(out, "pub enum {ident} {{");
            let mut taken = Names::new("variant");
            for (word, description, within) in variants {
                let word = word
                    .as_str()
                    .ok_or_else(|| unrenderable(id, name, "an enum value that is not a string"))?;
                let variant = taken.admit(
                    id,
                    &format!("{at}/{within}"),
                    "enum value",
                    word,
                    pascal(word),
                )?;
                doc(description, "    ", out);
                let _ = writeln!(out, "    #[serde(rename = \"{}\")]", escape(word));
                let _ = writeln!(out, "    {variant},");
            }
            let _ = writeln!(out, "}}");
            return Ok(());
        }
        let properties = schema
            .get("properties")
            .and_then(Value::as_object)
            .ok_or_else(|| {
                unrenderable(
                    id,
                    name,
                    "a schema that is neither an object with properties nor a string enum",
                )
            })?;
        let required: Vec<&str> = schema
            .get("required")
            .and_then(Value::as_array)
            .map(|required| required.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default();
        let closed = schema.get("additionalProperties") == Some(&Value::Bool(false));
        let flattened = !closed
            && schema
                .get("additionalProperties")
                .is_some_and(|extra| extra != &Value::Bool(false));
        let _ = writeln!(
            out,
            "#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]"
        );
        if closed {
            let _ = writeln!(out, "#[serde(deny_unknown_fields)]");
        }
        let _ = writeln!(out, "pub struct {ident} {{");
        let mut taken = Names::new("field");
        if flattened {
            taken.reserve("extra");
        }
        for (property, property_schema) in properties {
            let field = taken.admit(
                id,
                &format!("{at}/properties/{}", pointer_token(property)),
                "property name",
                property,
                field_name(property),
            )?;
            doc(property_schema.get("description"), "    ", out);
            let at = format!("{name}.{property}");
            let (nullable, inner) = nullable(property_schema);
            let ty = type_of(id, &at, &inner)?;
            let is_required = required.contains(&property.as_str());
            let mut attributes = Vec::new();
            if field != *property {
                attributes.push(format!("rename = \"{}\"", escape(property)));
            }
            let ty = if nullable {
                if !is_required {
                    attributes.push("default".to_owned());
                    attributes.push("skip_serializing_if = \"Option::is_none\"".to_owned());
                }
                format!("Option<{ty}>")
            } else {
                if !is_required {
                    attributes.push("default".to_owned());
                }
                ty
            };
            if !attributes.is_empty() {
                let _ = writeln!(out, "    #[serde({})]", attributes.join(", "));
            }
            let _ = writeln!(out, "    pub {field}: {ty},");
        }
        if flattened {
            let _ = writeln!(out, "    /// Every other key, carried through untouched.");
            let _ = writeln!(out, "    #[serde(flatten)]");
            let _ = writeln!(
                out,
                "    pub extra: serde_json::Map<String, serde_json::Value>,"
            );
        }
        let _ = writeln!(out, "}}");
        Ok(())
    }

    /// The words of a closed string set, each with its description and its
    /// JSON pointer below the set: schemars spells an undocumented set as
    /// `enum` and a documented one as `oneOf` string constants.
    fn words_of(schema: &Value) -> Option<Vec<(&Value, Option<&Value>, String)>> {
        if let Some(words) = schema.get("enum").and_then(Value::as_array) {
            return Some(
                words
                    .iter()
                    .enumerate()
                    .map(|(index, word)| (word, None, format!("enum/{index}")))
                    .collect(),
            );
        }
        let branches = schema.get("oneOf")?.as_array()?;
        let mut words = Vec::new();
        for (index, branch) in branches.iter().enumerate() {
            if branch.get("type") != Some(&Value::String("string".to_owned())) {
                return None;
            }
            words.push((
                branch.get("const")?,
                branch.get("description"),
                format!("oneOf/{index}/const"),
            ));
        }
        Some(words)
    }

    /// Whether a property schema admits null, and the schema of the value when
    /// it does not.
    fn nullable(schema: &Value) -> (bool, Value) {
        if let Some(types) = schema.get("type").and_then(Value::as_array) {
            let words: Vec<&str> = types.iter().filter_map(Value::as_str).collect();
            if words.contains(&"null") && words.len() == 2 {
                let mut inner = schema.clone();
                let other = words.iter().find(|word| **word != "null").copied();
                if let (Some(other), Some(object)) = (other, inner.as_object_mut()) {
                    object.insert("type".to_owned(), Value::String(other.to_owned()));
                }
                return (true, inner);
            }
        }
        if let Some(branches) = schema.get("anyOf").and_then(Value::as_array) {
            let null = Value::Object(Map::from_iter([(
                "type".to_owned(),
                Value::String("null".to_owned()),
            )]));
            if branches.len() == 2 && branches.contains(&null) {
                if let Some(other) = branches.iter().find(|branch| **branch != null) {
                    return (true, other.clone());
                }
            }
        }
        (false, schema.clone())
    }

    fn type_of(id: &SchemaId, at: &str, schema: &Value) -> Result<String, GenerateError> {
        // `true`, or an object saying nothing but a description: anything at all.
        let says_nothing = schema
            .as_object()
            .is_some_and(|object| object.keys().all(|key| key == "description"));
        if schema == &Value::Bool(true) || says_nothing {
            return Ok("serde_json::Value".to_owned());
        }
        if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
            let target = reference
                .strip_prefix("#/$defs/")
                .ok_or_else(|| unrenderable(id, at, "a reference outside the document's $defs"))?;
            return identifier(id, at, "reference target", target, target.to_owned());
        }
        let kind = schema
            .get("type")
            .and_then(Value::as_str)
            .ok_or_else(|| unrenderable(id, at, "a schema with no single type"))?;
        let format = schema.get("format").and_then(Value::as_str);
        Ok(match (kind, format) {
            ("string", _) => "String".to_owned(),
            ("boolean", _) => "bool".to_owned(),
            ("integer", Some("uint64")) => "u64".to_owned(),
            ("integer", Some("uint32")) => "u32".to_owned(),
            ("integer", Some("uint16")) => "u16".to_owned(),
            ("integer", Some("uint8")) => "u8".to_owned(),
            ("integer", Some("uint")) => "usize".to_owned(),
            ("integer", Some("int64")) => "i64".to_owned(),
            ("integer", Some("int32")) => "i32".to_owned(),
            ("integer", Some("int16")) => "i16".to_owned(),
            ("integer", Some("int8")) => "i8".to_owned(),
            ("integer", Some("int")) => "isize".to_owned(),
            ("integer", _) => "i64".to_owned(),
            ("number", Some("float")) => "f32".to_owned(),
            ("number", _) => "f64".to_owned(),
            ("array", _) => {
                let items = schema
                    .get("items")
                    .ok_or_else(|| unrenderable(id, at, "an array with no item schema"))?;
                format!("Vec<{}>", type_of(id, at, items)?)
            }
            ("object", _) => {
                if schema.get("properties").is_some() {
                    return Err(unrenderable(
                        id,
                        at,
                        "an inline object with properties; declare it in $defs",
                    ));
                }
                match schema.get("additionalProperties") {
                    None | Some(Value::Bool(true)) => {
                        "serde_json::Map<String, serde_json::Value>".to_owned()
                    }
                    Some(values) => format!(
                        "std::collections::BTreeMap<String, {}>",
                        type_of(id, at, values)?
                    ),
                }
            }
            (other, _) => return Err(unrenderable(id, at, &format!("a `{other}` schema"))),
        })
    }

    /// The snake-case spelling of `property`, before it is checked.
    fn field_name(property: &str) -> String {
        let mut out = String::new();
        for (index, ch) in property.chars().enumerate() {
            if ch.is_ascii_uppercase() {
                if index > 0 {
                    out.push('_');
                }
                out.push(ch.to_ascii_lowercase());
            } else if ch == '-' {
                out.push('_');
            } else {
                out.push(ch);
            }
        }
        out
    }

    /// The Pascal-case spelling of `word`, before it is checked.
    fn pascal(word: &str) -> String {
        let mut out = String::new();
        let mut upper = true;
        for ch in word.chars() {
            if ch == '-' || ch == '_' || ch == ' ' {
                upper = true;
            } else if upper {
                out.push(ch.to_ascii_uppercase());
                upper = false;
            } else {
                out.push(ch);
            }
        }
        out
    }

    fn escape(text: &str) -> String {
        text.replace('\\', "\\\\").replace('"', "\\\"")
    }
}

impl Bundle {
    /// The bundle as one JSON document.
    #[must_use]
    pub fn to_json(&self) -> String {
        let mut out = serde_json::to_string_pretty(self).unwrap_or_default();
        let _ = writeln!(out);
        out
    }
}