trilean-json-shape 3.1.6

One Rust definition for validating JSON, a JSON Schema and TypeScript declarations.
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
//! The JSON Schema a shape writes.

use crate::def::{Definitions, Kind, ObjectDef, ShapeDef};
use crate::shape::Shape;
use crate::value::Value;

/// The JSON Schema draft to write.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Draft {
    /// Writes `definitions` and references under `#/definitions/`, and `dependencies` for required-together keys.
    Draft07,
    /// Writes `$defs` and references under `#/$defs/`, and `dependentRequired`.
    #[default]
    Draft2020_12,
}

/// How a standalone schema document is written.
#[derive(Clone, Copy, Debug, Default)]
pub struct SchemaOptions<'a> {
    pub draft: Draft,
    /// The `$id` of the document.
    pub id: Option<&'a str>,
    /// The `title` of the document.
    pub title: Option<&'a str>,
}

/// Where references point and how the dependent keys are written.
#[derive(Clone, Copy)]
struct Writer<'a> {
    draft: Draft,
    pointer: &'a str,
}

/// A definition name as the last step of a `$ref`: a JSON Pointer token (`~` as `~0`, `/` as `~1`), then written as a
/// URI fragment, where every byte outside the characters a fragment allows is percent-encoded.
fn reference_token(name: &str) -> String {
    let token = name.replace('~', "~0").replace('/', "~1");
    let mut written = String::new();
    for byte in token.bytes() {
        if byte.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@".contains(&byte) {
            written.push(char::from(byte));
        } else {
            written.push_str(&format!("%{byte:02X}"));
        }
    }
    written
}

fn number(value: f64) -> Value {
    Value::Number(value)
}

fn count(value: usize) -> Value {
    // A count is far below 2^53, so it is exact as a JSON number.
    Value::Number(value as f64)
}

fn text(value: &str) -> Value {
    Value::String(value.to_owned())
}

fn push(pairs: &mut Vec<(String, Value)>, key: &str, value: Value) {
    pairs.push((key.to_owned(), value));
}

fn object(pairs: Vec<(String, Value)>) -> Value {
    Value::Object(pairs)
}

fn typed(name: &str) -> Vec<(String, Value)> {
    vec![("type".to_owned(), text(name))]
}

/// The schema of one shape, with references written as `options` say.
fn shape_schema(shape: &ShapeDef, options: Writer<'_>) -> Value {
    let mut pairs = match &shape.kind {
        Kind::Any => Vec::new(),
        Kind::Null => typed("null"),
        Kind::Bool => typed("boolean"),
        Kind::ConstBool(flag) => vec![("const".to_owned(), Value::Bool(*flag))],
        Kind::ConstString(value) => vec![("const".to_owned(), text(value))],
        Kind::Enum(options) => vec![(
            "enum".to_owned(),
            Value::Array(options.iter().map(|option| text(option)).collect()),
        )],
        Kind::String {
            min_length,
            pattern,
        } => {
            let mut pairs = typed("string");
            if let Some(least) = min_length {
                push(&mut pairs, "minLength", count(*least));
            }
            if let Some(source) = pattern {
                push(&mut pairs, "pattern", text(source));
            }
            pairs
        }
        Kind::Integer {
            min,
            exclusive_min,
            max,
        } => bounded("integer", [*min, *exclusive_min, *max]),
        Kind::Number {
            min,
            exclusive_min,
            max,
        } => bounded("number", [*min, *exclusive_min, *max]),
        Kind::Array {
            items,
            min_items,
            max_items,
            unique,
        } => {
            let mut pairs = typed("array");
            if items.kind != Kind::Any || items.description.is_some() {
                push(&mut pairs, "items", shape_schema(items, options));
            }
            if let Some(least) = min_items {
                push(&mut pairs, "minItems", count(*least));
            }
            if let Some(most) = max_items {
                push(&mut pairs, "maxItems", count(*most));
            }
            if *unique {
                push(&mut pairs, "uniqueItems", Value::Bool(true));
            }
            pairs
        }
        Kind::Map {
            values,
            min_properties,
            key_pattern,
        } => {
            let mut pairs = typed("object");
            push(
                &mut pairs,
                "additionalProperties",
                shape_schema(values, options),
            );
            if let Some(least) = min_properties {
                push(&mut pairs, "minProperties", count(*least));
            }
            if let Some(source) = key_pattern {
                push(
                    &mut pairs,
                    "propertyNames",
                    object(vec![("pattern".to_owned(), text(source))]),
                );
            }
            pairs
        }
        Kind::Object(definition) => object_pairs(definition, options),
        Kind::OneOf(alternatives) => vec![(
            "oneOf".to_owned(),
            Value::Array(
                alternatives
                    .iter()
                    .map(|alternative| shape_schema(alternative, options))
                    .collect(),
            ),
        )],
        Kind::Tagged { variants, .. } => vec![(
            "oneOf".to_owned(),
            Value::Array(
                variants
                    .iter()
                    .map(|(_, variant)| shape_schema(variant, options))
                    .collect(),
            ),
        )],
        Kind::Not(inner) => vec![("not".to_owned(), shape_schema(inner, options))],
        Kind::AllOf(parts) => merged_or_all_of(parts, options),
        Kind::Ref(name) => vec![(
            "$ref".to_owned(),
            text(&format!("{}/{}", options.pointer, reference_token(name))),
        )],
    };
    if let Some(description) = &shape.description {
        push(&mut pairs, "description", text(description));
    }
    object(pairs)
}

