Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Schematic

Schematic is a library that provides:

  • A layered serde-driven configuration system with support for merge strategies, validation rules, environment variables, and more!
  • A schema modeling system that can be used to generate TypeScript types, JSON schemas, and more!

Both of these features can be used independently or together.

cargo add schematic

Example references

The following projects are using Schematic and can be used as a reference:

  • moon - A build system for web based monorepos.
  • proto - A multi-language version manager with WASM plugin support.
  • ryot - Track various aspects of your life.

Configuration

Requires the config Cargo feature, which is enabled by default.

The primary feature of Schematic is a layered serde-driven configuration solution, and is powered through the Config and ConfigEnum traits, and their associated derive macro. These macros help to generate and automate the following (when applicable):

The struct or enum that derives Config represents the final state, after all partial layers have been merged, and default and environment variable values have been applied. This means that all fields (settings) should not be wrapped in Option, unless the setting is truly optional (think nullable in the config file).

#![allow(unused)]
fn main() {
#[derive(Config)]
struct ExampleConfig {
	pub number: usize,
	pub string: String,
	pub boolean: bool,
	pub array: Vec<String>,
	pub optional: Option<String>,
}
}

This pattern provides the optimal developer experience, as you can reference the settings as-is, without having to unwrap them, or use match or if-let statements!

Usage

Define a struct or enum and derive the Config trait. Fields within the struct (known as settings) can be annotated with the #[setting] attribute to provide additional functionality.

#![allow(unused)]
fn main() {
use schematic::Config;

#[derive(Config)]
struct AppConfig {
	#[setting(default = 3000, env = "PORT")]
	pub port: usize,

	#[setting(default = true)]
	pub secure: bool,

	#[setting(default = vec!["localhost".into()])]
	pub allowed_hosts: Vec<String>,
}
}

Loading sources

When all of your structs and enums have been defined, you can then load, parse, merge, and validate a configuration from one or many sources. A source is either a file path, secure URL, inline code string, or a partial in memory.

Begin by importing the ConfigLoader struct and initializing it with the Config type you want to load.

#![allow(unused)]
fn main() {
use schematic::ConfigLoader;

let loader = ConfigLoader::<AppConfig>::new();
}

From here, you can feed it sources to load. For file paths, use the ConfigLoader::file() or ConfigLoader::file_optional() methods. For URLs, use the ConfigLoader::url() method (requires the url Cargo feature, which is not enabled by default). For inline code, use the ConfigLoader::code() method, which requires an explicit format, and names the source within errors.

#![allow(unused)]
fn main() {
loader.code("secure: false", "example.yml")?;
loader.file("path/to/config.yml")?;
loader.url("https://ordomain.com/to/config.yaml")?;
}

The formats to use are derived from the trailing file extension.

An optional file that doesn’t exist provides nothing, so it’s left out of ConfigLoadResult.layers.

A partial that’s already in memory, like one parsed from command line arguments, is added with the ConfigLoader::partial() method, along with a name to use within error messages. Nothing is parsed, but it’s otherwise loaded like any other source: merged in the order it was added, validated, and able to extend other sources. A relative file it extends is resolved against the working directory.

#![allow(unused)]
fn main() {
loader.partial("CLI arguments", PartialAppConfig {
	port: Some(8080),
	..Default::default()
});
}

Like every source, a partial sits below environment variables, which are applied last. For command line arguments to take precedence over the environment, read the variables through your argument parser instead, such as with clap’s env argument, rather than with #[setting(env)].

And lastly call the ConfigLoader::load() method to generate the final configuration. This methods returns a result, which includes the final configuration, as well as all of the partial layers that were merged into it.

#![allow(unused)]
fn main() {
let result = loader.load()?;

result.config; // AppConfig
result.layers; // Vec<Layer<PartialAppConfig>>
}

The layers are in order of precedence, and each one holds only the values it set, so a value can be traced to where it came from. The default values come first, as Source::Defaults, then each source in order, and the environment variables last, as Source::EnvVars. The default values and environment variables are left out when they set nothing.

Both are read against what the sources set, so they hold what applies to it: the defaults and variables of the variant an enum’s sources picked, and those of an optional nested config only when it’s present. The environment variables are read first, as a tag’s variable can pick a variant, and the defaults then go under the result.

Automatic schemas

When the schema Cargo feature is enabled, the Schematic trait will be automatically implemented for all types that implement Config and ConfigEnum. You do not and should not derive both of these together.

#![allow(unused)]
fn main() {
// Correct
#[derive(Config)]
struct AppConfig {}

// Incorrect
#[derive(Config, Schematic)]
struct AppConfig {}
}

Supported source formats

Schematic is powered entirely by serde, and supports the following formats:

  • JSON - Uses serde_json and requires the json Cargo feature.
  • Pkl - Uses rpkl and requires the pkl Cargo feature.
  • RON - Uses ron and requires the ron Cargo feature.
  • TOML - Uses toml and requires the toml Cargo feature.
  • YAML - Uses serde_norway and requires the yaml Cargo feature. An externally tagged enum variant that holds a value is written as a YAML tag, like !file, rather than a map (more).

None of them is enabled by default, so enable the feature of each format you load. A source with no format to parse it fails to load, with an error that names the feature its extension needs.

Cargo features

The following Cargo features are available:

  • config (default) - Enables configuration support (all the above stuff).
  • env (default) - Enables environment variables for settings.
  • extends (default) - Enables configs to extend other configs.
  • json - Enables JSON.
  • pkl - Enables Pkl.
  • ron - Enables RON.
  • toml - Enables TOML.
  • url - Enables loading, extending, and parsing configs from URLs.
  • validate (default) - Enables setting value validation.
  • yaml - Enables YAML.

env, extends, url, and validate only apply to configs, so each enables config as well. The dependencies that only configs use are only compiled with config, so a build for schemas alone, or without any feature, doesn’t pull them in.

Settings

Settings are the individual fields of a Config struct, the variants of a Config enum, or the fields of a named variant, and can be annotated with the optional #[setting] attribute.

Third-party types

A setting that isn’t wrapped in Option falls back to Default::default() when the config provides no value and no default value is declared, so every such setting has to implement Default, even one marked required. Plenty of third-party types don’t, and being foreign, can’t be given it.

For the two we support directly, we provide a newtype that does:

SettingWrapsDefaultCargo feature
RegexSettingregex::Regex.type_regex
VersionSettingsemver::Version0.0.0type_semver
#![allow(unused)]
fn main() {
use schematic::{Config, RegexSetting, VersionSetting};

#[derive(Config)]
struct AppConfig {
	pub allowed: RegexSetting,
	pub version: VersionSetting,
}
}

Each derefs to the type it wraps, so its methods can be called directly, and each parses from a string, so the wrapper works without the upstream crate’s serde feature.

semver::VersionReq needs no wrapper, as it already defaults to *. Types that are only ever optional don’t need one either, since an Option setting defaults to None.

Required traits

Every setting is held by the partial, which derives Clone, Debug, Default, PartialEq, Deserialize, and Serialize, so a setting’s type has to implement those too, along with Schematic. Debug and PartialEq aren’t needed by the partial itself, but deriving them lets partials be printed and compared, and lets a struct that holds one derive them as well. A type that lacks one, like regex::Regex, which has no PartialEq, fails to compile at #[derive(Config)], so wrap it in a newtype that implements it, as RegexSetting does by comparing patterns.

Attribute fields

The following fields are supported for the #[setting] field/variant attribute:

  • default - Sets the default value. On an enum variant, it names the variant the partial defaults to, and on a variant holding a value, can also provide that value.
  • env (field only) - Sets the environment variable to receive a value from. On a field of a named variant, it’s read once a source has picked the variant. A nested config reads its own, so it takes env_prefix instead.
  • env_prefix (field only) - Adds an environment variable prefix for the nested config this field holds. Requires nested.
  • exclude - Omits the field or variant from the generated schema. Has no effect without the schema Cargo feature.
  • extend (struct only) - Enables a configuration to extend other configs.
  • merge - Defines a function to use for merging values.
  • nested - Marks the field as using a nested Config.
  • null (enum only) - Marks the variant as representing null, so it is never tagged.
  • parse_env (field only) - Parses the environment variable value using a function. Requires either env, or an env_prefix on the container, and can’t be used with nested.
  • partial - Forwards attributes to the field on the partial. May be repeated.
  • required - Marks the setting as required, so that loading fails when no source provides a value, instead of falling back to a default.
  • transform - Defines a function to use for transforming values.
  • validate - Defines a function to use for validating values.

And the following for serde compatibility:

  • alias
  • flatten
  • rename
  • skip - Also left out of the generated schema, as it’s never read or written, so its type needn’t implement Schematic.
  • skip_deserializing - Hidden in the generated schema, as it’s written but never read.
  • skip_serializing
  • skip_serializing_if - Only honored from #[setting], and written against the partial’s Option. The #[serde] form is left for the full type, whose field is not wrapped.
  • rename_all (named variant only) - Applies a casing to the fields of the variant, over the enum’s rename_all_fields.
  • untagged (enum only)

Serde support

A handful of serde attribute fields are currently supported (above) and will apply a #[serde] attribute to the partial implementation.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct Example {
	#[setting(rename = "type")]
	pub type_of: SomeEnum,
}
}

These values can also be applied using #[serde], which is useful if you want to apply them to the main struct as well, and not just the partial struct. When a field is set through both, the #[setting] value wins, except for alias, where the two lists are merged.

Names are used exactly as written. There is no default casing, so a field named allowed_hosts is parsed as allowed_hosts unless a rename or rename_all says otherwise. An explicit rename is never re-cased by rename_all.

Partials

A powerful feature of Schematic is what we call partial configurations. These are a mirror of the derived Config struct or Config enum, with all settings wrapped in Option, the item name prefixed with Partial, and have common serde and derive attributes automatically applied.

For example, the ExampleConfig from the first chapter would generate the following partial struct:

#![allow(unused)]
fn main() {
#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct PartialExampleConfig {
	#[serde(skip_serializing_if = "Option::is_none")]
	pub number: Option<usize>,

	#[serde(skip_serializing_if = "Option::is_none")]
	pub string: Option<String>,

	#[serde(skip_serializing_if = "Option::is_none")]
	pub boolean: Option<bool>,

	#[serde(skip_serializing_if = "Option::is_none")]
	pub array: Option<Vec<String>>,

	#[serde(skip_serializing_if = "Option::is_none")]
	pub optional: Option<String>,
}
}

The derives on a partial are always the same, so every setting’s type has to implement them. See required traits.

So what are partials used for exactly? Partials are used for the entire parsing, layering, extending, and merging process, and ultimately become the final configuration.

When deserializing a source with serde, we utilize the partial config as the target type, because not all fields are guaranteed to be present. This is especially true when merging multiple sources together, as each source may only contain a subset of the final config. Each source represents a layer to be merged.

Partials are also beneficial when serializing, as only settings with values will be written to the source, instead of everything! A common complaint of serde’s strictness.

As stated above, partials also handle the following:

Partial attribute forwarding

Attributes can be forwarded to the generated partial struct using the #[config(partial())] attribute on structs and enums.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(partial(derive(derive_more::AsRef)))]
struct ExampleConfig {
	//
}
}

Fields attributes can be forwarded using #[setting(partial())].

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(partial(derive(derive_more::AsRef)))]
struct ExampleConfig {
	#[setting(partial(as_ref))]
	port: usize
}
}

Each item within partial() is forwarded as its own attribute, and partial() itself may be repeated, so the following are equivalent. Attributes are forwarded in the order they’re declared.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(partial(derive(clap::Parser), command(about = "Example")))]
struct ExampleConfig {
	//
}

#[derive(Config)]
#[config(partial(derive(clap::Parser)))]
#[config(partial(command(about = "Example")))]
struct ExampleConfig {
	//
}
}

Nesting

Config structs can easily be nested within other Configs using the #[setting(nested)] attribute. Children will be deeply merged and validated alongside the parent.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct ChildConfig {
	// ...
}

#[derive(Config)]
struct ParentConfig {
	#[setting(nested)]
	pub nested: ChildConfig,

	#[setting(nested)]
	pub optional_nested: Option<ChildConfig>,
}

#[derive(Config)]
enum ParentEnum {
	#[setting(nested)]
	Variant(ChildConfig),
}
}

The #[setting(nested)] attribute is required, as the macro will substitute Config with its partial implementation.

Nested values can also be wrapped in collections, like Vec and HashMap. Each item is finalized and validated as a nested config, but the collection is replaced when merged, rather than merging its items. To merge a map of configs by key, use the merge_partials strategy.

A #[setting(nested)] on a variant applies to every value it holds. To hold a nested config alongside plain values, mark the value itself instead. Its config is merged, finalized, and validated as nested, while the other values are replaced, like any other setting.

#![allow(unused)]
fn main() {
#[derive(Config)]
enum ParentEnum {
	Both(#[setting(nested)] ChildConfig, bool),
}
}

Flattening

A nested config can be flattened with #[setting(flatten, nested)] (or serde’s own #[serde(flatten)]), so its settings are written alongside the parent’s own, rather than under the field’s name. A map can be flattened too, which collects every key the other settings don’t.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct ParentConfig {
	pub name: String,

	#[setting(flatten, nested)]
	pub server: ServerConfig,

	#[setting(flatten, nested)]
	pub plugins: HashMap<String, PluginConfig>,
}
}

A config rejects keys that aren’t its settings, unless #[config(allow_unknown_fields)], and serde can only do so for a flattened struct, which takes its keys from the parent’s. So:

  • A config with a flattened map accepts unknown keys, as the map collects them, and rejecting them would reject every key of the map.
  • A flattened config that flattens another can’t be loaded unless both allow unknown fields, as it reads the parent’s keys without taking them, so the parent would reject them. Deriving one fails to compile, naming the fix, rather than failing to load every setting it holds.
#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(allow_unknown_fields)]
struct ServerConfig {
	#[setting(flatten, nested)]
	pub tls: TlsConfig,
}
}

Bare structs

For structs that do not implement the Config trait, you can use them as-is without the #[setting(nested)] attribute. When using bare structs, be aware that all of the functionality provided by our Config trait is not available, like merging and validation.

#![allow(unused)]
fn main() {
struct BareConfig {
	// ...
}

#[derive(Config)]
pub struct ParentConfig {
	pub nested: BareConfig,
}
}

Context

Context is an important mechanism that allows for different default values, merge strategies, and validation rules to be used, for the same configuration struct, depending on context!

To begin, a context is a struct with a default implementation.

#![allow(unused)]
fn main() {
#[derive(Default)]
struct ExampleContext {
	pub some_value: bool,
	pub another_value: usize,
}
}

Context must then be associated with a Config derived struct through the context attribute field.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(context = ExampleContext)]
struct ExampleConfig {
	// ...
}
}

And then passed to the ConfigLoader::load_with_context() method.

#![allow(unused)]
fn main() {
let context = ExampleContext {
	some_value: true,
	another_value: 10,
};

let result = ConfigLoader::<ExampleConfig>::new()
	.url(url_to_config)?
	.load_with_context(&context)?;
}

