specta-typescript 0.0.11

Export your Rust types to TypeScript
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
// TODO: Drop this stuff

use std::{
    borrow::Cow,
    collections::BTreeSet,
    fmt::{self, Write},
};

use specta::{
    Types,
    datatype::{
        DataType, Deprecated, Enum, Field, Fields, GenericReference, Reference, Struct, Tuple,
        Variant,
    },
};

use crate::{Error, Exporter, reserved_names::RESERVED_TYPE_NAMES};

#[derive(Clone, Debug)]
pub(crate) enum PathItem {
    // Type(Cow<'static, str>),
    // TypeExtended(Cow<'static, str>, &'static str),
    Field(Cow<'static, str>),
    Variant(Cow<'static, str>),
}

#[derive(Clone)]
pub(crate) struct ExportContext<'a> {
    pub(crate) cfg: &'a Exporter,
    pub(crate) path: Vec<PathItem>,
}

impl ExportContext<'_> {
    pub(crate) fn with(&self, item: PathItem) -> Self {
        Self {
            path: self.path.iter().cloned().chain([item]).collect(),
            ..*self
        }
    }

    pub(crate) fn export_path(&self) -> ExportPath {
        ExportPath::new(&self.path)
    }
}

/// Represents the path of an error in the export tree.
/// This is designed to be opaque, meaning it's internal format and `Display` impl are subject to change at will.
pub struct ExportPath(String);

impl ExportPath {
    pub(crate) fn new(path: &[PathItem]) -> Self {
        let mut s = String::new();
        let mut path = path.iter().peekable();
        while let Some(item) = path.next() {
            s.push_str(match item {
                // PathItem::Type(v) => v,
                // PathItem::TypeExtended(_, loc) => loc,
                PathItem::Field(v) => v,
                PathItem::Variant(v) => v,
            });

            if let Some(next) = path.peek() {
                s.push_str(match next {
                    // PathItem::Type(_) => " -> ",
                    // PathItem::TypeExtended(_, _) => " -> ",
                    PathItem::Field(_) => ".",
                    PathItem::Variant(_) => "::",
                });
            } else {
                break;
            }
        }

        Self(s)
    }
}

