specta-typescript 0.0.12

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
use std::{borrow::Cow, error, fmt, io, panic::Location, path::PathBuf};

use specta::datatype::{NamedDataType, OpaqueReference, RecursiveInlineType};

use crate::Layout;

/// The error type for the TypeScript exporter.
///
/// ## BigInt Forbidden
///
/// Specta Typescript intentionally forbids exporting BigInt-style Rust integer types.
/// This includes [usize], [isize], [i64], [u64], [u128], [i128] and [f128].
///
/// This guard exists because `JSON.parse` will truncate large integers to fit into a JavaScript `number` type so we explicitly forbid exporting them.
///
/// We take the stance that correctness matters more than developer experience as people using Rust generally strive for correctness.
///
/// If you encounter this error, there are a few common migration paths (in order of preference):
///
/// 1. Use a Specta-based framework which can handle these types
///     - None currently exist but it would theoretically be possible refer to [#203](https://github.com/specta-rs/specta/issues/203#issuecomment-4387573925) for more information.
///
/// 2. Use a smaller integer types (any of `u8`/`i8`/`u16`/`i16`/`u32`/`i32`/`f64`).
///    - Only possible when the biggest integer you need to represent is small enough to be represented by a `number` in JS.
///    - This approach forces your application code to handle overflow/underflow values explicitly
///    - Downside is that it can introduce annoying glue code and doesn't actually work if your need large values.
///
/// 3. Serialize the value as a string
///     - This can be done using `#[specta(type = String)]` for the type combined with a Serde `#[serde(with = "...")]` attribute for runtime.
///     - Downside is that it can introduce annoying glue code, both on in Rust and in JS as you will need to turn it back into a `new BigInt(myString)` in JS but this will support numbers of any size losslessly.
///
/// 4. **UNSAFE:** Accept precision loss on per-field basis
///     - Accept that large numbers may be deserialized differently than they are in Rust and use `#[specta(type = specta_typescript::Number)]` to bypass this warning on a per-field basis.
///     - Marking each field explicitly encodes the decision similar to an `unsafe` block, ensuring everyone working on your codebase is aware of the risk and where it exists within the codebase.
///     - This doesn't work for external implementations like `serde_json::Value` which contain `BigInt`'s as you don't control the definition.
///
/// 5. **UNSAFE:** Accept precision loss using [`specta_util::Remapper`](https://docs.rs/specta-util/latest/specta_util/struct.Remapper.html)
///     - You can apply a `Remapper` to your [`Types`](specta::Types) collection to override types. This would allow you to remap `usize`/`isize`/`i64`/`u64`/`i128`/`u128`/`f128` into `number`.
///     - This is highly not recommended but it might be required if your using `serde_json::Value` or other built-in impls which contain `BigInt`'s as you can't override them.
///     - Refer to discussion around this on [#481](https://github.com/specta-rs/specta/issues/481).
///
#[non_exhaustive]
pub struct Error {
    kind: ErrorKind,
    named_datatype: Option<Box<NamedDataType>>,
    trace: Vec<ErrorTraceFrame>,
}

/// Additional TypeScript exporter context for an [`Error`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ErrorTraceFrame {
    /// The exporter was rendering a core-provided inline reference at `path` when the error occurred.
    Inlined {
        /// The named Rust type being inlined, if it could be resolved.
        named_datatype: Option<Box<NamedDataType>>,
        /// Field, variant, or variant-field path where the inline expansion occurred.
        path: String,
    },
}

type FrameworkSource = Box<dyn error::Error + Send + Sync + 'static>;
const BIGINT_DOCS_URL: &str =
    "https://docs.rs/specta-typescript/latest/specta_typescript/struct.Error.html#bigint-forbidden";

