helm-schema-gen 0.0.4

Generate an accurate JSON schema for any helm chart
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
use serde_json::{Map, Value};

use crate::schema_model::{empty_schema, is_annotation_keyword, is_empty_schema, schema_type};
use crate::schema_node::SchemaNode;

pub(crate) fn merge_schema_list(schemas: Vec<Value>) -> Value {
    let mut it = dedup_schemas(schemas).into_iter();
    let Some(first) = it.next() else {
        return empty_schema();
    };
    it.fold(first, merge_two_schemas)
}

pub(crate) fn union_schema_list(mut schemas: Vec<Value>) -> Value {
    match schemas.len() {
        0 => return empty_schema(),
        1 => return schemas.pop().unwrap_or_else(empty_schema),
        _ => {}
    }

    let mut out: Vec<Value> = Vec::new();
    for schema in schemas {
        out.extend(flatten_union_variants(schema));
    }
    if out.iter().any(|schema| !is_empty_schema(schema)) {
        out.retain(|schema| !is_empty_schema(schema));
    }
    deduped_sorted_any_of(out)
}

pub(crate) fn merge_two_schemas(a: Value, b: Value) -> Value {
    if a == b {
        return a;
    }

    if is_empty_schema(&a) {
        return b;
    }
    if is_empty_schema(&b) {
        return a;
    }

    if union_contains_schema(&a, &b) {
        return a;
    }
    if union_contains_schema(&b, &a) {
        return b;
    }

    if let Some(merged) = try_merge_nullable_scalar_schema(&a, &b) {
        return merged;
    }

    if let Some(merged) = try_merge_compatible(&a, &b) {
        return merged;
    }

    let mut out: Vec<Value> = Vec::new();
    out.extend(flatten_union_variants(a));
    out.extend(flatten_union_variants(b));
    deduped_sorted_any_of(collapse_compatible_variants(out))
}

fn deduped_sorted_any_of(variants: Vec<Value>) -> Value {
    let mut variants = dedup_schemas(variants);
    variants.sort_by_key(helm_schema_json_schema_walk::canonical_json_string);
    if let [variant] = variants.as_slice() {
        return variant.clone();
    }
    SchemaNode::any_of(variants.into_iter().map(SchemaNode::foreign).collect()).into_value()
}

fn flatten_union_variants(v: Value) -> Vec<Value> {
    if let Value::Object(obj) = &v
        && let Some(arr) = obj.get("anyOf").and_then(|x| x.as_array())
    {
        return arr.clone();
    }
    if let Value::Object(mut obj) = v.clone()
        && let Some(Value::Array(types)) = obj.remove("type")
    {
        let mut variants = Vec::new();
        for ty in types {
            let Some(ty) = ty.as_str() else {
                continue;
            };
            let mut variant = obj.clone();
            if ty == "null" {
                variant.retain(|key, _| key == "type");
            }
            variant.insert("type".to_string(), Value::String(ty.to_string()));
            variants.push(Value::Object(variant));
        }
        if !variants.is_empty() {
            return variants;
        }
    }
    vec![v]
}

fn union_contains_schema(union: &Value, candidate: &Value) -> bool {
    union_variants(union).is_some_and(|variants| {
        variants
            .iter()
            .any(|variant| variant == candidate || union_contains_schema(variant, candidate))
    })
}

fn union_variants(schema: &Value) -> Option<&Vec<Value>> {
    let object = schema.as_object()?;
    object
        .get("anyOf")
        .and_then(Value::as_array)
        .or_else(|| object.get("oneOf").and_then(Value::as_array))
}

fn try_merge_nullable_scalar_schema(a: &Value, b: &Value) -> Option<Value> {
    match (schema_type(a), schema_type(b)) {
        (Some("null"), Some(scalar_type)) => nullable_scalar_schema(b, scalar_type),
        (Some(scalar_type), Some("null")) => nullable_scalar_schema(a, scalar_type),
        _ => None,
    }
}