impl PartialEq for ExportPath {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl fmt::Debug for ExportPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl fmt::Display for ExportPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[allow(missing_docs)]
pub(crate) type Result<T> = std::result::Result<T, Error>;

pub(crate) type Output = Result<String>;

#[allow(clippy::ptr_arg)]
fn inner_comments(
    deprecated: Option<&Deprecated>,
    docs: &str,
    other: String,
    start_with_newline: bool,
    prefix: &str,
    single_line_comment: bool,
) -> String {
    let mut comments = String::new();
    js_doc(&mut comments, docs, deprecated, single_line_comment);
    if comments.is_empty() {
        return other;
    }

    let mut out = String::new();
    if start_with_newline {
        out.push('\n');
    }

    for line in comments.lines() {
        out.push_str(prefix);
        out.push_str(line);
        out.push('\n');
    }

    out.push_str(&other);
    out
}

pub(crate) fn datatype_inner(
    ctx: ExportContext,
    typ: &DataType,
    types: &Types,
    s: &mut String,
    generics: &[(GenericReference, DataType)],
) -> Result<()> {
    crate::primitives::datatype(s, ctx.cfg, types, typ, vec![], None, "", generics)
}

// Can be used with `StructUnnamedFields.fields` or `EnumNamedFields.fields`
fn unnamed_fields_datatype(
    ctx: ExportContext,
    fields: &[(&Field, &DataType)],
    types: &Types,
    s: &mut String,
    prefix: &str,
    generics: &[(GenericReference, DataType)],
    force_inline: bool,
) -> Result<()> {
    match fields {
        [(field, ty)] => {
            let mut v = String::new();
            crate::primitives::datatype_with_inline_attr(
                &mut v,
                ctx.cfg,
                types,
                ty,
                vec![],
                None,
                "",
                generics,
                force_inline || field.inline(),
            )?;
            s.push_str(&inner_comments(
                field.deprecated(),
                field.docs(),
                v,
                true,
                prefix,
                !ctx.cfg.jsdoc,
            ));
        }
        fields => {
            s.push('[');

            for (i, (field, ty)) in fields.iter().enumerate() {
                if i != 0 {
                    s.push_str(", ");
                }

                let mut v = String::new();
                crate::primitives::datatype_with_inline_attr(
                    &mut v,
                    ctx.cfg,
                    types,
                    ty,
                    vec![],
                    None,
                    "",
                    generics,
                    force_inline || field.inline(),
                )?;
                s.push_str(&inner_comments(
                    field.deprecated(),
                    field.docs(),
                    v,
                    true,
                    prefix,
                    !ctx.cfg.jsdoc,
                ));
            }

            s.push(']');
        }
    }

    Ok(())
}

pub(crate) fn tuple_datatype(
    ctx: ExportContext,
    tuple: &Tuple,
    types: &Types,
    generics: &[(GenericReference, DataType)],
) -> Output {
    match &tuple.elements() {
        [] => Ok(NULL.to_string()),
        tys => Ok(format!(
            "[{}]",
            tys.iter()
                .map(|v| {
                    let mut s = String::new();
                    datatype_inner(ctx.clone(), v, types, &mut s, generics).map(|_| s)
                })
                .collect::<Result<Vec<_>>>()?
                .join(", ")
        )),
    }
}

pub(crate) fn struct_datatype(
    ctx: ExportContext,
    _parent_name: Option<&str>,
    strct: &Struct,
    types: &Types,
    s: &mut String,
    prefix: &str,
    generics: &[(GenericReference, DataType)],
) -> Result<()> {
    match &strct.fields() {
        Fields::Unit => s.push_str(NULL),
        Fields::Unnamed(unnamed) => unnamed_fields_datatype(
            ctx,
            &unnamed
                .fields()
                .iter()
                .filter_map(|field| field.ty().map(|ty| (field, ty)))
                .collect::<Vec<_>>(),
            types,
            s,
            prefix,
            generics,
            false,
        )?,
        Fields::Named(named) => {
            let fields = named
                .fields()
                .iter()
                .filter_map(|(name, field)| field.ty().map(|ty| (name, (field, ty))))
                .collect::<Vec<_>>();

            if fields.is_empty() {
                // TODO: Handle this
                // match (named.tag().as_ref(), parent_name) {
                //     (Some(tag), Some(key)) => write!(s, r#"{{ "{tag}": "{key}" }}"#)?,
                //     (_, _) => write!(s, "Record<{STRING}, {NEVER}>")?,
                // }
                write!(s, "Record<{STRING}, {NEVER}>")?;
                return Ok(());
            }

            let (flattened, non_flattened): (Vec<_>, Vec<_>) =
                fields.iter().partition(|(_, (f, _))| f.flatten());

            let mut flattened_sections = flattened
                .into_iter()
                .map(|(_key, (field, ty))| {
                    let mut s = String::new();
                    crate::primitives::datatype_with_inline_attr(
                        &mut s,
                        ctx.cfg,
                        types,
                        ty,
                        vec![],
                        None,
                        "",
                        generics,
                        field.inline(),
                    )
                    .map(|_| {
                        inner_comments(
                            field.deprecated(),
                            field.docs(),
                            format!("({s})"),
                            true,
                            prefix,
                            !ctx.cfg.jsdoc,
                        )
                    })
                })
                .collect::<Result<Vec<_>>>()?;

            let unflattened_fields = non_flattened
                .into_iter()
                .map(|(key, field_ref)| {
                    let (field, ty) = field_ref;
                    let field_prefix = format!("{prefix}\t");

                    let mut other = String::new();
                    object_field_to_ts(
                        ctx.with(PathItem::Field(key.clone())),
                        key.clone(),
                        (field, ty),
                        types,
                        &mut other,
                        generics,
                        &field_prefix,
                        false,
                        None,
                    )?;

                    let docs = field
                        .docs()
                        .trim()
                        .is_empty()
                        .then(|| inline_reference_docs(types, (field, ty), false))
                        .flatten()
                        .unwrap_or(field.docs());

                    Ok(inner_comments(
                        field.deprecated(),
                        docs,
                        other,
                        false,
                        &field_prefix,
                        !ctx.cfg.jsdoc,
                    ))
                })
                .collect::<Result<Vec<_>>>()?;

            // TODO: Handle this
            // if let (Some(tag), Some(key)) = (&named.tag(), parent_name) {
            //     unflattened_fields.push(format!("{tag}: \"{key}\""));
            // }

            if !unflattened_fields.is_empty() {
                let mut s = "{".to_string();

                for field in unflattened_fields {
                    s.push('\n');
                    s.push_str(&field);
                    s.push(',');
                }

                s.push('\n');
                s.push_str(prefix);
                s.push('}');
                flattened_sections.insert(0, s);
            }

            // Remove duplicates while preserving source order.
            let mut seen = BTreeSet::new();
            flattened_sections.retain(|section| seen.insert(section.clone()));
            s.push_str(&flattened_sections.join(" & "));
        }
    }

    Ok(())
}

fn enum_variant_datatype(
    ctx: ExportContext,
    types: &Types,
    name: Cow<'static, str>,
    variant: &Variant,
    prefix: &str,
    generics: &[(GenericReference, DataType)],
    ty_override: Option<VariantTypeOverride<'_>>,
) -> Result<Option<String>> {
    match &variant.fields() {
        Fields::Unit => Ok(Some(sanitise_key(name, true).to_string())),
        Fields::Named(obj) => {
            let all_fields = obj
                .fields()
                .iter()
                .filter_map(|(name, field)| field.ty().map(|ty| (name, (field, ty))))
                .collect::<Vec<_>>();

            let (flattened, non_flattened): (Vec<_>, Vec<_>) =
                all_fields.iter().partition(|(_, (f, _))| f.flatten());

            let field_sections = flattened
                .into_iter()
                .map(|(_key, (field, ty))| {
                    let mut s = String::new();
                    crate::primitives::datatype_with_inline_attr(
                        &mut s,
                        ctx.cfg,
                        types,
                        ty,
                        vec![],
                        None,
                        "",
                        generics,
                        field.inline(),
                    )
                    .map(|_| {
                        inner_comments(
                            field.deprecated(),
                            field.docs(),
                            format!("({s})"),
                            true,
                            prefix,
                            !ctx.cfg.jsdoc,
                        )
                    })
                })
                .collect::<Result<Vec<_>>>()?;

            let mut regular_fields = vec![];
            // TODO
            // let mut regular_fields = if let Some(tag) = &obj.tag() {
            //     let sanitised_name = sanitise_key(name, true);
            //     vec![format!("{tag}: {sanitised_name}")]
            // } else {
            //     vec![]
            // };

            regular_fields.extend(
                non_flattened
                    .into_iter()
                    .map(|(name, field_ref)| {
                        let (field, ty) = field_ref;

                        let mut other = String::new();
                        object_field_to_ts(
                            ctx.with(PathItem::Field(name.clone())),
                            name.clone(),
                            (field, ty),
                            types,
                            &mut other,
                            generics,
                            "",
                            false,
                            ty_override
                                .as_ref()
                                .filter(|override_ty| override_ty.key == name.as_ref())
                                .map(|override_ty| override_ty.ty),
                        )?;

                        let docs = field
                            .docs()
                            .trim()
                            .is_empty()
                            .then(|| inline_reference_docs(types, (field, ty), false))
                            .flatten()
                            .unwrap_or(field.docs());

                        Ok(inner_comments(
                            field.deprecated(),
                            docs,
                            other,
                            true,
                            prefix,
                            !ctx.cfg.jsdoc,
                        ))
                    })
                    .collect::<Result<Vec<_>>>()?,
            );

            Ok(Some(match (&field_sections[..], &regular_fields[..]) {
                ([], []) => format!("Record<{STRING}, {NEVER}>").to_string(),
                ([], fields) => format!("{{ {} }}", fields.join("; ")),
                (_, []) => field_sections.join(" & "),
                (_, _) => {
                    let mut sections = vec![format!("{{ {} }}", regular_fields.join("; "))];
                    sections.extend(field_sections);
                    sections.join(" & ")
                }
            }))
        }
        Fields::Unnamed(obj) => {
            let fields = obj
                .fields()
                .iter()
                .filter_map(|field| field.ty().map(|ty| (field, ty)))
                .map(|(field, ty)| {
                    let mut s = String::new();
                    crate::primitives::datatype_with_inline_attr(
                        &mut s,
                        ctx.cfg,
                        types,
                        ty,
                        vec![],
                        None,
                        "",
                        generics,
                        field.inline(),
                    )
                    .map(|_| s)
                })
                .collect::<Result<Vec<_>>>()?;

            Ok(match &fields[..] {
                [] => {
                    // If the actual length is 0, we know `#[serde(skip)]` was not used.
                    if obj.fields().is_empty() {
                        Some("[]".to_string())
                    } else {
                        // We wanna render `{tag}` not `{tag}: {type}` (where `{type}` is what this function returns)
                        None
                    }
                }
                // If the actual length is 1, we know `#[serde(skip)]` was not used.
                [field] if obj.fields().len() == 1 => Some(field.to_string()),
                fields => Some(format!("[{}]", fields.join(", "))),
            })
        }
    }
}

struct EnumVariantOutput {
    value: String,
    strict_keys: Option<BTreeSet<String>>,
}

#[derive(Debug, Clone)]
struct DiscriminatorAnalysis {
    key: String,
    known_literals: Vec<String>,
    fallback_variant_idx: Option<usize>,
}

#[derive(Debug, Clone, Copy)]
struct VariantTypeOverride<'a> {
    key: &'a str,
    ty: &'a str,
}

