utoipa-ts 0.1.5

Generate TypeScript API definitions from utoipa paths
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Generate TypeScript API definitions from [`utoipa`] endpoint definitions.
//!
//! [`utoipa-ts`] wraps [`utoipa::path`] with [`path`] so the same endpoint metadata
//! can be used to generate a TypeScript `Api` type.
//!
//! [`utoipa-ts`]: https://docs.rs/utoipa-ts/latest/utoipa_ts
//! [`utoipa::path`]: https://docs.rs/utoipa/latest/utoipa/attr.path.html
//!
//! # Quick start
//!
//! Derive both [`ts_rs::TS`] and [`utoipa::ToSchema`] for types that should appear
//! in generated TypeScript:
//!
//! ```rust
//! use utoipa::ToSchema;
//!
//! #[derive(ts_rs::TS, ToSchema)]
//! struct Todo {
//!     id: String,
//!     title: String,
//!     done: bool,
//! }
//!
//! #[utoipa_ts::path(
//!     get,
//!     path = "/todos",
//!     responses(
//!         (status = 200, description = "Todo list", body = Vec<Todo>),
//!     )
//! )]
//! async fn list_todos() {}
//!
//! utoipa_ts::export!("types/api.ts");
//!
//! fn main() {}
//! ```
//!
//! Then generate the file with:
//!
//! ```text
//! cargo test export_api
//! ```
//!
//! # Existing utoipa projects
//!
//! Replace `#[utoipa::path(...)]` with `#[utoipa_ts::path(...)]` and add
//! [`export!`] somewhere in your crate.
//!
//! # Export path
//!
//! [`export!`] writes to `types.ts` by default. You can pass a path:
//!
//! ```rust
//! utoipa_ts::export!("types/api.ts");
//! ```
//!
//! The `UTOIPA_TS_PATH` environment variable overrides the macro path.
//!
//! # Generated type shape
//!
//! The generated file exports all collected schema declarations and an `Api` type
//! indexed by `"METHOD /path"`.
//!
//! # Supported endpoint metadata
//!
//! `utoipa-ts` currently reads:
//!
//! - HTTP method
//! - `path = "..."`
//! - `params(...)`
//! - `request_body = Type` and `request_body(content = Type, ...)`
//! - response status/body pairs

use std::{
    any::TypeId,
    collections::{BTreeMap, HashSet},
    fmt::Write as _,
    path::{Path, PathBuf},
};

pub use ts_rs;
pub use utoipa_ts_macros::path;

#[doc(hidden)]
pub mod __private {
    pub use inventory;
}

const NOTE: &str = "// This file was generated by utoipa-ts. Do not edit it manually.\n";
/// Environment variable that can be used to override the export path for [`export!`]
pub const EXPORT_PATH_ENV: &str = "UTOIPA_TS_PATH";
/// Default export path for [`export!`]
pub const DEFAULT_EXPORT_PATH: &str = "types.ts";
const DEFAULT_EXPORT_FILE_NAME: &str = "types.ts";

#[doc(hidden)]
pub struct Endpoint {
    pub name: &'static str,
    pub method: &'static str,
    pub path: &'static str,
    pub render: fn(&mut TypeCollector) -> EndpointSpec,
}

inventory::collect!(Endpoint);

#[derive(Debug, Clone)]
#[doc(hidden)]
pub struct EndpointSpec {
    pub name: &'static str,
    pub method: &'static str,
    pub path: &'static str,
    pub params: Vec<FieldSpec>,
    pub request_body: Option<String>,
    pub responses: Vec<ResponseSpec>,
}

#[derive(Debug, Clone)]
#[doc(hidden)]
pub struct FieldSpec {
    pub name: String,
    pub ty: String,
    pub required: bool,
}

#[derive(Debug, Clone)]
#[doc(hidden)]
pub struct ResponseSpec {
    pub status: &'static str,
    pub body: Option<String>,
}

#[doc(hidden)]
pub struct EndpointRender<'a> {
    collector: &'a mut TypeCollector,
    spec: EndpointSpec,
}

impl<'a> EndpointRender<'a> {
    pub fn new(
        collector: &'a mut TypeCollector,
        name: &'static str,
        method: &'static str,
        path: &'static str,
    ) -> Self {
        Self {
            collector,
            spec: EndpointSpec {
                name,
                method,
                path,
                params: Vec::new(),
                request_body: None,
                responses: Vec::new(),
            },
        }
    }