/// The parts as one node when no keyword is used by two of them, which is what a reader of the schema expects of a
/// shape built from several; as `allOf` otherwise.
fn merged_or_all_of(parts: &[ShapeDef], options: Writer<'_>) -> Vec<(String, Value)> {
    let written: Vec<Vec<(String, Value)>> = parts
        .iter()
        .map(|part| match shape_schema(part, options) {
            Value::Object(pairs) => pairs,
            other => unreachable!("a shape's schema is an object, not {other}"),
        })
        .collect();
    let mut merged: Vec<(String, Value)> = Vec::new();
    for pairs in &written {
        if pairs
            .iter()
            .any(|(key, _)| merged.iter().any(|(known, _)| known == key))
        {
            return vec![(
                "allOf".to_owned(),
                Value::Array(written.into_iter().map(Value::Object).collect()),
            )];
        }
        merged.extend(pairs.iter().cloned());
    }
    merged
}

fn bounded(name: &str, [min, exclusive_min, max]: [Option<f64>; 3]) -> Vec<(String, Value)> {
    let mut pairs = typed(name);
    if let Some(least) = min {
        push(&mut pairs, "minimum", number(least));
    }
    if let Some(above) = exclusive_min {
        push(&mut pairs, "exclusiveMinimum", number(above));
    }
    if let Some(most) = max {
        push(&mut pairs, "maximum", number(most));
    }
    pairs
}

fn object_pairs(definition: &ObjectDef, options: Writer<'_>) -> Vec<(String, Value)> {
    let mut pairs = typed("object");
    if !definition.fields.is_empty() {
        push(
            &mut pairs,
            "properties",
            object(
                definition
                    .fields
                    .iter()
                    .map(|field| (field.name.clone(), shape_schema(&field.shape, options)))
                    .collect(),
            ),
        );
    }
    let required: Vec<Value> = definition
        .fields
        .iter()
        .filter(|field| field.required)
        .map(|field| text(&field.name))
        .collect();
    if !required.is_empty() {
        push(&mut pairs, "required", Value::Array(required));
    }
    if let Some(additional) = &definition.additional {
        push(
            &mut pairs,
            "additionalProperties",
            shape_schema(additional, options),
        );
    } else if definition.closed {
        push(&mut pairs, "additionalProperties", Value::Bool(false));
    }
    for (keyword, keys) in [
        ("anyOf", &definition.any_of_keys),
        ("oneOf", &definition.one_of_keys),
    ] {
        if !keys.is_empty() {
            let alternatives = keys
                .iter()
                .map(|key| {
                    object(vec![
                        (
                            "properties".to_owned(),
                            object(vec![(key.clone(), Value::Object(Vec::new()))]),
                        ),
                        ("required".to_owned(), Value::Array(vec![text(key)])),
                        ("type".to_owned(), text("object")),
                    ])
                })
                .collect();
            push(&mut pairs, keyword, Value::Array(alternatives));
        }
    }
    if let Some(least) = definition.min_properties {
        push(&mut pairs, "minProperties", count(least));
    }
    if !definition.dependent_required.is_empty() {
        let keyword = match options.draft {
            Draft::Draft07 => "dependencies",
            Draft::Draft2020_12 => "dependentRequired",
        };
        push(
            &mut pairs,
            keyword,
            object(
                definition
                    .dependent_required
                    .iter()
                    .map(|(key, others)| {
                        (
                            key.clone(),
                            Value::Array(others.iter().map(|other| text(other)).collect()),
                        )
                    })
                    .collect(),
            ),
        );
    }
    pairs
}