#[derive(Debug, Clone)]
enum DiscriminatorValue {
    StringLiteral(String),
    String,
}

fn analyze_discriminator(
    variants: &[&(Cow<'static, str>, Variant)],
) -> Option<DiscriminatorAnalysis> {
    let mut key = None::<String>;
    let mut known_literals = BTreeSet::new();
    let mut fallback_variant_idx = None;

    for (idx, (_, variant)) in variants.iter().enumerate() {
        let (variant_key, value) = variant_discriminator(variant)?;

        if let Some(expected) = &key {
            if expected != &variant_key {
                return None;
            }
        } else {
            key = Some(variant_key.clone());
        }

        match value {
            DiscriminatorValue::StringLiteral(value) => {
                known_literals.insert(value);
            }
            DiscriminatorValue::String => {
                if fallback_variant_idx.replace(idx).is_some() {
                    return None;
                }
            }
        }
    }

    if known_literals.is_empty() {
        return None;
    }

    Some(DiscriminatorAnalysis {
        key: key.expect("at least one variant when called"),
        known_literals: known_literals.into_iter().collect(),
        fallback_variant_idx,
    })
}

fn variant_discriminator(variant: &Variant) -> Option<(String, DiscriminatorValue)> {
    let Fields::Named(named) = variant.fields() else {
        return None;
    };

    let (name, field) = named
        .fields()
        .iter()
        .find(|(_, field)| !field.flatten() && !field.optional())?;
    let ty = field.ty()?;

    if matches!(ty, DataType::Primitive(specta::datatype::Primitive::str)) {
        return Some((name.to_string(), DiscriminatorValue::String));
    }

    string_literal_datatype_value(ty)
        .map(|value| (name.to_string(), DiscriminatorValue::StringLiteral(value)))
}

fn string_literal_datatype_value(ty: &DataType) -> Option<String> {
    let DataType::Enum(enm) = ty else {
        return None;
    };

    let mut variants = enm.variants().iter();
    let (name, variant) = variants.next()?;

    if variants.next().is_some() {
        return None;
    }

    if !matches!(variant.fields(), Fields::Unit) {
        return None;
    }

    Some(name.to_string())
}

fn exclude_known_literals_type(literals: &[String]) -> Option<String> {
    if literals.is_empty() {
        return None;
    }

    let known = literals
        .iter()
        .map(|value| format!("\"{}\"", escape_typescript_string_literal(value.as_str())))
        .collect::<Vec<_>>()
        .join(" | ");

    Some(format!("Exclude<string, {known}>"))
}

fn untagged_strict_keys(variant: &Variant) -> Option<BTreeSet<String>> {
    match variant.fields() {
        Fields::Named(obj) => {
            let all_fields = obj
                .fields()
                .iter()
                .filter_map(|(name, field)| field.ty().map(|ty| (name, (field, ty))))
                .collect::<Vec<_>>();
            if all_fields.iter().any(|(_, (field, _))| field.flatten()) {
                return None;
            }

            Some(
                all_fields
                    .into_iter()
                    .map(|(name, _)| sanitise_key(name.clone(), false).to_string())
                    .collect(),
            )
        }
        _ => None,
    }
}

fn strictify_enum_variants(variants: &mut [EnumVariantOutput]) {
    let strict_key_universe = variants
        .iter()
        .filter_map(|variant| variant.strict_keys.as_ref())
        .flat_map(|keys| keys.iter().cloned())
        .collect::<BTreeSet<_>>();

    if strict_key_universe.len() < 2 {
        return;
    }

    for variant in variants {
        let Some(keys) = variant.strict_keys.as_ref() else {
            continue;
        };

        let missing_keys = strict_key_universe
            .iter()
            .filter(|key| !keys.contains(*key))
            .map(|key| format!("{key}?: {NEVER}"))
            .collect::<Vec<_>>();

        if missing_keys.is_empty() {
            continue;
        }

        variant.value = format!("({}) & {{ {} }}", variant.value, missing_keys.join("; "));
    }
}

pub(crate) fn enum_datatype(
    ctx: ExportContext,
    e: &Enum,
    types: &Types,
    s: &mut String,
    prefix: &str,
    generics: &[(GenericReference, DataType)],
) -> Result<()> {
    if e.variants().is_empty() {
        return Ok(write!(s, "{NEVER}")?);
    }

    let filtered_variants = e
        .variants()
        .iter()
        .filter(|(_, variant)| !variant.skip())
        .collect::<Vec<_>>();

    let discriminator = analyze_discriminator(&filtered_variants);
    let fallback_override = discriminator.as_ref().and_then(|discriminator| {
        discriminator.fallback_variant_idx.and_then(|idx| {
            exclude_known_literals_type(&discriminator.known_literals)
                .map(|ty| (idx, discriminator.key.as_str(), ty))
        })
    });

    let mut rendered_variants = Vec::with_capacity(filtered_variants.len());
    for (idx, (variant_name, variant)) in filtered_variants.iter().enumerate() {
        let variant_override = fallback_override
            .as_ref()
            .and_then(|(fallback_idx, key, ty)| {
                if *fallback_idx == idx {
                    Some(VariantTypeOverride {
                        key,
                        ty: ty.as_str(),
                    })
                } else {
                    None
                }
            });

        let ts_values = enum_variant_datatype(
            ctx.with(PathItem::Variant(variant_name.clone())),
            types,
            variant_name.clone(),
            variant,
            prefix,
            generics,
            variant_override,
        )?;

        rendered_variants.push(EnumVariantOutput {
            value: ts_values.unwrap_or_else(|| NEVER.to_string()),
            strict_keys: untagged_strict_keys(variant),
        });
    }

    if discriminator.is_none() {
        strictify_enum_variants(&mut rendered_variants);
    }

    let mut variants = filtered_variants
        .into_iter()
        .zip(rendered_variants)
        .map(|((_, variant), rendered)| {
            inner_comments(
                variant.deprecated(),
                variant.docs(),
                rendered.value,
                true,
                prefix,
                !ctx.cfg.jsdoc,
            )
        })
        .collect::<Vec<_>>();

    let mut seen = BTreeSet::new();
    variants.retain(|variant| seen.insert(variant.clone()));

    // If all variants are skipped, the enum has no valid values
    if variants.is_empty() {
        s.push_str(NEVER);
    } else {
        s.push_str(&variants.join(" | "));
    }

    Ok(())
}

/// convert an object field into a Typescript string
fn object_field_to_ts(
    ctx: ExportContext,
    key: Cow<'static, str>,
    field_ref: (&Field, &DataType),
    types: &Types,
    s: &mut String,
    generics: &[(GenericReference, DataType)],
    prefix: &str,
    force_inline: bool,
    ty_override: Option<&str>,
) -> Result<()> {
    let (field, ty) = field_ref;
    let field_name_safe = sanitise_key(key, false);

    // https://github.com/specta-rs/rspc/issues/100#issuecomment-1373092211
    let (key, ty) = match field.optional() {
        true => (format!("{field_name_safe}?").into(), ty),
        false => (field_name_safe, ty),
    };

    let value = match ty_override {
        Some(ty_override) => ty_override.to_string(),
        None => {
            let mut value = String::new();
            crate::primitives::datatype_with_inline_attr(
                &mut value,
                ctx.cfg,
                types,
                ty,
                vec![],
                None,
                prefix,
                generics,
                force_inline || field.inline(),
            )?;
            value
        }
    };

    Ok(write!(s, "{prefix}{key}: {value}",)?)
}

fn inline_reference_docs<'a>(
    types: &'a Types,
    (field, ty): (&Field, &'a DataType),
    force_inline: bool,
) -> Option<&'a str> {
    let DataType::Reference(Reference::Named(r)) = ty else {
        return None;
    };

    if !(force_inline || field.inline() || r.inline()) {
        return None;
    }

    r.get(types)
        .filter(|ndt| !ndt.docs().trim().is_empty())
        .map(|ndt| ndt.docs().as_ref())
}

/// sanitise a string to be a valid Typescript key
fn sanitise_key<'a>(field_name: Cow<'static, str>, force_string: bool) -> Cow<'a, str> {
    let valid = is_identifier(&field_name);

    if force_string || !valid {
        format!(r#""{}""#, escape_typescript_string_literal(&field_name)).into()
    } else {
        field_name
    }
}