Refer to the default values, merge strategies, and validation rules sections for more information on how to use context.

Nested configs with another context

A nested config receives its parent’s context, so by default it must declare the same one. A config from a library can’t know an application’s context, so the context field of #[setting(nested)] maps the parent’s context to the nested config’s own, with a function from a reference to one to a reference to the other.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(context = AppContext)]
struct AppConfig {
	// A library config, whose context is `()`
	#[setting(nested, context = schematic::context::unit)]
	pub lib: LibConfig,

	// A config whose context is part of the application's
	#[setting(nested, context = plugin_context)]
	pub plugin: PluginConfig,
}

fn plugin_context(context: &AppContext) -> &PluginContext {
	&context.plugin
}
}

The mapped context is what the nested config’s own default values, merge strategies, and validation rules receive. schematic::context::unit passes (), whatever the parent’s context. A Default of the parent, which has no context to map, gives each nested config the Default of its own context instead.

Metadata

Alongside the configuration itself, the derive records a little metadata about each setting, reachable with Config::settings(). It returns a map keyed by the serde name of each setting, or by position for unnamed ones.

#![allow(unused)]
fn main() {
for (name, setting) in ExampleConfig::settings() {
	println!("{name}: {}", setting.type_alias);

	if let Some(key) = &setting.env_key {
		println!("  reads {key}");
	}

	if let Some(nested) = &setting.nested {
		println!("  has {} nested settings", nested.len());
	}
}
}

Each entry carries the setting’s type_alias (the Rust type as written), its env_key, and a nested map when the setting holds another nested config.

A key derived from an env_prefix is reported with the container’s own prefix. A parent’s #[setting(nested, env_prefix)] override is applied at runtime, so it isn’t reflected here.

Generics

Config, ConfigEnum, and Schematic can all be derived for types with type parameters. The parameters are carried into the partial and into every generated implementation.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct Wrapper<T> {
	pub inner: T,
	pub label: String,
}
}

Bounds are not inferred

The derive does not add bounds for you. A partial has to be Clone + Default + DeserializeOwned + Schematic + Serialize, because that is what PartialConfig requires, so every type parameter needs them too. A type that is missing one fails to compile at the generated impl, not at the definition.

Declaring them once as a trait alias keeps the noise down:

#![allow(unused)]
fn main() {
use serde::{Serialize, de::DeserializeOwned};

pub trait Setting:
	Clone + Default + PartialEq + Serialize + DeserializeOwned + schematic::Schematic
{
}

impl<T> Setting for T where
	T: Clone + Default + PartialEq + Serialize + DeserializeOwned + schematic::Schematic
{
}

#[derive(Config)]
struct Wrapper<T: Setting> {
	pub inner: T,
	pub label: String,
}
}

A generic Schematic only needs T: Schematic, since it has no partial.

Serde bounds

The partial is emitted with an explicit #[serde(bound(deserialize = "T: DeserializeOwned"))]. Without it serde would infer a T: Deserialize<'de> bound of its own, which is ambiguous against the DeserializeOwned already in scope. Supplying your own bound through #[config(partial(serde(bound(...))))] suppresses the generated one.

Nesting generic configs

A generic config can be nested like any other, including within an Option or a collection. The type it’s written with is the config, so the derive doesn’t look inside its type arguments.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(nested)]
	pub names: Wrapper<String>,

	#[setting(nested)]
	pub counts: Vec<Wrapper<usize>>,
}
}

A type parameter can also be the nested config. Its partial is derived like any other, which bounds every type parameter, so it needs the same bounds as any other parameter. Its partial is printed and compared with the rest, and shares the parent’s context, which the where clause states:

#![allow(unused)]
fn main() {
#[derive(Config)]
struct Outer<C: Config + Setting>
where
	C::Partial: Debug + PartialEq + PartialConfig<Context = ()>,
{
	#[setting(nested)]
	pub inner: C,
}
}

Schema names

Schemas are keyed by name alone, so every instantiation of a generic type would otherwise claim the same one. The derive appends each type argument to the name, so Wrapper<String> becomes WrapperString and its partial PartialWrapperString. See defining names for the manual equivalent.

Enums

A generic ConfigEnum only makes sense with a fallback variant, since unit variants carry no data. The parameter needs whatever the generated implementations use: Default for variants(), TryFrom<&str> for parsing into the fallback, Display for formatting back out, and Schematic for the schema name.

#![allow(unused)]
fn main() {
#[derive(Clone, Debug, PartialEq, ConfigEnum)]
enum Value<T>
where
	T: Clone + Default + std::fmt::Display + for<'a> TryFrom<&'a str> + schematic::Schematic,
{
	Known,
	Other,
	#[variant(fallback)]
	Custom(T),
}
}

Display is written one arm at a time, so the fallback goes through T: Display rather than having to resolve to a &str.

Structs & enums

The Config trait can be derived for structs and enums.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	pub base: String,
	pub port: usize,
	pub secure: bool,
	pub allowed_hosts: Vec<String>,
}

#[derive(Config)]
enum Host {
	Local,
	#[setting(nested)]
	Remote(HostConfig),
}
}

Enum variants

An enum’s variants may be unit, tuple, or named, and mixed freely. A tuple variant is a single setting, so the values it holds are written in full, while each field of a named variant is a setting of its own, like the fields of a struct.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Source {
	#[setting(default)]
	File {
		#[setting(default = "config.json")]
		path: String,
		#[setting(default = 30, validate = schematic::validate::in_range(1, 60))]
		timeout: u32,
	},
	Url {
		#[setting(required)]
		address: Option<String>,
		#[setting(nested)]
		retry: RetryConfig,
	},
	Inline(String),
}
}

Every field of a named variant is optional within the partial, so a layer can provide some of them and leave the rest to another. When two layers pick the same variant, its fields are merged one by one, each with its own merge, while a layer picking another variant replaces it. Each field takes the same #[setting] fields as a struct’s, except extend. The variant itself takes only default, exclude, partial, and the serde fields, while the fields hold the rest.

A source may pick a variant other than the default, so the defaults and environment variables of a named variant’s fields are read for the variant the sources picked, and apply however it was picked. A field that fails validation is reported under the variant, like source.url.address.

The fields are named as written, unless the variant has a #[serde(rename_all)] of its own, or the enum has a rename_all_fields. The enum’s own rename_all names the variants, as with serde.

If you’d like to support unit-only enums, you can use the ConfigEnum trait instead.

Attribute fields

The following fields are supported for the #[config] container attribute:

  • allow_unknown_fields - Removes the serde deny_unknown_fields from the partial struct, or an enum with named variants. Defaults to false.
  • context - Sets the struct to be used as the context. Defaults to None.
  • env_prefix - Sets the prefix to use for environment variable mapping, of a struct’s fields or a named variant’s, and of a tagged enum’s tag. Defaults to None.
  • partial - Forwards attributes to the partial.
#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(allow_unknown_fields, env_prefix = "EXAMPLE_")]
struct ExampleConfig {
	// ...
}
}

And the following for serde compatibility:

  • rename
  • rename_all - Has no default. Field names are used exactly as written unless this is set.
  • rename_all_fields (enum only) - Applies a casing to the fields of every variant.

Serde support

By default the Config macro will apply the following #[serde] to the partial struct. The default and deny_unknown_fields ensure proper parsing and layer merging.

#![allow(unused)]
fn main() {
#[serde(default, deny_unknown_fields)]
}

However, the deny_unknown_fields field can be customized, and we also support the rename and rename_all fields, all via the top-level #[config] attribute.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(allow_unknown_fields, rename = "ExampleConfig", rename_all = "snake_case")]
struct Example {
	// ...
}
}

These values can also be applied using #[serde], which is useful if you want to apply them to the main struct as well, and not just the partial struct.

The partial of an enum with a named variant denies unknown fields as well. Serde applies it to the enum as a whole, so every named variant denies them, as do the keys around an internally or adjacently tagged variant, unless a named variant flattens a map, which collects them.

Enum tagging

Serde’s tagging attributes are read straight off the #[serde] attribute and forwarded to the partial, so untagged, tag, content, and expecting work as they normally would.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[serde(untagged)]
enum Host {
	Local,
	#[setting(nested)]
	Remote(HostConfig),
}
}

The derive registers serde as a helper attribute, so this is accepted even when the type derives only Config and not Serialize or Deserialize.

When a value matches none of an untagged enum’s variants, the error lists why each one failed, rather than serde’s “data did not match any variant”. Each starts with the path to the setting that failed within the variant, and a nested untagged enum lists its own variants beneath the one that holds it.

failed to parse as any variant of PartialHost:
- Local: expected null
- Remote: port: expected a 16-bit unsigned integer, found "abc"

A unit-only enum is always externally tagged, no matter what you set. Marking one untagged would leave its variants deserializable only from null.

An untagged named variant is attempted like any other, and unless unknown fields are allowed, fails on a field it doesn’t know, so an input with an extra key moves on to the next variant.

YAML and externally tagged variants

An enum without tag or untagged is externally tagged, so a variant holding a value is written as a map of its name to the value, like { "file": { "path": "a" } } in JSON. YAML is the exception: its parser, serde_norway, only reads such a variant from a YAML tag, and fails on the map, with expected a YAML tag starting with '!'.

# Loads
source: !file
  path: a

# Fails
source:
  file:
    path: a

A unit variant is still written as its name, like source: local. For a YAML config, prefer an internally tagged enum, with #[serde(tag = "type")], which is written the same in every format, and which JSON schemas and templates describe as it’s loaded. They describe an externally tagged variant as the map, which YAML doesn’t load.

Literal unions

A setting that accepts a few named values, or a value of another type, like "local" | "remote" | boolean, is known as a literal union. Leave the enum externally tagged, so that each unit variant is written as its name, and mark every variant that holds a value with #[serde(untagged)], so that it’s written as that value alone.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[serde(rename_all = "kebab-case")]
enum Cache {
	Local,
	#[setting(default)]
	Remote,
	#[serde(untagged)]
	Enabled(bool),
}

#[derive(Config)]
struct AppConfig {
	#[setting(nested)]
	pub cache: Cache,
}
}

With the above, cache accepts "local", "remote", true, or false, and generates the TypeScript type 'local' | 'remote' | boolean. The named values are matched first, then each untagged variant in the order declared, which serde requires to come last. An untagged unit variant is written as null.

To default to a value rather than a name, provide it on the untagged variant, like #[setting(default = true)]. See default values.

When a value matches none of them, the error lists the named values together, followed by each untagged variant.

failed to parse as any variant of PartialCache:
- expected one of "local", "remote", found "qux"
- enabled: expected a boolean, found "qux"

Only mark the variants as untagged, not the enum. An untagged enum writes its unit variants as null, so they would no longer be named.

A literal union that holds only scalars, and should be settable through an environment variable, can derive ConfigEnum instead, which implements FromStr for it.

Default values

In Schematic, there are 2 forms of default values:

  • The first is applied through the partial configuration, is defined with the #[setting] attribute, and is the layer below every other.
  • The second is on the final configuration itself, and uses the Default trait to generate the final value if none was provided. This acts more like a fallback. To fail instead, mark the setting as required.

To define a default value, use the #[setting(default)] attribute. The default attribute field accepts any expression of the setting’s type, like a number, a boolean, an array, tuple, or struct literal, a path that names a value, or a function, method, or macro call. A string converts into the setting’s type, and a bare path in snake_case names a handler function.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(default = "/")]
	pub base: String,

	#[setting(default = 3000)]
	pub port: usize,

	#[setting(default = true)]
	pub secure: bool,

	#[setting(default = vec!["localhost".into()])]
	pub allowed_hosts: Vec<String>,

	#[setting(default = LevelFilter::Debug)]
	pub log_level: LevelFilter,

	#[setting(default = Retry { attempts: 3, backoff: 500 })]
	pub retry: Retry,

	#[setting(default = PathBuf::from("/etc").join("app"))]
	pub config_dir: PathBuf,
}
}

A string that fails to convert, or a handler function that fails, is an error naming the setting, like Invalid default value for port. invalid digit found in string.

Paths: value or function?

A bare path is ambiguous — LevelFilter::Debug names a value, while find_unused_port names a handler function to call. Nothing at compile time can tell them apart, so Schematic goes by Rust’s naming conventions:

Last segment of the pathTreated asExample
Starts uppercaseA valueLevelFilter::Debug
Starts lowercaseA handler functionfind_unused_port

That covers enum variants, unit structs, and constants on one side, and functions on the other, since a name breaking those conventions would already be earning a compiler lint.

A handler function that must keep a non-conventional name can be reached through a snake_case wrapper, or called directly with default = my_wrapper() when it needs no context.

Enum variants

For enums, the default field marks which variant to use as the default. A unit variant holds no value, so default takes none, or a boolean.

#![allow(unused)]
fn main() {
#[derive(Config)]
enum Host {
	#[setting(default)]
	Local,
	Remote(HostConfig),
}
}

A variant that holds a single value can take a value as well, which marks it as the default and is what it holds. It accepts anything a setting’s default does, including a handler function that returns the value. Without one, the variant holds the default of its type.

#![allow(unused)]
fn main() {
#[derive(Config)]
enum Compress {
	Fast,
	Best,
	#[serde(untagged)]
	#[setting(default = true)]
	Enabled(bool),
}
}

A value can’t be provided for a variant holding several values, or a nested configuration, which sources its defaults from its own settings.

A named variant takes no value either, as each of its fields takes a default of its own. They’re applied whenever the variant is picked, not only when it’s the default, as the defaults are read for the variant the sources picked, so a source that picks Url below gets a timeout of 30.

#![allow(unused)]
fn main() {
#[derive(Config)]
enum Host {
	#[setting(default)]
	Local,
	Url {
		address: String,
		#[setting(default = 30)]
		timeout: u32,
	},
}
}

Handler function

If you need more control or need to calculate a complex value, you can pass a reference to a function to call. This function receives the context as the first argument, and can return an optional value. If None is returned, the Default value will be used instead.

#![allow(unused)]
fn main() {
fn find_unused_port(ctx: &Context) -> DefaultValueResult<usize> {
	let port = do_find()?;

	Ok(Some(port))
}

#[derive(Config)]
struct AppConfig {
	#[setting(default = find_unused_port)]
	pub port: usize,
}
}

Context handling

If you’re not using context, you can use () as the context type, or rely on generic inferrence.

#![allow(unused)]
fn main() {
fn using_unit_type(_: &()) -> DefaultValueResult<usize> {
	// ...
}

fn using_generics<C>(_: &C) -> DefaultValueResult<usize> {
	// ...
}
}

Transforming values

Sometimes a value is configured by a user, but it needs to be transformed in some way to be usable, for example, expanding file system paths to absolute from relative.

This can be achieved with the #[setting(transform)] attribute field, which requires a reference to a function to call. Only values with a defined value are transformed, while optional values remain None.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(transform = make_absolute)]
	pub env_file: Option<PathBuf>,
}
}

Transformations happen during the finalize phase, after environment variables are inherited, and before it is validated.

Transform handler function

