Skip to main content

tilo_resource/
schema.rs

1//! JSON Schemas for the values actions carry, so a caller with no screen can
2//! read what an operation takes instead of guessing it.
3//!
4//! [`JsonSchema`] describes a type's serde JSON form. `#[derive(JsonSchema)]`
5//! implements it from the type's definition and its serde attributes, so the
6//! schema is the type: a new variant or field is described the moment it is
7//! written. [`Resource::action_schema`](crate::Resource::action_schema) is
8//! what the generic [`APPLY`](crate::APPLY) operation publishes as its
9//! parameter's schema, less what the named actions already publish.
10//!
11//! Schemas stay within the vocabulary `tilo-actions` validates and publishes
12//! (`type`, `const`, `enum`, `properties`, `required`,
13//! `additionalProperties: false`, `items`, `oneOf`, bounds, `description`):
14//! everything is inline, with no references, so every surface that lists an
15//! operation shows the whole shape and binding enforces it.
16
17use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
18use tilo_sort::CompactSort as _;
19
20use serde_json::{Map, Value, json};
21use tilo_actions::{ActionParam, ParamType};
22
23mod table;
24pub use table::{Body, Bounds, Content, Field, Tagging, TypeSchema, Variant, build};
25
26/// A type whose serde JSON form has a JSON Schema.
27///
28/// Derive it with `#[derive(JsonSchema)]` next to `Serialize` and
29/// `Deserialize`. The derive follows the serde attributes that change the
30/// JSON form (`rename`, `rename_all`, `tag`, `content`, `transparent`,
31/// `default`, `skip`) and refuses the ones it cannot describe (`flatten`,
32/// `untagged`, custom `with` functions), so a schema never silently differs
33/// from what serde reads. Doc comments become descriptions.
34pub trait JsonSchema {
35    /// Whether serde reads an absent field of this type as its default, as it
36    /// does for [`Option`]: such a field is not required.
37    const OPTIONAL: bool = false;
38
39    /// The schema of this type's JSON form.
40    fn json_schema() -> Value;
41
42    /// This type in the language-neutral vocabulary a surface publishes
43    /// ([`FieldType`](crate::FieldType)), declaring the records and enums it
44    /// names in `types`: what a verb's parameter of it is published as. The
45    /// default describes no type: any value.
46    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
47        let _ = types;
48        crate::FieldType::Any
49    }
50}
51
52macro_rules! primitive {
53    ($($ty:ty => $schema:expr, $field:ident),* $(,)?) => {
54        $(impl JsonSchema for $ty {
55            fn json_schema() -> Value {
56                $schema
57            }
58            fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
59                crate::FieldType::$field
60            }
61        })*
62    };
63}
64
65primitive! {
66    bool => json!({"type": "boolean"}), Bool,
67    String => json!({"type": "string"}), Text,
68    str => json!({"type": "string"}), Text,
69    char => json!({"type": "string", "minLength": 1, "maxLength": 1}), Text,
70    f32 => json!({"type": "number"}), Float,
71    f64 => json!({"type": "number"}), Float,
72    i8 => json!({"type": "integer", "minimum": i8::MIN, "maximum": i8::MAX}), Int,
73    i16 => json!({"type": "integer", "minimum": i16::MIN, "maximum": i16::MAX}), Int,
74    i32 => json!({"type": "integer", "minimum": i32::MIN, "maximum": i32::MAX}), Int,
75    i64 => json!({"type": "integer"}), Int,
76    isize => json!({"type": "integer"}), Int,
77    u8 => json!({"type": "integer", "minimum": 0, "maximum": u8::MAX}), Int,
78    u16 => json!({"type": "integer", "minimum": 0, "maximum": u16::MAX}), Int,
79    u32 => json!({"type": "integer", "minimum": 0, "maximum": u32::MAX}), Int,
80    u64 => json!({"type": "integer", "minimum": 0}), Int,
81    usize => json!({"type": "integer", "minimum": 0}), Int,
82    serde_json::Value => json!({}), Any,
83    crate::Id => json!({"type": "string"}), Text,
84    crate::Counter => json!({"type": "integer"}), Int,
85    uuid::Uuid => json!({"type": "string", "format": "uuid"}), Text,
86}
87
88/// A member as serde writes it: `{"person": "<id>"}`, `{"bot": "<id>"}`, or an agent by its
89/// id and the person its certificate chains to (`{"agent": {"id": …, "person": …}}`).
90impl JsonSchema for tilo_action_policy::MemberId {
91    fn json_schema() -> Value {
92        let text = || json!({"type": "string"});
93        let kind = |name: &str| {
94            json!({
95                "type": "object",
96                "properties": { name: text() },
97                "required": [name],
98                "additionalProperties": false,
99            })
100        };
101        let agent = json!({
102            "type": "object",
103            "properties": {
104                "agent": {
105                    "type": "object",
106                    "properties": {"id": text(), "person": text()},
107                    "required": ["id", "person"],
108                    "additionalProperties": false,
109                },
110            },
111            "required": ["agent"],
112            "additionalProperties": false,
113        });
114        json!({"oneOf": [kind("person"), agent, kind("bot")]})
115    }
116}
117
118/// Who made a change, as serde writes it: `{"member": {"person": "<id>"}}`
119/// (or `agent` or `bot`), `{"automation": "<id>"}`, `{"app": "<id>"}` or
120/// `{"visitor": "<key>"}`.
121impl JsonSchema for tilo_actions::Actor {
122    fn json_schema() -> Value {
123        let kind = |name: &str, value: Value| {
124            json!({
125                "type": "object",
126                "properties": { name: value },
127                "required": [name],
128                "additionalProperties": false,
129            })
130        };
131        json!({"oneOf": [
132            kind("member", <tilo_action_policy::MemberId as JsonSchema>::json_schema()),
133            kind("automation", json!({"type": "string"})),
134            kind("app", json!({"type": "string"})),
135            kind("visitor", json!({"type": "string"})),
136        ]})
137    }
138}
139
140/// What an action ran with, as serde writes it beside the change it made: the app and the
141/// resource it changed, what it did, and who asked for it. Which of those fields a change
142/// carries depends on the action, so its schema is the open object it is rather than a fixed set.
143impl JsonSchema for tilo_actions::ActionContext {
144    fn json_schema() -> Value {
145        json!({"type": "object"})
146    }
147}
148
149/// Where a message sent from a window goes, as serde writes it: one of
150/// `new-agent`, `agent`, `person`, `conversation` or `feedback`.
151impl JsonSchema for tilo_actions::RecipientKind {
152    fn json_schema() -> Value {
153        json!({
154            "type": "string",
155            "enum": ["new-agent", "agent", "person", "conversation", "feedback"],
156        })
157    }
158
159    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
160        crate::surface::enum_type(
161            types,
162            "tilo_actions::RecipientKind",
163            "RecipientKind",
164            "Who a message sent from a window goes to.",
165            &[
166                ("new-agent", "New agent", &[]),
167                ("agent", "Agent", &[]),
168                ("person", "Person", &[]),
169                ("conversation", "Conversation", &[]),
170                ("feedback", "Feedback", &[]),
171            ],
172        )
173    }
174}
175
176/// A recipient of a message sent from a window: who it goes to, and what the
177/// person reads on its chip.
178impl JsonSchema for tilo_actions::Recipient {
179    fn json_schema() -> Value {
180        json!({
181            "type": "object",
182            "additionalProperties": false,
183            "properties": {
184                "kind": <tilo_actions::RecipientKind as JsonSchema>::json_schema(),
185                "id": {"type": "string"},
186                "name": {"type": "string"},
187                "detail": {"type": ["string", "null"]},
188            },
189            "required": ["kind", "name"],
190        })
191    }
192
193    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
194        crate::surface::resource_of(
195            types,
196            "tilo_actions::Recipient",
197            "Recipient",
198            "One recipient of a message sent from a window.",
199            &[
200                (
201                    "kind",
202                    <tilo_actions::RecipientKind as JsonSchema>::field_type,
203                ),
204                ("id", |_| crate::FieldType::Text),
205                ("name", |_| crate::FieldType::Text),
206                ("detail", |_| {
207                    crate::FieldType::Option(Box::new(crate::FieldType::Text))
208                }),
209            ],
210        )
211    }
212}
213
214/// A reference to an item of the workspace's vault (`vault.item:<id>`): the address of a
215/// resource of that kind, which a parameter of it takes as a secret by reference.
216impl JsonSchema for tilo_actions::remote::ItemRef {
217    fn json_schema() -> Value {
218        let mut schema = serde_json::Map::new();
219        schema.insert("type".to_owned(), json!("string"));
220        schema.insert(
221            tilo_actions::params::RESOURCE_KIND_ANNOTATION.to_owned(),
222            json!(tilo_actions::remote::VAULT_ITEM_KIND),
223        );
224        Value::Object(schema)
225    }
226
227    fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
228        crate::FieldType::Resource(tilo_actions::remote::VAULT_ITEM_KIND.to_owned())
229    }
230}
231
232impl<T: JsonSchema> JsonSchema for Option<T> {
233    const OPTIONAL: bool = true;
234
235    fn json_schema() -> Value {
236        nullable(T::json_schema())
237    }
238
239    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
240        crate::FieldType::Option(Box::new(T::field_type(types)))
241    }
242}
243
244impl<T: JsonSchema + ?Sized> JsonSchema for Box<T> {
245    const OPTIONAL: bool = T::OPTIONAL;
246
247    fn json_schema() -> Value {
248        T::json_schema()
249    }
250
251    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
252        T::field_type(types)
253    }
254}
255
256impl<T: JsonSchema + ?Sized> JsonSchema for std::sync::Arc<T> {
257    const OPTIONAL: bool = T::OPTIONAL;
258
259    fn json_schema() -> Value {
260        T::json_schema()
261    }
262
263    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
264        T::field_type(types)
265    }
266}
267
268impl<T: JsonSchema + ?Sized> JsonSchema for &T {
269    const OPTIONAL: bool = T::OPTIONAL;
270
271    fn json_schema() -> Value {
272        T::json_schema()
273    }
274
275    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
276        T::field_type(types)
277    }
278}
279
280impl<T: JsonSchema> JsonSchema for [T] {
281    fn json_schema() -> Value {
282        array(T::json_schema())
283    }
284
285    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
286        crate::FieldType::List(Box::new(T::field_type(types)))
287    }
288}
289
290impl<T: JsonSchema> JsonSchema for Vec<T> {
291    fn json_schema() -> Value {
292        array(T::json_schema())
293    }
294
295    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
296        crate::FieldType::List(Box::new(T::field_type(types)))
297    }
298}
299
300impl<T: JsonSchema, const N: usize> JsonSchema for [T; N] {
301    fn json_schema() -> Value {
302        let mut schema = array(T::json_schema());
303        if let Some(object) = schema.as_object_mut() {
304            object.insert("minItems".into(), N.into());
305            object.insert("maxItems".into(), N.into());
306        }
307        schema
308    }
309
310    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
311        crate::FieldType::List(Box::new(T::field_type(types)))
312    }
313}
314
315macro_rules! tuples {
316    ($($len:literal => ($($name:ident),+)),* $(,)?) => {
317        $(impl<$($name: JsonSchema),+> JsonSchema for ($($name,)+) {
318            fn json_schema() -> Value {
319                tuple($len)
320            }
321        })*
322    };
323}
324
325tuples! {
326    1 => (A),
327    2 => (A, B),
328    3 => (A, B, C),
329    4 => (A, B, C, D),
330}
331
332// Serde reads a set from any array and keeps one of each value, so a
333// repeated value is not an error the schema should assert.
334impl<T: JsonSchema, S> JsonSchema for HashSet<T, S> {
335    fn json_schema() -> Value {
336        array(T::json_schema())
337    }
338
339    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
340        crate::FieldType::Set(Box::new(T::field_type(types)))
341    }
342}
343
344impl<T: JsonSchema> JsonSchema for BTreeSet<T> {
345    fn json_schema() -> Value {
346        array(T::json_schema())
347    }
348
349    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
350        crate::FieldType::Set(Box::new(T::field_type(types)))
351    }
352}
353
354// The published vocabulary has no schema for a map's values, so a map is
355// described as an object and its values are checked by the action itself.
356impl<K, V: JsonSchema, S> JsonSchema for HashMap<K, V, S> {
357    fn json_schema() -> Value {
358        json!({"type": "object"})
359    }
360
361    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
362        crate::FieldType::Map(Box::new(V::field_type(types)))
363    }
364}
365
366impl<K, V: JsonSchema> JsonSchema for BTreeMap<K, V> {
367    fn json_schema() -> Value {
368        json!({"type": "object"})
369    }
370
371    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
372        crate::FieldType::Map(Box::new(V::field_type(types)))
373    }
374}
375
376impl<V: JsonSchema> JsonSchema for serde_json::Map<String, V> {
377    fn json_schema() -> Value {
378        json!({"type": "object"})
379    }
380
381    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
382        crate::FieldType::Map(Box::new(V::field_type(types)))
383    }
384}
385
386/// An array of `items`.
387pub fn array(items: Value) -> Value {
388    let mut schema = Map::new();
389    schema.insert("type".into(), "array".into());
390    schema.insert("items".into(), items);
391    Value::Object(schema)
392}
393
394/// An array of exactly `len` values. The published vocabulary has no
395/// per-position item schema, so the positions are described in words.
396pub fn tuple(len: usize) -> Value {
397    json!({"type": "array", "minItems": len, "maxItems": len})
398}
399
400/// `schema`, or JSON `null`.
401pub fn nullable(schema: Value) -> Value {
402    let Value::Object(mut object) = schema else {
403        return schema;
404    };
405    if object.is_empty() {
406        return Value::Object(object);
407    }
408    let simple = !object.contains_key("oneOf")
409        && !object.contains_key("const")
410        && !object.contains_key("enum");
411    match object.get_mut("type") {
412        Some(Value::String(name)) if simple => {
413            if name != "null" {
414                let name = std::mem::take(name);
415                object.insert("type".into(), json!([name, "null"]));
416            }
417            Value::Object(object)
418        }
419        Some(Value::Array(types)) if simple => {
420            if !types.iter().any(|name| name == "null") {
421                types.push("null".into());
422            }
423            Value::Object(object)
424        }
425        _ => {
426            let description = object.remove("description");
427            let mut wrapped = Map::new();
428            wrapped.insert(
429                "oneOf".into(),
430                json!([{"type": "null"}, Value::Object(object)]),
431            );
432            if let Some(description) = description {
433                wrapped.insert("description".into(), description);
434            }
435            Value::Object(wrapped)
436        }
437    }
438}
439
440/// `schema` with its bounds narrowed to `minimum` and `maximum`, those
441/// given: `#[schema(range(min = 1, max = 100))]` on a field. A number's range
442/// is its value's, a text's its length (`minLength`, `maxLength`) and a
443/// list's its number of items. An optional field's bounds go on its value's
444/// alternative.
445pub fn range(schema: Value, minimum: Option<Value>, maximum: Option<Value>) -> Value {
446    let Value::Object(mut object) = schema else {
447        return schema;
448    };
449    if let Some(Value::Array(alternatives)) = object.get_mut("oneOf") {
450        for alternative in alternatives.iter_mut() {
451            if alternative.get("type") != Some(&json!("null")) {
452                *alternative = range(alternative.take(), minimum.clone(), maximum.clone());
453            }
454        }
455        return Value::Object(object);
456    }
457    // A text's range bounds its length, a list's its items, a number itself.
458    let named = match object.get("type") {
459        Some(Value::String(name)) => Some(name.as_str()),
460        // A nullable value (`["string", "null"]`) is bounded as its value.
461        Some(Value::Array(names)) => names
462            .iter()
463            .filter_map(Value::as_str)
464            .find(|name| *name != "null"),
465        _ => None,
466    };
467    let keys = match named {
468        Some("string") => ("minLength", "maxLength"),
469        Some("array") => ("minItems", "maxItems"),
470        _ => ("minimum", "maximum"),
471    };
472    for (key, bound) in [(keys.0, minimum), (keys.1, maximum)] {
473        if let Some(bound) = bound {
474            object.insert(key.into(), bound);
475        }
476    }
477    Value::Object(object)
478}
479
480/// `schema` narrowed to the texts `choices`: `#[model(choices = ..)]` on a
481/// field. An optional field may still be absent (`null`).
482pub fn choices(schema: Value, choices: &[&str]) -> Value {
483    let Value::Object(mut object) = schema else {
484        return schema;
485    };
486    if let Some(Value::Array(alternatives)) = object.get_mut("oneOf") {
487        for alternative in alternatives.iter_mut() {
488            if alternative.get("type") != Some(&json!("null")) {
489                *alternative = self::choices(alternative.take(), choices);
490            }
491        }
492        return Value::Object(object);
493    }
494    let mut values: Vec<Value> = choices.iter().map(|choice| json!(choice)).collect();
495    if matches!(object.get("type"), Some(Value::Array(names)) if names.iter().any(|name| name == "null"))
496    {
497        values.push(Value::Null);
498    }
499    object.insert("enum".into(), Value::Array(values));
500    Value::Object(object)
501}
502
503/// `schema` saying the value a field has until someone changes it:
504/// `#[model(defaults)]` on a record.
505pub fn with_default(schema: Value, default: Option<Value>) -> Value {
506    match (schema, default) {
507        (Value::Object(mut object), Some(default)) => {
508            object.insert("default".into(), default);
509            Value::Object(object)
510        }
511        (schema, _) => schema,
512    }
513}
514
515/// `schema` with `description`, when there is one.
516pub fn describe(schema: Value, description: &str) -> Value {
517    if description.is_empty() {
518        return schema;
519    }
520    match schema {
521        Value::Object(mut object) => {
522            object.insert("description".into(), description.into());
523            Value::Object(object)
524        }
525        other => other,
526    }
527}
528
529/// A closed object: `properties` as `(name, schema, required)`, nothing else.
530pub fn object(properties: Vec<(&str, Value, bool)>) -> Value {
531    let required: Vec<Value> = properties
532        .iter()
533        .filter(|(_, _, required)| *required)
534        .map(|(name, _, _)| Value::from(*name))
535        .collect();
536    let properties: Map<String, Value> = properties
537        .into_iter()
538        .map(|(name, schema, _)| (name.to_owned(), schema))
539        .collect();
540    let mut schema = Map::new();
541    schema.insert("type".into(), "object".into());
542    if !required.is_empty() {
543        schema.insert("required".into(), Value::Array(required));
544    }
545    schema.insert("properties".into(), Value::Object(properties));
546    schema.insert("additionalProperties".into(), false.into());
547    Value::Object(schema)
548}
549
550/// Exactly one of `alternatives`.
551pub fn one_of(alternatives: Vec<Value>) -> Value {
552    let mut schema = Map::new();
553    schema.insert("oneOf".into(), Value::Array(alternatives));
554    Value::Object(schema)
555}
556
557/// The string `value`.
558pub fn constant(value: &str) -> Value {
559    json!({"type": "string", "const": value})
560}
561
562/// One of `values`.
563pub fn string_enum(values: &[&str]) -> Value {
564    json!({"type": "string", "enum": values})
565}
566
567/// An externally tagged variant: `{ name: content }`.
568pub fn external(name: &str, content: Value) -> Value {
569    object(vec![(name, content, true)])
570}
571
572/// An adjacently tagged variant: `{ tag: name, content_key: content }`, or
573/// only the tag for a unit variant.
574pub fn adjacent(tag: &str, content_key: &str, name: &str, content: Option<Value>) -> Value {
575    let mut properties = vec![(tag, constant(name), true)];
576    if let Some(content) = content {
577        properties.push((content_key, content, true));
578    }
579    object(properties)
580}
581
582/// An internally tagged variant: `content`'s fields with `tag` naming the
583/// variant among them.
584pub fn internal(tag: &str, name: &str, content: Value) -> Value {
585    let Value::Object(mut schema) = content else {
586        return object(vec![(tag, constant(name), true)]);
587    };
588    if let Some(Value::Object(properties)) = schema.get_mut("properties") {
589        properties.insert(tag.to_owned(), constant(name));
590    } else {
591        schema.insert("type".into(), "object".into());
592        schema.insert("properties".into(), json!({ tag: constant(name) }));
593    }
594    match schema.get_mut("required") {
595        Some(Value::Array(required)) => required.insert(0, tag.into()),
596        _ => {
597            schema.insert("required".into(), json!([tag]));
598        }
599    }
600    Value::Object(schema)
601}
602
603/// `schema` without its descriptions: the same shape, smaller, for a copy
604/// nested where the documented original is published beside it.
605pub fn undescribed(schema: &Value) -> Value {
606    match schema {
607        Value::Object(object) => Value::Object(
608            object
609                .iter()
610                .filter(|(key, _)| key.as_str() != "description")
611                .map(|(key, value)| {
612                    let value = if key == "properties" {
613                        match value {
614                            Value::Object(properties) => Value::Object(
615                                properties
616                                    .iter()
617                                    .map(|(name, child)| (name.clone(), undescribed(child)))
618                                    .collect(),
619                            ),
620                            other => other.clone(),
621                        }
622                    } else {
623                        undescribed(value)
624                    };
625                    (key.clone(), value)
626                })
627                .collect(),
628        ),
629        Value::Array(values) => Value::Array(values.iter().map(undescribed).collect()),
630        other => other.clone(),
631    }
632}
633
634/// The schema of one declared parameter's value as serde reads it: `null`
635/// reads into an optional field.
636pub(crate) fn param_schema(param: &ActionParam) -> Value {
637    let base = match param.ty {
638        ParamType::Text | ParamType::Secret | ParamType::Resource => json!({"type": "string"}),
639        ParamType::DateTime => json!({"type": "string", "format": "date-time"}),
640        ParamType::Integer => json!({"type": "integer"}),
641        ParamType::Number => json!({"type": "number"}),
642        ParamType::Boolean => json!({"type": "boolean"}),
643        ParamType::Array => json!({"type": "array"}),
644        // Serde reads whatever the field's type is, which a declaration
645        // does not record.
646        ParamType::Object => json!({}),
647    };
648    let mut schema = match (param.schema.as_deref(), base) {
649        (Some(Value::Object(declared)), Value::Object(base)) => {
650            let mut merged = declared.clone();
651            for (key, value) in base {
652                merged.entry(key).or_insert(value);
653            }
654            merged
655        }
656        (_, Value::Object(base)) => base,
657        (_, _) => Map::new(),
658    };
659    if !param.choices.is_empty() && !schema.contains_key("enum") {
660        let choices = param
661            .choices
662            .iter()
663            .map(|choice| match param.ty {
664                ParamType::Text | ParamType::Secret | ParamType::Resource | ParamType::DateTime => {
665                    Value::String(choice.to_string())
666                }
667                _ => serde_json::from_str(choice).unwrap_or_else(|_| choice.to_string().into()),
668            })
669            .collect();
670        schema.insert("enum".into(), Value::Array(choices));
671    }
672    let schema = describe(Value::Object(schema), &param.description);
673    if param.nullable || !param.required {
674        nullable(schema)
675    } else {
676        schema
677    }
678}
679
680/// The arguments object of a declaration, as serde reads it.
681///
682/// This is the one projection of an action's parameters to a JSON Schema:
683/// what its own typed call publishes, what a generic invoke takes, and what
684/// every other caller reads to know the shape of a call (a model's function,
685/// an MCP tool's `inputSchema`, a REST body).
686pub fn args_schema(params: &[ActionParam]) -> Value {
687    object(
688        params
689            .iter()
690            .map(|param| (param.name.as_ref(), param_schema(param), param.required))
691            .collect(),
692    )
693}
694
695/// `schema` with every alternative that only restates a declared action
696/// folded into one that names those actions, so `apply` does not publish a
697/// second copy of what each named action already publishes. `declared` maps
698/// an action id to its arguments object as serde reads it. An alternative
699/// folds when it is `{"action": id, ..fields}` or `{"action": id, "args":
700/// fields}` with exactly the declaration's fields; the folded alternative
701/// is permissive, and [`declared_invocation`] checks the fields against
702/// the declaration, so binding refuses nothing it refused before.
703pub(crate) fn fold_declared(schema: &Value, declared: &BTreeMap<&str, Value>) -> Value {
704    match schema {
705        Value::Object(object) => {
706            let mut out = Map::new();
707            for (key, value) in object {
708                let value = match (key.as_str(), value) {
709                    ("oneOf", Value::Array(alternatives)) => {
710                        Value::Array(fold_alternatives(alternatives, declared))
711                    }
712                    _ => fold_declared(value, declared),
713                };
714                out.insert(key.clone(), value);
715            }
716            Value::Object(out)
717        }
718        Value::Array(values) => Value::Array(
719            values
720                .iter()
721                .map(|value| fold_declared(value, declared))
722                .collect(),
723        ),
724        other => other.clone(),
725    }
726}
727
728fn fold_alternatives(alternatives: &[Value], declared: &BTreeMap<&str, Value>) -> Vec<Value> {
729    let (mut internal, mut adjacent, mut kept) = (Vec::new(), Vec::new(), Vec::new());
730    for alternative in alternatives {
731        match restated(alternative, declared) {
732            Some((id, false)) => internal.push(id),
733            Some((id, true)) => adjacent.push(id),
734            None => kept.push(fold_declared(alternative, declared)),
735        }
736    }
737    let names = |ids: &[&str]| json!({"type": "string", "enum": ids});
738    if !internal.is_empty() {
739        kept.push(json!({
740            "type": "object",
741            "required": ["action"],
742            "properties": {"action": names(&internal)},
743            "description": "A named action: `action` is its id, the other fields its parameters",
744        }));
745    }
746    if !adjacent.is_empty() {
747        kept.push(json!({
748            "type": "object",
749            "required": ["action", "args"],
750            "properties": {"action": names(&adjacent), "args": {"type": "object"}},
751            "additionalProperties": false,
752            "description": "A named action: `action` is its id, `args` its parameters",
753        }));
754    }
755    kept
756}
757
758/// The declared id an alternative restates, and whether its fields sit
759/// under `args`.
760fn restated<'a>(
761    alternative: &Value,
762    declared: &BTreeMap<&'a str, Value>,
763) -> Option<(&'a str, bool)> {
764    let properties = alternative.get("properties")?.as_object()?;
765    let tag = properties.get("action")?.get("const")?.as_str()?;
766    let (id, args) = declared.get_key_value(tag)?;
767    let args = shape(args);
768    if properties.len() == 2
769        && let Some(nested) = properties.get("args")
770        && shape(nested) == args
771    {
772        return Some((id, true));
773    }
774    let mut fields = undescribed(alternative);
775    if let Some(Value::Object(properties)) = fields.get_mut("properties") {
776        properties.remove("action");
777    }
778    if let Some(Value::Array(required)) = fields.get_mut("required") {
779        required.retain(|name| name != "action");
780        if required.is_empty() {
781            fields.as_object_mut()?.remove("required");
782        }
783    }
784    (shape(&fields) == args).then_some((id, false))
785}
786
787/// A schema as compared for sameness: no descriptions, `required` in order,
788/// and no `null`: a declaration and serde may differ in whether a field
789/// takes `null`, and serde still reads the folded value strictly.
790fn shape(schema: &Value) -> Value {
791    let mut schema = non_null(&undescribed(schema));
792    sort_required(&mut schema);
793    schema
794}
795
796fn non_null(schema: &Value) -> Value {
797    let Value::Object(object) = schema else {
798        return match schema {
799            Value::Array(values) => Value::Array(values.iter().map(non_null).collect()),
800            other => other.clone(),
801        };
802    };
803    if let Some(Value::Array(alternatives)) = object.get("oneOf") {
804        let rest: Vec<&Value> = alternatives
805            .iter()
806            .filter(|alternative| **alternative != json!({"type": "null"}))
807            .collect();
808        if object.len() == 1
809            && let [only] = rest.as_slice()
810        {
811            return non_null(only);
812        }
813    }
814    Value::Object(
815        object
816            .iter()
817            .map(|(key, value)| {
818                let value = match (key.as_str(), value) {
819                    ("type", Value::Array(types)) => {
820                        let types: Vec<&Value> =
821                            types.iter().filter(|name| *name != "null").collect();
822                        match types.as_slice() {
823                            [only] => (*only).clone(),
824                            _ => Value::Array(types.into_iter().cloned().collect()),
825                        }
826                    }
827                    _ => non_null(value),
828                };
829                (key.clone(), value)
830            })
831            .collect(),
832    )
833}
834
835fn sort_required(schema: &mut Value) {
836    match schema {
837        Value::Object(object) => {
838            for (key, value) in object.iter_mut() {
839                if key == "required"
840                    && let Value::Array(names) = value
841                {
842                    names.compact_sort_by(|a, b| a.as_str().cmp(&b.as_str()));
843                } else {
844                    sort_required(value);
845                }
846            }
847        }
848        Value::Array(values) => values.iter_mut().for_each(sort_required),
849        _ => {}
850    }
851}
852
853/// The declared action a JSON action value names and its fields, in either
854/// form [`fold_declared`] folds.
855pub(crate) fn declared_invocation<'a>(
856    value: &'a Value,
857    declared: &[&str],
858) -> Option<(&'a str, Map<String, Value>)> {
859    let value = value.get("op").unwrap_or(value);
860    let id = value.get("action")?.as_str()?;
861    if !declared.contains(&id) {
862        return None;
863    }
864    let fields = if let Some(Value::Object(args)) = value.get("args") {
865        args.clone()
866    } else {
867        let mut fields = value.as_object()?.clone();
868        fields.remove("action");
869        fields
870    };
871    Some((id, fields))
872}
873
874/// One declared action as a member of a record's action schema.
875fn declared_operation(id: &str, params: &[ActionParam], description: &str) -> Value {
876    let variant = object(vec![
877        ("action", constant(id), true),
878        ("args", args_schema(params), true),
879    ]);
880    describe(variant, description)
881}
882
883/// The replayable action of a `#[resource]` record, as the generic
884/// [`APPLY`](crate::APPLY) takes it: `{"op": {"action": id, "args": {..}},
885/// "at": ms}`, one alternative per declaration.
886pub fn resource_action_schema<R: crate::Resource>() -> Value {
887    resource_action_schema_of(crate::vocabulary::<R>(), R::seed().is_some())
888}
889
890/// [`resource_action_schema`] of the resource `vocabulary`, which `seeds` its
891/// first content or not.
892fn resource_action_schema_of(vocabulary: &crate::Vocabulary, seeds: bool) -> Value {
893    let mut operations: Vec<Value> = Vec::new();
894    for decl in vocabulary.declarations().iter() {
895        operations.push(declared_operation(
896            decl.id,
897            &decl.params,
898            decl.description.as_deref().unwrap_or(&decl.label),
899        ));
900    }
901    if vocabulary.edits {
902        // Described in full by the field-edit action itself.
903        operations.push(describe(
904            object(vec![
905                ("action", constant(crate::FIELD_EDIT), true),
906                ("args", json!({"type": "object"}), true),
907            ]),
908            "A field edit, as the field-edit action takes it",
909        ));
910    }
911    if seeds {
912        operations.push(describe(
913            object(vec![("action", constant("seed"), true)]),
914            "Write the record's first content",
915        ));
916    }
917    object(vec![
918        ("op", one_of(operations), true),
919        (
920            "at",
921            describe(
922                json!({"type": "integer"}),
923                "When the action was authored, in milliseconds since the Unix epoch: set by the host that applies it, which replaces a value given here. When content was first written elsewhere, the action that writes it takes that as its `origin`",
924            ),
925            false,
926        ),
927    ])
928}
929
930/// A vocabulary's schema in a line: each alternative of an enum by its name
931/// and its arguments (`Name {a, b?}`; `?` marks an optional one), or by the
932/// value it takes.
933#[must_use]
934pub fn summary(schema: &Value) -> String {
935    let alternatives = schema
936        .get("oneOf")
937        .or_else(|| schema.get("anyOf"))
938        .and_then(Value::as_array)
939        .map_or_else(
940            || vec![schema],
941            |alternatives| alternatives.iter().collect(),
942        );
943    alternatives
944        .into_iter()
945        .filter_map(summarise_alternative)
946        .collect::<Vec<_>>()
947        .join("; ")
948}
949
950fn summarise_alternative(schema: &Value) -> Option<String> {
951    if let Some(value) = schema.get("const") {
952        return Some(
953            value
954                .as_str()
955                .map_or_else(|| value.to_string(), str::to_owned),
956        );
957    }
958    if let Some(values) = schema.get("enum").and_then(Value::as_array) {
959        return Some(
960            values
961                .iter()
962                .map(|value| {
963                    value
964                        .as_str()
965                        .map_or_else(|| value.to_string(), str::to_owned)
966                })
967                .collect::<Vec<_>>()
968                .join(" | "),
969        );
970    }
971    let properties = schema.get("properties")?.as_object()?;
972    // An externally tagged variant: one property, its name, holding its
973    // arguments.
974    if let [(name, inner)] = properties.iter().collect::<Vec<_>>().as_slice() {
975        let arguments = arguments_of(inner);
976        return Some(if arguments.is_empty() {
977            (*name).clone()
978        } else {
979            format!("{name} {{{arguments}}}")
980        });
981    }
982    Some(format!("{{{}}}", arguments_of(schema)))
983}
984
985fn arguments_of(schema: &Value) -> String {
986    let required: Vec<&str> = schema
987        .get("required")
988        .and_then(Value::as_array)
989        .map(|names| names.iter().filter_map(Value::as_str).collect())
990        .unwrap_or_default();
991    schema
992        .get("properties")
993        .and_then(Value::as_object)
994        .map(|properties| {
995            properties
996                .keys()
997                .map(|name| {
998                    if required.contains(&name.as_str()) {
999                        name.clone()
1000                    } else {
1001                        format!("{name}?")
1002                    }
1003                })
1004                .collect::<Vec<_>>()
1005                .join(", ")
1006        })
1007        .unwrap_or_default()
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use super::*;
1013
1014    tilo_test_env::scenario! {
1015        fn schemas_keep_nulls_tags_and_fields_named_description;
1016
1017        phase optional_values_accept_null_and_keep_their_shape;
1018        {
1019            assert_eq!(
1020                <Option<String>>::json_schema(),
1021                json!({"type": ["string", "null"]})
1022            );
1023            let choice = nullable(one_of(vec![constant("a"), constant("b")]));
1024            assert!(tilo_actions::validate_json_schema(&Value::Null, &choice).is_ok());
1025            assert!(tilo_actions::validate_json_schema(&json!("a"), &choice).is_ok());
1026            assert!(tilo_actions::validate_json_schema(&json!("c"), &choice).is_err());
1027            const { assert!(<Option<u8>>::OPTIONAL) };
1028            const { assert!(!<Vec<u8>>::OPTIONAL) };
1029        }
1030
1031        phase internal_tags_join_the_variant_fields;
1032        {
1033            let schema = internal(
1034                "kind",
1035                "Circle",
1036                object(vec![("radius", f64::json_schema(), true)]),
1037            );
1038            assert!(
1039                tilo_actions::validate_json_schema(&json!({"kind": "Circle", "radius": 1.5}), &schema)
1040                    .is_ok()
1041            );
1042            assert!(tilo_actions::validate_json_schema(&json!({"radius": 1.5}), &schema).is_err());
1043        }
1044
1045        phase a_copy_without_descriptions_keeps_fields_named_description;
1046        {
1047            let schema = describe(
1048                object(vec![(
1049                    "description",
1050                    describe(String::json_schema(), "Text"),
1051                    true,
1052                )]),
1053                "A note",
1054            );
1055            let copy = undescribed(&schema);
1056            assert!(copy.get("description").is_none());
1057            assert_eq!(copy["properties"]["description"], json!({"type": "string"}));
1058        }
1059    }
1060}