pub(crate) fn is_identifier(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };

    (first.is_ascii_alphabetic() || first == '_' || first == '$')
        && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '$')
}

pub(crate) fn escape_typescript_string_literal(value: &str) -> Cow<'_, str> {
    if !value.chars().any(|ch| {
        ch == '"' || ch == '\\' || ch == '\u{2028}' || ch == '\u{2029}' || ch.is_control()
    }) {
        return Cow::Borrowed(value);
    }

    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '"' => escaped.push_str(r#"\""#),
            '\\' => escaped.push_str(r#"\\"#),
            '\n' => escaped.push_str(r#"\n"#),
            '\r' => escaped.push_str(r#"\r"#),
            '\t' => escaped.push_str(r#"\t"#),
            '\u{2028}' => escaped.push_str(r#"\u2028"#),
            '\u{2029}' => escaped.push_str(r#"\u2029"#),
            ch if ch.is_control() => {
                write!(escaped, r#"\u{:04X}"#, ch as u32).expect("infallible");
            }
            _ => escaped.push(ch),
        }
    }

    Cow::Owned(escaped)
}

pub(crate) fn sanitise_type_name(ctx: ExportContext, ident: &str) -> Output {
    if let Some(name) = RESERVED_TYPE_NAMES.iter().find(|v| **v == ident) {
        return Err(Error::forbidden_name_legacy(ctx.export_path(), name));
    }

    if let Some(first_char) = ident.chars().next()
        && !first_char.is_alphabetic()
        && first_char != '_'
    {
        return Err(Error::invalid_name_legacy(
            ctx.export_path(),
            ident.to_string(),
        ));
    }

    if ident
        .find(|c: char| !c.is_alphanumeric() && c != '_')
        .is_some()
    {
        return Err(Error::invalid_name_legacy(
            ctx.export_path(),
            ident.to_string(),
        ));
    }

    Ok(ident.to_string())
}

const STRING: &str = "string";
const NULL: &str = "null";
const NEVER: &str = "never";

// TODO: Merge this into main expoerter
pub(crate) fn js_doc(
    s: &mut String,
    docs: &str,
    deprecated: Option<&Deprecated>,
    single_line_comment: bool,
) {
    // Early return - no-op if nothing to document
    if docs.is_empty() && deprecated.is_none() {
        return;
    }

    if single_line_comment && deprecated.is_none() {
        let mut lines = docs.lines();
        if let (Some(line), None) = (lines.next(), lines.next()) {
            s.push_str("//");
            s.push_str(&escape_jsdoc_text(line));
            s.push('\n');
            return;
        }
    }

    // Start JSDoc comment
    s.push_str("/**\n");

    // Add documentation lines
    if !docs.is_empty() {
        for line in docs.lines() {
            s.push_str(" * ");
            s.push_str(&escape_jsdoc_text(line));
            s.push('\n');
        }
    }

    // Add @deprecated tag if present
    if let Some(typ) = deprecated {
        s.push_str(" * @deprecated");

        if let Some(details) = deprecated_details(typ) {
            s.push(' ');
            s.push_str(&details);
        }

        s.push('\n');
    }

    // Close JSDoc comment
    s.push_str(" */\n");
}

pub(crate) fn escape_jsdoc_text(text: &str) -> Cow<'_, str> {
    if text.contains("*/") {
        Cow::Owned(text.replace("*/", "*\\/"))
    } else {
        Cow::Borrowed(text)
    }
}

pub(crate) fn deprecated_details(typ: &Deprecated) -> Option<String> {
    let note = typ.note().map(|v| v.trim()).filter(|v| !v.is_empty());
    let since = typ.since().map(|v| v.trim()).filter(|v| !v.is_empty());

    match (note, since) {
        (Some(note), Some(since)) => Some(format!("{note} since {since}")),
        (Some(note), None) => Some(note.to_string()),
        (None, Some(since)) => Some(format!("since {since}")),
        (None, None) => None,
    }
}

// pub fn typedef_named_datatype(
//     cfg: &Typescript,
//     typ: &NamedDataType,
//     types: &Types,
// ) -> Output {
//     typedef_named_datatype_inner(
//         &ExportContext {
//             cfg,
//             path: vec![],
//         },
//         typ,
//         types,
//     )
// }

// fn typedef_named_datatype_inner(
//     ctx: &ExportContext,
//     typ: &NamedDataType,
//     types: &Types,
// ) -> Output {
//     let name = typ.name();
//     let docs = typ.docs();
//     let deprecated = typ.deprecated();
//     let item = typ.ty();

//     let ctx = ctx.with(PathItem::Type(name.clone()));

//     let name = sanitise_type_name(ctx.clone(), name)?;

//     let mut inline_ts = String::new();
//     datatype_inner(
//         ctx.clone(),
//         &FunctionReturnType::Value(typ.ty().clone()),
//         types,
//         &mut inline_ts,
//     )?;

//     let mut builder = js_doc_builder(docs, deprecated);

//     typ.generics()
//         .into_iter()
//         .for_each(|generic| builder.push_generic(generic));

//     builder.push_internal(["@typedef { ", &inline_ts, " } ", &name]);

//     Ok(builder.build())
// }