When defining a custom transform function, the defined value and context are passed as arguments, and the function must return the transformed result.

Here’s an example of the transform function above.

#![allow(unused)]
fn main() {
fn make_absolute(value: PathBuf, context: &Context) -> TransformResult<PathBuf> {
	Ok(if value.is_absolute() {
		value
	} else {
		context.root.join(value)
	})
}
}

A transform that fails is an error naming the setting, like Failed to transform env_file. ..., followed by the function’s own message.

Nested values

Transformers can also be used on nested configs, but when defining the transformer function, the value being transformed is the partial nested config, not the final one. For example:

#![allow(unused)]
fn main() {
fn transform_nested(value: PartialChildConfig, context: &Context) -> TransformResult<PartialChildConfig> {
	Ok(value)
}

#[derive(Config)]
struct ParentConfig {
	#[setting(nested, transform = transform_nested)]
	pub child: ChildConfig,
}
}

Context handling

If you’re not using context, you can use () as the context type, or rely on generic inferrence.

#![allow(unused)]
fn main() {
fn using_unit_type<T>(value: T, _: &()) -> TransformResult<T> {
	// ...
}

fn using_generics<T, C>(value: T, _: &C) -> TransformResult<T> {
	// ...
}
}

Environment variables

Requires the env Cargo feature, which is enabled by default.

Settings can also inherit values from environment variables via the #[setting(env)] attribute field. When using this, variables take the highest precedence, and are merged as the last layer.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(default = 3000, env = "PORT")]
	pub port: usize,
}
}

Container prefixes

If you’d prefer to not define env for every setting, you can instead define a prefix on the containing struct using the #[config(env_prefix)] container attribute field. This will define an environment variable for all direct fields in the struct, in the format of “env prefix + field name” in uppercase.

For example, the environment variable below for port is now APP_PORT.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(env_prefix = "APP_")]
struct AppConfig {
	#[setting(default = 3000)]
	pub port: usize,
}
}

A derived key is the field’s Rust name (or its explicit rename) uppercased, and nothing more. It is deliberately not reshaped by rename_all, so changing how a setting is spelled in a config file never moves its environment variable.

An explicit #[setting(env)] is absolute. A prefix is never applied to it, and the two cannot be combined on the same setting.

Nested prefixes

env_prefix only applies to direct fields, not to nested children, and prefixes are not concatenated between parent and child. Each struct declares its own.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(env_prefix = "APP_SERVER_")]
struct AppServerConfig {
	// ...
}

#[derive(Config)]
#[config(env_prefix = "APP_")]
struct AppConfig {
	#[setting(nested)]
	pub server: AppServerConfig,
}
}

A parent can add a prefix for a nested child to read, with env_prefix on the field itself. The child must still declare an env_prefix of its own, as that is what opts its fields into being derived at all. Without one, the parent’s prefix would have no effect, so it fails to compile.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(nested, env_prefix = "OVERRIDE_")]
	pub server: AppServerConfig,
}
}

The parent’s prefix is only known at runtime, so it isn’t reflected in the schema. A derived key appears in a generated config template and in Config::settings() with the child’s own prefix, which always works.

Enums

The fields of a named variant read environment variables like a struct’s, with env, parse_env, and an env_prefix on the enum, which derives a key for each field.

#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(env_prefix = "AUTH_")]
#[serde(tag = "type", rename_all = "snake_case")]
enum Auth {
	#[setting(default)]
	None,
	Token {
		// AUTH_TOKEN
		token: String,
	},
	Basic {
		// AUTH_USER
		user: String,
		#[setting(env = "AUTH_PASSWORD")]
		password: String,
	},
}
}

The variables are those of the variant that’s been picked, by a source, the default, or the tag’s variable, and they’re merged over its fields as the last layer, as for a struct. So with type = "basic" in a file, and nothing picking another variant, AUTH_TOKEN does nothing. Variants may share a derived key, like a path in each, as only one is ever picked.

A nested config that a variant holds reads its own variables, whether the variant is named or holds it as a value. An optional enum, like Option<Auth>, that no source provided reads those of its default variant, and is provided by them when one is set, as an optional struct is.

A nested config within a variant that holds other values too, like Both(Child, bool), reads its variables when it’s finalized instead, as the layer would have to restate the values beside it. So ConfigLoadResult.layers doesn’t include them, as with the items of a nested collection.

A parent’s #[setting(nested, env_prefix)] reaches an enum as it does a struct, adding its prefix to the keys of the enum’s fields and its tag, as long as the enum has an env_prefix of its own.

Picking a variant

A tagged enum, with serde’s tag (and optionally content), also derives a key from its tag, which picks the variant. Above, AUTH_TYPE=token picks Token, and AUTH_TOKEN then fills it in. It’s part of the environment layer, so it replaces a variant a source picked, while a source that picked the same one keeps its fields.

  • The value is matched against each variant’s name, after rename_all, and its aliases, exactly as serde matches the tag. Any other value fails to load, listing the names it accepts.
  • A unit variant, a named variant, or one that holds only nested configs can be picked, as its fields are filled in from their defaults and variables. One that holds a plain value, like Path(String), has nothing to fill it in, so it can’t be.
  • An externally tagged or untagged enum has no tag, so a variable can only fill in its variants.
  • Each item of a nested collection reads the variable for itself, so AUTH_TYPE picks the variant of every item in a Vec<Auth>.

The key is reported on the tag in the schema, so TypeScript renders it as @env AUTH_TYPE. An env_prefix is accepted on a tagged enum without named variants too, as long as it has a variant to pick.

Parsing values

Without a parse_env, a variable is parsed with the setting’s FromStr, so its error type must implement Display, which is what a variable that fails to parse reports, like Failed to parse "70000" into u16: number too large to fit in target type.

That makes a bool setting accept only true and false. For values like 1, yes, or on, use parse_env = schematic::env::parse_bool, which ignores case, treats an empty variable as unset, and fails on anything it doesn’t recognize.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(env = "APP_DEBUG", parse_env = schematic::env::parse_bool)]
	pub debug: bool,
}
}

We also support parsing environment variables into the required type. For example, the variable may be a comma separated list of values, or a JSON string.

The #[setting(parse_env)] attribute field can be used, which requires a path to a function to handle the parsing, and receives the variable value as a single argument.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(env = "ALLOWED_HOSTS", parse_env = schematic::env::split_comma)]
	pub allowed_hosts: Vec<String>,
}
}

We provide a handful of built-in parsing functions in the env module.

parse_env needs a variable to read, so it requires either an env on the setting, or an env_prefix on the container. It’s a derive-time error otherwise.

Parse handler function

You can also define your own function for parsing values out of environment variables.

When defining a custom parse_env function, the variable value is passed as the 1st argument. A None value can be returned, which will fallback to the previous or default value.

#![allow(unused)]
fn main() {
pub fn custom_parse(var: String) -> ParseEnvResult<ReturnValue> {
	do_parse()
		.map(|v| Some(v))
		.map_err(|e| HandlerError::new(e.to_string()))
}

#[derive(Config)]
struct ExampleConfig {
	#[setting(env = "FIELD", parse_env = custom_parse)]
	pub field: String,
}
}

Extendable sources

Requires the extends Cargo feature, which is enabled by default.

Not supported for enums.

Configs can extend other configs, generating an accurate layer chain, via the #[setting(extend)] attribute field. Extended configs can either be a file path (relative from the current config) or a secure URL.

When defining extend, we currently support 3 types of patterns. We also suggest making the setting optional, so that extending is not required by consumers!

Single source

The first pattern is with a single string, which only allows a single file or URL to be extended.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(extend, validate = schematic::validate::extends_string)]
	pub extends: Option<String>,
}
}

Example:

extends: "./another/file.yml"

Multiple sources

The second pattern is with a list of strings, allowing multiple files or URLs to be extended. Each item in the list is merged from top to bottom (lowest precedence to highest).

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(extend, validate = schematic::validate::extends_list)]
	pub extends: Option<Vec<String>>,
}
}

Example:

extends:
  - "./another/file.yml"
  - "https://domain.com/some/other/file.yml"

Either pattern

And lastly, supporting both a string or a list, using our built-in enum.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(extend, validate = schematic::validate::extends_from)]
	pub extends: Option<schematic::ExtendsFrom>,
}
}

Merge strategies

A common requirement for configuration is to merge multiple sources/layers into a final result. By default Schematic will replace the previous setting value with the next value if the next value is Some, but sometimes you want far more control, like shallow or deep merging collections.

This can be achieved with the #[setting(merge)] attribute field, which requires a reference to a function to call.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(merge = schematic::merge::append_vec)]
	pub allowed_hosts: Vec<String>,
}

#[derive(Config)]
enum Projects {
	#[setting(merge = schematic::merge::append_vec)]
	List(Vec<String>),
	// ...
}
}

We provide a handful of built-in merge functions in the merge module.

Built-in functions

FunctionMerges
discardNeither value, so the setting is None.
preserveThe previous value.
replaceThe next value, which is the default for every setting.
append_vec, prepend_vecA Vec, with the next items after or before the previous.
append_vec_uniqueA Vec, appending only the next items it doesn’t contain yet.
merge_btreemap, merge_hashmap, merge_indexmapA map, the next value of a key replacing the previous.
merge_btreeset, merge_hashset, merge_indexsetA set.
merge_iterAny collection that implements Extend, like a VecDeque.
merge_partialsA map of nested configs, by key.
merge_listA MergeList, as it directs.

The hash-based functions support any hasher, like FxHashMap’s, and the indexmap functions require the type_indexmap Cargo feature.

append_vec_unique is useful for a list with a default, as it doesn’t repeat the default items that a source lists again.

Nested maps

A collection of nested configs is replaced by default, as there’s no way to pair up its items. For a map, merge_partials pairs them up by key: a config under a key in both layers is merged with its own strategies, and a key only in the next layer is added.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(nested, merge = schematic::merge::merge_partials)]
	pub plugins: HashMap<String, PluginConfig>,
}
}

It supports HashMap, BTreeMap, and IndexMap, or any map that implements MergeableMap. The configs receive the parent’s context, so it can’t be combined with a nested context function.

Merging chosen by the source

A merge function decides how every source merges a setting. To let each source decide for itself, use a MergeList. It’s merged with the merge_list function without a merge of its own.

#![allow(unused)]
fn main() {
use schematic::{Config, MergeList};

#[derive(Config)]
struct AppConfig {
	#[setting(default = MergeList::new(vec!["localhost".into()]))]
	pub allowed_hosts: MergeList<String>,
}
}

A source then writes a list, which replaces the previous items, or a map of how to merge with them, with any of the prepend, append, and replace keys.

# Replaces the previous items, including the default
allowed_hosts: [example.com]

# Adds to the previous items
allowed_hosts:
  prepend: [example.com]
  append: [example.org]

A MergeList derefs to a slice of its items, so it reads like a Vec, and the length validators accept it. Its schema is a union of the list and the map, so editors suggest both.

The derive knows a MergeList by name, including within an Option or a variant, so a merge of the setting’s own still takes precedence, and a collection of them is replaced like any other.

Through a type alias the derive can’t tell it’s a MergeList, so add #[setting(merge = schematic::merge::merge_list)], or it’s replaced like any other setting, and a source that appends loses the previous items. Items are plain values for now, not nested configs.

Merge handler function

You can also define your own function for merging values.

When defining a custom merge function, the previous value, next value, and context are passed as arguments, and the function must return an optional merged result. If None is returned, neither value will be used.

Here’s an example of the merge function above.

#![allow(unused)]
fn main() {
fn append_vec<T>(mut prev: Vec<T>, next: Vec<T>, context: &Context) -> MergeResult<Vec<T>> {
	prev.extend(next);

	Ok(Some(prev))
}

#[derive(Config)]
struct ExampleConfig {
	#[setting(merge = append_vec)]
	pub field: Vec<String>,
}
}

Context handling

If you’re not using context, you can use () as the context type, or rely on generic inferrence.

#![allow(unused)]
fn main() {
fn using_unit_type<T>(prev: T, next: T, _: &()) -> MergeResult<T> {
	// ...
}

fn using_generics<T, C>(prev: T, next: T, _: &C) -> MergeResult<T> {
	// ...
}
}

Validation rules

Requires the validate Cargo feature, which is enabled by default.

What kind of configuration crate would this be without built-in validation? As such, we support it as a first-class feature, with built-in validation rules provided by the garde crate.

In Schematic, validation does not happen as part of the serde parsing process, and instead happens for each partial configuration to be merged. However, with that said, prefer serde parsing over validation rules for structural adherence (learn more).

Validation can be applied on a per-setting basis with the #[setting(validate)] attribute field, which requires a reference to a function to call.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(validate = schematic::validate::alphanumeric)]
	pub secret_key: String,

	#[setting(validate = schematic::validate::regex("^\.env"))]
	pub env_file: String,
}
}

Or on a per-variant basis when using an enum.

#![allow(unused)]
fn main() {
#[derive(Config)]
enum Projects {
	#[setting(validate = schematic::validate::min_length(1))]
	List(Vec<String>),
	// ...
}
}

A variant holding several values passes them as a tuple of references, not as a reference to a tuple.

#![allow(unused)]
fn main() {
fn validate_pair<P, C>(value: (&String, &usize), partial: &P, context: &C, finalize: bool) -> ValidateResult {
	// ...
}

#[derive(Config)]
enum Entry {
	#[setting(validate = validate_pair)]
	Pair(String, usize),
	// ...
}
}

We provide a handful of built-in validation functions in the validate module. Furthermore, some functions are factories which can be called to produce a validator, like min(1), max(10), and in_range(1, 10) for numbers, or min_length(1) for strings and lists.

Validation passes

A configuration is validated more than once while loading. Each source is validated on its own as it’s parsed, and the final configuration is validated again once every source, default value, and environment variable has been merged, and every transform has run. A validator is told which pass it’s in by its last argument, finalizing, which is only true for the final pass.

A source only holds part of the configuration, and a later one may replace a value an earlier one set, so a check that needs the final value should wait for the final pass. For example, a path that a transform makes absolute isn’t absolute yet when its source is validated.

#![allow(unused)]
fn main() {
fn absolute_path<P, C>(value: &str, partial: &P, context: &C, finalizing: bool) -> ValidateResult {
	if finalizing && !Path::new(value).is_absolute() {
		return Err(ValidateError::new("must be an absolute path"));
	}

	Ok(())
}
}

Settings that no source provided are None in each source’s pass, and are skipped, while the final pass has a value for every setting.

An error in a source’s pass names that source, like Failed to validate config.yml. The final pass validates what every layer merged into, so its error names each source, and the environment variables when any were set, like Failed to validate base.yml, config.yml, environment variables, or the config’s name when there are neither.

Required settings

Every setting in a partial configuration is optional, so a setting that no source provides falls back to its default value, or to Default::default() when it has none. To fail instead, as serde does for a missing field, mark the setting with #[setting(required)].

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(required)]
	pub name: String,

	#[setting(required, env = "APP_TOKEN")]
	pub token: String,

	#[setting(required)]
	pub port: Option<usize>,
}
}