#[allow(dead_code)]
enum ErrorKind {
    /// A map key type cannot be represented as a valid Typescript index signature.
    ///
    /// Typescript map keys must resolve to string-like, number-like, symbol-like, or literal key
    /// types. Complex structural values cannot safely be represented as object keys.
    InvalidMapKey {
        path: String,
        reason: Cow<'static, str>,
    },
    /// Attempted to export a bigint type but the configuration forbids it.
    BigIntForbidden {
        path: String,
    },
    /// A type's name conflicts with a reserved keyword in Typescript.
    ForbiddenName {
        path: String,
        name: &'static str,
    },
    /// A type's name contains invalid characters or is not valid.
    InvalidName {
        path: String,
        name: Cow<'static, str>,
    },
    /// A type's name is empty and cannot be emitted as a Typescript type name.
    EmptyName {
        path: String,
    },
    /// Anonymous enum variants cannot be represented by the Typescript exporter.
    UnsupportedAnonymousEnumVariant {
        path: String,
        variant_kind: &'static str,
    },
    /// Detected multiple items within the same scope with the same name.
    /// Typescript doesn't support this so we error out.
    ///
    /// Using anything other than [Layout::FlatFile] should make this basically impossible.
    DuplicateTypeName {
        name: Cow<'static, str>,
        first: String,
        second: String,
    },
    /// An filesystem IO error.
    /// This is possible when using `Typescript::export_to` when writing to a file or formatting the file.
    Io(io::Error),
    /// Failed to read a directory while exporting files.
    ReadDir {
        path: PathBuf,
        source: io::Error,
    },
    /// Failed to inspect filesystem metadata while exporting files.
    Metadata {
        path: PathBuf,
        source: io::Error,
    },
    /// Failed to remove a stale file while exporting files.
    RemoveFile {
        path: PathBuf,
        source: io::Error,
    },
    /// Failed to remove an empty directory while exporting files.
    RemoveDir {
        path: PathBuf,
        source: io::Error,
    },
    /// Failed to create an output directory while exporting files.
    CreateDir {
        path: PathBuf,
        source: io::Error,
    },
    /// Failed to write an output file while exporting files.
    WriteFile {
        path: PathBuf,
        source: io::Error,
    },
    /// Failed to read a generated file while exporting files.
    ReadFile {
        path: PathBuf,
        source: io::Error,
    },
    /// Found an opaque reference which the Typescript exporter doesn't know how to handle.
    /// You may be referencing a type which is not supported by the Typescript exporter.
    UnsupportedOpaqueReference {
        path: String,
        reference: OpaqueReference,
    },
    /// Found a named reference that cannot be resolved from the provided
    /// [`Types`](specta::Types).
    DanglingNamedReference {
        path: String,
        reference: String,
    },
    /// Found a recursive named reference marked by core inline resolution.
    InfiniteRecursiveInlineType {
        path: String,
        reference: String,
        cycle: RecursiveInlineType,
    },
    /// Reached the recursion limit while rendering an anonymous Typescript type.
    InlineRecursionLimitExceeded {
        path: String,
    },
    /// An error occurred in your exporter framework.
    Framework {
        message: Cow<'static, str>,
        source: FrameworkSource,
    },
    /// An error occurred in a format callback.
    Format {
        message: Cow<'static, str>,
        path: Option<String>,
        source: FrameworkSource,
    },
    /// The requested export layout is not supported by the current exporter configuration.
    ///
    /// Some layouts require the higher-level [`Exporter`](crate::Exporter) APIs so imports,
    /// file paths, and module boundaries can be coordinated correctly.
    ExportRequiresExportTo(Layout),
    JsdocNamespacesUnsupported,
}

impl Error {
    fn new(kind: ErrorKind) -> Self {
        Self {
            kind,
            named_datatype: None,
            trace: Vec::new(),
        }
    }

    /// The named Rust type being exported when this error occurred, if known.
    pub fn named_datatype(&self) -> Option<&NamedDataType> {
        self.named_datatype.as_deref()
    }

    /// TypeScript exporter traversal context for this error.
    pub fn trace(&self) -> &[ErrorTraceFrame] {
        &self.trace
    }