fn definitions_keyword(draft: Draft) -> &'static str {
    match draft {
        Draft::Draft07 => "definitions",
        Draft::Draft2020_12 => "$defs",
    }
}

/// Just the definitions, each as a schema whose references are written under `pointer`, a JSON Pointer fragment
/// such as `#/definitions/trilean`, which is where the document that embeds them holds them.
pub fn schema_definitions(
    definitions: &Definitions,
    draft: Draft,
    pointer: &str,
) -> Vec<(String, Value)> {
    let writer = Writer { draft, pointer };
    definitions
        .iter()
        .map(|(name, shape)| (name.to_owned(), shape_schema(shape, writer)))
        .collect()
}

/// A standalone document for `root`, written inline at the top with every other definition under `$defs` (or
/// `definitions`). `root_name` is the root's own definition, dropped from the block unless another definition
/// refers to it.
pub fn json_schema(
    root: &ShapeDef,
    root_name: &str,
    definitions: &Definitions,
    options: &SchemaOptions<'_>,
) -> Value {
    let mut pairs = Vec::new();
    push(
        &mut pairs,
        "$schema",
        text(match options.draft {
            Draft::Draft07 => "http://json-schema.org/draft-07/schema#",
            Draft::Draft2020_12 => "https://json-schema.org/draft/2020-12/schema",
        }),
    );
    if let Some(id) = options.id {
        push(&mut pairs, "$id", text(id));
    }
    if let Some(title) = options.title {
        push(&mut pairs, "title", text(title));
    }
    let pointer = match options.draft {
        Draft::Draft07 => "#/definitions",
        Draft::Draft2020_12 => "#/$defs",
    };
    let writer = Writer {
        draft: options.draft,
        pointer,
    };
    let Value::Object(body) = shape_schema(root, writer) else {
        unreachable!("a shape's schema is an object")
    };
    pairs.extend(body);
    let kept = if refers_to(definitions, root_name) || mentions(root, root_name) {
        definitions.clone()
    } else {
        definitions.clone().without(root_name)
    };
    if !kept.is_empty() {
        push(
            &mut pairs,
            definitions_keyword(options.draft),
            object(schema_definitions(&kept, options.draft, pointer)),
        );
    }
    object(pairs)
}

/// Whether any definition other than `name` refers to it.
fn refers_to(definitions: &Definitions, name: &str) -> bool {
    definitions
        .iter()
        .filter(|(entry, _)| *entry != name)
        .any(|(_, shape)| mentions(shape, name))
}

fn mentions(shape: &ShapeDef, name: &str) -> bool {
    match &shape.kind {
        Kind::Ref(target) => target == name,
        Kind::Array { items, .. } => mentions(items, name),
        Kind::Map { values, .. } => mentions(values, name),
        Kind::Object(definition) => {
            definition
                .fields
                .iter()
                .any(|field| mentions(&field.shape, name))
                || definition
                    .additional
                    .as_ref()
                    .is_some_and(|additional| mentions(additional, name))
        }
        Kind::OneOf(alternatives) | Kind::AllOf(alternatives) => alternatives
            .iter()
            .any(|alternative| mentions(alternative, name)),
        Kind::Not(inner) => mentions(inner, name),
        Kind::Tagged { variants, .. } => {
            variants.iter().any(|(_, variant)| mentions(variant, name))
        }
        _ => false,
    }
}

/// The standalone document for the type `T`, named by `root_name`, with the definitions it needs.
pub fn schema_of<T: Shape>(root_name: &str, options: &SchemaOptions<'_>) -> Value {
    json_schema(&T::definition(), root_name, &T::definitions(), options)
}