A required setting has no default value, and is checked by the final validation pass, once every source and environment variable has been merged. Any one of them may provide it, so each source is free to omit it. A null counts as missing, while an empty value, like "" or [], does not.

When the setting is wrapped in Option, the value must be Some, but the field stays an Option in the final configuration. Its schema describes the type the Option holds, as null isn’t a value. A setting that isn’t wrapped still has to implement Default, which AppConfig::default() falls back to.

A required setting can’t declare a default, as it would always have a value. Nor can a nested config that isn’t wrapped in Option, as one always exists in the final configuration. Mark the settings within it as required instead, which are then checked even when no source provided the nested config at all.

Validate handler function

You can also define your own function for validating values, also known as a validator.

When defining a custom validate function, the value to check is passed as the first argument, the current/parent partial as the second, the context as the third, and whether this is the final validation pass.

#![allow(unused)]
fn main() {
fn validate_string(
	value: &str,
	partial: &PartialAppConfig,
	context: &Context
	finalize: bool
) -> ValidateResult {
	if !do_check(value) {
		return Err(ValidateError::new("Some failure message"));
	}

	Ok(())
}
}

If validation fails, you must return a ValidateError with a failure message.

The setting is passed by reference, and deref coerces on its way in, so the first argument can take a borrowed form of the type instead of the type itself. A String setting reaches a &str validator, as above, and a Vec<T> setting reaches a &[T] one.

Factories

For composition and reusability concerns, we also support factory functions that can be called to create a unique validator. This can be seen above with schematic::validate::regex. To create your own factory, declare a normal function, with any number of arguments, that returns a Validator.

Using the regex factory as an example, it would look something like this. The closure takes the same four arguments a plain validator does.

#![allow(unused)]
fn main() {
use schematic::Validator;

fn regex<T, P, C>(pattern: &str) -> Validator<T, P, C> {
	let pattern = regex::Regex::new(pattern).unwrap();

	Box::new(move |value, _, _, _| {
		if !pattern.is_match(value) {
			return Err(ValidateError::new("Some failure message"));
		}

		Ok(())
	})
}
}

Several errors

A validator returns one error, but may return several instead, such as one for each item of a list that fails, by returning a Vec<ValidateError>, or a garde Report. Anything that implements IntoValidateErrors can be returned.

#![allow(unused)]
fn main() {
fn no_empty_items<P, C>(items: &[String], partial: &P, context: &C, finalizing: bool) -> Result<(), Vec<ValidateError>> {
	let errors = items
		.iter()
		.enumerate()
		.filter(|(_, item)| item.is_empty())
		.map(|(index, _)| ValidateError::with_segment("must not be empty", PathSegment::Index(index)))
		.collect::<Vec<_>>();

	if errors.is_empty() { Ok(()) } else { Err(errors) }
}
}

Path targeting

If validating an item in a list or collection, you can specifiy the nested path when failing. This is extremely useful when building error messages.

#![allow(unused)]
fn main() {
use schematic::PathSegment;

ValidateError::with_segments(
	"Some failure message",
	// [i].key
	[PathSegment::Index(i), PathSegment::Key(key.to_string())]
)
}

Context and partial handling

If you’re not using context, or want to create a validator for any kind of partial, we suggest generic inferrence.

#![allow(unused)]
fn main() {
fn using_generics<P, C>(value: &str, partial: &P, context: &C, finalize: bool) -> ValidateResult {
	// ...
}
}

Config validation

A rule that compares settings, rather than checking one, can validate the configuration as a whole, with the #[config(validate)] container attribute field. The function receives the partial configuration, the context, and whether this is the final pass, and may return several errors. It runs after the validators of each setting, for structs and enums alike, and is a factory when called, like #[config(validate = at_most(10))].

#![allow(unused)]
fn main() {
fn min_below_max<C>(partial: &PartialRangeConfig, context: &C, finalizing: bool) -> ValidateResult {
	// A source may only set one of them
	if let (Some(min), Some(max)) = (partial.min, partial.max)
		&& min > max
	{
		return Err(ValidateError::with_segment(
			"must be at most max",
			PathSegment::Key("min".into()),
		));
	}

	Ok(())
}

#[derive(Config)]
#[config(validate = min_below_max)]
struct RangeConfig {
	pub min: usize,
	pub max: usize,
}
}

An error is reported at the configuration’s own path, like range when it’s nested, unless it targets a setting within it, like range.min.

Cargo features

The following Cargo features can be enabled for more functionality:

  • validate_email - Enables email validation with the schematic::validate::email function.
  • validate_url - Enables URL validation with the schematic::validate::url and url_secure functions.

Unit-only enums

Configurations typically use enums to support multiple values within a specific setting. To simplify this process, and to provide streamlined interoperability with Config, we offer a ConfigEnum trait and macro that can be derived for enums with unit-only variants.

#![allow(unused)]
fn main() {
#[derive(ConfigEnum)]
enum LogLevel {
	Info,
	Error,
	Debug,
	Off
}
}

When paired with Config, it’ll look like:

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	pub log_level: LogLevel
}
}

This enum will generate the following implementations:

  • Provides a static T::variants() method, that returns a list of all variants. Perfect for iteration.
  • Implements FromStr and TryFrom for parsing from a string.
  • Implements Display for formatting into a string.

Attribute fields

The following fields are supported for the #[config] container attribute:

  • before_parse - Transform the incoming string before parsing, so that loosely cased input still matches. Accepts the same case names as rename_all: lowercase, UPPERCASE, PascalCase, camelCase, snake_case, SCREAMING_SNAKE_CASE, kebab-case, and SCREAMING-KEBAB-CASE.
#![allow(unused)]
fn main() {
#[derive(ConfigEnum)]
#[config(before_parse = "kebab-case")]
enum ExampleEnum {
	// ...
}
}

With the above, very_high, VeryHigh, and VERY HIGH all parse into the same variant.

And the following for serde compatibility:

  • rename
  • rename_all - Has no default. Variant names are used exactly as written unless this is set.

Variants

The following fields are supported for the #[variant] variant attribute:

  • fallback - Marks the variant as the fallback.

And the following for serde compatibility:

  • alias
  • rename - Overrides (explicitly sets) the string value used for parsing and formatting.
  • untagged - Marks the variant as holding a value, rather than being named.

Deriving common traits

All enums (not just unit-only enums) typically support the same derived traits, like Clone, Eq, etc. To reduce boilerplate, we offer a derive_enum! macro that will apply these traits for you.

#![allow(unused)]
fn main() {
derive_enum!(
	#[derive(ConfigEnum)]
	enum LogLevel {
		Info,
		Error,
		Debug,
		Off
	}
);
}

This macro will inject the following attributes:

#![allow(unused)]
fn main() {
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
}

Default variant

To define a default variant, use the Default trait and the optional #[default] variant attribute. We provide no special functionality or syntax for handling defaults.

#![allow(unused)]
fn main() {
#[derive(ConfigEnum, Default)]
enum LogLevel {
	Info,
	Error,
	Debug,
	#[default]
	Off
}
}

Fallback variant

Although ConfigEnum only supports unit variants, we do support a catch-all variant known as the “fallback variant”, which can be defined with #[variant(fallback)]. Fallback variants are primarily used when parsing from a string, and will be used if no other variant matches.

#![allow(unused)]
fn main() {
#[derive(ConfigEnum)]
enum Value {
	Foo,
	Bar,
	Baz
	#[variant(fallback)]
	Other(String)
}
}

However, this pattern does have a few caveats:

  • Only 1 fallback variant can be defined.
  • The fallback variant must be a tuple variant with a single field.
  • The field type can be anything and we’ll attempt to convert it with try_into().
  • The fallback inner value is not casing formatted based on serde’s rename_all.
#![allow(unused)]
fn main() {
let qux = Value::from_str("qux")?; // Value::Other("qux")
}

Untagged variants

A setting that accepts a few named values, or a value of another type, like "auto" | "off" | number, is known as a literal union. To model one, mark each variant that holds a value with #[serde(untagged)], so that serde reads it as that value alone.

#![allow(unused)]
fn main() {
derive_enum!(
	#[derive(ConfigEnum, Default)]
	enum Threads {
		#[default]
		Auto,
		Off,
		#[serde(untagged)]
		Count(u32),
	}
);
}

Parsing from a string matches the named values first, then attempts each untagged variant in the order declared, using the inner type’s FromStr. Formatting writes the inner value with Display. This is what allows the setting to be read from an environment variable.

#![allow(unused)]
fn main() {
let auto = Threads::from_str("auto")?; // Threads::Auto
let count = Threads::from_str("8")?; // Threads::Count(8)
}

However, this pattern does have a few caveats:

  • An untagged variant must be a tuple variant with a single field.
  • The field type must implement Default, Display, and FromStr.
  • Untagged variants are attempted before the fallback variant, if there is one.
  • The input is parsed as written, without the before_parse transform, which only exists to normalize named values.
  • serde requires untagged variants to come after every other variant.

A literal union with a variant that holds a nested configuration can derive Config instead.

Experimental

Pkl configuration format (>= v0.17)

Thanks to the rpkl crate, we have experimental support for the Pkl configuration language. Pkl is a dynamic and programmable configuration format built and maintained by Apple.

port = 3000
secure = true
allowed_hosts = List(".localhost")

Pkl support can be enabled with the pkl Cargo feature.

Caveats

Unlike our other static formats, Pkl requires the following to work correctly:

  • The pkl binary must exist on PATH. This requires every user to install Pkl onto their machine.
  • Pkl parses local file system paths only.
    • Passing source code directly to ConfigLoader is NOT supported.
    • Reading configuration from URLs is NOT supported, but can be worked around by implementing a custom file-based Cacher.

Known issues

  • The rpkl crate is relatively new and may be buggy or have missing/incomplete functionality.
  • When parsing fails and a code snippet is rendered in the terminal using miette, the line/column offset may not be accurate.

Schemas

Requires the schema Cargo feature, which is not enabled by default.

The other feature of Schematic is the ability to model schemas for Rust types using the Schematic trait and associated macro. Schemas are useful for:

  • Generating code, documentation, and other formats.
  • Ensuring data integrity across systems.
  • Standardizing interoperability and enforcing contracts.

Usage

Define a struct, enum, or type and derive the Schematic trait. Our macro will attempt to convert all fields, variants, values, and generics into a schema representation using SchemaType.

#![allow(unused)]
fn main() {
use schematic::Schematic;

#[derive(Schematic)]
enum UserStatus {
	Active,
	Inactive,
}

#[derive(Schematic)]
struct User {
	pub name: String;
	pub age: usize;
	pub status: UserStatus;
}
}

Once a type has a schema associated with it, it can be fed into the generator.

Custom implementation

Our derive macro will always implement schemas using the default state of Schema, SchemaType, and associated types. If you want these types to use custom settings, you can implement the Schematic trait and Schematic::build_schema() method manually.

The Schematic::schema_name() method is optional, but is encouraged for non-primitive types. It will associate references between types, and avoid circular references.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::*};

#[derive(Schematic)]
enum UserStatus {
	Active,
	Inactive,
}

struct User {
	pub name: String;
	pub age: usize;
	pub status: UserStatus;
}

impl Schematic for User {
	fn schema_name() -> Option<String> {
		Some("User".into())
	}

	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.structure(StructType::new([
			("name".into(), schema.nest().string(StringType {
				min_length: Some(1),
				..StringType::default()
			})),
			("age".into(), schema.nest().integer(IntegerType::new_kind(IntegerKind::Usize))),
			("status".into(), schema.infer::<UserStatus>()),
		]))
	}
}
}

Learn more about our supported types.

Cargo features

The following Cargo features are available:

Renderers

Learn more about renderers.

  • renderer_api_docs - Enables markdown API documentation generation.
  • renderer_json_schema - Enables JSON schema generation.
  • renderer_pkl_schema - Enables Pkl module generation.
  • renderer_template - Enables config template generation.
  • renderer_typescript - Enables TypeScript types generation.

External types

Learn more about external types.

  • type_arrayvec - Implements schematic for the arrayvec crate.
  • type_chrono - Implements schematic for the chrono crate.
  • type_compact_str - Implements schematic for the compact_str crate.
  • type_hashbrown - Implements schematic for the hashbrown crate.
  • type_indexmap - Implements schematic for the indexmap crate.
  • type_jiff - Implements schematic for the jiff crate.
  • type_regex - Implements schematic for the regex crate.
  • type_relative_path - Implements schematic for the relative-path crate.
  • type_rust_decimal - Implements schematic for the rust_decimal crate.
  • type_semver - Implements schematic for the semver crate.
  • type_smallvec - Implements schematic for the smallvec crate.
  • type_smol_str - Implements schematic for the smol_str crate.
  • type_url - Implements schematic for the url crate.
  • type_uuid - Implements schematic for the uuid crate.

Types

Schema types are the building blocks when modeling your schema. They are used to define the explicit shape of your types, data, or configuration. This type information is then passed to a generator, which can then generate and render the schema types in a variety of formats.

Defining names

Schemas can be named, which is useful for referencing them in other types when generating code. By default the Schematic derive macro will use the name of the type, but when implementing the trait manually, you can use the Schematic::schema_name() method.

#![allow(unused)]
fn main() {
impl Schematic for T {
	fn schema_name() -> Option<String> {
		Some("CustomName".into())
	}
}
}

This method is optional, but is encouraged for non-primitive types. It will associate references between types, and avoid circular references.

Names must be unique across every type added to a generator, since schemas are keyed by name alone. Adding two different types under the same name panics rather than silently rendering one of them.

For generic types, the derive appends the name of each type argument, so Wrapper<T> becomes WrapperString, WrapperBool, and so on, and instantiations don’t collide. Arguments that name themselves are used as-is; the rest fall back to their Rust type name. When implementing the trait by hand, do the same with schema_name_of.

#![allow(unused)]
fn main() {
impl<T: Schematic> Schematic for Wrapper<T> {
	fn schema_name() -> Option<String> {
		Some(format!("Wrapper{}", schema_name_of::<T>()))
	}
}
}

Inferring schemas

When building a schema, you’ll almost always need to reference schemas from other types that implement Schematic. To do so, you can use the SchemaBuilder.infer::<T>() method, which will create a nested builder, and build an isolated schema based on its implementation.

#![allow(unused)]
fn main() {
struct OtherType {}

impl Schematic for OtherType {
	// ...
}


impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		let builtin_type = schema.infer::<String>();
		let custom_type = schema.infer::<OtherType>();

		// ...
	}
}
}

Creating nested schemas

When building a schema, you may have situations where you need to build nested schemas, for example, within struct fields. You cannot use the type-based methods on SchemaBuilder, as they mutate the current builder. Instead you must created another builder, which can be achieved with the SchemaBuilder.nest() method.

#![allow(unused)]
fn main() {
impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		// Mutates self
		schema.string_default();

		// Creates a new builder and mutates it
		schema.nest().string_default();

		// ...
	}
}
}

Arrays