fn nullable_scalar_schema(schema: &Value, scalar_type: &str) -> Option<Value> {
    if !matches!(scalar_type, "boolean" | "integer" | "number" | "string") {
        return None;
    }

    let mut object = schema.as_object()?.clone();
    if object.contains_key("enum") || object.contains_key("const") {
        return None;
    }
    object.insert(
        "type".to_string(),
        Value::Array(vec![
            Value::String(scalar_type.to_string()),
            Value::String("null".to_string()),
        ]),
    );
    Some(Value::Object(object))
}

fn collapse_compatible_variants(variants: Vec<Value>) -> Vec<Value> {
    if variants.len() < 2 {
        return variants;
    }

    let mut out: Vec<Value> = Vec::new();
    'variants: for variant in variants {
        for existing in &mut out {
            if let Some(merged) = try_merge_compatible(existing, &variant) {
                *existing = merged;
                continue 'variants;
            }
        }
        out.push(variant);
    }
    out
}

fn dedup_schemas(schemas: Vec<Value>) -> Vec<Value> {
    if schemas.len() < 2 {
        return schemas;
    }

    let mut out = Vec::new();
    for schema in schemas {
        if out.iter().any(|existing| existing == &schema) {
            continue;
        }
        out.push(schema);
    }
    out
}

fn is_exact_empty_object_schema(v: &Value) -> bool {
    let Some(obj) = v.as_object() else {
        return false;
    };
    schema_type(v) == Some("object") && obj.get("maxProperties").and_then(Value::as_u64) == Some(0)
}

fn try_merge_compatible(a: &Value, b: &Value) -> Option<Value> {
    let ta = schema_type(a)?;
    let tb = schema_type(b)?;
    if ta != tb {
        return None;
    }

    match ta {
        "object" if is_exact_empty_object_schema(a) || is_exact_empty_object_schema(b) => None,
        "object" => merge_object_schemas(a, b),
        "array" => merge_array_schemas(a, b),
        _ => merge_scalar_like_schemas(a, b),
    }
}

fn merge_array_schemas(a: &Value, b: &Value) -> Option<Value> {
    let mut out = a.as_object()?.clone();
    let bobj = b.as_object()?;

    match (out.get("items").cloned(), bobj.get("items").cloned()) {
        (Some(items_a), Some(items_b)) => {
            if !items_a.is_null() && !items_b.is_null() {
                out.insert("items".to_string(), merge_two_schemas(items_a, items_b));
            } else if items_a.is_null() {
                out.insert("items".to_string(), items_b);
            }
        }
        (None, Some(items_b)) => {
            out.insert("items".to_string(), items_b);
        }
        _ => {}
    }

    for (k, bv) in bobj {
        if k == "type" || k == "items" {
            continue;
        }
        match out.get(k) {
            None => {
                out.insert(k.clone(), bv.clone());
            }
            Some(av) if av == bv => {}
            _ => {
                return None;
            }
        }
    }

    out.insert("type".to_string(), Value::String("array".to_string()));
    // No `items` stamp when neither side had an opinion: `items: null` is
    // not a schema, and the null-tolerant arms above already treat an
    // absent `items` as no opinion.
    Some(Value::Object(out))
}

