aion-package 0.6.0

Archive validation, content hashing, and namespacing for Aion workflow packages.
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
//! Gleam source emission for parsed schema artifacts.
//!
//! Emission is a pure function of the artifact list, so generation is
//! deterministic: same schemas in, byte-identical module out. The emitted
//! idioms mirror the hand-written codecs in the repository examples:
//! `json.object` / `json.array` encoders and `gleam/dynamic/decode`
//! use-chained decoders, with `decode.optional_field` + `decode.optional`
//! for optional properties (omitted from the wire when `None`).

use std::fmt::Write as _;

use super::schema::{EnumDef, Field, GleamType, RecordDef, SchemaArtifact, TypeDef};

/// Header line every generated module starts with (the do-not-edit contract).
pub(crate) const GENERATED_HEADER: &str =
    "//// Generated by aion codegen — do not edit; regenerate from schemas/.";

/// Renders the complete generated module for `artifacts` (already in
/// deterministic schema-file order).
pub(crate) fn emit_module(project_name: &str, artifacts: &[SchemaArtifact]) -> String {
    let has_optionals = artifacts.iter().any(|artifact| {
        artifact.defs.iter().any(|def| match def {
            TypeDef::Record(record) => record.fields.iter().any(|field| !field.required),
            TypeDef::Enum(_) => false,
        })
    });

    let mut out = String::new();
    let _ = writeln!(out, "{GENERATED_HEADER}");
    out.push_str("////\n");
    let _ = writeln!(
        out,
        "//// Types and JSON codecs for the `{project_name}` workflow project,"
    );
    out.push_str("//// derived from every `schemas/*.json` document in filename order.\n");
    out.push('\n');
    out.push_str("import gleam/dynamic/decode\n");
    out.push_str("import gleam/json\n");
    if has_optionals {
        out.push_str("import gleam/list\n");
        out.push_str("import gleam/option\n");
    }

    for artifact in artifacts {
        if !matches!(artifact.root, GleamType::Named { .. }) {
            emit_root_wrapper(&mut out, artifact);
        }
        for def in &artifact.defs {
            match def {
                TypeDef::Record(record) => emit_record(&mut out, artifact, record),
                TypeDef::Enum(definition) => emit_enum(&mut out, artifact, definition),
            }
        }
    }
    out
}

/// `schemas/output.json` documents whose root is not an object or enum still
/// get a `<stem>_to_json` / `<stem>_decoder` pair for the payload itself.
fn emit_root_wrapper(out: &mut String, artifact: &SchemaArtifact) {
    let file = artifact.file.display();
    let stem = &artifact.stem;
    let ty = type_text(&artifact.root);
    let _ = write!(
        out,
        "\n/// Encodes the `{file}` payload as schema-shaped JSON.\n\
         pub fn {stem}_to_json(value: {ty}) -> json.Json {{\n  {}\n}}\n",
        encode_call(&artifact.root, "value", 0)
    );
    let _ = write!(
        out,
        "\n/// Decoder for the `{file}` payload.\n\
         pub fn {stem}_decoder() -> decode.Decoder({ty}) {{\n  {}\n}}\n",
        decoder_expr(&artifact.root)
    );
}

fn origin(artifact: &SchemaArtifact, pointer: &str) -> String {
    if pointer.is_empty() {
        format!("`{}`", artifact.file.display())
    } else {
        format!("`{}` at `{pointer}`", artifact.file.display())
    }
}