The ArrayType can be used to represent a variable list of homogeneous values of a given type, as defined by items_type. For example, a list of strings:

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::ArrayType};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.array(ArrayType {
			items_type: Box::new(schema.infer::<String>()),
			..ArrayType::default()
		})
	}
}
}

If you’re only defining the items_type field, you can use the shorthand ArrayType::new() method.

#![allow(unused)]
fn main() {
schema.array(ArrayType::new(schema.infer::<String>()));
}

Automatically implemented for Vec, VecDeque, LinkedList, BinaryHeap, BTreeSet, HashSet, [T; N], [T], and &[T].

Settings

The following fields can be passed to ArrayType, which are then fed into the generator.

Contains

The contains field takes a schema that at least one item must match. It applies alongside items_type, which constrains every item, rather than replacing it.

#![allow(unused)]
fn main() {
ArrayType {
	// ...
	contains: Some(Box::new(Schema::string(StringType::default()))),
}
}

Length

The min_length and max_length fields can be used to restrict the length of the array. Both fields accept a non-zero number, and can be used together or individually.

#![allow(unused)]
fn main() {
ArrayType {
	// ...
	min_length: Some(1),
	max_length: Some(10),
}
}

Uniqueness

The unique field can be used to indicate that all items in the array must be unique. Note that Schematic does not verify uniqueness.

#![allow(unused)]
fn main() {
ArrayType {
	// ...
	unique: Some(true),
}
}

Booleans

The BooleanType can be used to represent a boolean true or false value. Values that evaluate to true or false, such as 1 and 0, are not accepted by the schema.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::BooleanType};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.boolean_default()
	}
}
}

Automatically implemented for bool.

Default value

To customize the default value for use within generators, pass the desired value to the BooleanType constructor.

#![allow(unused)]
fn main() {
schema.boolean(BooleanType::new(true));
}

Enums

The EnumType can be used to represent a list of literal values.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, schema::{EnumType, LiteralValue}};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.enumerable(EnumType {
			values: vec![
				LiteralValue::String("debug".into()),
				LiteralValue::String("error".into()),
				LiteralValue::String("warning".into()),
			],
			..EnumType::default()
		})
	}
}
}

If you’re only defining the values field, you can use the shorthand EnumType::new() method.

#![allow(unused)]
fn main() {
schema.enumerable(EnumType::new([
	LiteralValue::String("debug".into()),
	LiteralValue::String("error".into()),
	LiteralValue::String("warning".into()),
]));
}

Detailed variants

If you’d like to provide more detailed information for each variant (value), like descriptions and visibility, you can define the variants field and pass a map of SchemaFields.

#![allow(unused)]
fn main() {
schema.enumerable(EnumType {
	values: vec![
		LiteralValue::String("debug".into()),
		LiteralValue::String("error".into()),
		LiteralValue::String("warning".into()),
	],
	variants: Some(IndexMap::from_iter([
		(
			"Debug".into(),
			Box::new(SchemaField {
				comment: Some("Shows debug messages and above".into()),
				schema: Schema::literal_value(LiteralValue::String("debug".into())),
				..SchemaField::default()
			})
		),
		(
			"Error".into(),
			Box::new(SchemaField {
				comment: Some("Shows only error messages".into()),
				schema: Schema::literal_value(LiteralValue::String("error".into())),
				..SchemaField::default()
			})
		),
		(
			"Warning".into(),
			Box::new(SchemaField {
				comment: Some("Shows warning and error messages".into()),
				schema: Schema::literal_value(LiteralValue::String("warning".into())),
				..SchemaField::default()
			})
		),
	])),
	..EnumType::default()
})
}

This comes in handy when working with specific generators, like TypeScript.

variants is the source of truth, and values is a derived subset of it. A variant whose schema holds no literal value contributes no entry to values, so the two can differ in length.

Default value

The default_index field points at the entry that is the default. It indexes variants when that map is set, and values otherwise, so prefer the EnumType::get_default() and EnumType::set_default() methods over indexing either list yourself.

#![allow(unused)]
fn main() {
let mut ty = EnumType::new([
	LiteralValue::String("debug".into()),
	LiteralValue::String("error".into()),
]);

// Returns false and keeps the current default when no entry matches
ty.set_default(LiteralValue::String("error".into()));

assert_eq!(ty.get_default(), Some(&LiteralValue::String("error".into())));
}

Floats

The FloatType can be used to represent a float or double.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::{FloatType, FloatKind}};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.float(FloatType {
			kind: FloatKind::F32,
			..FloatType::default()
		})
	}
}
}

If you’re only defining the kind field, you can use the shorthand FloatType::new_kind() method.

#![allow(unused)]
fn main() {
schema.float(FloatType::new_kind(FloatKind::F32));
}

Automatically implemented for f32 and f64.

Default value

To customize the default value for use within generators, pass the desired value to the FloatType constructor.

#![allow(unused)]
fn main() {
schema.float(FloatType::new_32(32.0));
// Or
schema.float(FloatType::new_64(64.0));
}

Settings

The following fields can be passed to FloatType, which are then fed into the generator.

Enumerable

The enum_values field can be used to specify a list of literal values that are allowed for the field.

#![allow(unused)]
fn main() {
FloatType {
	// ...
	enum_values: Some(vec![0.0, 0.25, 0.5, 0.75, 1.0]),
}
}

Formats

The format field can be used to associate semantic meaning to the float, and how the float will be used and displayed.

#![allow(unused)]
fn main() {
FloatType {
	// ...
	format: Some("currency".into()),
}
}

This is primarily used by JSON Schema.

Min/max

The min and max fields can be used to specify the minimum and maximum inclusive values allowed. Both fields accept a non-zero number, and can be used together or individually.

#![allow(unused)]
fn main() {
FloatType {
	// ...
	min: Some(0.0), // >0
	max: Some(1.0), // <1
}
}

These fields are not exclusive and do not include the lower and upper bound values. To include them, use min_exclusive and max_exclusive instead.

#![allow(unused)]
fn main() {
FloatType {
	// ...
	min_exclusive: Some(0.0), // >=0
	max_exclusive: Some(1.0), // <=1
}
}

Multiple of

The multiple_of field can be used to specify a value that the float must be a multiple of.

#![allow(unused)]
fn main() {
FloatType {
	// ...
	multiple_of: Some(0.25), // 0.0, 0.25, 0.50, etc
}
}

Integers

The IntegerType can be used to represent an integer (number).

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::{IntegerType, IntegerKind}};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.integer(IntegerType {
			kind: IntegerKind::U32,
			..IntegerType::default()
		})
	}
}
}

If you’re only defining the kind field, you can use the shorthand IntegerType::new_kind() method.

#![allow(unused)]
fn main() {
schema.integer(IntegerType::new_kind(IntegerKind::U32));
}

Automatically implemented for usize-u128, isize-i128, and their NonZero counterparts. Unsigned NonZero types carry a min of 1; signed ones cannot express “not zero” as a bound, so they stay unconstrained.

Default value

To customize the default value for use within generators, pass the desired value to the IntegerType constructor.

#![allow(unused)]
fn main() {
schema.integer(IntegerType::new(IntegerKind::I32, 100));
// Or
schema.integer(IntegerType::new_unsigned(IntegerKind::U32, 100));
}

Settings

The following fields can be passed to IntegerType, which are then fed into the generator.

Enumerable

The enum_values field can be used to specify a list of literal values that are allowed for the field.

#![allow(unused)]
fn main() {
IntegerType {
	// ...
	enum_values: Some(vec![0, 25, 50, 75, 100]),
}
}

Formats

The format field can be used to associate semantic meaning to the integer, and how the integer will be used and displayed.

#![allow(unused)]
fn main() {
IntegerType {
	// ...
	format: Some("age".into()),
}
}

This is primarily used by JSON Schema.

Min/max

The min and max fields can be used to specify the minimum and maximum inclusive values allowed. Both fields accept a non-zero number, and can be used together or individually.

#![allow(unused)]
fn main() {
IntegerType {
	// ...
	min: Some(0), // >0
	max: Some(100), // <100
}
}

These fields are not exclusive and do not include the lower and upper bound values. To include them, use min_exclusive and max_exclusive instead.

#![allow(unused)]
fn main() {
IntegerType {
	// ...
	min_exclusive: Some(0), // >=0
	max_exclusive: Some(100), // <=100
}
}

Multiple of

The multiple_of field can be used to specify a value that the integer must be a multiple of.

#![allow(unused)]
fn main() {
IntegerType {
	// ...
	multiple_of: Some(25), // 0, 25, 50, etc
}
}

Literals

The LiteralType can be used to represent a literal primitive value, such as a string or number.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::{LiteralType, LiteralValue}};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.literal(LiteralType::new(LiteralValue::String("enabled".into())))
		// Or
		schema.literal_value(LiteralValue::String("enabled".into()))
	}
}
}

The LiteralValue type is used by other schema types for their default or enumerable values.

Nulls

The SchemaType::Null variant can be used to represent a literal null value. This works best when paired with unions or fields that need to be nullable.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.set_type_and_build(SchemaType::Null)
	}
}
}

Automatically implemented for () and Option<T>.

Marking as nullable

If you want a concrete schema to also accept null (an Optional value), you can use the SchemaBuilder::nullable() method. Under the hood, this will create a union of the defined type, and the null type.

#![allow(unused)]
fn main() {
// string | null
schema.nullable(schema.infer::<String>());
}

Objects

The ObjectType can be used to represent a key-value object of homogenous types. This is also known as a map, record, keyed object, or indexed object.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::ObjectType};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.object(ObjectType {
			key_type: Box::new(schema.infer::<String>()),
			value_type: Box::new(schema.infer::<String>()),
			..ObjectType::default()
		})
	}
}
}

If you’re only defining the key_type and value_type fields, you can use the shorthand ObjectType::new() method.

#![allow(unused)]
fn main() {
schema.object(ObjectType::new(schema.infer::<String>(), schema.infer::<String>()));
}

Automatically implemented for BTreeMap and HashMap.

Settings

The following fields can be passed to ObjectType, which are then fed into the generator.

Length

The min_length and max_length fields can be used to restrict the length (key-value pairs) of the object. Both fields accept a non-zero number, and can be used together or individually.

#![allow(unused)]
fn main() {
ObjectType {
	// ...
	min_length: Some(1),
	max_length: Some(10),
}
}

Required keys

The required field can be used to specify a list of keys that are required for the object, and must exist when the object is validated.

#![allow(unused)]
fn main() {
ObjectType {
	// ...
	required: Some(vec!["foo".into(), "bar".into()]),
}
}

This is primarily used by JSON Schema.

Strings

The StringType can be used to represent a sequence of bytes, you know, a string.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::{StringType, IntegerKind}};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.string_default()
	}
}
}

Automatically implemented for char, str, String, Path, PathBuf, IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, and SocketAddrV6.

SystemTime and Duration are not strings. Serde encodes them as maps — { secs, nanos } and { secs_since_epoch, nanos_since_epoch } — so they model as structs.

Default value

To customize the default value for use within generators, pass the desired value to the StringType constructor.

#![allow(unused)]
fn main() {
schema.string(StringType::new("abc"));
}

Settings

The following fields can be passed to StringType, which are then fed into the generator.

Enumerable

The enum_values field can be used to specify a list of literal values that are allowed for the field.

#![allow(unused)]
fn main() {
StringType {
	// ...
	enum_values: Some(vec!["a".into(), "b".into(), "c".into()]),
}
}

Formats

The format field can be used to associate semantic meaning to the string, and how the string will be used and displayed.

#![allow(unused)]
fn main() {
StringType {
	// ...
	format: Some("url".into()),
}
}

This is primarily used by JSON Schema.

Length

The min_length and max_length fields can be used to restrict the length of the string. Both fields accept a non-zero number, and can be used together or individually.

#![allow(unused)]
fn main() {
StringType {
	// ...
	min_length: Some(1),
	max_length: Some(10),
}
}

Patterns

The pattern field can be used to define a regex pattern that the string must abide by.

#![allow(unused)]
fn main() {
StringType {
	// ...
	format: Some("version".into()),
	pattern: Some("\d+\.\d+\.\d+".into()),
}
}

This is primarily used by JSON Schema.

Structs

The StructType can be used to represent a struct with explicitly named fields and typed values. This is also known as a “shape” or “model”.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::StructType};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.structure(StructType {
			fields: IndexMap::from_iter([
				(
					"name".into(),
					Box::new(SchemaField {
						comment: Some("Name of the user".into()),
						schema: schema.infer::<String>(),
						..SchemaField::default()
					})
				),
				(
					"age".into(),
					Box::new(SchemaField {
						comment: Some("Age of the user".into()),
						schema: schema.nest().integer(IntegerType::new_kind(IntegerKind::U16)),
						..SchemaField::default()
					})
				),
				(
					"active".into(),
					Box::new(SchemaField {
						comment: Some("Is the user active".into()),
						schema: schema.infer::<bool>(),
						..SchemaField::default()
					})
				),
			]),
			..StructType::default()
		})
	}
}
}

If you’re only defining fields, you can use the shorthand StructType::new() method. When using this approach, the Boxs are automatically inserted for you.

#![allow(unused)]
fn main() {
schema.structure(StructType::new([
	(
		"name".into(),
		SchemaField {
			comment: Some("Name of the user".into()),
			schema: schema.infer::<String>(),
			..SchemaField::default()
		}
	),
	// ...
]));
}

Automatically implemented for Duration, SystemTime, Range, and RangeInclusive. These look like scalars but serde encodes them as maps, so the schema describes the map.

Fields keep the order they were inserted in, which is the declaration order when the schema comes from a derive. Generators sort them by name when rendering, so generated output stays alphabetical regardless of how the source type is written.

Optional and nullable fields

Each field’s SchemaField describes two separate things about its value:

  • optional - The key may be left out of the input entirely.
  • nullable - The key may be present with a null value.

Renderers read them independently. JSON Schema leaves an optional field out of required, and gives a nullable one an anyOf that includes null. TypeScript marks an optional property with ?, and a nullable one with | null.

When the schema comes from a derive, they follow what serde accepts:

FieldOptionalNullableTypeScript
name: StringNoNoname: string
#[setting(default = "x")] name: StringYesNoname?: string
name: Option<String>YesYesname?: string | null
#[setting(required)] name: Option<String>NoNoname: string

An Option is optional as well as nullable, as serde fills in an omitted one with None. A #[serde(default)] on the field, or on the struct, makes a field optional too. A required Option must be given a value, which null isn’t, so it’s described by the type it holds.

For a config, a field that isn’t optional describes what a source should provide, which is stricter than what loads. Every setting of a partial may be omitted, and one that no source provides falls back to its default value. Only #[setting(required)] makes a missing value an error when loading, as described in required settings.

Settings

The following fields can be passed to StructType, which are then fed into the generator.

Required fields

The required field can be used to specify a list of fields that are required for the struct.

#![allow(unused)]
fn main() {
StructType {
	// ...
	required: Some(vec!["name".into()]),
}
}

This is primarily used by JSON Schema.

Unknown fields

The allow_unknown_fields field marks a struct that accepts keys other than its fields, as serde does unless #[serde(deny_unknown_fields)]. It defaults to false, closing the struct, which JSON Schema renders as additionalProperties: false.