fn merge_scalar_like_schemas(a: &Value, b: &Value) -> Option<Value> {
    let mut out = a.as_object()?.clone();
    let bobj = b.as_object()?;
    let is_string_type = out.get("type").and_then(Value::as_str) == Some("string");

    match (
        out.get("enum").and_then(|v| v.as_array()).cloned(),
        bobj.get("enum").and_then(|v| v.as_array()).cloned(),
    ) {
        (Some(ae), Some(be)) => {
            let mut inter: Vec<Value> = ae.into_iter().filter(|v| be.contains(v)).collect();
            inter.sort_by_key(std::string::ToString::to_string);
            inter.dedup();
            if inter.is_empty() {
                return None;
            }
            out.insert("enum".to_string(), Value::Array(inter));
        }
        (None, Some(be)) => {
            out.insert("enum".to_string(), Value::Array(be));
        }
        _ => {}
    }

    for (k, bv) in bobj {
        if k == "type" || k == "enum" {
            continue;
        }
        match out.get(k) {
            None => {
                out.insert(k.clone(), bv.clone());
            }
            Some(av) if av == bv => {}
            Some(_) if is_string_type => {
                out.remove(k);
            }
            Some(_) if is_annotation_keyword(k) => {
                out.remove(k);
            }
            _ => {
                return None;
            }
        }
    }

    if let Some(values) = out.get("enum").and_then(Value::as_array)
        && !values
            .iter()
            .all(|value| enum_value_satisfies_scalar_schema(value, &out))
    {
        return None;
    }

    Some(Value::Object(out))
}

fn enum_value_satisfies_scalar_schema(value: &Value, schema: &Map<String, Value>) -> bool {
    match schema.get("type").and_then(Value::as_str) {
        Some("string") => {
            let Some(value) = value.as_str() else {
                return false;
            };
            let len = value.chars().count() as u64;
            if schema
                .get("minLength")
                .and_then(Value::as_u64)
                .is_some_and(|min_length| len < min_length)
            {
                return false;
            }
            if schema
                .get("maxLength")
                .and_then(Value::as_u64)
                .is_some_and(|max_length| len > max_length)
            {
                return false;
            }
            !schema.contains_key("pattern")
        }
        Some("integer") => value.as_i64().is_some() || value.as_u64().is_some(),
        Some("number") => value.is_number(),
        Some("boolean") => value.is_boolean(),
        Some("null") => value.is_null(),
        _ => true,
    }
}