    pub fn param<T>(&mut self, name: &'static str)
    where
        T: ts_rs::TS + 'static,
    {
        self.spec.params.push(FieldSpec {
            name: name.to_owned(),
            ty: self.collector.type_ref::<T>(),
            required: true,
        });
    }

    pub fn params<T>(&mut self)
    where
        T: utoipa::IntoParams + utoipa::ToSchema,
    {
        self.collector.collect_schema_declarations::<T>();

        self.spec.params.extend(
            T::into_params(|| Some(utoipa::openapi::path::ParameterIn::Query))
                .into_iter()
                .map(|param| {
                    let nullable = param.schema.as_ref().is_some_and(schema_ref_is_nullable);
                    let defaulted = param.schema.as_ref().is_some_and(schema_ref_has_default);
                    let required = matches!(param.required, utoipa::openapi::Required::True)
                        && !nullable
                        && !defaulted;

                    FieldSpec {
                        name: param.name,
                        ty: param
                            .schema
                            .as_ref()
                            .map(schema_ref_to_ts)
                            .unwrap_or_else(|| "unknown".to_owned()),
                        required,
                    }
                }),
        );
    }

    pub fn request_body<T>(&mut self)
    where
        T: ts_rs::TS + 'static,
    {
        self.spec.request_body = Some(self.collector.type_ref::<T>());
    }

    pub fn response<T>(&mut self, status: &'static str)
    where
        T: ts_rs::TS + 'static,
    {
        self.spec.responses.push(ResponseSpec {
            status,
            body: Some(self.collector.type_ref::<T>()),
        });
    }

    pub fn empty_response(&mut self, status: &'static str) {
        self.spec
            .responses
            .push(ResponseSpec { status, body: None });
    }

    pub fn finish(self) -> EndpointSpec {
        self.spec
    }
}

#[doc(hidden)]
pub struct TypeCollector {
    cfg: ts_rs::Config,
    seen: HashSet<TypeId>,
    declarations: BTreeMap<String, String>,
}

impl TypeCollector {
    pub fn new() -> Self {
        Self {
            cfg: ts_rs::Config::from_env(),
            seen: HashSet::new(),
            declarations: BTreeMap::new(),
        }
    }

    pub fn type_ref<T>(&mut self) -> String
    where
        T: ts_rs::TS + 'static,
    {
        self.collect::<T>();
        T::name(&self.cfg)
    }

    fn collect<T>(&mut self)
    where
        T: ts_rs::TS + 'static,
    {
        if !self.seen.insert(TypeId::of::<T>()) {
            return;
        }

        struct Visitor<'a>(&'a mut TypeCollector);

        impl ts_rs::TypeVisitor for Visitor<'_> {
            fn visit<T>(&mut self)
            where
                T: ts_rs::TS + 'static + ?Sized,
            {
                self.0.collect_unsized::<T>();
            }
        }

        T::visit_dependencies(&mut Visitor(self));
        T::visit_generics(&mut Visitor(self));
        self.insert_declaration::<T>();
    }

    fn collect_unsized<T>(&mut self)
    where
        T: ts_rs::TS + 'static + ?Sized,
    {
        if !self.seen.insert(TypeId::of::<T>()) {
            return;
        }

        struct Visitor<'a>(&'a mut TypeCollector);

        impl ts_rs::TypeVisitor for Visitor<'_> {
            fn visit<T>(&mut self)
            where
                T: ts_rs::TS + 'static + ?Sized,
            {
                self.0.collect_unsized::<T>();
            }
        }

        T::visit_dependencies(&mut Visitor(self));
        T::visit_generics(&mut Visitor(self));
        self.insert_declaration_unsized::<T>();
    }

    fn insert_declaration<T>(&mut self)
    where
        T: ts_rs::TS + 'static,
    {
        self.insert_declaration_unsized::<T>();
    }

    fn insert_declaration_unsized<T>(&mut self)
    where
        T: ts_rs::TS + 'static + ?Sized,
    {
        if T::output_path().is_none() {
            return;
        }

        let ident = T::ident(&self.cfg);
        self.declarations
            .entry(ident)
            .or_insert_with(|| format!("export {}", T::decl(&self.cfg)));
    }

    fn collect_schema_declarations<T>(&mut self)
    where
        T: utoipa::ToSchema,
    {
        let mut schemas = Vec::new();
        T::schemas(&mut schemas);

        for (name, schema) in schemas {
            self.declarations
                .entry(name.clone())
                .or_insert_with(|| render_schema_declaration(&name, &schema));
        }
    }
}

impl Default for TypeCollector {
    fn default() -> Self {
        Self::new()
    }
}

/// Export all endpoints registered with [`path`] to a TypeScript file using a path
pub fn export_all(path: impl AsRef<Path>) -> std::io::Result<()> {
    let path = resolve_export_path(path);
    let mut collector = TypeCollector::new();
    let mut endpoints = inventory::iter::<Endpoint>
        .into_iter()
        .map(|endpoint| (endpoint.render)(&mut collector))
        .collect::<Vec<_>>();

    endpoints.sort_by_key(|endpoint| (endpoint.method, endpoint.path, endpoint.name));

    if let Some(parent) = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        std::fs::create_dir_all(parent)?;
    }

    std::fs::write(path, render_file(&collector.declarations, &endpoints))
}