#![allow(unused)]
fn main() {
StructType {
	// ...
	allow_unknown_fields: true,
}
}

The derive sets it to what’s deserialized: a config’s partial denies unknown fields unless #[config(allow_unknown_fields)], while a type that only derives Schematic follows its own #[serde(deny_unknown_fields)].

Tagged variants

The TaggedType paired with SchemaType::Tagged represents an enum variant that serde writes with its name, as a tag around or within the value it holds. It’s a variant of a union, and the derive creates one for every variant of an enum that’s tagged, so it’s rarely built by hand.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, schema::{TaggedType, TagFormat, UnionType}};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.union(UnionType::new_any([
			Schema::tagged(TaggedType::new(
				TagFormat::Internal { tag: "type".into() },
				"git",
				Some(schema.infer::<GitSource>()),
			)),
			Schema::tagged(TaggedType::new(
				TagFormat::Internal { tag: "type".into() },
				"none",
				None,
			)),
		]))
	}
}
}

Formats

The format field is how serde writes the variant’s name, from the enum’s #[serde(tag)] and #[serde(content)] attributes.

  • TagFormat::External (default) - { "name": value }.
  • TagFormat::Internal { tag } - { "tag": "name", ...value }.
  • TagFormat::Adjacent { tag, content } - { "tag": "name", "content": value }.

A unit variant holds no value, so it’s only its tag, like { "tag": "name" }. An externally tagged unit variant is written as its name alone, so it’s a literal instead, and an untagged variant is its value alone, without a tagged type around it.

The value is kept apart from the tag, rather than within a struct of them, as a named type’s schema is shared by every type that holds it. The tag’s env_var is the environment variable that picks the variant, from an enum’s env_prefix.

Rendering

A renderer can render each format as it sees fit, through SchemaRenderer::render_tagged, which defaults to rendering the struct serde writes for the variant, from TaggedType::to_schema(). An internally tagged variant holding a named struct is flattened into a struct of its tag, as adding the tag to the named struct would claim it for every type that holds it, so a TypeScript type renders it as { type: 'git' } & GitSource.

A renderer that reads the shape of the structs it renders, rather than rendering each tag format, can replace every tagged variant with that struct up front, with Schema::expand_tagged().

Tuples

The TupleType can be used to represent a fixed list of heterogeneous values of a given type, as defined by items_types.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::{TupleType, IntegerKind}};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.tuple(TupleType {
			items_types: vec![
				Box::new(schema.infer::<String>()),
				Box::new(schema.infer::<bool>()),
				Box::new(schema.nest().integer(IntegerType::new_kind(IntegerKind::U32))),
			],
			..TupleType::default()
		})
	}
}
}

If you’re only defining the items_types field, you can use the shorthand TupleType::new() method. When using this approach, the Boxs are automatically inserted for you.

#![allow(unused)]
fn main() {
schema.tuple(TupleType::new([
	schema.infer::<String>(),
	schema.infer::<bool>(),
	schema.nest().integer(IntegerType::new_kind(IntegerKind::U32)),
]));
}

Automatically implemented for tuples of 0-12 length.

Unions

The UnionType paired with SchemaType::Union can be used to represent a list of heterogeneous schema types (variants), in which a value must match one or more of the types.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::{UnionType, UnionOperator}};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.union(UnionType {
			operator: UnionOperator::AnyOf,
			variants_types: vec![
				Box::new(schema.infer::<String>()),
				Box::new(schema.infer::<bool>()),
				Box::new(schema.nest().integer(IntegerType::new_kind(IntegerKind::U32))),
			],
			..UnionType::default()
		})
	}
}
}

If you’re only defining the variants_types field, you can use the shorthand UnionType::new_any() (any of) or UnionType::new_one() (one of) methods. When using this approach, the Boxs are automatically inserted for you.

#![allow(unused)]
fn main() {
// Any of
schema.union(UnionType::new_any([
	schema.infer::<String>(),
	schema.infer::<bool>(),
	schema.nest().integer(IntegerType::new_kind(IntegerKind::U32)),
]));

// One of
schema.union(UnionType::new_one([
	// ...
]));
}

Variant names

A union derived from an enum with #[derive(Config)] or #[derive(Schematic)] records the name of each variant in variants_names, by position in variants_types, so that renderers such as API documentation can label a variant. A union built by hand carries no names, and UnionType::get_variant_name() returns None for it.

Operators

Unions support 2 kinds of operators, any of and one of, both of which can be defined with the operator field.

  • Any of requires the value to match any of the variants.
  • One of requires the value to match only one of the variants.
#![allow(unused)]
fn main() {
UnionType {
	// ...
	operator: UnionOperator::OneOf,
}
}

Unknown

The SchemaType::Unknown variant can be used to represent an unknown type. This is sometimes known as an “any” or “mixed” type.

#![allow(unused)]
fn main() {
use schematic::{Schematic, Schema, SchemaBuilder, SchemaType};

impl Schematic for T {
	fn build_schema(mut schema: SchemaBuilder) -> Schema {
		schema.build()
	}
}
}

The SchemaType::Unknown variant is also the default variant, and the default implementation for Schematic::build_schema(), so the above can simply be written as:

#![allow(unused)]
fn main() {
impl Schematic for T {}
}

External types

Schematic provides schema implementations for third-party crates through a concept known as external types. This functionality is opt-in through Cargo features.

Each feature implements the version of the crate that Schematic depends on, so the version in your own Cargo.toml must be compatible with it, or the type won’t implement Schematic.

arrayvec

Requires the type_arrayvec Cargo feature, and arrayvec 0.7.

Implements schemas for ArrayVec and ArrayString from the arrayvec crate. Each one’s capacity is its maximum length, which for an ArrayString is in bytes, so a schema only rejects a string with more characters than that.

chrono

Requires the type_chrono Cargo feature.

Implements schemas for Date, DateTime, Duration, Days, Months, IsoWeek, NaiveWeek, NaiveDate, NaiveDateTime, and NaiveTime from the chrono crate.

compact_str

Requires the type_compact_str Cargo feature, and compact_str 0.10.

Implements a schema for CompactString from the compact_str crate.

hashbrown

Requires the type_hashbrown Cargo feature, and hashbrown 0.17.

Implements schemas for HashMap and HashSet from the hashbrown crate.

indexmap

Requires the type_indexmap Cargo feature.

Implements a schema for IndexMap and IndexSet from the indexmap crate.

jiff

Requires the type_jiff Cargo feature, and jiff 1.

Implements schemas for Timestamp, ZonedDateTime, Span, and SignedDuration, and the civil Date, DateTime, Time, and ISOWeekDate, from the jiff crate.

Only Timestamp and Date have a format, date-time and date. The others are strings, as their format would reject what jiff writes or reads: a ZonedDateTime ends with its time zone, like [America/New_York], a civil DateTime and Time have no offset, an ISOWeekDate is a week, like 2024-W01-2, and a Span and SignedDuration are also read in jiff’s friendly format, like 1h 30m.

regex

Requires the type_regex Cargo feature.

Implements a schema for Regex from the regex crate.

To use Regex as a setting, reach for RegexSetting, which supplies the Default a required setting needs.

relative-path

Requires the type_relative_path Cargo feature.

Implements schemas for RelativePath and RelativePathBuf from the relative-path crate.

rpkl

Requires the pkl Cargo feature.

Implements a schema for Value from the rpkl crate.

rust_decimal

Requires the type_rust_decimal Cargo feature.

Implements a schema for Decimal from the rust_decimal crate.

semver

Requires the type_semver Cargo feature.

Implements schemas for Version and VersionReq from the semver crate.

To use Version as a setting, reach for VersionSetting, which supplies the Default a required setting needs.

ron

Requires the ron Cargo feature.

Implements a schema for Value from the ron crate.

serde_json

Requires the json Cargo feature.

Implements schemas for Value, Number, and Map from the serde_json crate.

serde_yaml

Requires the serde_yaml Cargo feature on schematic_types directly. The schematic crate does not enable it, as its yaml feature uses serde_norway instead.

Implements schemas for Value, Number, and Mapping from the serde_yaml crate.

serde_yaml_norway

Requires the yaml Cargo feature.

Implements schemas for Value, Number, and Mapping from the serde_norway crate.

smallvec

Requires the type_smallvec Cargo feature, and smallvec 1.

Implements a schema for SmallVec from the smallvec crate.

smol_str

Requires the type_smol_str Cargo feature, and smol_str 0.3.

Implements a schema for SmolStr from the smol_str crate.

toml

Requires the toml Cargo feature.

Implements schemas for Value and Map from the toml crate.

url

Requires the type_url Cargo feature.

Implements a schema for Url from the url crate.

uuid

Requires the type_uuid Cargo feature.

Implements a schema for Uuid from the uuid crate.

Code generation

The primary benefit of a schema modeling system, is that you can consume this type information to generate code into multiple output formats. This is a common pattern in many languages, and is a great way to reduce boilerplate.

In the context of Rust, why use multiple disparate crates, each with their own unique implementations and #[derive] macros, just to generate some output. With Schematic, you can ditch all of these and use a single standardized approach.

Usage

To make use of the generator, import and instantiate our SchemaGenerator. This is typically done within a one-off main function that can be ran from Cargo.

#![allow(unused)]
fn main() {
use schematic::schema::SchemaGenerator;

let mut generator = SchemaGenerator::default();
}

Adding types

From here, for every type that implements Schematic and you want to include in the generated output, call SchemaGenerator::add(). If you already have a Schema rather than a type, you can use the SchemaGenerator::add_schema() method instead.

#![allow(unused)]
fn main() {
use schematic::schema::SchemaGenerator;

let mut generator = SchemaGenerator::default();
generator.add::<FirstConfig>();
generator.add::<SecondConfig>();
generator.add::<ThirdConfig>();
}

We’ll recursively add referenced and nested schemas for types that are added. No need to explicitly add all required types!

Schemas are keyed by name, so adding two different types that report the same one panics. Rendering both is impossible, and silently keeping one would leave every reference to the other pointing at the wrong type. Adding the same type twice is fine.

Generating output

From here, call SchemaGenerator::generate() to render the schemes with a chosen renderer to an output file of your choice. This method can be called multiple times, each with a different output file or renderer.

#![allow(unused)]
fn main() {
use schematic::schema::SchemaGenerator;

let mut generator = SchemaGenerator::default();
generator.add::<FirstConfig>();
generator.add::<SecondConfig>();
generator.add::<ThirdConfig>();
generator.generate(PathBuf::from("output/file"), CustomRenderer::default())?;
generator.generate(PathBuf::from("output/another/file"), AnotherRenderer::default())?;
}

To keep the output in memory instead, such as to compare it, or write it somewhere other than a file, call SchemaGenerator::render(), which returns it as a string.

#![allow(unused)]
fn main() {
let output = generator.render(CustomRenderer::default())?;
}

Renderers

The following built-in renderers are available, but custom renderers can be created as well by implementing the SchemaRenderer trait.

Custom renderers

A custom renderer implements is_reference, which says whether a named type is rendered by reference, and render, which renders every collected schema. Each render_* method, one per type, defaults to an error naming the renderer and the type, so only the types a renderer supports need implementing.

#![allow(unused)]
fn main() {
use schematic::schema::{RenderResult, Schema, SchemaRenderer, StringType, StructType};

struct CustomRenderer;

impl SchemaRenderer for CustomRenderer {
	fn is_reference(&self, _name: &str) -> bool {
		false
	}

	fn render_string(&mut self, _string: &StringType, _schema: &Schema) -> RenderResult {
		Ok("string".into())
	}

	fn render_struct(&mut self, structure: &StructType, _schema: &Schema) -> RenderResult {
		// ...
	}

	fn render(&mut self, schemas: IndexMap<String, Schema>) -> RenderResult {
		// ...
	}
}
}

A tagged enum variant defaults to rendering as the struct serde writes for it, so a renderer only implements render_tagged to render each tag format itself.

A renderer whose types render to something other than a string, like the JSON schema renderer, sets the trait’s type parameter, as in SchemaRenderer<schemars::Schema>, while render always returns a string. A helper that takes any renderer is generic over both, like fn emit<O, R: SchemaRenderer<O>>(renderer: R).

API documentation

Requires the renderer_api_docs Cargo feature.

With our ApiDocsRenderer, you can generate markdown API documentation for all types that implement Schematic. Each type becomes its own page, describing every property or variant, and linking to the pages of the types it references.

To utilize, instantiate a generator, add types to render, and generate the output file.

#![allow(unused)]
fn main() {
use schematic::schema::{SchemaGenerator, ApiDocsRenderer};

let mut generator = SchemaGenerator::default();
generator.add::<CustomType>();
generator.generate(output_dir.join("CustomType.md"), ApiDocsRenderer::default())?;
}

One page per type

Like a JSON schema, each render produces a single document, and the last type to be added to SchemaGenerator is the one rendered. Every other type in the generator is known to the renderer, so a property whose type is one of them links to that type’s page. A composite type, such as a list of a config, is rendered as code, which cannot hold a link, so the types it refers to are linked in a references row of their own.

To generate a page for every type at once, including the ones that were added by nesting, use ApiDocsRenderer::generate_all() with an output directory instead. It writes a page per type, named after the type with a .md extension, along with an index page.

#![allow(unused)]
fn main() {
let mut generator = SchemaGenerator::default();
generator.add::<RootConfig>();

ApiDocsRenderer::default().generate_all(&generator, output_dir.join("config"))?;
}

The file_extension option changes the extension, for tools that expect another, such as MDX. Links are rendered separately, so pair it with a render_link that points at the same files, and an index_page if the index should match.

#![allow(unused)]
fn main() {
ApiDocsRenderer::new(ApiDocsOptions {
	file_extension: "mdx".into(),
	index_page: Some("index.mdx".into()),
	render_link: Box::new(|name| format!("[`{name}`](./{name}.mdx)")),
	..ApiDocsOptions::default()
})
.generate_all(&generator, output_dir.join("config"))?;
}

To control each page individually, generate them one at a time. Adding a type that is already in the generator, because an earlier type nested it, moves it to the end, so add each one before generating its file.

#![allow(unused)]
fn main() {
generator.add::<RootConfig>();
generator.generate(output_dir.join("RootConfig.md"), ApiDocsRenderer::default())?;

// Nested by `RootConfig`, so already in the generator
generator.add::<NestedConfig>();
generator.generate(output_dir.join("NestedConfig.md"), ApiDocsRenderer::default())?;
}

By default links are relative, so all pages are expected to live in the same directory, and to be named after the type they document, which is what generate_all produces. The render_link option changes that, and a custom link should agree with wherever the pages are written.

Index page

generate_all also writes an index page, a table of every type that links to its page, with its kind and the first paragraph of its description.

---
title: Index
---

## Types

| Type | Kind | Description |
| --- | --- | --- |
| [`ServerConfig`](./ServerConfig.md) | Struct | Configures the HTTP server. |
| [`TlsConfig`](./TlsConfig.md) | Struct | TLS settings, when serving over HTTPS. |