#[expect(
    clippy::too_many_lines,
    reason = "merging object keywords is clearer as one exhaustive, stateful operation"
)]
fn merge_object_schemas(a: &Value, b: &Value) -> Option<Value> {
    fn has_meaningful_additional_properties(obj: &Map<String, Value>) -> bool {
        obj.get("additionalProperties")
            .and_then(|value| value.as_object())
            .is_some_and(|map| !map.is_empty())
            || preserves_unknown_fields(obj)
    }

    fn preserves_unknown_fields(obj: &Map<String, Value>) -> bool {
        obj.get("x-kubernetes-preserve-unknown-fields")
            .and_then(Value::as_bool)
            == Some(true)
    }

    fn is_structured_object(obj: &Map<String, Value>) -> bool {
        obj.get("properties")
            .and_then(|v| v.as_object())
            .is_some_and(|m| !m.is_empty())
            || obj
                .get("patternProperties")
                .and_then(|v| v.as_object())
                .is_some_and(|m| !m.is_empty())
            || has_meaningful_additional_properties(obj)
            || obj
                .get("required")
                .and_then(|v| v.as_array())
                .is_some_and(|a| !a.is_empty())
            || obj
                .get("allOf")
                .and_then(|v| v.as_array())
                .is_some_and(|a| !a.is_empty())
            // A sibling `anyOf` (a member-requirement alternation) is
            // structure: replacing the object with the other side would
            // silently drop the alternation.
            || obj
                .get("anyOf")
                .and_then(|v| v.as_array())
                .is_some_and(|a| !a.is_empty())
    }

    let mut out = a.as_object()?.clone();
    let bobj = b.as_object()?;

    let a_structured = is_structured_object(&out);
    let b_structured = is_structured_object(bobj);
    if !a_structured && b_structured {
        return Some(Value::Object(bobj.clone()));
    }
    if !b_structured && a_structured {
        return Some(Value::Object(out));
    }

    let a_map_like = has_meaningful_additional_properties(&out);
    let b_map_like = has_meaningful_additional_properties(bobj);
    let a_preserves_unknown = preserves_unknown_fields(&out);
    let b_preserves_unknown = preserves_unknown_fields(bobj);

    match (
        out.get("additionalProperties").cloned(),
        bobj.get("additionalProperties").cloned(),
    ) {
        _ if a_preserves_unknown || b_preserves_unknown => {
            out.remove("additionalProperties");
        }
        (Some(ap_a), Some(ap_b)) if a_map_like && b_map_like => {
            out.insert(
                "additionalProperties".to_string(),
                merge_two_schemas(ap_a, ap_b),
            );
        }
        (Some(Value::Bool(false)), Some(ap_b)) if ap_b.is_object() => {
            out.insert("additionalProperties".to_string(), ap_b);
        }
        (Some(ap_a), Some(Value::Bool(false))) if ap_a.is_object() => {
            out.insert("additionalProperties".to_string(), ap_a);
        }
        (Some(Value::Bool(false)), _) | (_, Some(Value::Bool(false))) => {
            out.insert("additionalProperties".to_string(), Value::Bool(false));
        }
        (Some(Value::Bool(true)) | None, Some(ap_b)) => {
            out.insert("additionalProperties".to_string(), ap_b);
        }
        (Some(ap_a), Some(Value::Bool(true))) => {
            out.insert("additionalProperties".to_string(), ap_a);
        }
        (Some(ap_a), Some(ap_b)) => {
            out.insert(
                "additionalProperties".to_string(),
                merge_two_schemas(ap_a, ap_b),
            );
        }
        _ => {}
    }

    // Merge required lists by union.
    let mut required: Vec<String> = out
        .get("required")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|x| x.as_str().map(std::string::ToString::to_string))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    if let Some(breq) = bobj.get("required").and_then(|v| v.as_array()) {
        for v in breq {
            if let Some(s) = v.as_str() {
                required.push(s.to_string());
            }
        }
    }
    required.sort();
    required.dedup();
    if !required.is_empty() {
        out.insert(
            "required".to_string(),
            Value::Array(required.into_iter().map(Value::String).collect()),
        );
    }

    out.insert(
        "properties".to_string(),
        Value::Object(merge_schema_maps(&out, bobj, "properties")),
    );

    let pattern_properties = merge_schema_maps(&out, bobj, "patternProperties");
    if !pattern_properties.is_empty() {
        out.insert(
            "patternProperties".to_string(),
            Value::Object(pattern_properties),
        );
    }

    let mut all_of = out
        .get("allOf")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    if let Some(b_all_of) = bobj.get("allOf").and_then(Value::as_array) {
        all_of.extend(b_all_of.iter().cloned());
    }
    // A sibling `anyOf` is conjunctive with the object keywords (a
    // member-requirement alternation such as traefik's hostPath-or-type
    // local plugins): carry the other side's alternation instead of
    // silently dropping it, nesting under `allOf` when both sides
    // alternate.
    if let Some(b_any_of) = bobj.get("anyOf")
        && out.get("anyOf") != Some(b_any_of)
    {
        if out.contains_key("anyOf") {
            all_of.push(serde_json::json!({ "anyOf": b_any_of }));
        } else {
            out.insert("anyOf".to_string(), b_any_of.clone());
        }
    }
    all_of = dedup_schemas(all_of);
    if !all_of.is_empty() {
        out.insert("allOf".to_string(), Value::Array(all_of));
    }

    out.insert("type".to_string(), Value::String("object".to_string()));

    Some(Value::Object(out))
}

fn merge_schema_maps(
    left: &Map<String, Value>,
    right: &Map<String, Value>,
    key: &str,
) -> Map<String, Value> {
    let mut merged = left
        .get(key)
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_else(Map::new);
    let right_entries = right
        .get(key)
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_else(Map::new);
    for (entry_key, right_value) in right_entries {
        match merged.remove(&entry_key) {
            None => {
                merged.insert(entry_key, right_value);
            }
            Some(left_value) => {
                merged.insert(entry_key, merge_two_schemas(left_value, right_value));
            }
        }
    }
    merged
}

#[cfg(test)]
#[path = "tests/merge.rs"]
mod tests;