fn emit_record(out: &mut String, artifact: &SchemaArtifact, record: &RecordDef) {
    let name = &record.type_name;
    let prefix = &record.fn_prefix;
    let source = origin(artifact, &record.pointer);

    // Type declaration.
    let _ = write!(out, "\n/// Generated from {source}.\npub type {name} {{\n");
    if record.fields.is_empty() {
        let _ = writeln!(out, "  {name}");
    } else {
        let _ = writeln!(out, "  {name}(");
        for field in &record.fields {
            let _ = writeln!(out, "    {}: {},", field.wire, field_type_text(field));
        }
        out.push_str("  )\n");
    }
    out.push_str("}\n");

    // Encoder.
    let _ = write!(
        out,
        "\n/// Encodes `{name}` as schema-shaped JSON; optional fields are\n\
         /// omitted when `None`.\n\
         pub fn {prefix}_to_json(value: {name}) -> json.Json {{\n"
    );
    if record.fields.iter().all(|field| field.required) {
        out.push_str("  json.object([\n");
        for field in &record.fields {
            let _ = writeln!(out, "    {},", field_pair(field));
        }
        out.push_str("  ])\n");
    } else {
        out.push_str("  json.object(\n    list.flatten([\n");
        for field in &record.fields {
            if field.required {
                let _ = writeln!(out, "      [{}],", field_pair(field));
            } else {
                let _ = writeln!(out, "      case value.{} {{", field.wire);
                let _ = writeln!(
                    out,
                    "        option.Some(present) -> [#(\"{}\", {})]",
                    field.wire,
                    encode_call(&field.ty, "present", 0)
                );
                out.push_str("        option.None -> []\n      },\n");
            }
        }
        out.push_str("    ]),\n  )\n");
    }
    out.push_str("}\n");

    // Decoder. Bindings are hygienic (`field_<wire>`): a raw `use <wire>`
    // binding for a property named `decode` or `option` would shadow the
    // generated imports for the rest of the decoder and fail `gleam build`.
    let _ = write!(
        out,
        "\n/// Decoder for `{name}` from schema-shaped JSON.\n\
         pub fn {prefix}_decoder() -> decode.Decoder({name}) {{\n"
    );
    for field in &record.fields {
        if field.required {
            let _ = writeln!(
                out,
                "  use field_{wire} <- decode.field(\"{wire}\", {})",
                decoder_expr(&field.ty),
                wire = field.wire,
            );
        } else {
            let _ = writeln!(
                out,
                "  use field_{wire} <- decode.optional_field(\n    \"{wire}\",\n    \
                 option.None,\n    decode.optional({}),\n  )",
                decoder_expr(&field.ty),
                wire = field.wire,
            );
        }
    }
    if record.fields.is_empty() {
        let _ = writeln!(out, "  decode.success({name})");
    } else {
        let _ = writeln!(out, "  decode.success({name}(");
        for field in &record.fields {
            let _ = writeln!(out, "    {wire}: field_{wire},", wire = field.wire);
        }
        out.push_str("  ))\n");
    }
    out.push_str("}\n");
}

fn emit_enum(out: &mut String, artifact: &SchemaArtifact, definition: &EnumDef) {
    // `parse_schema` rejects empty enums, so an `EnumDef` always has a first
    // variant (needed below as the `decode.failure` placeholder). Were the
    // invariant ever broken, the missing type would fail `gleam build`
    // loudly rather than panic here.
    let Some(first_variant) = definition.variants.first() else {
        return;
    };
    let name = &definition.type_name;
    let prefix = &definition.fn_prefix;
    let source = origin(artifact, &definition.pointer);

    let _ = write!(out, "\n/// Generated from {source}.\npub type {name} {{\n");
    for variant in &definition.variants {
        let _ = writeln!(out, "  {}", variant.constructor);
    }
    out.push_str("}\n");

    let _ = write!(
        out,
        "\n/// Encodes `{name}` as its wire string.\n\
         pub fn {prefix}_to_json(value: {name}) -> json.Json {{\n  case value {{\n"
    );
    for variant in &definition.variants {
        let _ = writeln!(
            out,
            "    {} -> json.string(\"{}\")",
            variant.constructor, variant.wire
        );
    }
    out.push_str("  }\n}\n");

    let _ = write!(
        out,
        "\n/// Decoder for `{name}` from its wire string.\n\
         pub fn {prefix}_decoder() -> decode.Decoder({name}) {{\n  \
         decode.then(decode.string, fn(raw) {{\n    case raw {{\n"
    );
    for variant in &definition.variants {
        let _ = writeln!(
            out,
            "      \"{}\" -> decode.success({})",
            variant.wire, variant.constructor
        );
    }
    let _ = writeln!(
        out,
        "      _ -> decode.failure({}, \"{name}\")",
        first_variant.constructor
    );
    out.push_str("    }\n  })\n}\n");
}

/// `#("wire", <encoded value.field>)` for a required field.
fn field_pair(field: &Field) -> String {
    format!(
        "#(\"{wire}\", {})",
        encode_call(&field.ty, &format!("value.{}", field.wire), 0),
        wire = field.wire,
    )
}

/// The Gleam type annotation for a field, wrapping optionals.
fn field_type_text(field: &Field) -> String {
    let inner = type_text(&field.ty);
    if field.required {
        inner
    } else {
        format!("option.Option({inner})")
    }
}

fn type_text(ty: &GleamType) -> String {
    match ty {
        GleamType::String => "String".to_owned(),
        GleamType::Int => "Int".to_owned(),
        GleamType::Float => "Float".to_owned(),
        GleamType::Bool => "Bool".to_owned(),
        GleamType::List(inner) => format!("List({})", type_text(inner)),
        GleamType::Named { type_name, .. } => type_name.clone(),
    }
}