The index_page option names the file, and None skips it. When generating pages one at a time, ApiDocsRenderer::render_index_page() renders the same content from the generator’s schemas.

#![allow(unused)]
fn main() {
ApiDocsOptions {
	// ...
	index_page: Some("README.md".into()),
}
}

Page structure

A page starts with frontmatter that titles it after the type, followed by the type’s description, and an index that summarizes every section to come, linking to each. A struct then lists its properties, and an enum lists its variants, headed by the variant name. A union that was built by hand has no variant names, so each of its variants is headed by its type instead. Types that are referenced from the page are listed at the end.

---
title: ServerConfig
---

Configures the HTTP server.

## Index

| Property        | Type                          | Description                            |
| --------------- | ----------------------------- | -------------------------------------- |
| [`port`](#port) | `number`                      | The port to listen on.                 |
| [`tls`](#tls)   | [`TlsConfig`](./TlsConfig.md) | TLS settings, when serving over HTTPS. |

## Properties

### `port`

> **Optional**

The port to listen on.

| Attribute            | Value         |
| -------------------- | ------------- |
| Type                 | `number`      |
| Default              | `8080`        |
| Minimum              | `1024`        |
| Environment variable | `SERVER_PORT` |

### `tls`

> **Nullable**

TLS settings, when serving over HTTPS.

| Attribute | Value                         |
| --------- | ----------------------------- |
| Type      | [`TlsConfig`](./TlsConfig.md) |

## References

- [`TlsConfig`](./TlsConfig.md)

The tags after a name describe how a property may be provided: whether it is required or optional, nullable, deprecated (with the deprecation message when there is one), read only, write only, or flattened into its parent. Enum variants are tagged with whether they are the default.

A line of a doc comment that starts with @ is a tag too, and is left out of the description. A @since line declares the version it was added in, a @deprecated line deprecates it (unless it’s deprecated already), and any other, such as @experimental, is labelled by its name. These follow the tags above, in the order they were written. A line within a fenced code block is never a tag.

#![allow(unused)]
fn main() {
/// Enables the cache.
/// @since 1.2.0
/// @experimental
cache: bool,
}
> **Required** · **Since** (1.2.0) · **Experimental**

Enables the cache.

The table describes the type itself: its shape, default value, accepted values, constraints such as minimums and patterns, aliases, and the environment variable it can be set with.

Options

Custom options can be passed to the renderer using ApiDocsOptions.

#![allow(unused)]
fn main() {
use schematic::schema::ApiDocsOptions;

ApiDocsRenderer::new(ApiDocsOptions {
	// ...
	..ApiDocsOptions::default()
});
}

Frontmatter

Each page opens with frontmatter that titles it after the type. Documentation tools often read more from it, such as a sidebar position or a label, which the frontmatter map adds as key: value lines after the title, in key order. Values are written verbatim, so quote them as the tool expects. A title entry replaces the type name.

#![allow(unused)]
fn main() {
use std::collections::BTreeMap;

ApiDocsOptions {
	// ...
	frontmatter: BTreeMap::from_iter([
		("sidebar_position".into(), "2".into()),
		("description".into(), "\"Configures the server.\"".into()),
	]),
}
}

The renderer is created for each page, so per-type values can be set when generating that type.

Custom anchors

Each index entry links to its section by a fragment, rendered from the heading text by the render_anchor function. The default follows the GitHub convention that most documentation tools share, lowercasing the text, removing punctuation, and hyphenating spaces, so the heading `expand_array` is linked as #expand_array. A tool that ids headings differently needs the function to match it.

#![allow(unused)]
fn main() {
ApiDocsOptions {
	// ...
	render_anchor: Box::new(|heading| format!("prop-{}", heading.replace('_', "-"))),
}
}

Links to other pages are rendered by the render_link function, which receives the name of the referenced type and returns the whole link, label included. The default labels the link with the name as inline code and links to a markdown file named after the type in the same directory, such as [`Name`](./Name.md). Documentation tools that route on a path rather than a file, pages split across directories, or a site with its own link component can return whatever they need. The same function renders the inline links and the references list.

#![allow(unused)]
fn main() {
ApiDocsOptions {
	// ...
	render_link: Box::new(|name| format!("<Link to=\"/docs/config/{name}\">{name}</Link>")),
}
}

Enum format

A unit enum renders a section per variant, which is thorough but long for an enum with many variants. The enum_format option can render them as a single table instead, one row per variant with its value, tags, and description. The index is omitted for it, as the table already summarizes every variant. Unions always render as sections, since their variants carry values that need describing.

#![allow(unused)]
fn main() {
use schematic::schema::ApiDocsEnumFormat;

ApiDocsOptions {
	// ...
	enum_format: ApiDocsEnumFormat::Table,
}
}
## Variants

| Variant | Value     | Tags                                 | Description            |
| ------- | --------- | ------------------------------------ | ---------------------- |
| `debug` | `"debug"` |                                      | Log everything.        |
| `info`  | `"info"`  | **Default**                          | Log at info and above. |
| `off`   | `"off"`   | **Deprecated** (Use `none` instead.) | Disable logging.       |

Tags in the table are rendered as labels, not through the render_tags function, as its output is a block that cannot sit inside a table cell.

Index

The index ahead of the properties or variants shows each one’s type and the first paragraph of its description. Disable it with the include_index option.

#![allow(unused)]
fn main() {
ApiDocsOptions {
	// ...
	include_index: false,
}
}

Required fields

When a struct is rendered, fields that are not optional, nullable, or flattened are tagged as required. This is enabled by default.

#![allow(unused)]
fn main() {
ApiDocsOptions {
	// ...
	mark_struct_fields_required: false,
}
}

Custom tags

Tags are rendered by the render_tags function, which receives the tags of a type, property, or variant as a list of ApiDocsTag values, and returns markdown. The default renders a block quote of bold labels, with the value a tag carries, such as a deprecation message or a version, in parentheses after its label. A documentation site may prefer its own components.

#![allow(unused)]
fn main() {
use schematic::schema::ApiDocsTag;

ApiDocsOptions {
	// ...
	render_tags: Box::new(|tags| {
		tags.iter()
			.map(|tag| match tag.value() {
				Some(value) => format!("<Badge>{tag}</Badge> {value}"),
				None => format!("<Badge>{tag}</Badge>"),
			})
			.collect::<Vec<_>>()
			.join(" ")
	}),
}
}

The function is only called when there is at least one tag, and returning an empty string omits the tags entirely.

Custom descriptions

Descriptions are rendered by the render_description function, which receives the doc comment as written, without its tags, and returns markdown. The default keeps the comment as is, only trimming each line. Use this to wrap descriptions in a component, or to rewrite links.

#![allow(unused)]
fn main() {
ApiDocsOptions {
	// ...
	render_description: Box::new(|description| format!(":::note\n{}\n:::", description.trim())),
}
}

Returning an empty string omits the description.

Aliases

A field’s aliases are listed in its table. Disable this with the exclude_aliases option.

#![allow(unused)]
fn main() {
ApiDocsOptions {
	// ...
	exclude_aliases: true,
}
}

Config templates (experimental)

Requires the renderer_template and desired format Cargo feature.

With our format renderers, you can generate a config template in a specific format. This template will include all fields, default values, comments, metadata, and is useful for situations like scaffolding files during installation.

To utilize, instantiate a generator, add types to render, and generate the output file.

#![allow(unused)]
fn main() {
use schematic::schema::SchemaGenerator;

let mut generator = SchemaGenerator::default();
generator.add::<CustomType>();
generator.generate(output_dir.join("config.json"), renderer)?;
}

Supported formats

JSON

The JsonTemplateRenderer will render JSON templates without comments. Any commented related options will be force disabled.

#![allow(unused)]
fn main() {
use schematic::schema::{JsonTemplateRenderer, TemplateOptions};

JsonTemplateRenderer::default();
JsonTemplateRenderer::new(TemplateOptions::default());
}

JSONC

The JsoncTemplateRenderer will render JSON templates with comments. We suggest using the .jsonc file extension, but not required.

#![allow(unused)]
fn main() {
use schematic::schema::{JsoncTemplateRenderer, TemplateOptions};

JsoncTemplateRenderer::default();
JsoncTemplateRenderer::new(TemplateOptions::default());
}

Pkl

The PklTemplateRenderer will render Pkl templates.

#![allow(unused)]
fn main() {
use schematic::schema::{PklTemplateRenderer, TemplateOptions};

PklTemplateRenderer::default();
PklTemplateRenderer::new(TemplateOptions::default());
}

A template can amend the Pkl modules of its types, so that Pkl type checks it, by adding an amends clause to the header option. The modules then type every property, so lists and maps amend the values they’re declared with, as in tags { "web" }, which gives the objects within them their declared type. Without one, lists and maps are created with new Listing {} and new Mapping {}.

#![allow(unused)]
fn main() {
PklTemplateRenderer::new(TemplateOptions {
	header: "amends \"pkl/ServerConfig.pkl\"\n\n".into(),
	..TemplateOptions::default()
});
}

A module with required fields expects the template to set them, so render the modules with mark_struct_fields_required disabled when fields are hidden or commented out.

TOML

The TomlTemplateRenderer will render TOML templates.

#![allow(unused)]
fn main() {
use schematic::schema::{TomlTemplateRenderer, TemplateOptions};

TomlTemplateRenderer::default();
TomlTemplateRenderer::new(TemplateOptions::default());
}

YAML

The YamlTemplateRenderer will render YAML templates.

#![allow(unused)]
fn main() {
use schematic::schema::{YamlTemplateRenderer, TemplateOptions};

YamlTemplateRenderer::default();
YamlTemplateRenderer::new(TemplateOptions::default());
}

Root document

A template represents a single document, typically for a struct. In Schematic, the last type to be added to SchemaGenerator will be the root document, while all other types will be ignored. For example:

#![allow(unused)]
fn main() {
// These are only used for type information
generator.add::<FirstConfig>();
generator.add::<SecondConfig>();
generator.add::<ThirdConfig>();

// This is the root document
generator.add::<LastType>();
generator.generate(output_dir.join("config.json"), renderer)?;
}

Caveats

By default arrays and objects do not support default values, and will render [] and {} respectively. This can be customized with the expand_fields option.

Furthermore, enums and unions only support default values when explicitly marked as such. For example, with #[default].

When we’re unsure of what to render for a value, we’ll render null. This isn’t a valid value for TOML, and may not be what you expect.

An externally tagged enum’s default variant, when it holds a value, is rendered as a map of its name to the value, which a YAML config can’t load, as YAML only reads it from a tag, like !file (more). Prefer an internally tagged enum for a YAML config.

A flattened struct’s settings are rendered alongside the struct’s own, as serde reads them, rather than under the field that holds it. In TOML, that means they’re part of the same table. A flattened map collects keys that a template has no names for, so it renders nothing.

Example output

Given the following type:

#![allow(unused)]
fn main() {
#[derive(Config)]
struct ServerConfig {
	/// The base URL to serve from.
	#[setting(default = "/")]
	pub base_url: String,

	/// The default port to listen on.
	#[setting(default = 8080, env = "PORT")]
	pub port: usize,
}
}

Would render the following formats:

JSONC Pkl
{
	// The base URL to serve from.
	"base_url": "/",

	// The default port to listen on.
	// @env PORT
	"port": 8080
}
// The base URL to serve from.
base_url = "/"

// The default port to listen on.
// @env PORT
port = 8080

TOML YAML
# The base URL to serve from.
base_url = "/"

# The default port to listen on.
# @env PORT
port = 8080
# The base URL to serve from.
base_url: "/"

# The default port to listen on.
# @env PORT
port: 8080

Applying the desired casing for field names should be done with serde rename_all on the container.

Options

Custom options can be passed to the renderer using TemplateOptions.

#![allow(unused)]
fn main() {
use schematic::schema::TemplateOptions;

JsoncTemplateRenderer::new(TemplateOptions {
	// ...
	..TemplateOptions::default()
});
}

The format option is required!

Indentation

The indentation of the generated template can be customized using the indent_char option. By default this is 2 spaces ( ).

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	indent_char: "\t".into(),
}
}

The spacing between fields can also be toggled with the newline_between_fields option. By default this is enabled, which adds a newline between each field.

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	newline_between_fields: false,
}
}

Comments

All Rust doc comments (///) are rendered as comments above each field in the template. This can be disabled with the comments option.

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	comments: false,
}
}

The header and footer options can be customized to add additional content to the top and bottom of the rendered template respectively.

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	header: "$schema: \"https://example.com/schema.json\"\n\n".into(),
	footer: "\n\n# Learn more: https://example.com".into(),
}
}

Field display

By default all non-skipped fields in the root document (struct) are rendered in the template. If you’d like to hide certain fields from being rendered, you can use the hide_fields option. This option accepts a list of field names and also supports dot-notation for nested fields.

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	hide_fields: vec!["key".into(), "nested.key".into()],
}
}

Alternatively, you can choose to only render specific fields with only_fields.

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	only_fields: vec!["key".into(), "nested.key".into()],
}
}

And lastly, if you’d like to render a field but have it commented out by default, use the comment_fields option instead. This also supports dot-notation for nested fields.

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	comment_fields: vec!["key".into(), "nested.key".into()],
}
}

Field names use the serde cased name, not the Rust struct field name.

Field expansion

For arrays and objects, we render an empty value ([] or {}) by default because there’s no actual data associated with the schema. However, if you’d like to render a single example item for a field, you can use the expand_fields option.

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	expand_fields: vec!["key".into(), "nested.key".into()],
}
}

Here’s an example of how this works:

Not expanded Expanded
{
	"proxies": []
}
{
	"proxies": [
		// An example proxy configuration.
		{
			"host": "",
			"port": 8080
		}
	]
}

Custom values

If you need more control of what gets rendered for a specific field, you can use the custom_values option. This option accepts a map of field names to custom values (schemas), and will take priority over default and empty values. Dot-notation for nested fields is also supported.

Using the example output above, we can override the port field to render 3000 instead of 8080 like so:

#![allow(unused)]
fn main() {
TemplateOptions {
	// ...
	custom_values: HashMap::from_iter([
		("port".into(), Schema::integer(IntegerType::new_unsigned(IntegerKind::Usize, 3000)))
	]),
}
}

If the custom schema type does not match the field type, it will trigger a panic.

JSON schemas

Requires the renderer_json_schema Cargo feature.

With our JsonSchemaRenderer, you can generate a JSON Schema document for all types that implement Schematic. Internally this renderer uses the schemars crate to generate the JSON document.

To utilize, instantiate a generator, add types to render, and generate the output file.

#![allow(unused)]
fn main() {
use schematic::schema::{SchemaGenerator, JsonSchemaRenderer};

let mut generator = SchemaGenerator::default();
generator.add::<CustomType>();
generator.generate(output_dir.join("schema.json"), JsonSchemaRenderer::default())?;
}

For a reference implementation, check out moonrepo/moon.

Root document

Unlike other renderers, a JSON schema represents a single document, with referenced types being organized into definitions. In Schematic, the last type to be added to SchemaGenerator will be the root document, while all other types will become definitions. For example:

