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
200        | ScalarType::Int64
201        | ScalarType::Safeint
202        | ScalarType::Float32
203        | ScalarType::Float64 => "number",
204        ScalarType::Boolean => "boolean",
205        ScalarType::Unknown => "unknown",
206    }
207}
208
209/// Render a field's constraints as a human-readable note.
210fn constraint_note(f: &CompiledField) -> Option<String> {
211    let c = f.constraints.as_ref()?;
212    let mut parts = Vec::new();
213
214    if let Some(v) = c.min_length {
215        parts.push(format!("minLength {v}"));
216    }
217    if let Some(v) = c.max_length {
218        parts.push(format!("maxLength {v}"));
219    }
220    if let Some(v) = c.min_value {
221        parts.push(format!("minimum {v}"));
222    }
223    if let Some(v) = c.max_value {
224        parts.push(format!("maximum {v}"));
225    }
226    if let Some(v) = &c.pattern {
227        parts.push(format!("pattern {v}"));
228    }
229    if let Some(v) = &c.format {
230        parts.push(format!("format {v}"));
231    }
232    if let Some(v) = c.multiple_of {
233        parts.push(format!("multipleOf {v}"));
234    }
235
236    if parts.is_empty() {
237        None
238    } else {
239        // not enforced: interfaces validate nothing, so this is documentation
240        Some(format!("constraints: {}", parts.join(", ")))
241    }
242}
243
244/// Render a property name, quoting it when it is not a bare identifier.
245fn property_name(name: &str) -> String {
246    if is_ts_identifier(name) {
247        name.to_string()
248    } else {
249        format!("\"{}\"", escape(name))
250    }
251}
252
253/// Whether a string is a valid bare TypeScript property identifier.
254fn is_ts_identifier(name: &str) -> bool {
255    let mut chars = name.chars();
256    match chars.next() {
257        Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
258        _ => return false,
259    }
260    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
261}
262
263fn escape(s: &str) -> String {
264    s.replace('\\', "\\\\").replace('"', "\\\"")
265}
266
267/// Collapse a description to a single line so it cannot break out of a comment.
268fn one_line(s: &str) -> String {
269    s.replace(['\n', '\r'], " ").trim().to_string()
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use odk_schema::{
276        CompiledField, CompiledModel, CompiledType, CompiledUnion, CompiledUnionVariant,
277        FieldConstraints, ScalarType,
278    };
279
280    fn scalar(name: ScalarType) -> CompiledType {
281        CompiledType::Scalar { name }
282    }
283
284    fn schema_with(models: Vec<CompiledModel>) -> CompiledSchema {
285        let mut schema = CompiledSchema::new("Test");
286        for m in models {
287            schema.add_model(m);
288        }
289        schema
290    }
291
292    fn render(schema: &CompiledSchema) -> String {
293        generate(schema)
294            .get("models.ts")
295            .expect("models.ts emitted")
296            .clone()
297    }
298
299    #[test]
300    fn an_empty_schema_emits_nothing() {
301        assert!(generate(&CompiledSchema::new("Empty")).is_empty());
302    }
303
304    #[test]
305    fn a_model_becomes_an_interface() {
306        let mut model = CompiledModel::new("Track").with_description("A track");
307        model.add_field(CompiledField::new("id", scalar(ScalarType::String)));
308
309        let out = render(&schema_with(vec![model]));
310
311        assert!(out.contains("export interface Track {"));
312        assert!(out.contains("// A track"));
313        assert!(out.contains("  id: string;\n"));
314    }
315
316    #[test]
317    fn scalars_map_to_typescript_types() {
318        let mut model = CompiledModel::new("M");
319        model.add_field(CompiledField::new("s", scalar(ScalarType::String)));
320        model.add_field(CompiledField::new("i", scalar(ScalarType::Int64)));
321        model.add_field(CompiledField::new("f", scalar(ScalarType::Float64)));
322        model.add_field(CompiledField::new("b", scalar(ScalarType::Boolean)));
323        model.add_field(CompiledField::new("u", scalar(ScalarType::Unknown)));
324        model.add_field(CompiledField::new("t", scalar(ScalarType::UtcDateTime)));
325
326        let out = render(&schema_with(vec![model]));
327
328        assert!(out.contains("s: string;"));
329        assert!(out.contains("i: number;"));
330        assert!(out.contains("f: number;"));
331        assert!(out.contains("b: boolean;"));
332        assert!(out.contains("u: unknown;"));
333        assert!(out.contains("t: string;"));
334    }
335
336    #[test]
337    fn optional_fields_use_the_question_mark_marker() {
338        let mut model = CompiledModel::new("M");
339        model.add_field(CompiledField::new("must", scalar(ScalarType::String)));
340        model.add_field(CompiledField::new("maybe", scalar(ScalarType::Int64)).optional());
341
342        let out = render(&schema_with(vec![model]));
343
344        assert!(out.contains("must: string;"));
345        assert!(out.contains("maybe?: number;"));
346    }
347
348    #[test]
349    fn arrays_and_refs_nest() {
350        let mut model = CompiledModel::new("M");
351        model.add_field(CompiledField::new(
352            "tracks",
353            CompiledType::Array {
354                items: Box::new(CompiledType::Ref {
355                    name: "Track".to_string(),
356                }),
357                length: None,
358            },
359        ));
360
361        assert!(render(&schema_with(vec![model])).contains("tracks: Track[];"));
362    }
363
364    #[test]
365    fn an_array_of_a_union_is_parenthesized() {
366        let mut model = CompiledModel::new("M");
367        model.add_field(CompiledField::new(
368            "xs",
369            CompiledType::Array {
370                items: Box::new(CompiledType::Union {
371                    variants: vec![scalar(ScalarType::String), scalar(ScalarType::Int64)],
372                }),
373                length: None,
374            },
375        ));
376
377        assert!(render(&schema_with(vec![model])).contains("xs: (string | number)[];"));
378    }
379
380    #[test]
381    fn a_union_becomes_a_string_literal_alias() {
382        let mut schema = CompiledSchema::new("Test");
383        schema.add_union(CompiledUnion {
384            name: "TrackType".to_string(),
385            variants: ["audio", "midi"]
386                .iter()
387                .map(|v| CompiledUnionVariant {
388                    name: (*v).to_string(),
389                    variant_type: None,
390                })
391                .collect(),
392            tag: None,
393            rename_all: None,
394            description: None,
395            extensions: odk_schema::Extensions::default(),
396            source: None,
397        });
398        schema.add_model(CompiledModel::new("M"));
399
400        assert!(render(&schema).contains("export type TrackType = \"audio\" | \"midi\";"));
401    }
402
403    #[test]
404    fn a_data_carrying_union_becomes_a_discriminated_union() {
405        fn obj(fields: Vec<CompiledField>) -> CompiledType {
406            CompiledType::Object { fields }
407        }
408        let vec3 = || CompiledType::fixed_array(scalar(ScalarType::Float64), 3);
409
410        let mut schema = CompiledSchema::new("Geo");
411        schema.add_union(CompiledUnion {
412            name: "OpNode".to_string(),
413            tag: Some("op".to_string()),
414            rename_all: Some("lowercase".to_string()),
415            variants: vec![
416                CompiledUnionVariant {
417                    name: "cube".to_string(),
418                    variant_type: Some(obj(vec![
419                        CompiledField::new("size", vec3()),
420                        CompiledField::new("center", scalar(ScalarType::Boolean)),
421                    ])),
422                },
423                CompiledUnionVariant {
424                    name: "translate".to_string(),
425                    variant_type: Some(obj(vec![
426                        CompiledField::new("v", vec3()),
427                        CompiledField::new("child", CompiledType::reference("OpNode")),
428                    ])),
429                },
430                CompiledUnionVariant {
431                    name: "union".to_string(),
432                    variant_type: Some(obj(vec![CompiledField::new(
433                        "children",
434                        CompiledType::array(CompiledType::reference("OpNode")),
435                    )])),
436                },
437            ],
438            description: None,
439            extensions: odk_schema::Extensions::default(),
440            source: None,
441        });
442
443        let out = render(&schema);
444
445        assert!(
446            out.contains("export type OpNode ="),
447            "not a type alias:\n{out}"
448        );
449        assert!(
450            out.contains("{ op: \"cube\"; size: [number, number, number]; center: boolean }"),
451            "cube variant / tuple wrong:\n{out}"
452        );
453        assert!(
454            out.contains("{ op: \"translate\"; v: [number, number, number]; child: OpNode }"),
455            "translate / recursion wrong:\n{out}"
456        );
457        assert!(
458            out.contains("{ op: \"union\"; children: OpNode[] }"),
459            "union / list recursion wrong:\n{out}"
460        );
461    }
462
463    #[test]
464    fn property_names_that_are_not_identifiers_are_quoted() {
465        let mut model = CompiledModel::new("M");
466        model.add_field(CompiledField::new("kebab-case", scalar(ScalarType::String)));
467
468        let out = render(&schema_with(vec![model]));
469
470        assert!(out.contains("\"kebab-case\": string;"));
471    }
472
473    #[test]
474    fn constraints_are_emitted_as_comments_not_validation() {
475        let mut model = CompiledModel::new("M");
476        let mut f = CompiledField::new("tempo", scalar(ScalarType::Float64));
477        f.constraints = Some(FieldConstraints {
478            min_length: None,
479            max_length: None,
480            min_value: Some(20.0),
481            max_value: Some(300.0),
482            pattern: None,
483            format: None,
484            multiple_of: None,
485        });
486        model.add_field(f);
487
488        let out = render(&schema_with(vec![model]));
489        assert!(out.contains("// constraints: minimum 20, maximum 300"));
490    }
491
492    #[test]
493    fn descriptions_are_collapsed_so_they_cannot_break_the_comment() {
494        let mut model = CompiledModel::new("M");
495        let mut f = CompiledField::new("a", scalar(ScalarType::String));
496        f.description = Some("line one\nline two".to_string());
497        model.add_field(f);
498
499        let out = render(&schema_with(vec![model]));
500        assert!(out.contains("// line one line two"));
501    }
502
503    #[test]
504    fn an_empty_model_is_still_valid_typescript() {
505        let out = render(&schema_with(vec![CompiledModel::new("Empty")]));
506        assert!(out.contains("export interface Empty {}"));
507    }
508
509    #[test]
510    fn a_literal_scalar_renders_as_a_literal_type() {
511        let mut model = CompiledModel::new("M");
512        model.add_field(CompiledField::new(
513            "kind",
514            CompiledType::Literal {
515                value: odk_schema::LiteralValue::String("audio".to_string()),
516            },
517        ));
518
519        assert!(render(&schema_with(vec![model])).contains("kind: \"audio\";"));
520    }
521}