/// An applied encoder expression for `expr` of type `ty`.
fn encode_call(ty: &GleamType, expr: &str, depth: usize) -> String {
    match ty {
        GleamType::String => format!("json.string({expr})"),
        GleamType::Int => format!("json.int({expr})"),
        GleamType::Float => format!("json.float({expr})"),
        GleamType::Bool => format!("json.bool({expr})"),
        GleamType::List(inner) => format!("json.array({expr}, {})", encode_fn(inner, depth)),
        GleamType::Named { fn_prefix, .. } => format!("{fn_prefix}_to_json({expr})"),
    }
}

/// A point-free (or lambda, for nested lists) encoder function for `ty`.
fn encode_fn(ty: &GleamType, depth: usize) -> String {
    match ty {
        GleamType::String => "json.string".to_owned(),
        GleamType::Int => "json.int".to_owned(),
        GleamType::Float => "json.float".to_owned(),
        GleamType::Bool => "json.bool".to_owned(),
        GleamType::List(inner) => {
            let var = format!("items{depth}");
            format!(
                "fn({var}) {{ json.array({var}, {}) }}",
                encode_fn(inner, depth + 1)
            )
        }
        GleamType::Named { fn_prefix, .. } => format!("{fn_prefix}_to_json"),
    }
}

/// A decoder expression for `ty`.
fn decoder_expr(ty: &GleamType) -> String {
    match ty {
        GleamType::String => "decode.string".to_owned(),
        GleamType::Int => "decode.int".to_owned(),
        GleamType::Float => "decode.float".to_owned(),
        GleamType::Bool => "decode.bool".to_owned(),
        GleamType::List(inner) => format!("decode.list({})", decoder_expr(inner)),
        GleamType::Named { fn_prefix, .. } => format!("{fn_prefix}_decoder()"),
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::{GENERATED_HEADER, emit_module};
    use crate::codegen::json::parse_ordered;
    use crate::codegen::names::NameRegistry;
    use crate::codegen::schema::{SchemaArtifact, parse_schema};

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    fn artifact(stem: &str, json: &str, registry: &mut NameRegistry) -> TestResult2 {
        let document = parse_ordered(json.as_bytes())?;
        Ok(parse_schema(
            Path::new(&format!("schemas/{stem}.json")),
            stem,
            &document,
            registry,
        )?)
    }

    type TestResult2 = Result<SchemaArtifact, Box<dyn std::error::Error>>;

    #[test]
    fn full_module_golden_with_enum_array_and_optional() -> TestResult {
        let mut registry = NameRegistry::default();
        let artifacts = vec![artifact(
            "event",
            r#"{
                "type": "object",
                "required": ["kind", "tags"],
                "additionalProperties": false,
                "properties": {
                    "kind": { "type": "string", "enum": ["created", "closed_out"] },
                    "tags": { "type": "array", "items": { "type": "string" } },
                    "note": { "type": "string" }
                }
            }"#,
            &mut registry,
        )?];

        let expected = r#"//// Generated by aion codegen — do not edit; regenerate from schemas/.
////
//// Types and JSON codecs for the `demo` workflow project,
//// derived from every `schemas/*.json` document in filename order.

import gleam/dynamic/decode
import gleam/json
import gleam/list
import gleam/option

/// Generated from `schemas/event.json`.
pub type Event {
  Event(
    kind: EventKind,
    tags: List(String),
    note: option.Option(String),
  )
}

/// Encodes `Event` as schema-shaped JSON; optional fields are
/// omitted when `None`.
pub fn event_to_json(value: Event) -> json.Json {
  json.object(
    list.flatten([
      [#("kind", event_kind_to_json(value.kind))],
      [#("tags", json.array(value.tags, json.string))],
      case value.note {
        option.Some(present) -> [#("note", json.string(present))]
        option.None -> []
      },
    ]),
  )
}

/// Decoder for `Event` from schema-shaped JSON.
pub fn event_decoder() -> decode.Decoder(Event) {
  use field_kind <- decode.field("kind", event_kind_decoder())
  use field_tags <- decode.field("tags", decode.list(decode.string))
  use field_note <- decode.optional_field(
    "note",
    option.None,
    decode.optional(decode.string),
  )
  decode.success(Event(
    kind: field_kind,
    tags: field_tags,
    note: field_note,
  ))
}

/// Generated from `schemas/event.json` at `/properties/kind`.
pub type EventKind {
  EventKindCreated
  EventKindClosedOut
}

/// Encodes `EventKind` as its wire string.
pub fn event_kind_to_json(value: EventKind) -> json.Json {
  case value {
    EventKindCreated -> json.string("created")
    EventKindClosedOut -> json.string("closed_out")
  }
}

/// Decoder for `EventKind` from its wire string.
pub fn event_kind_decoder() -> decode.Decoder(EventKind) {
  decode.then(decode.string, fn(raw) {
    case raw {
      "created" -> decode.success(EventKindCreated)
      "closed_out" -> decode.success(EventKindClosedOut)
      _ -> decode.failure(EventKindCreated, "EventKind")
    }
  })
}
"#;
        assert_eq!(emit_module("demo", &artifacts), expected);
        Ok(())
    }

    #[test]
    fn scalar_root_emits_payload_wrappers_without_optional_imports() -> TestResult {
        let mut registry = NameRegistry::default();
        let artifacts = vec![artifact(
            "output",
            r#"{ "type": "string" }"#,
            &mut registry,
        )?];

        let module = emit_module("demo", &artifacts);
        assert!(module.starts_with(GENERATED_HEADER));
        assert!(!module.contains("import gleam/list"));
        assert!(!module.contains("import gleam/option"));
        assert!(module.contains(
            "/// Encodes the `schemas/output.json` payload as schema-shaped JSON.\n\
             pub fn output_to_json(value: String) -> json.Json {\n  json.string(value)\n}\n"
        ));
        assert!(module.contains(
            "/// Decoder for the `schemas/output.json` payload.\n\
             pub fn output_decoder() -> decode.Decoder(String) {\n  decode.string\n}\n"
        ));
        Ok(())
    }

    #[test]
    fn all_required_records_use_plain_object_lists() -> TestResult {
        let mut registry = NameRegistry::default();
        let artifacts = vec![artifact(
            "pair",
            r#"{
                "type": "object",
                "required": ["count", "ratio", "flag"],
                "properties": {
                    "count": { "type": "integer" },
                    "ratio": { "type": "number" },
                    "flag": { "type": "boolean" }
                }
            }"#,
            &mut registry,
        )?];

        let module = emit_module("demo", &artifacts);
        assert!(module.contains(
            "pub fn pair_to_json(value: Pair) -> json.Json {\n  json.object([\n    \
             #(\"count\", json.int(value.count)),\n    \
             #(\"ratio\", json.float(value.ratio)),\n    \
             #(\"flag\", json.bool(value.flag)),\n  ])\n}\n"
        ));
        assert!(module.contains("use field_count <- decode.field(\"count\", decode.int)\n"));
        assert!(!module.contains("list.flatten"));
        Ok(())
    }

    #[test]
    fn nested_lists_encode_with_depth_named_lambdas() -> TestResult {
        let mut registry = NameRegistry::default();
        let artifacts = vec![artifact(
            "grid",
            r#"{
                "type": "object",
                "required": ["matrix"],
                "properties": {
                    "matrix": {
                        "type": "array",
                        "items": { "type": "array", "items": { "type": "integer" } }
                    }
                }
            }"#,
            &mut registry,
        )?];

        let module = emit_module("demo", &artifacts);
        assert!(module.contains(
            "#(\"matrix\", json.array(value.matrix, fn(items0) { json.array(items0, json.int) }))"
        ));
        assert!(module.contains(
            "use field_matrix <- decode.field(\"matrix\", decode.list(decode.list(decode.int)))"
        ));
        assert!(module.contains("matrix: List(List(Int)),"));
        Ok(())
    }

    #[test]
    fn empty_records_emit_bare_constructors() -> TestResult {
        let mut registry = NameRegistry::default();
        let artifacts = vec![artifact(
            "blank",
            r#"{ "type": "object", "required": [], "properties": {} }"#,
            &mut registry,
        )?];

        let module = emit_module("demo", &artifacts);
        assert!(module.contains("pub type Blank {\n  Blank\n}\n"));
        assert!(module.contains("json.object([\n  ])"));
        assert!(module.contains("decode.success(Blank)\n"));
        Ok(())
    }

    #[test]
    fn emission_is_deterministic() -> TestResult {
        let schema = r#"{
            "type": "object",
            "required": ["kind"],
            "properties": {
                "kind": { "enum": ["a", "b"] },
                "note": { "type": "string" }
            }
        }"#;
        let mut first_registry = NameRegistry::default();
        let first = emit_module("demo", &[artifact("event", schema, &mut first_registry)?]);
        let mut second_registry = NameRegistry::default();
        let second = emit_module("demo", &[artifact("event", schema, &mut second_registry)?]);

        assert_eq!(first, second);
        Ok(())
    }
}