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 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
//! <h1 align="center" style="padding-top: 0; margin-top: 0;">
//! <img width="150px" src="https://raw.githubusercontent.com/Aleph-Alpha/ts-rs/main/logo.png" alt="logo">
//! <br/>
//! ts-rs
//! </h1>
//! <p align="center">
//! generate typescript type declarations from rust types
//! </p>
//!
//! <div align="center">
//! <!-- Github Actions -->
//! <img src="https://img.shields.io/github/actions/workflow/status/Aleph-Alpha/ts-rs/test.yml?branch=main" alt="actions status" />
//! <a href="https://crates.io/crates/ts-rs">
//! <img src="https://img.shields.io/crates/v/ts-rs.svg?style=flat-square"
//! alt="Crates.io version" />
//! </a>
//! <a href="https://docs.rs/ts-rs">
//! <img src="https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square"
//! alt="docs.rs docs" />
//! </a>
//! <a href="https://crates.io/crates/ts-rs">
//! <img src="https://img.shields.io/crates/d/ts-rs.svg?style=flat-square"
//! alt="Download" />
//! </a>
//! </div>
//!
//! ## why?
//! When building a web application in rust, data structures have to be shared between backend and frontend.
//! Using this library, you can easily generate TypeScript bindings to your rust structs & enums so that you can keep your
//! types in one place.
//!
//! ts-rs might also come in handy when working with webassembly.
//!
//! ## how?
//! ts-rs exposes a single trait, `TS`. Using a derive macro, you can implement this interface for your types.
//! Then, you can use this trait to obtain the TypeScript bindings.
//! We recommend doing this in your tests.
//! [See the example](https://github.com/Aleph-Alpha/ts-rs/blob/main/example/src/lib.rs) and [the docs](https://docs.rs/ts-rs/latest/ts_rs/).
//!
//! ## get started
//! ```toml
//! [dependencies]
//! ts-rs = "8.1"
//! ```
//!
//! ```rust
//! use ts_rs::TS;
//!
//! #[derive(TS)]
//! #[ts(export)]
//! struct User {
//! user_id: i32,
//! first_name: String,
//! last_name: String,
//! }
//! ```
//! When running `cargo test`, the TypeScript bindings will be exported to the file `bindings/User.ts`.
//!
//! ## features
//! - generate type declarations from rust structs
//! - generate union declarations from rust enums
//! - inline types
//! - flatten structs/types
//! - generate necessary imports when exporting to multiple files
//! - serde compatibility
//! - generic types
//! - support for ESM imports
//!
//! ## cargo features
//! | **Feature** | **Description** |
//! |:-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
//! | serde-compat | **Enabled by default** <br/>See the *"serde compatibility"* section below for more information. |
//! | format | Enables formatting of the generated TypeScript bindings. <br/>Currently, this unfortunately adds quite a few dependencies. |
//! | no-serde-warnings | By default, warnings are printed during build if unsupported serde attributes are encountered. <br/>Enabling this feature silences these warnings. |
//! | import-esm | When enabled,`import` statements in the generated file will have the `.js` extension in the end of the path to conform to the ES Modules spec. <br/> Example: `import { MyStruct } from "./my_struct.js"` |
//! | serde-json-impl | Implement `TS` for types from *serde_json* |
//! | chrono-impl | Implement `TS` for types from *chrono* |
//! | bigdecimal-impl | Implement `TS` for types from *bigdecimal* |
//! | url-impl | Implement `TS` for types from *url* |
//! | uuid-impl | Implement `TS` for types from *uuid* |
//! | bson-uuid-impl | Implement `TS` for types from *bson* |
//! | bytes-impl | Implement `TS` for types from *bytes* |
//! | indexmap-impl | Implement `TS` for types from *indexmap* |
//! | ordered-float-impl | Implement `TS` for types from *ordered_float* |
//! | heapless-impl | Implement `TS` for types from *heapless* |
//! | semver-impl | Implement `TS` for types from *semver* |
//!
//! <br/>
//!
//! If there's a type you're dealing with which doesn't implement `TS`, use either
//! `#[ts(as = "..")]` or `#[ts(type = "..")]`, or open a PR.
//!
//! ## serde compatability
//! With the `serde-compat` feature (enabled by default), serde attributes can be parsed for enums and structs.
//! Supported serde attributes:
//! - `rename`
//! - `rename-all`
//! - `rename-all-fields`
//! - `tag`
//! - `content`
//! - `untagged`
//! - `skip`
//! - `flatten`
//! - `default`
//!
//! Note: `skip_serializing` and `skip_deserializing` are ignored. If you wish to exclude a field
//! from the generated type, but cannot use `#[serde(skip)]`, use `#[ts(skip)]` instead.
//!
//! When ts-rs encounters an unsupported serde attribute, a warning is emitted, unless the feature `no-serde-warnings` is enabled.
//!
//! ## contributing
//! Contributions are always welcome!
//! Feel free to open an issue, discuss using GitHub discussions or open a PR.
//! [See CONTRIBUTING.md](https://github.com/Aleph-Alpha/ts-rs/blob/main/CONTRIBUTING.md)
//!
//! ## todo
//! - [x] serde compatibility layer
//! - [x] documentation
//! - [x] use typescript types across files
//! - [x] more enum representations
//! - [x] generics
//! - [x] don't require `'static`
use std::{
any::TypeId,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
},
ops::{Range, RangeInclusive},
path::{Path, PathBuf},
};
pub use ts_rs_macros::TS;
pub use crate::export::ExportError;
use crate::typelist::TypeList;
#[cfg(feature = "chrono-impl")]
mod chrono;
mod export;
#[cfg(feature = "serde-json-impl")]
mod serde_json;
pub mod typelist;
/// A type which can be represented in TypeScript.
/// Most of the time, you'd want to derive this trait instead of implementing it manually.
/// ts-rs comes with implementations for all primitives, most collections, tuples,
/// arrays and containers.
///
/// ### exporting
/// Because Rusts procedural macros are evaluated before other compilation steps, TypeScript
/// bindings __cannot__ be exported during compile time.
///
/// Bindings can be exported within a test, which ts-rs generates for you by adding `#[ts(export)]`
/// to a type you wish to export to a file.
/// When `cargo test` is run, all types annotated with `#[ts(export)]` and all of their
/// dependencies will be written to `TS_RS_EXPORT_DIR`, or `./bindings` by default.
///
/// For each individual type, path and filename within the output directory can be changed using
/// `#[ts(export_to = "...")]`. By default, the filename will be derived from the name of the type.
///
/// If, for some reason, you need to do this during runtime or cannot use `#[ts(export)]`, bindings
/// can be exported manually:
///
/// | Function | Includes Dependencies | To |
/// |-----------------------|-----------------------|--------------------|
/// | [`TS::export`] | ❌ | `TS_RS_EXPORT_DIR` |
/// | [`TS::export_all`] | ✔️ | `TS_RS_EXPORT_DIR` |
/// | [`TS::export_all_to`] | ✔️ | _custom_ |
///
/// ### serde compatibility
/// By default, the feature `serde-compat` is enabled.
/// ts-rs then parses serde attributes and adjusts the generated typescript bindings accordingly.
/// Not all serde attributes are supported yet - if you use an unsupported attribute, you'll see a
/// warning.
///
/// ### container attributes
/// attributes applicable for both structs and enums
///
/// - **`#[ts(crate = "..")]`**
/// Generates code which references the module passed to it instead of defaulting to `::ts_rs`
/// This is useful for cases where you have to re-export the crate.
///
/// - **`#[ts(export)]`**
/// Generates a test which will export the type, by default to `bindings/<name>.ts` when running
/// `cargo test`. The default base directory can be overridden with the `TS_RS_EXPORT_DIR` environment variable.
/// Adding the variable to a project's [config.toml](https://doc.rust-lang.org/cargo/reference/config.html#env) can
/// make it easier to manage.
/// ```toml
/// # <project-root>/.cargo/config.toml
/// [env]
/// TS_RS_EXPORT_DIR = { value = "<OVERRIDE_DIR>", relative = true }
/// ```
/// <br/>
///
/// - **`#[ts(export_to = "..")]`**
/// Specifies where the type should be exported to. Defaults to `<name>.ts`.
/// The path given to the `export_to` attribute is relative to the `TS_RS_EXPORT_DIR` environment variable,
/// or, if `TS_RS_EXPORT_DIR` is not set, to `./bindings`
/// If the provided path ends in a trailing `/`, it is interpreted as a directory.
/// Note that you need to add the `export` attribute as well, in order to generate a test which exports the type.
/// <br/><br/>
///
/// - **`#[ts(rename = "..")]`**
/// Sets the typescript name of the generated type
/// <br/><br/>
///
/// - **`#[ts(rename_all = "..")]`**
/// Rename all fields/variants of the type.
/// Valid values are `lowercase`, `UPPERCASE`, `camelCase`, `snake_case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, "kebab-case"
/// <br/><br/>
///
/// - **`#[ts(concrete(..)]`**
/// Disables one ore more generic type parameters by specifying a concrete type for them.
/// The resulting TypeScript definition will not be generic over these parameters and will use the
/// provided type instead.
/// This is especially useful for generic types containing associated types. Since TypeScript does
/// not have an equivalent construct to associated types, we cannot generate a generic definition
/// for them. Using `#[ts(concrete(..)]`, we can however generate a non-generic definition.
/// Example:
/// ```
/// # use ts_rs::TS;
/// ##[derive(TS)]
/// ##[ts(concrete(I = std::vec::IntoIter<String>))]
/// struct SearchResult<I: Iterator>(Vec<I::Item>);
/// // will always generate `type SearchResult = Array<String>`.
/// ```
/// <br/><br/>
///
/// - **`#[ts(bound)]`**
/// Override the bounds generated on the `TS` implementation for this type. This is useful in
/// combination with `#[ts(concrete)]`, when the type's generic parameters aren't directly used
/// in a field or variant.
///
/// Example:
/// ```
/// # use ts_rs::TS;
///
/// trait Container {
/// type Value: TS;
/// }
///
/// struct MyContainer;
///
/// ##[derive(TS)]
/// struct MyValue;
///
/// impl Container for MyContainer {
/// type Value = MyValue;
/// }
///
/// ##[derive(TS)]
/// ##[ts(export, concrete(C = MyContainer))]
/// struct Inner<C: Container> {
/// value: C::Value,
/// }
///
/// ##[derive(TS)]
/// // Without `#[ts(bound)]`, `#[derive(TS)]` would generate an unnecessary
/// // `C: TS` bound
/// ##[ts(export, concrete(C = MyContainer), bound = "C::Value: TS")]
/// struct Outer<C: Container> {
/// inner: Inner<C>,
/// }
/// ```
/// <br/><br/>
///
/// ### struct attributes
/// - **`#[ts(tag = "..")]`**
/// Include the structs name (or value of `#[ts(rename = "..")]`) as a field with the given key.
/// <br/><br/>
///
/// ### struct field attributes
///
/// - **`#[ts(type = "..")]`**
/// Overrides the type used in TypeScript.
/// This is useful when there's a type for which you cannot derive `TS`.
/// <br/><br/>
///
/// - **`#[ts(as = "..")]`**
/// Overrides the type of the annotated field, using the provided Rust type instead.
/// This is useful when there's a type for which you cannot derive `TS`.
/// <br/><br/>
///
/// - **`#[ts(rename = "..")]`**
/// Renames this field. To rename all fields of a struct, see the container attribute `#[ts(rename_all = "..")]`.
/// <br/><br/>
///
/// - **`#[ts(inline)]`**
/// Inlines the type of this field, replacing its name with its definition.
/// <br/><br/>
///
/// - **`#[ts(skip)]`**
/// Skips this field, omitting it from the generated *TypeScript* type.
/// <br/><br/>
///
/// - **`#[ts(optional)]`**
/// May be applied on a struct field of type `Option<T>`. By default, such a field would turn into `t: T | null`.
/// If `#[ts(optional)]` is present, `t?: T` is generated instead.
/// If `#[ts(optional = nullable)]` is present, `t?: T | null` is generated.
/// <br/><br/>
///
/// - **`#[ts(flatten)]`**
/// Flatten this field, inlining all the keys of the field's type into its parent.
/// <br/><br/>
///
/// ### enum attributes
///
/// - **`#[ts(tag = "..")]`**
/// Changes the representation of the enum to store its tag in a separate field.
/// See [the serde docs](https://serde.rs/enum-representations.html) for more information.
/// <br/><br/>
///
/// - **`#[ts(content = "..")]`**
/// Changes the representation of the enum to store its content in a separate field.
/// See [the serde docs](https://serde.rs/enum-representations.html) for more information.
/// <br/><br/>
///
/// - **`#[ts(untagged)]`**
/// Changes the representation of the enum to not include its tag.
/// See [the serde docs](https://serde.rs/enum-representations.html) for more information.
/// <br/><br/>
///
/// - **`#[ts(rename_all = "..")]`**
/// Rename all variants of this enum.
/// Valid values are `lowercase`, `UPPERCASE`, `camelCase`, `snake_case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, "kebab-case"
/// <br/><br/>
///
/// - **`#[ts(rename_all_fieds = "..")]`**
/// Renames the fields of all the struct variants of this enum. This is equivalent to using
/// `#[ts(rename_all = "..")]` on all of the enum's variants.
/// Valid values are `lowercase`, `UPPERCASE`, `camelCase`, `snake_case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, "kebab-case"
/// <br/><br/>
///
/// ### enum variant attributes
///
/// - **`#[ts(rename = "..")]`**
/// Renames this variant. To rename all variants of an enum, see the container attribute `#[ts(rename_all = "..")]`.
/// <br/><br/>
///
/// - **`#[ts(skip)]`**
/// Skip this variant, omitting it from the generated *TypeScript* type.
/// <br/><br/>
///
/// - **`#[ts(untagged)]`**
/// Changes this variant to be treated as if the enum was untagged, regardless of the enum's tag
/// and content attributes
/// <br/><br/>
///
/// - **`#[ts(rename_all = "..")]`**
/// Renames all the fields of a struct variant.
/// Valid values are `lowercase`, `UPPERCASE`, `camelCase`, `snake_case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, "kebab-case"
/// <br/><br/>
pub trait TS {
/// If this type does not have generic parameters, then `WithoutGenerics` should just be `Self`.
/// If the type does have generic parameters, then all generic parameters must be replaced with
/// a dummy type, e.g `ts_rs::Dummy` or `()`.
/// The only requirement for these dummy types is that `EXPORT_TO` must be `None`.
///
/// # Example:
/// ```
/// use ts_rs::TS;
/// struct GenericType<A, B>(A, B);
/// impl<A, B> TS for GenericType<A, B> {
/// type WithoutGenerics = GenericType<ts_rs::Dummy, ts_rs::Dummy>;
/// // ...
/// # fn decl() -> String { todo!() }
/// # fn decl_concrete() -> String { todo!() }
/// # fn name() -> String { todo!() }
/// # fn inline() -> String { todo!() }
/// # fn inline_flattened() -> String { todo!() }
/// }
/// ```
type WithoutGenerics: TS + ?Sized;
/// JSDoc comment to describe this type in TypeScript - when `TS` is derived, docs are
/// automatically read from your doc comments or `#[doc = ".."]` attributes
const DOCS: Option<&'static str> = None;
/// Identifier of this type, excluding generic parameters.
fn ident() -> String {
// by default, fall back to `TS::name()`.
let name = Self::name();
match name.find('<') {
Some(i) => name[..i].to_owned(),
None => name,
}
}
/// Declaration of this type, e.g. `type User = { user_id: number, ... }`.
/// This function will panic if the type has no declaration.
///
/// If this type is generic, then all provided generic parameters will be swapped for
/// placeholders, resulting in a generic typescript definition.
/// Both `SomeType::<i32>::decl()` and `SomeType::<String>::decl()` will therefore result in
/// the same TypeScript declaration `type SomeType<A> = ...`.
fn decl() -> String;
/// Declaration of this type using the supplied generic arguments.
/// The resulting TypeScript definition will not be generic. For that, see `TS::decl()`.
/// If this type is not generic, then this function is equivalent to `TS::decl()`.
fn decl_concrete() -> String;
/// Name of this type in TypeScript, including generic parameters
fn name() -> String;
/// Formats this types definition in TypeScript, e.g `{ user_id: number }`.
/// This function will panic if the type cannot be inlined.
fn inline() -> String;
/// Flatten an type declaration.
/// This function will panic if the type cannot be flattened.
fn inline_flattened() -> String;
/// Returns a [`TypeList`] of all types on which this type depends.
fn dependency_types() -> impl TypeList
where
Self: 'static,
{
}
/// Returns a [`TypeList`] containing all generic parameters of this type.
/// If this type is not generic, this will return an empty [`TypeList`].
fn generics() -> impl TypeList
where
Self: 'static,
{
}
/// Resolves all dependencies of this type recursively.
fn dependencies() -> Vec<Dependency>
where
Self: 'static,
{
use crate::typelist::TypeVisitor;
let mut deps: Vec<Dependency> = vec![];
struct Visit<'a>(&'a mut Vec<Dependency>);
impl<'a> TypeVisitor for Visit<'a> {
fn visit<T: TS + 'static + ?Sized>(&mut self) {
if let Some(dep) = Dependency::from_ty::<T>() {
self.0.push(dep);
}
}
}
Self::dependency_types().for_each(&mut Visit(&mut deps));
deps
}
/// Manually export this type to the filesystem.
/// To export this type together with all of its dependencies, use [`TS::export_all`].
///
/// # Automatic Exporting
/// Types annotated with `#[ts(export)]`, together with all of their dependencies, will be
/// exported automatically whenever `cargo test` is run.
/// In that case, there is no need to manually call this function.
///
/// # Target Directory
/// The target directory to which the type will be exported may be changed by setting the
/// `TS_RS_EXPORT_DIR` environment variable. By default, `./bindings` will be used.
///
/// To specify a target directory manually, use [`TS::export_all_to`], which also exports all
/// dependencies.
///
/// To alter the filename or path of the type within the target directory,
/// use `#[ts(export_to = "...")]`.
fn export() -> Result<(), ExportError>
where
Self: 'static,
{
let path = Self::default_output_path()
.ok_or_else(std::any::type_name::<Self>)
.map_err(ExportError::CannotBeExported)?;
export::export_to::<Self, _>(path)
}
/// Manually export this type to the filesystem, together with all of its dependencies.
/// To export only this type, without its dependencies, use [`TS::export`].
///
/// # Automatic Exporting
/// Types annotated with `#[ts(export)]`, together with all of their dependencies, will be
/// exported automatically whenever `cargo test` is run.
/// In that case, there is no need to manually call this function.
///
/// # Target Directory
/// The target directory to which the types will be exported may be changed by setting the
/// `TS_RS_EXPORT_DIR` environment variable. By default, `./bindings` will be used.
///
/// To specify a target directory manually, use [`TS::export_all_to`].
///
/// To alter the filenames or paths of the types within the target directory,
/// use `#[ts(export_to = "...")]`.
fn export_all() -> Result<(), ExportError>
where
Self: 'static,
{
export::export_all_into::<Self>(&*export::default_out_dir())
}
/// Manually export this type into the given directory, together with all of its dependencies.
/// To export only this type, without its dependencies, use [`TS::export`].
///
/// Unlike [`TS::export_all`], this function disregards `TS_RS_EXPORT_DIR`, using the provided
/// directory instead.
///
/// To alter the filenames or paths of the types within the target directory,
/// use `#[ts(export_to = "...")]`.
///
/// # Automatic Exporting
/// Types annotated with `#[ts(export)]`, together with all of their dependencies, will be
/// exported automatically whenever `cargo test` is run.
/// In that case, there is no need to manually call this function.
fn export_all_to(out_dir: impl AsRef<Path>) -> Result<(), ExportError>
where
Self: 'static,
{
export::export_all_into::<Self>(out_dir)
}
/// Manually generate bindings for this type, returning a [`String`].
/// This function does not format the output, even if the `format` feature is enabled. TODO
///
/// # Automatic Exporting
/// Types annotated with `#[ts(export)]`, together with all of their dependencies, will be
/// exported automatically whenever `cargo test` is run.
/// In that case, there is no need to manually call this function.
fn export_to_string() -> Result<String, ExportError>
where
Self: 'static,
{
export::export_to_string::<Self>()
}
/// Returns the output path to where `T` should be exported.
/// The returned path does _not_ include the base directory from `TS_RS_EXPORT_DIR`.
///
/// To get the output path containing `TS_RS_EXPORT_DIR`, use [`TS::default_output_path`].
///
/// When deriving `TS`, the output path can be altered using `#[ts(export_to = "...")]`.
/// See the documentation of [`TS`] for more details.
///
/// The output of this function depends on the environment variable `TS_RS_EXPORT_DIR`, which is
/// used as base directory. If it is not set, `./bindings` is used as default directory.
///
/// If `T` cannot be exported (e.g because it's a primitive type), this function will return
/// `None`.
fn output_path() -> Option<&'static Path> {
None
}
/// Returns the output path to where `T` should be exported.
///
/// The output of this function depends on the environment variable `TS_RS_EXPORT_DIR`, which is
/// used as base directory. If it is not set, `./bindings` is used as default directory.
///
/// To get the output path relative to `TS_RS_EXPORT_DIR` and without reading the environment
/// variable, use [`TS::output_path`].
///
/// When deriving `TS`, the output path can be altered using `#[ts(export_to = "...")]`.
/// See the documentation of [`TS`] for more details.
///
/// If `T` cannot be exported (e.g because it's a primitive type), this function will return
/// `None`.
fn default_output_path() -> Option<PathBuf> {
Some(export::default_out_dir().join(Self::output_path()?))
}
}
/// A typescript type which is depended upon by other types.
/// This information is required for generating the correct import statements.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct Dependency {
/// Type ID of the rust type
pub type_id: TypeId,
/// Name of the type in TypeScript
pub ts_name: String,
/// Path to where the type would be exported. By default a filename is derived from the types
/// name, which can be customized with `#[ts(export_to = "..")]`.
/// This path does _not_ include a base directory.
pub output_path: &'static Path,
}
impl Dependency {
/// Constructs a [`Dependency`] from the given type `T`.
/// If `T` is not exportable (meaning `T::EXPORT_TO` is `None`), this function will return
/// `None`
pub fn from_ty<T: TS + 'static + ?Sized>() -> Option<Self> {
let output_path = T::output_path()?;
Some(Dependency {
type_id: TypeId::of::<T>(),
ts_name: T::ident(),
output_path,
})
}
}
// generate impls for primitive types
macro_rules! impl_primitives {
($($($ty:ty),* => $l:literal),*) => { $($(
impl TS for $ty {
type WithoutGenerics = Self;
fn name() -> String { $l.to_owned() }
fn inline() -> String { <Self as $crate::TS>::name() }
fn inline_flattened() -> String { panic!("{} cannot be flattened", <Self as $crate::TS>::name()) }
fn decl() -> String { panic!("{} cannot be declared", <Self as $crate::TS>::name()) }
fn decl_concrete() -> String { panic!("{} cannot be declared", <Self as $crate::TS>::name()) }
}
)*)* };
}
// generate impls for tuples
macro_rules! impl_tuples {
( impl $($i:ident),* ) => {
impl<$($i: TS),*> TS for ($($i,)*) {
type WithoutGenerics = (Dummy, );
fn name() -> String {
format!("[{}]", [$($i::name()),*].join(", "))
}
fn inline() -> String {
panic!("tuple cannot be inlined!");
}
fn dependency_types() -> impl TypeList
where
Self: 'static
{
()$(.push::<$i>())*
}
fn inline_flattened() -> String { panic!("tuple cannot be flattened") }
fn decl() -> String { panic!("tuple cannot be declared") }
fn decl_concrete() -> String { panic!("tuple cannot be declared") }
}
};
( $i2:ident $(, $i:ident)* ) => {
impl_tuples!(impl $i2 $(, $i)* );
impl_tuples!($($i),*);
};
() => {};
}
// generate impls for wrapper types
macro_rules! impl_wrapper {
($($t:tt)*) => {
$($t)* {
type WithoutGenerics = Self;
fn name() -> String { T::name() }
fn inline() -> String { T::inline() }
fn inline_flattened() -> String { T::inline_flattened() }
fn dependency_types() -> impl $crate::typelist::TypeList
where
Self: 'static
{
T::dependency_types()
}
fn generics() -> impl $crate::typelist::TypeList
where
Self: 'static
{
((std::marker::PhantomData::<T>,), T::generics())
}
fn decl() -> String { panic!("wrapper type cannot be declared") }
fn decl_concrete() -> String { panic!("wrapper type cannot be declared") }
}
};
}
// implement TS for the $shadow, deferring to the impl $s
macro_rules! impl_shadow {
(as $s:ty: $($impl:tt)*) => {
$($impl)* {
type WithoutGenerics = <$s as TS>::WithoutGenerics;
fn ident() -> String { <$s>::ident() }
fn name() -> String { <$s>::name() }
fn inline() -> String { <$s>::inline() }
fn inline_flattened() -> String { <$s>::inline_flattened() }
fn dependency_types() -> impl $crate::typelist::TypeList
where
Self: 'static
{
<$s>::dependency_types()
}
fn generics() -> impl $crate::typelist::TypeList
where
Self: 'static
{
<$s>::generics()
}
fn decl() -> String { <$s>::decl() }
fn decl_concrete() -> String { <$s>::decl_concrete() }
fn output_path() -> Option<&'static std::path::Path> { <$s>::output_path() }
}
};
}
impl<T: TS> TS for Option<T> {
type WithoutGenerics = Self;
fn name() -> String {
format!("{} | null", T::name())
}
fn inline() -> String {
format!("{} | null", T::inline())
}
fn dependency_types() -> impl TypeList
where
Self: 'static,
{
T::dependency_types()
}
fn generics() -> impl TypeList
where
Self: 'static,
{
T::generics().push::<T>()
}
fn decl() -> String {
panic!("{} cannot be declared", Self::name())
}
fn decl_concrete() -> String {
panic!("{} cannot be declared", Self::name())
}
fn inline_flattened() -> String {
panic!("{} cannot be flattened", Self::name())
}
}
impl<T: TS, E: TS> TS for Result<T, E> {
type WithoutGenerics = Result<Dummy, Dummy>;
fn name() -> String {
format!("{{ Ok : {} }} | {{ Err : {} }}", T::name(), E::name())
}
fn inline() -> String {
format!("{{ Ok : {} }} | {{ Err : {} }}", T::inline(), E::inline())
}
fn dependency_types() -> impl TypeList
where
Self: 'static,
{
T::dependency_types().extend(E::dependency_types())
}
fn generics() -> impl TypeList
where
Self: 'static,
{
T::generics().push::<T>().extend(E::generics()).push::<E>()
}
fn decl() -> String {
panic!("{} cannot be declared", Self::name())
}
fn decl_concrete() -> String {
panic!("{} cannot be declared", Self::name())
}
fn inline_flattened() -> String {
panic!("{} cannot be flattened", Self::name())
}
}
impl<T: TS> TS for Vec<T> {
type WithoutGenerics = Vec<Dummy>;
fn ident() -> String {
"Array".to_owned()
}
fn name() -> String {
format!("Array<{}>", T::name())
}
fn inline() -> String {
format!("Array<{}>", T::inline())
}
fn dependency_types() -> impl TypeList
where
Self: 'static,
{
T::dependency_types()
}
fn generics() -> impl TypeList
where
Self: 'static,
{
T::generics().push::<T>()
}
fn decl() -> String {
panic!("{} cannot be declared", Self::name())
}
fn decl_concrete() -> String {
panic!("{} cannot be declared", Self::name())
}
fn inline_flattened() -> String {
panic!("{} cannot be flattened", Self::name())
}
}
// Arrays longer than this limit will be emitted as Array<T>
const ARRAY_TUPLE_LIMIT: usize = 64;
impl<T: TS, const N: usize> TS for [T; N] {
type WithoutGenerics = [Dummy; N];
fn name() -> String {
if N > ARRAY_TUPLE_LIMIT {
return Vec::<T>::name();
}
format!(
"[{}]",
(0..N).map(|_| T::name()).collect::<Box<[_]>>().join(", ")
)
}
fn inline() -> String {
if N > ARRAY_TUPLE_LIMIT {
return Vec::<T>::inline();
}
format!(
"[{}]",
(0..N).map(|_| T::inline()).collect::<Box<[_]>>().join(", ")
)
}
fn dependency_types() -> impl TypeList
where
Self: 'static,
{
T::dependency_types()
}
fn generics() -> impl TypeList
where
Self: 'static,
{
T::generics().push::<T>()
}
fn decl() -> String {
panic!("{} cannot be declared", Self::name())
}
fn decl_concrete() -> String {
panic!("{} cannot be declared", Self::name())
}
fn inline_flattened() -> String {
panic!("{} cannot be flattened", Self::name())
}
}
impl<K: TS, V: TS, H> TS for HashMap<K, V, H> {
type WithoutGenerics = HashMap<Dummy, Dummy>;
fn ident() -> String {
panic!()
}
fn name() -> String {
format!("{{ [key: {}]: {} }}", K::name(), V::name())
}
fn inline() -> String {
format!("{{ [key: {}]: {} }}", K::inline(), V::inline())
}
fn dependency_types() -> impl TypeList
where
Self: 'static,
{
K::dependency_types().extend(V::dependency_types())
}
fn generics() -> impl TypeList
where
Self: 'static,
{
K::generics().push::<K>().extend(V::generics()).push::<V>()
}
fn decl() -> String {
panic!("{} cannot be declared", Self::name())
}
fn decl_concrete() -> String {
panic!("{} cannot be declared", Self::name())
}
fn inline_flattened() -> String {
panic!("{} cannot be flattened", Self::name())
}
}
impl<I: TS> TS for Range<I> {
type WithoutGenerics = Range<Dummy>;
fn name() -> String {
format!("{{ start: {}, end: {}, }}", I::name(), I::name())
}
fn dependency_types() -> impl TypeList
where
Self: 'static,
{
I::dependency_types()
}
fn generics() -> impl TypeList
where
Self: 'static,
{
I::generics().push::<I>()
}
fn decl() -> String {
panic!("{} cannot be declared", Self::name())
}
fn decl_concrete() -> String {
panic!("{} cannot be declared", Self::name())
}
fn inline() -> String {
panic!("{} cannot be inlined", Self::name())
}
fn inline_flattened() -> String {
panic!("{} cannot be flattened", Self::name())
}
}
impl_shadow!(as Range<I>: impl<I: TS> TS for RangeInclusive<I>);
impl_shadow!(as Vec<T>: impl<T: TS, H> TS for HashSet<T, H>);
impl_shadow!(as Vec<T>: impl<T: TS> TS for BTreeSet<T>);
impl_shadow!(as HashMap<K, V>: impl<K: TS, V: TS> TS for BTreeMap<K, V>);
impl_shadow!(as Vec<T>: impl<T: TS> TS for [T]);
impl_wrapper!(impl<T: TS + ?Sized> TS for &T);
impl_wrapper!(impl<T: TS + ?Sized> TS for Box<T>);
impl_wrapper!(impl<T: TS + ?Sized> TS for std::sync::Arc<T>);
impl_wrapper!(impl<T: TS + ?Sized> TS for std::rc::Rc<T>);
impl_wrapper!(impl<'a, T: TS + ToOwned + ?Sized> TS for std::borrow::Cow<'a, T>);
impl_wrapper!(impl<T: TS> TS for std::cell::Cell<T>);
impl_wrapper!(impl<T: TS> TS for std::cell::RefCell<T>);
impl_wrapper!(impl<T: TS> TS for std::sync::Mutex<T>);
impl_wrapper!(impl<T: TS + ?Sized> TS for std::sync::Weak<T>);
impl_wrapper!(impl<T: TS> TS for std::marker::PhantomData<T>);
impl_tuples!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
#[cfg(feature = "bigdecimal-impl")]
impl_primitives! { bigdecimal::BigDecimal => "string" }
#[cfg(feature = "uuid-impl")]
impl_primitives! { uuid::Uuid => "string" }
#[cfg(feature = "url-impl")]
impl_primitives! { url::Url => "string" }
#[cfg(feature = "ordered-float-impl")]
impl_primitives! { ordered_float::OrderedFloat<f32> => "number" }
#[cfg(feature = "ordered-float-impl")]
impl_primitives! { ordered_float::OrderedFloat<f64> => "number" }
#[cfg(feature = "bson-uuid-impl")]
impl_primitives! { bson::Uuid => "string" }
#[cfg(feature = "indexmap-impl")]
impl_shadow!(as Vec<T>: impl<T: TS> TS for indexmap::IndexSet<T>);
#[cfg(feature = "indexmap-impl")]
impl_shadow!(as HashMap<K, V>: impl<K: TS, V: TS> TS for indexmap::IndexMap<K, V>);
#[cfg(feature = "heapless-impl")]
impl_shadow!(as Vec<T>: impl<T: TS, const N: usize> TS for heapless::Vec<T, N>);
#[cfg(feature = "semver-impl")]
impl_primitives! { semver::Version => "string" }
#[cfg(feature = "bytes-impl")]
mod bytes {
use super::TS;
impl_shadow!(as Vec<u8>: impl TS for bytes::Bytes);
impl_shadow!(as Vec<u8>: impl TS for bytes::BytesMut);
}
impl_primitives! {
u8, i8, NonZeroU8, NonZeroI8,
u16, i16, NonZeroU16, NonZeroI16,
u32, i32, NonZeroU32, NonZeroI32,
usize, isize, NonZeroUsize, NonZeroIsize, f32, f64 => "number",
u64, i64, NonZeroU64, NonZeroI64,
u128, i128, NonZeroU128, NonZeroI128 => "bigint",
bool => "boolean",
char, Path, PathBuf, String, str,
Ipv4Addr, Ipv6Addr, IpAddr, SocketAddrV4, SocketAddrV6, SocketAddr => "string",
() => "null"
}
#[rustfmt::skip]
pub(crate) use impl_primitives;
#[rustfmt::skip]
pub(crate) use impl_shadow;
#[doc(hidden)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Dummy;
impl std::fmt::Display for Dummy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl TS for Dummy {
type WithoutGenerics = Self;
fn name() -> String {
"Dummy".to_owned()
}
fn decl() -> String {
panic!("{} cannot be declared", Self::name())
}
fn decl_concrete() -> String {
panic!("{} cannot be declared", Self::name())
}
fn inline() -> String {
panic!("{} cannot be inlined", Self::name())
}
fn inline_flattened() -> String {
panic!("{} cannot be flattened", Self::name())
}
}