Skip to main content

odk_cli/generate/
typescript.rs

1//! TypeScript model generation.
2//!
3//! Emits a `models.ts` of plain interfaces, one `export interface` per model
4//! and one `export type` string-literal union per string union.
5//!
6//! # Why interfaces rather than classes
7//!
8//! Generated code inherits its shape onto every consumer. A schema describing
9//! a file format (the motivating case is a DAW project document) wants to
10//! describe the JSON it reads without pulling a runtime in first. Interfaces
11//! are erased at compile time, so the output is pure type information with no
12//! runtime cost and no dependency.
13//!
14//! The cost is that this validates nothing beyond shape: an out-of-range value
15//! that the JSON Schema would reject still type-checks. Constraints in the IR
16//! are emitted as comments so they are visible, not enforced.
17
18use std::collections::BTreeMap;
19
20use odk_schema::{CompiledField, CompiledSchema, CompiledType, LiteralValue, ScalarType};
21
22/// Generate TypeScript models for a schema.
23pub fn generate(schema: &CompiledSchema) -> BTreeMap<String, String> {
24    let mut output = BTreeMap::new();
25
26    if schema.models.is_empty() && schema.unions.is_empty() {
27        return output;
28    }
29
30    output.insert("models.ts".to_string(), generate_models(schema));
31    output
32}
33
34fn generate_models(schema: &CompiledSchema) -> String {
35    let mut out = String::new();
36
37    out.push_str(&format!(
38        "// {} models.\n//\n// Generated by ODK. Do not edit by hand.\n\n",
39        schema.name
40    ));
41
42    for union in &schema.unions {
43        if let Some(desc) = &union.description {
44            out.push_str(&format!("// {}\n", one_line(desc)));
45        }
46
47        // a discriminator tag marks a data-carrying union, emitted as a
48        // discriminated union; otherwise it is a plain string-literal union
49        if let Some(tag) = &union.tag {
50            out.push_str(&discriminated_union(union, tag));
51        } else {
52            let variants: Vec<String> = union
53                .variants
54                .iter()
55                .map(|v| format!("\"{}\"", escape(&v.name)))
56                .collect();
57            out.push_str(&format!(
58                "export type {} = {};\n\n",
59                union.name,
60                variants.join(" | ")
61            ));
62        }
63    }
64
65    for model in &schema.models {
66        out.push_str(&interface(model));
67        out.push('\n');
68    }
69
70    out
71}
72
73/// Render a data-carrying union as a TypeScript discriminated union: one object
74/// type per variant, each carrying the discriminator property plus the
75/// variant's payload. Recursion needs no indirection in TypeScript.
76fn discriminated_union(union: &odk_schema::CompiledUnion, tag: &str) -> String {
77    let mut parts: Vec<String> = Vec::new();
78    for v in &union.variants {
79        let mut props = vec![format!("{tag}: \"{}\"", escape(&v.name))];
80        match &v.variant_type {
81            Some(CompiledType::Object { fields }) => {
82                for f in fields {
83                    let key = property_name(&f.name);
84                    let marker = if f.optional == Some(true) { "?" } else { "" };
85                    props.push(format!("{key}{marker}: {}", type_to_ts(&f.field_type)));
86                }
87                parts.push(format!("{{ {} }}", props.join("; ")));
88            }
89            Some(CompiledType::Ref { name }) => {
90                // a referenced payload is intersected with the tag object
91                parts.push(format!("({{ {} }} & {name})", props.join("; ")));
92            }
93            Some(other) => {
94                props.push(format!("value: {}", type_to_ts(other)));
95                parts.push(format!("{{ {} }}", props.join("; ")));
96            }
97            None => parts.push(format!("{{ {} }}", props.join("; "))),
98        }
99    }
100    format!(
101        "export type {} =\n  | {};\n\n",
102        union.name,
103        parts.join("\n  | ")
104    )
105}
106
107fn interface(model: &odk_schema::CompiledModel) -> String {
108    let mut out = String::new();
109
110    if let Some(desc) = &model.description {
111        out.push_str(&format!("// {}\n", one_line(desc)));
112    }
113
114    if model.fields.is_empty() {
115        out.push_str(&format!("export interface {} {{}}\n", model.name));
116        return out;
117    }
118
119    out.push_str(&format!("export interface {} {{\n", model.name));
120
121    for f in &model.fields {
122        if let Some(desc) = &f.description {
123            out.push_str(&format!("  // {}\n", one_line(desc)));
124        }
125        if let Some(note) = constraint_note(f) {
126            out.push_str(&format!("  // {note}\n"));
127        }
128
129        let key = property_name(&f.name);
130        let marker = if f.optional == Some(true) { "?" } else { "" };
131        out.push_str(&format!(
132            "  {key}{marker}: {};\n",
133            type_to_ts(&f.field_type)
134        ));
135    }
136
137    out.push_str("}\n");
138    out
139}
140
141/// Map an IR type onto a TypeScript type.
142fn type_to_ts(t: &CompiledType) -> String {
143    match t {
144        CompiledType::Scalar { name } => scalar_to_ts(name).to_string(),
145        // a fixed length becomes a TypeScript tuple, holding the size invariant
146        CompiledType::Array {
147            items,
148            length: Some(n),
149        } => {
150            let inner = type_to_ts(items);
151            format!("[{}]", vec![inner; *n as usize].join(", "))
152        }
153        CompiledType::Array {
154            items,
155            length: None,
156        } => {
157            let inner = type_to_ts(items);
158            // a bare union or literal-union as an element binds looser than the
159            // array suffix, so it has to be parenthesized to stay an array of
160            // that whole type
161            if needs_parens_as_array_element(items) {
162                format!("({inner})[]")
163            } else {
164                format!("{inner}[]")
165            }
166        }
167        CompiledType::Ref { name } => name.clone(),
168        CompiledType::Literal { value } => match value {
169            LiteralValue::String(s) => format!("\"{}\"", escape(s)),
170            LiteralValue::Number(n) => format!("{n}"),
171            LiteralValue::Bool(b) => format!("{b}"),
172        },
173        CompiledType::Union { variants } => {
174            let parts: Vec<String> = variants.iter().map(type_to_ts).collect();
175            parts.join(" | ")
176        }
177        // an inline object has no name to reference, so it stays an index signature
178        CompiledType::Object { .. } => "Record<string, unknown>".to_string(),
179    }
180}
181
182/// Whether a type rendered as an array element needs wrapping in parentheses.
183fn needs_parens_as_array_element(t: &CompiledType) -> bool {
184    matches!(t, CompiledType::Union { variants } if variants.len() > 1)
185}
186
187fn scalar_to_ts(s: &ScalarType) -> &'static str {
188    match s {
189        ScalarType::String
190        | ScalarType::Date
191        | ScalarType::Datetime
192        | ScalarType::UtcDateTime
193        | ScalarType::OffsetDateTime
194        | ScalarType::PlainDate
195        | ScalarType::PlainTime
196        | ScalarType::Duration
197        | ScalarType::Bytes
198        | ScalarType::Url => "string",
199        ScalarType::Int32 | ScalarType::Int64 | ScalarType::Float32 | ScalarType::Float64 => {
200            "number"
201        }
202        ScalarType::Boolean => "boolean",
203        ScalarType::Unknown => "unknown",
204    }
205}
206
207/// Render a field's constraints as a human-readable note.
208fn constraint_note(f: &CompiledField) -> Option<String> {
209    let c = f.constraints.as_ref()?;
210    let mut parts = Vec::new();
211
212    if let Some(v) = c.min_length {
213        parts.push(format!("minLength {v}"));
214    }
215    if let Some(v) = c.max_length {
216        parts.push(format!("maxLength {v}"));
217    }
218    if let Some(v) = c.min_value {
219        parts.push(format!("minimum {v}"));
220    }
221    if let Some(v) = c.max_value {
222        parts.push(format!("maximum {v}"));
223    }
224    if let Some(v) = &c.pattern {
225        parts.push(format!("pattern {v}"));
226    }
227    if let Some(v) = &c.format {
228        parts.push(format!("format {v}"));
229    }
230    if let Some(v) = c.multiple_of {
231        parts.push(format!("multipleOf {v}"));
232    }
233
234    if parts.is_empty() {
235        None
236    } else {
237        // not enforced: interfaces validate nothing, so this is documentation
238        Some(format!("constraints: {}", parts.join(", ")))
239    }
240}
241
242/// Render a property name, quoting it when it is not a bare identifier.
243fn property_name(name: &str) -> String {
244    if is_ts_identifier(name) {
245        name.to_string()
246    } else {
247        format!("\"{}\"", escape(name))
248    }
249}
250
251/// Whether a string is a valid bare TypeScript property identifier.
252fn is_ts_identifier(name: &str) -> bool {
253    let mut chars = name.chars();
254    match chars.next() {
255        Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
256        _ => return false,
257    }
258    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
259}
260
261fn escape(s: &str) -> String {
262    s.replace('\\', "\\\\").replace('"', "\\\"")
263}
264
265/// Collapse a description to a single line so it cannot break out of a comment.
266fn one_line(s: &str) -> String {
267    s.replace(['\n', '\r'], " ").trim().to_string()
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use odk_schema::{
274        CompiledField, CompiledModel, CompiledType, CompiledUnion, CompiledUnionVariant,
275        FieldConstraints, ScalarType,
276    };
277
278    fn scalar(name: ScalarType) -> CompiledType {
279        CompiledType::Scalar { name }
280    }
281
282    fn schema_with(models: Vec<CompiledModel>) -> CompiledSchema {
283        let mut schema = CompiledSchema::new("Test");
284        for m in models {
285            schema.add_model(m);
286        }
287        schema
288    }
289
290    fn render(schema: &CompiledSchema) -> String {
291        generate(schema)
292            .get("models.ts")
293            .expect("models.ts emitted")
294            .clone()
295    }
296
297    #[test]
298    fn an_empty_schema_emits_nothing() {
299        assert!(generate(&CompiledSchema::new("Empty")).is_empty());
300    }
301
302    #[test]
303    fn a_model_becomes_an_interface() {
304        let mut model = CompiledModel::new("Track").with_description("A track");
305        model.add_field(CompiledField::new("id", scalar(ScalarType::String)));
306
307        let out = render(&schema_with(vec![model]));
308
309        assert!(out.contains("export interface Track {"));
310        assert!(out.contains("// A track"));
311        assert!(out.contains("  id: string;\n"));
312    }
313
314    #[test]
315    fn scalars_map_to_typescript_types() {
316        let mut model = CompiledModel::new("M");
317        model.add_field(CompiledField::new("s", scalar(ScalarType::String)));
318        model.add_field(CompiledField::new("i", scalar(ScalarType::Int64)));
319        model.add_field(CompiledField::new("f", scalar(ScalarType::Float64)));
320        model.add_field(CompiledField::new("b", scalar(ScalarType::Boolean)));
321        model.add_field(CompiledField::new("u", scalar(ScalarType::Unknown)));
322        model.add_field(CompiledField::new("t", scalar(ScalarType::UtcDateTime)));
323
324        let out = render(&schema_with(vec![model]));
325
326        assert!(out.contains("s: string;"));
327        assert!(out.contains("i: number;"));
328        assert!(out.contains("f: number;"));
329        assert!(out.contains("b: boolean;"));
330        assert!(out.contains("u: unknown;"));
331        assert!(out.contains("t: string;"));
332    }
333
334    #[test]
335    fn optional_fields_use_the_question_mark_marker() {
336        let mut model = CompiledModel::new("M");
337        model.add_field(CompiledField::new("must", scalar(ScalarType::String)));
338        model.add_field(CompiledField::new("maybe", scalar(ScalarType::Int64)).optional());
339
340        let out = render(&schema_with(vec![model]));
341
342        assert!(out.contains("must: string;"));
343        assert!(out.contains("maybe?: number;"));
344    }
345
346    #[test]
347    fn arrays_and_refs_nest() {
348        let mut model = CompiledModel::new("M");
349        model.add_field(CompiledField::new(
350            "tracks",
351            CompiledType::Array {
352                items: Box::new(CompiledType::Ref {
353                    name: "Track".to_string(),
354                }),
355                length: None,
356            },
357        ));
358
359        assert!(render(&schema_with(vec![model])).contains("tracks: Track[];"));
360    }
361
362    #[test]
363    fn an_array_of_a_union_is_parenthesized() {
364        let mut model = CompiledModel::new("M");
365        model.add_field(CompiledField::new(
366            "xs",
367            CompiledType::Array {
368                items: Box::new(CompiledType::Union {
369                    variants: vec![scalar(ScalarType::String), scalar(ScalarType::Int64)],
370                }),
371                length: None,
372            },
373        ));
374
375        assert!(render(&schema_with(vec![model])).contains("xs: (string | number)[];"));
376    }
377
378    #[test]
379    fn a_union_becomes_a_string_literal_alias() {
380        let mut schema = CompiledSchema::new("Test");
381        schema.add_union(CompiledUnion {
382            name: "TrackType".to_string(),
383            variants: ["audio", "midi"]
384                .iter()
385                .map(|v| CompiledUnionVariant {
386                    name: (*v).to_string(),
387                    variant_type: None,
388                })
389                .collect(),
390            tag: None,
391            rename_all: None,
392            description: None,
393            extensions: odk_schema::Extensions::default(),
394            source: None,
395        });
396        schema.add_model(CompiledModel::new("M"));
397
398        assert!(render(&schema).contains("export type TrackType = \"audio\" | \"midi\";"));
399    }
400
401    #[test]
402    fn a_data_carrying_union_becomes_a_discriminated_union() {
403        fn obj(fields: Vec<CompiledField>) -> CompiledType {
404            CompiledType::Object { fields }
405        }
406        let vec3 = || CompiledType::fixed_array(scalar(ScalarType::Float64), 3);
407
408        let mut schema = CompiledSchema::new("Geo");
409        schema.add_union(CompiledUnion {
410            name: "OpNode".to_string(),
411            tag: Some("op".to_string()),
412            rename_all: Some("lowercase".to_string()),
413            variants: vec![
414                CompiledUnionVariant {
415                    name: "cube".to_string(),
416                    variant_type: Some(obj(vec![
417                        CompiledField::new("size", vec3()),
418                        CompiledField::new("center", scalar(ScalarType::Boolean)),
419                    ])),
420                },
421                CompiledUnionVariant {
422                    name: "translate".to_string(),
423                    variant_type: Some(obj(vec![
424                        CompiledField::new("v", vec3()),
425                        CompiledField::new("child", CompiledType::reference("OpNode")),
426                    ])),
427                },
428                CompiledUnionVariant {
429                    name: "union".to_string(),
430                    variant_type: Some(obj(vec![CompiledField::new(
431                        "children",
432                        CompiledType::array(CompiledType::reference("OpNode")),
433                    )])),
434                },
435            ],
436            description: None,
437            extensions: odk_schema::Extensions::default(),
438            source: None,
439        });
440
441        let out = render(&schema);
442
443        assert!(
444            out.contains("export type OpNode ="),
445            "not a type alias:\n{out}"
446        );
447        assert!(
448            out.contains("{ op: \"cube\"; size: [number, number, number]; center: boolean }"),
449            "cube variant / tuple wrong:\n{out}"
450        );
451        assert!(
452            out.contains("{ op: \"translate\"; v: [number, number, number]; child: OpNode }"),
453            "translate / recursion wrong:\n{out}"
454        );
455        assert!(
456            out.contains("{ op: \"union\"; children: OpNode[] }"),
457            "union / list recursion wrong:\n{out}"
458        );
459    }
460
461    #[test]
462    fn property_names_that_are_not_identifiers_are_quoted() {
463        let mut model = CompiledModel::new("M");
464        model.add_field(CompiledField::new("kebab-case", scalar(ScalarType::String)));
465
466        let out = render(&schema_with(vec![model]));
467
468        assert!(out.contains("\"kebab-case\": string;"));
469    }
470
471    #[test]
472    fn constraints_are_emitted_as_comments_not_validation() {
473        let mut model = CompiledModel::new("M");
474        let mut f = CompiledField::new("tempo", scalar(ScalarType::Float64));
475        f.constraints = Some(FieldConstraints {
476            min_length: None,
477            max_length: None,
478            min_value: Some(20.0),
479            max_value: Some(300.0),
480            pattern: None,
481            format: None,
482            multiple_of: None,
483        });
484        model.add_field(f);
485
486        let out = render(&schema_with(vec![model]));
487        assert!(out.contains("// constraints: minimum 20, maximum 300"));
488    }
489
490    #[test]
491    fn descriptions_are_collapsed_so_they_cannot_break_the_comment() {
492        let mut model = CompiledModel::new("M");
493        let mut f = CompiledField::new("a", scalar(ScalarType::String));
494        f.description = Some("line one\nline two".to_string());
495        model.add_field(f);
496
497        let out = render(&schema_with(vec![model]));
498        assert!(out.contains("// line one line two"));
499    }
500
501    #[test]
502    fn an_empty_model_is_still_valid_typescript() {
503        let out = render(&schema_with(vec![CompiledModel::new("Empty")]));
504        assert!(out.contains("export interface Empty {}"));
505    }
506
507    #[test]
508    fn a_literal_scalar_renders_as_a_literal_type() {
509        let mut model = CompiledModel::new("M");
510        model.add_field(CompiledField::new(
511            "kind",
512            CompiledType::Literal {
513                value: odk_schema::LiteralValue::String("audio".to_string()),
514            },
515        ));
516
517        assert!(render(&schema_with(vec![model])).contains("kind: \"audio\";"));
518    }
519}