/// Export all endpoints registered with [`path`] to a TypeScript file using defaults
pub fn export_all_default() -> std::io::Result<()> {
    export_all_from_env_or_path(None::<&Path>)
}

/// Export all endpoints registered with [`path`] to a TypeScript file using a path with fallbacks
pub fn export_all_from_env_or_path(path: Option<impl AsRef<Path>>) -> std::io::Result<()> {
    let path = std::env::var_os(EXPORT_PATH_ENV)
        .map(PathBuf::from)
        .or_else(|| path.map(|path| path.as_ref().to_path_buf()))
        .unwrap_or_else(|| PathBuf::from(DEFAULT_EXPORT_PATH));
    export_all(path)
}

fn resolve_export_path(path: impl AsRef<Path>) -> PathBuf {
    let path = path.as_ref();

    if path.is_dir() || path.extension().is_none() {
        path.join(DEFAULT_EXPORT_FILE_NAME)
    } else {
        path.to_path_buf()
    }
}

/// Export TypeScript API definitions for all collected endpoints to a file
#[macro_export]
macro_rules! export {
    () => {
        #[test]
        fn export_api() -> ::std::io::Result<()> {
            $crate::export_all_default()
        }
    };

    ($path:expr $(,)?) => {
        #[test]
        fn export_api() -> ::std::io::Result<()> {
            $crate::export_all_from_env_or_path(Some($path))
        }
    };
}

fn render_file(declarations: &BTreeMap<String, String>, endpoints: &[EndpointSpec]) -> String {
    let mut out = String::new();
    out.push_str(NOTE);

    for declaration in declarations.values() {
        out.push('\n');
        out.push_str(declaration);
        out.push('\n');
    }

    out.push_str("\nexport type Api = {\n");

    for endpoint in endpoints {
        let _ = writeln!(
            out,
            "  \"{} {}\": {{",
            endpoint.method,
            endpoint.path.replace('"', "\\\"")
        );

        if !&endpoint.params.is_empty() {
            write_fields_object(&mut out, "params", &endpoint.params, 4);
        }

        if let Some(body) = &endpoint.request_body {
            let _ = writeln!(out, "    body: {body};");
        }

        out.push_str("    responses: {\n");
        for response in &endpoint.responses {
            let body = response.body.as_deref().unwrap_or("never");
            let _ = writeln!(out, "      {}: {};", ts_key(response.status), body);
        }
        out.push_str("    };\n");

        out.push_str("  };\n");
    }

    out.push_str("};\n");
    out
}

fn write_fields_object(out: &mut String, name: &str, fields: &[FieldSpec], indent: usize) {
    let padding = " ".repeat(indent);
    if fields.is_empty() {
        let _ = writeln!(out, "{padding}{name}: Record<string, never>;");
        return;
    }

    let _ = writeln!(out, "{padding}{name}: {{");
    for field in fields {
        let optional = if field.required { "" } else { "?" };
        let _ = writeln!(
            out,
            "{padding}  {}{}: {};",
            ts_key(&field.name),
            optional,
            field.ty
        );
    }
    let _ = writeln!(out, "{padding}}};");
}

fn schema_ref_to_ts(schema: &utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>) -> String {
    match schema {
        utoipa::openapi::RefOr::T(schema) => schema_to_ts(schema),
        utoipa::openapi::RefOr::Ref(reference) => reference
            .ref_location
            .rsplit('/')
            .next()
            .filter(|name| !name.is_empty())
            .unwrap_or("unknown")
            .to_owned(),
    }
}

fn schema_ref_is_nullable(
    schema: &utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
) -> bool {
    match schema {
        utoipa::openapi::RefOr::T(schema) => schema_is_nullable(schema),
        utoipa::openapi::RefOr::Ref(_) => false,
    }
}

fn schema_ref_has_default(
    schema: &utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
) -> bool {
    match schema {
        utoipa::openapi::RefOr::T(schema) => schema_has_default(schema),
        utoipa::openapi::RefOr::Ref(_) => false,
    }
}

fn schema_is_nullable(schema: &utoipa::openapi::schema::Schema) -> bool {
    match schema {
        utoipa::openapi::schema::Schema::Object(object) => {
            schema_type_is_nullable(&object.schema_type)
        }
        utoipa::openapi::schema::Schema::OneOf(one_of) => {
            one_of.items.iter().any(schema_ref_is_nullable)
        }
        utoipa::openapi::schema::Schema::AllOf(all_of) => {
            all_of.items.iter().any(schema_ref_is_nullable)
        }
        utoipa::openapi::schema::Schema::AnyOf(any_of) => {
            any_of.items.iter().any(schema_ref_is_nullable)
        }
        _ => false,
    }
}