#![allow(unused)]
fn main() {
// These are definitions
generator.add::<FirstConfig>();
generator.add::<SecondConfig>();
generator.add::<ThirdConfig>();

// This is the root document
generator.add::<LastType>();
generator.generate(output_dir.join("schema.json"), JsonSchemaRenderer::default())?;
}

When rendered, will look something like the following:

{
	"$schema": "http://json-schema.org/draft-07/schema#",
	"title": "LastType",
	"type": "object",
	"properties": {
		// Fields in LastType...
	},
	"definitions": {
		// Other types...
	}
}

Options

Custom options can be passed to the renderer using JsonSchemaOptions.

#![allow(unused)]
fn main() {
use schematic::schema::JsonSchemaOptions;

JsonSchemaRenderer::new(JsonSchemaOptions {
	// ...
	..JsonSchemaOptions::default()
});
}

This type also carries some fields from the upstream SchemaSettings type in the schemars crate — meta_schema, transforms, and inline_subschemas. Refer to their documentation for more information.

definitions_path is the prefix each $ref is built from, such as #/definitions/. Schemars models its own field of that name as a JSON pointer instead, so the two are not interchangeable.

Markdown descriptions

By default, the description field in the JSON schema specification is supposed to be a plain text string, but some tools support markdown through another field called markdownDescription.

To support this pattern, enable the markdown_description option, which will inject the markdownDescription field if markdown was detected in the description field.

#![allow(unused)]
fn main() {
JsonSchemaOptions {
	// ...
	markdown_description: true,
}
}

This is a non-standard extension to the JSON schema specification.

Required fields

When a struct is rendered, automatically mark every struct field that may not be omitted as required, which is any that isn’t optional, and include them in the JSON schema required field. This is enabled by default.

#![allow(unused)]
fn main() {
JsonSchemaOptions {
	// ...
	mark_struct_fields_required: false,
}
}

Field titles

The JSON schema specification supports a title annotation for each field, which is a human-readable string. By default this is the name of the Rust struct, enum, or type field.

But depending on the tool that consumes the schema, this may not be the best representation. As an alternative, the set_field_name_as_title option can be enabled to use the field name itself as the title.

#![allow(unused)]
fn main() {
JsonSchemaOptions {
	// ...
	set_field_name_as_title: true,
}
}

Pkl modules

Requires the renderer_pkl_schema Cargo feature.

With our PklSchemaRenderer, you can generate Pkl modules for all types that implement Schematic. Each struct becomes its own module, and each enum a type alias, with its Rust types converted to Pkl types, so that a Pkl config can amend it and be type checked by Pkl itself.

To utilize, instantiate a generator, add types to render, and generate a module for every type into a directory. Modules import each other by relative path, so they must stay together.

#![allow(unused)]
fn main() {
use schematic::schema::{SchemaGenerator, PklSchemaRenderer};

let mut generator = SchemaGenerator::default();
generator.add::<ServerConfig>();

PklSchemaRenderer::default().generate_all(&generator, output_dir.join("pkl"))?;
}

Each module is named after its type with a .pkl extension, so the above writes ServerConfig.pkl, and a module for every struct it nests. A config then amends the module of its root type.

amends "pkl/ServerConfig.pkl"

port = 3000
timeout = 30.s
tags { "web"; "api" }

To scaffold that config, render a Pkl template with an amends clause in its header.

Like a JSON schema, rendering through SchemaGenerator::generate() produces a single document, which is the module of the last type to be added to SchemaGenerator. The modules it imports are not written, so prefer generate_all().

Module structure

A struct becomes a module that declares each of its fields as a property, with its doc comment and deprecation carried over. Fields are rendered in alphabetical order, and skipped fields are omitted.

/// Configures the HTTP server.
module ServerConfig

import "TlsConfig.pkl"

/// The level to log at.
level: LogLevel

/// The port to listen on.
@Since { version = "1.2.0" }
port: UInt16 = 8080

/// TLS settings, when serving over HTTPS.
tls: TlsConfig?

/// The level to log at.
typealias LogLevel = *"info" | "debug" | "error"

A @since line in a doc comment becomes a @Since annotation, which is how Pkl declares the version a member was added in, and a deprecation, or a @deprecated line, becomes a @Deprecated annotation. Any other line that starts with @ stays in the doc comment, after its description.

A module is a type, but it can’t be a union or a string, so every other type, such as an enum, becomes a type alias of the same name, which each module that uses it declares, after its properties. An alias that only another alias uses is declared alongside that one. The default variant of an enum is marked with *, which makes it the default of any property of that type that isn’t nullable.

An alias is declared by a module of its own instead, referenced as Name.Name, when no other module can declare it:

  • It’s a type that was added to the generator, rather than one that a struct nests.
  • It declares classes, and more than one module uses it. A class is a distinct type in each module that declares it.
  • It refers to a module that uses it, as a module can’t refer to itself by name.
  • It shares its name with a property, or with one of Pkl’s base types, such as Duration.

A struct without a name of its own, such as a variant of a tagged enum, becomes a class in the module it’s found in, named after its position, such as ActionRun for the Run variant of Action. A class is referenced from other modules as Module.Class.

typealias Action = "Stop" | ActionRun

class ActionRun {
  Run: String
}

Inheritance

A struct that flattens another struct with #[serde(flatten)] includes all of its fields, which is what extending a module does. Its module extends the module of the flattened struct, which is then declared open, as Pkl requires to extend it.

open module BaseConfig

shared: String = "shared"
module ServerConfig

extends "BaseConfig.pkl"

port: UInt16 = 8080

When the struct declares nothing but the flattened field, it has the same shape as the struct it flattens, so its module amends that module instead. Pkl can’t use a module that amends another as a type, so this only happens when no other type refers to the struct.

A module can only extend one other, so any further flattened structs have their fields declared directly.

A class extends the module of a struct it flattens in the same way. An internally tagged variant holding a struct is written as that struct with the tag beside it, so its class extends the struct’s module, and only declares the tag itself.

import "FileSource.pkl"
import "GitSource.pkl"

typealias Source = SourceGit | SourceFile

class SourceGit extends GitSource {
  type: "git"
}

class SourceFile extends FileSource {
  type: "file"
}

Other settings

A flattened map collects every setting a struct doesn’t declare, such as the configuration of a plugin. A typed Pkl object only accepts the properties its type declares, so no type can hold such a struct. Wherever it’s used, it’s typed as Dynamic instead, which accepts any property.

/// Configures a plugin.
plugin: Dynamic?
plugin {
  version = "1.0"
  manager = "pnpm"
}

Its module is declared open, with a comment naming the map. A config can’t declare new properties while amending a module, but it can while extending one, so a config of that struct extends its module.

extends "pkl/PluginsConfig.pkl"

registry = "https://registry.example.com"
node { version = "20" }

Types

Rust types are converted to their closest Pkl types, and constraints, such as a minimum or a pattern, become type constraints.

RustPkl
boolBoolean
i8, i16, i32Int8, Int16, Int32
i64, i128, isizeInt
u8, u16, u32UInt8, UInt16, UInt32
u64, u128, usizeUInt
f32, f64Float
charChar
String, PathBuf, Url, …String
Vec<T>Listing<T>
HashSet<T>, BTreeSet<T>Listing<T>(isDistinct)
[T; N]Listing<T>(length == N)
HashMap<K, V>, BTreeMap<K, V>Mapping<K, V>
(A, B)Pair<A, B>
(A, B, C, ...)Listing<A|B|C>(length == N)
Option<T>T?
std::time::DurationDuration
serde_json::Value, …Any
Unit-only enum"a"|"b"|"c"

Pair and Duration are decoded by the Pkl format into the same shapes as a Rust tuple and Duration, so timeout = 30.s loads as expected. Pkl’s own JSON and YAML renderers can’t output them without a converter, however.

Configuration is data, so lists and maps are typed as Pkl’s amendable objects, Listing and Mapping, which a config amends, as in tags { "web" }. Pkl’s eager collections, List, Set, and Map, are for computing values, such as concatenating two lists, and aren’t accepted where an object is. Convert one with toListing() or toMapping().

local shared = List("api")

tags = (List("web") + shared).toListing()

A union with a struct among its variants, such as an untagged enum, has no default to amend, and Pkl can’t tell which struct a new {} creates. Create the struct by its module instead.

import "pkl/TaskDependencyConfig.pkl"

deps { "build"; new TaskDependencyConfig { target = "~:lint"; optional = true } }

Aliases

Pkl outputs every property, and serde rejects a setting that’s given under both its name and an alias, so an alias is declared hidden, which Pkl doesn’t output. The setting falls back to its alias, so setting either one outputs the setting under its name.

/// The default value of the variable.
default: Boolean? = defaultValue

/// An alias of `default`.
hidden defaultValue: Boolean?

A setting that isn’t nullable would lose the default of its type by falling back, so only a nullable setting declares its aliases.

A few things can’t be expressed in Pkl, and are rendered as close as possible:

  • A setting named output can’t be declared by a module, as every module reserves it. It is left out, with a comment in its place.
  • Pkl rejects a type alias that refers to itself, so a recursive enum refers to itself as Any. A recursive struct refers to its own module, which is fine.
  • A tuple of more than two values can only be typed as a list of each of its types, so the position of each type isn’t checked.

Options

Custom options can be passed to the renderer using PklSchemaOptions.

#![allow(unused)]
fn main() {
use schematic::schema::PklSchemaOptions;

PklSchemaRenderer::new(PklSchemaOptions {
	// ...
	..PklSchemaOptions::default()
});
}

Indentation

The indentation of class properties can be customized using the indent_char option. By default this is 2 spaces.

#![allow(unused)]
fn main() {
PklSchemaOptions {
	// ...
	indent_char: "\t".into(),
}
}

Required fields

By default, struct fields are rendered as they are declared. A field that isn’t optional has no default, so a config must set it, and a field with a default value renders it as the property’s default.

Pkl outputs every property of a module, including the defaults a config didn’t set. A config is only one layer of many however, so a default it outputs overrides the value of any layer beneath it, such as a config it extends. Disable the mark_struct_fields_required option to render every property of a struct’s module as nullable, without a default, so that a config only outputs the settings it sets, and everything else falls back to the defaults of the Rust types.

#![allow(unused)]
fn main() {
PklSchemaOptions {
	// ...
	mark_struct_fields_required: false,
}
}
// Enabled
port: UInt16 = 8080
host: String

// Disabled
port: UInt16?
host: String?

This only applies to structs that are loaded as partials, which is what makes their settings optional. A struct that’s loaded in full, such as the value of a setting that isn’t nested, or a type that doesn’t derive Config, can’t take null for a field that isn’t an Option, so it’s always rendered as declared. Classes, such as the variants of an enum, are too, as their value is only valid in full, though a class that extends a struct’s module inherits its properties as that module declares them.

Rendering partial types has the same effect, as every field of a partial is optional, but names every module after its partial type.

TypeScript types

Requires the renderer_typescript Cargo feature.

With our TypeScriptRenderer, you can generate TypeScript types for all types that implement Schematic. To utilize, instantiate a generator, add types to render, and generate the output file.

#![allow(unused)]
fn main() {
use schematic::schema::{SchemaGenerator, TypeScriptRenderer};

let mut generator = SchemaGenerator::default();
generator.add::<CustomType>();
generator.generate(output_dir.join("types.ts"), TypeScriptRenderer::default())?;
}

For a reference implementation, check out moonrepo/moon.

Options

Custom options can be passed to the renderer using TypeScriptOptions.

#![allow(unused)]
fn main() {
use schematic::schema::TypeScriptOptions;

TypeScriptRenderer::new(TypeScriptOptions {
	// ...
	..TypeScriptOptions::default()
});
}

Indentation

The indentation of the generated TypeScript code can be customized using the indent_char option. By default this is a tab (\t).

#![allow(unused)]
fn main() {
TypeScriptOptions {
	// ...
	indent_char: "  ".into(),
}
}

Enum types

Enum types can be rendered in a format of your choice using the enum_format option and the EnumFormat enum. By default enums are rendered as TypeScript string unions, but can be rendered as TypeScript enums instead.

#![allow(unused)]
fn main() {
TypeScriptOptions {
	// ...
	enum_format: EnumFormat::Enum,
}
}
// Default
export type LogLevel = "debug" | "info" | "error";

// As enum
export enum LogLevel {
	Debug,
	Info,
	Error,
}

Furthermore, the const_enum option can be enabled to render const enum types instead of enum types. This does not apply when EnumFormat::Union is used.

#![allow(unused)]
fn main() {
TypeScriptOptions {
	// ...
	const_enum: true,
}
}
// Enabled
export const enum LogLevel {}

// Disabled
export enum LogLevel {}

Object types

Struct types can be rendered as either TypeScript interfaces or type aliases using the object_format option and the ObjectFormat enum. By default structs are rendered as TypeScript interfaces.

#![allow(unused)]
fn main() {
TypeScriptOptions {
	// ...
	object_format: ObjectFormat::Type,
}
}
// Default
export interface User {
	name: string;
}

// As alias
export type User = {
	name: string;
};

Properties format

Properties within a struct can be rendered as either optional or required in TypeScript, depending on usage. The default format for all properties can be customized with the property_format option and the PropertyFormat enum. By default a property is required, unless it’s optional: an Option, which serde fills in with None, or a setting with a default.

#![allow(unused)]
fn main() {
TypeScriptOptions {
	// ...
	property_format: PropertyFormat::Required,
}
}
// Default / required
export interface User {
	name: string;
}

// Optional
export interface User {
	name?: string;
}

// Optional with undefined union
export interface User {
	name?: string | undefined;
}

Type references

In the context of this renderer, a type reference is simply a reference to another type by its name, and is used by other types of another name. For example, the fields of a struct type may reference another type by name.

export type UserStatus = "active" | "inactive";

export interface User {
	status: UserStatus;
}

Depending on your use case, this may not be desirable. If so, you can enable the disable_references option, which disables references entirely, and inlines all type information. So the example above would become:

#![allow(unused)]
fn main() {
TypeScriptOptions {
	// ...
	disable_references: true,
}
}
export type UserStatus = "active" | "inactive";

export interface User {
	status: "active" | "inactive";
}

Additionally, the exclude_references option can be used to exclude a type reference by name entirely from the output, as demonstrated below.

#![allow(unused)]
fn main() {
TypeScriptOptions {
	// ...
	exclude_references: vec!["UserStatus".into()],
}
}
export interface User {
	status: "active" | "inactive";
}

Importing external types

For better interoperability, you can import external types from other TypeScript modules using the external_types option, which is a map of file paths (relative from the output location) to a list of types to import from that file. This is useful if:

  • You have existing types that aren’t generated and want to reference.
  • You want to reference types from other generated files, and don’t want to duplicate them.
#![allow(unused)]
fn main() {
TypeScriptOptions {
	// ...
	external_types: HashMap::from_iter([
		("./states".into(), vec!["UserStatus".into()]),
	]),
}
}
import type { UserStatus } from "./states";

export interface User {
	status: UserStatus;
}