    pub(crate) fn with_named_datatype(mut self, ndt: &NamedDataType) -> Self {
        self.named_datatype
            .get_or_insert_with(|| Box::new(ndt.clone()));
        self
    }

    pub(crate) fn with_inline_trace(
        mut self,
        ndt: Option<&NamedDataType>,
        path: impl Into<String>,
    ) -> Self {
        self.trace.push(ErrorTraceFrame::Inlined {
            named_datatype: ndt.map(|ndt| Box::new(ndt.clone())),
            path: path.into(),
        });
        self
    }

    pub(crate) fn invalid_map_key(
        path: impl Into<String>,
        reason: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self::new(ErrorKind::InvalidMapKey {
            path: path.into(),
            reason: reason.into(),
        })
    }

    /// Construct an error for framework-specific logic.
    pub fn framework(
        message: impl Into<Cow<'static, str>>,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        Self::new(ErrorKind::Framework {
            message: message.into(),
            source: source.into(),
        })
    }

    /// Construct an error for custom format callbacks.
    pub(crate) fn format(
        message: impl Into<Cow<'static, str>>,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        Self::new(ErrorKind::Format {
            message: message.into(),
            path: None,
            source: source.into(),
        })
    }

    pub(crate) fn format_at(
        message: impl Into<Cow<'static, str>>,
        path: impl Into<String>,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        Self::new(ErrorKind::Format {
            message: message.into(),
            path: Some(path.into()),
            source: source.into(),
        })
    }

    pub(crate) fn bigint_forbidden(path: String) -> Self {
        Self::new(ErrorKind::BigIntForbidden { path })
    }

    pub(crate) fn invalid_name(path: String, name: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::InvalidName {
            path,
            name: name.into(),
        })
    }

    pub(crate) fn empty_name(path: String) -> Self {
        Self::new(ErrorKind::EmptyName { path })
    }

    pub(crate) fn unsupported_anonymous_enum_variant(
        path: String,
        variant_kind: &'static str,
    ) -> Self {
        Self::new(ErrorKind::UnsupportedAnonymousEnumVariant { path, variant_kind })
    }

    pub(crate) fn forbidden_name(path: String, name: &'static str) -> Self {
        Self::new(ErrorKind::ForbiddenName { path, name })
    }

    pub(crate) fn duplicate_type_name(
        name: Cow<'static, str>,
        first: Location<'static>,
        second: Location<'static>,
    ) -> Self {
        Self::new(ErrorKind::DuplicateTypeName {
            name,
            first: format_location(first),
            second: format_location(second),
        })
    }

    pub(crate) fn read_dir(path: PathBuf, source: io::Error) -> Self {
        Self::new(ErrorKind::ReadDir { path, source })
    }

    pub(crate) fn metadata(path: PathBuf, source: io::Error) -> Self {
        Self::new(ErrorKind::Metadata { path, source })
    }

    pub(crate) fn remove_file(path: PathBuf, source: io::Error) -> Self {
        Self::new(ErrorKind::RemoveFile { path, source })
    }

    pub(crate) fn remove_dir(path: PathBuf, source: io::Error) -> Self {
        Self::new(ErrorKind::RemoveDir { path, source })
    }

    pub(crate) fn create_dir(path: PathBuf, source: io::Error) -> Self {
        Self::new(ErrorKind::CreateDir { path, source })
    }

    pub(crate) fn write_file(path: PathBuf, source: io::Error) -> Self {
        Self::new(ErrorKind::WriteFile { path, source })
    }

    pub(crate) fn read_file(path: PathBuf, source: io::Error) -> Self {
        Self::new(ErrorKind::ReadFile { path, source })
    }

    pub(crate) fn unsupported_opaque_reference(path: String, reference: OpaqueReference) -> Self {
        Self::new(ErrorKind::UnsupportedOpaqueReference { path, reference })
    }

    pub(crate) fn dangling_named_reference(path: String, reference: String) -> Self {
        Self::new(ErrorKind::DanglingNamedReference { path, reference })
    }

    pub(crate) fn infinite_recursive_inline_type(
        path: String,
        reference: String,
        cycle: RecursiveInlineType,
    ) -> Self {
        Self::new(ErrorKind::InfiniteRecursiveInlineType {
            path,
            reference,
            cycle,
        })
    }

    pub(crate) fn inline_recursion_limit_exceeded(path: String) -> Self {
        Self::new(ErrorKind::InlineRecursionLimitExceeded { path })
    }

    pub(crate) fn export_requires_export_to(layout: Layout) -> Self {
        Self::new(ErrorKind::ExportRequiresExportTo(layout))
    }

    pub(crate) fn jsdoc_namespaces_unsupported() -> Self {
        Self::new(ErrorKind::JsdocNamespacesUnsupported)
    }
}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Self {
        Self::new(ErrorKind::Io(error))
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ErrorKind::InvalidMapKey { path, reason } => {
                write!(f, "Invalid map key at '{path}': {reason}")
            }
            ErrorKind::BigIntForbidden { path } => write!(
                f,
                "Attempted to export {path:?} but Specta forbids exporting BigInt-style types (usize, isize, i64, u64, i128, u128) to avoid precision loss. See {BIGINT_DOCS_URL} for a full explanation."
            ),
            ErrorKind::ForbiddenName { path, name } => write!(
                f,
                "Attempted to export {} but was unable to due to name {name:?} conflicting with a reserved keyword in Typescript. Try renaming it or using `#[specta(rename = \"new name\")]`",
                display_path(path)
            ),
            ErrorKind::InvalidName { path, name } => write!(
                f,
                "Attempted to export {} but was unable to due to name {name:?} containing an invalid character. Try renaming it or using `#[specta(rename = \"new name\")]`",
                display_path(path)
            ),
            ErrorKind::EmptyName { path } => write!(
                f,
                "Attempted to export {} but was unable to because the Typescript type name is empty. Try renaming it or using `#[specta(rename = \"new name\")]`",
                display_path(path)
            ),
            ErrorKind::UnsupportedAnonymousEnumVariant { path, variant_kind } => write!(
                f,
                "Attempted to export {} but anonymous {variant_kind} enum variants cannot be exported to Typescript. Try giving the variant a name or changing the enum representation.",
                display_path(path)
            ),
            ErrorKind::DuplicateTypeName {
                name,
                first,
                second,
            } => write!(
                f,
                "Detected multiple types with the same name: {name:?} at {first} and {second}"
            ),
            ErrorKind::Io(err) => write!(f, "IO error: {err}"),
            ErrorKind::ReadDir { path, source } => {
                write!(f, "Failed to read directory '{}': {source}", path.display())
            }
            ErrorKind::Metadata { path, source } => {
                write!(
                    f,
                    "Failed to read metadata for '{}': {source}",
                    path.display()
                )
            }
            ErrorKind::RemoveFile { path, source } => {
                write!(f, "Failed to remove file '{}': {source}", path.display())
            }
            ErrorKind::RemoveDir { path, source } => {
                write!(
                    f,
                    "Failed to remove directory '{}': {source}",
                    path.display()
                )
            }
            ErrorKind::CreateDir { path, source } => {
                write!(
                    f,
                    "Failed to create directory '{}': {source}",
                    path.display()
                )
            }
            ErrorKind::WriteFile { path, source } => {
                write!(f, "Failed to write file '{}': {source}", path.display())
            }
            ErrorKind::ReadFile { path, source } => {
                write!(f, "Failed to read file '{}': {source}", path.display())
            }
            ErrorKind::UnsupportedOpaqueReference { path, reference } => write!(
                f,
                "Found unsupported opaque reference '{}' at {}. It is not supported by the Typescript exporter.",
                reference.type_name(),
                display_path(path)
            ),
            ErrorKind::DanglingNamedReference { path, reference } => write!(
                f,
                "Found dangling named reference {reference} at {}. The referenced type is missing from the resolved type collection.",
                display_path(path)
            ),
            ErrorKind::InfiniteRecursiveInlineType {
                path,
                reference,
                cycle,
            } => {
                write!(
                    f,
                    "Found infinitely recursive inline named reference {reference} at {}. Recursive inline types cannot be expanded because they would produce an infinite Typescript type.",
                    display_path(path)
                )?;
                write!(f, "\nInline cycle:\n  {cycle:?}")?;
                Ok(())
            }
            ErrorKind::InlineRecursionLimitExceeded { path } if path.is_empty() => write!(
                f,
                "Type recursion limit exceeded while expanding the provided inline type. Recursive inline types cannot be expanded because they would produce an infinite Typescript type."
            ),
            ErrorKind::InlineRecursionLimitExceeded { path } => write!(
                f,
                "Type recursion limit exceeded while expanding an inline Typescript type at {}. Recursive inline types cannot be expanded because they would produce an infinite Typescript type.",
                display_path(path)
            ),
            ErrorKind::Framework { message, source } => {
                let source = source.to_string();
                if message.is_empty() && source.is_empty() {
                    write!(f, "Framework error")
                } else if source.is_empty() {
                    write!(f, "Framework error: {message}")
                } else {
                    write!(f, "Framework error: {message}: {source}")
                }
            }
            ErrorKind::Format {
                message,
                path,
                source,
            } => {
                let source = source.to_string();
                let location = path
                    .as_deref()
                    .filter(|path| !path.is_empty())
                    .map(|path| format!(" at {}", display_path(path)))
                    .unwrap_or_default();
                if message.is_empty() && source.is_empty() {
                    write!(f, "Format error{location}")
                } else if source.is_empty() {
                    write!(f, "Format error{location}: {message}")
                } else {
                    write!(f, "Format error{location}: {message}: {source}")
                }
            }
            ErrorKind::ExportRequiresExportTo(layout) => write!(
                f,
                "Unable to export layout {layout} as a single string. Use `Exporter::export_to` with a directory path for file-based exports."
            ),
            ErrorKind::JsdocNamespacesUnsupported => write!(
                f,
                "Unable to export JSDoc with the Namespaces layout. Disable JSDoc or use FlatFile, ModulePrefixedName, or Files layout."
            ),
        }?;

        if let Some(ndt) = self.named_datatype() {
            write!(
                f,
                "\nRust type: {}::{} at {}",
                ndt.module_path,
                ndt.name,
                format_location(ndt.location)
            )?;
        }

        if !self.trace.is_empty() {
            write!(f, "\nWhile inlining:")?;
            for frame in self.trace.iter().rev() {
                match frame {
                    ErrorTraceFrame::Inlined {
                        named_datatype,
                        path,
                    } => {
                        write!(f, "\n  {path} -> ")?;
                        if let Some(ndt) = named_datatype.as_deref() {
                            write!(f, "{}::{}", ndt.module_path, ndt.name)?;
                        } else {
                            write!(f, "<unresolved named type>")?;
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match &self.kind {
            ErrorKind::Io(error) => Some(error),
            ErrorKind::ReadDir { source, .. }
            | ErrorKind::Metadata { source, .. }
            | ErrorKind::RemoveFile { source, .. }
            | ErrorKind::RemoveDir { source, .. }
            | ErrorKind::CreateDir { source, .. }
            | ErrorKind::WriteFile { source, .. }
            | ErrorKind::ReadFile { source, .. } => Some(source),
            ErrorKind::Framework { source, .. } | ErrorKind::Format { source, .. } => {
                Some(source.as_ref())
            }
            _ => None,
        }
    }
}

fn format_location(location: Location<'static>) -> String {
    format!(
        "{}:{}:{}",
        location.file(),
        location.line(),
        location.column()
    )
}

fn display_path(path: &str) -> Cow<'_, str> {
    if path.is_empty() {
        Cow::Borrowed("<unknown path>")
    } else {
        Cow::Owned(format!("{path:?}"))
    }
}