fn schema_has_default(schema: &utoipa::openapi::schema::Schema) -> bool {
    match schema {
        utoipa::openapi::schema::Schema::Object(object) => object.default.is_some(),
        utoipa::openapi::schema::Schema::Array(array) => array.default.is_some(),
        utoipa::openapi::schema::Schema::OneOf(one_of) => one_of.default.is_some(),
        utoipa::openapi::schema::Schema::AllOf(all_of) => all_of.default.is_some(),
        utoipa::openapi::schema::Schema::AnyOf(any_of) => any_of.default.is_some(),
        _ => false,
    }
}

fn schema_type_is_nullable(schema_type: &utoipa::openapi::schema::SchemaType) -> bool {
    match schema_type {
        utoipa::openapi::schema::SchemaType::Type(utoipa::openapi::schema::Type::Null) => true,
        utoipa::openapi::schema::SchemaType::Array(types) => {
            types.contains(&utoipa::openapi::schema::Type::Null)
        }
        _ => false,
    }
}

fn schema_to_ts(schema: &utoipa::openapi::schema::Schema) -> String {
    match schema {
        utoipa::openapi::schema::Schema::Object(object) => object_to_ts(object),
        utoipa::openapi::schema::Schema::Array(array) => match &array.items {
            utoipa::openapi::schema::ArrayItems::RefOrSchema(item) => {
                format!("{}[]", schema_ref_to_ts(item))
            }
            utoipa::openapi::schema::ArrayItems::False => "never[]".to_owned(),
        },
        utoipa::openapi::schema::Schema::OneOf(one_of) => one_of
            .items
            .iter()
            .map(schema_ref_to_ts)
            .collect::<Vec<_>>()
            .join(" | "),
        utoipa::openapi::schema::Schema::AllOf(all_of) => all_of
            .items
            .iter()
            .map(schema_ref_to_ts)
            .collect::<Vec<_>>()
            .join(" & "),
        utoipa::openapi::schema::Schema::AnyOf(any_of) => any_of
            .items
            .iter()
            .map(schema_ref_to_ts)
            .collect::<Vec<_>>()
            .join(" | "),
        _ => "unknown".to_owned(),
    }
}

fn render_schema_declaration(
    name: &str,
    schema: &utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
) -> String {
    format!(
        "export type {} = {};",
        ts_key(name),
        schema_ref_to_ts(schema)
    )
}

fn object_to_ts(object: &utoipa::openapi::schema::Object) -> String {
    if let Some(enum_values) = &object.enum_values {
        if enum_values.is_empty() {
            return "never".to_owned();
        }

        return enum_values
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" | ");
    }

    if !object.properties.is_empty() {
        let fields = object
            .properties
            .iter()
            .map(|(name, schema)| FieldSpec {
                name: name.clone(),
                ty: schema_ref_to_ts(schema),
                required: object.required.contains(name),
            })
            .collect::<Vec<_>>();
        let mut out = String::new();
        out.push_str("{\n");

        for field in fields {
            let optional = if field.required { "" } else { "?" };
            let _ = writeln!(out, "  {}{}: {};", ts_key(&field.name), optional, field.ty);
        }

        out.push('}');
        return out;
    }

    schema_type_to_ts(&object.schema_type)
}

fn schema_type_to_ts(schema_type: &utoipa::openapi::schema::SchemaType) -> String {
    match schema_type {
        utoipa::openapi::schema::SchemaType::Type(ty) => primitive_type_to_ts(ty).to_owned(),
        utoipa::openapi::schema::SchemaType::Array(types) => types
            .iter()
            .filter(|ty| **ty != utoipa::openapi::schema::Type::Null)
            .map(primitive_type_to_ts)
            .collect::<Vec<_>>()
            .join(" | "),
        utoipa::openapi::schema::SchemaType::AnyValue => "unknown".to_owned(),
    }
}

fn primitive_type_to_ts(ty: &utoipa::openapi::schema::Type) -> &'static str {
    match ty {
        utoipa::openapi::schema::Type::Object => "Record<string, unknown>",
        utoipa::openapi::schema::Type::String => "string",
        utoipa::openapi::schema::Type::Integer | utoipa::openapi::schema::Type::Number => "number",
        utoipa::openapi::schema::Type::Boolean => "boolean",
        utoipa::openapi::schema::Type::Array => "unknown[]",
        utoipa::openapi::schema::Type::Null => "null",
    }
}

fn ts_key(key: &str) -> String {
    if key
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
    {
        key.to_owned()
    } else {
        format!("\"{}\"", key.replace('"', "\\\""))
    }
}