use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::sync::Arc;
use serde::Serialize;
use crate::Recipient;
use crate::defaults::DefaultTemplate;
#[derive(Debug, Clone, PartialEq)]
pub enum Node {
Text,
Number,
Bool,
Date,
Recipient,
Optional(Box<Node>),
List(Box<Node>),
Object(Vec<Field>),
Any,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Field {
pub name: &'static str,
pub description: &'static str,
pub node: Node,
}
impl Field {
#[must_use]
pub fn new(name: &'static str, description: &'static str, node: Node) -> Self {
Self {
name,
description,
node,
}
}
}
impl Node {
#[must_use]
pub fn required(&self) -> &Node {
match self {
Node::Optional(inner) => inner.required(),
other => other,
}
}
#[must_use]
pub fn fields(&self) -> Option<Vec<Field>> {
match self.required() {
Node::Object(fields) => Some(fields.clone()),
Node::Recipient => Some(recipient_fields()),
_ => None,
}
}
#[must_use]
pub fn type_name(&self) -> &'static str {
match self.required() {
Node::Text => "text",
Node::Number => "number",
Node::Bool => "bool",
Node::Date => "date",
Node::Recipient => "recipient",
Node::List(_) => "list",
Node::Object(_) => "object",
Node::Any | Node::Optional(_) => "any",
}
}
}
fn recipient_fields() -> Vec<Field> {
vec![
Field::new("email", "Email address", Node::Text),
Field::new("name", "Name", Node::Optional(Box::new(Node::Text))),
Field::new(
"locale",
"Preferred language, such as `uk` or `en`",
Node::Optional(Box::new(Node::Text)),
),
]
}
pub trait Describe {
fn describe() -> Node;
}
macro_rules! describe_as {
($node:expr => $($ty:ty),* $(,)?) => {
$(impl Describe for $ty {
fn describe() -> Node {
$node
}
})*
};
}
describe_as!(Node::Text => String, str, char, std::borrow::Cow<'_, str>);
describe_as!(Node::Number => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64);
describe_as!(Node::Bool => bool);
describe_as!(Node::Recipient => Recipient);
describe_as!(Node::Any => serde_json::Value);
describe_as!(Node::Date => laravel::time::Timestamp, laravel::time::ZonedDateTime, laravel::time::civil::Date,
laravel::time::civil::DateTime, chrono::NaiveDate, chrono::NaiveDateTime);
impl<Tz: chrono::TimeZone> Describe for chrono::DateTime<Tz> {
fn describe() -> Node {
Node::Date
}
}
impl<T: Describe + ?Sized> Describe for &T {
fn describe() -> Node {
T::describe()
}
}
impl<T: Describe + ?Sized> Describe for Box<T> {
fn describe() -> Node {
T::describe()
}
}
impl<T: Describe + ?Sized> Describe for Arc<T> {
fn describe() -> Node {
T::describe()
}
}
impl<T: Describe> Describe for Option<T> {
fn describe() -> Node {
Node::Optional(Box::new(T::describe()))
}
}
macro_rules! describe_list {
($($ty:ty),*) => {
$(impl<T: Describe> Describe for $ty {
fn describe() -> Node {
Node::List(Box::new(T::describe()))
}
})*
};
}
describe_list!(Vec<T>, [T], VecDeque<T>, BTreeSet<T>, HashSet<T>);
impl<T: Describe, const N: usize> Describe for [T; N] {
fn describe() -> Node {
Node::List(Box::new(T::describe()))
}
}
impl<K, V: Describe> Describe for BTreeMap<K, V> {
fn describe() -> Node {
Node::Any
}
}
impl<K, V: Describe, S> Describe for HashMap<K, V, S> {
fn describe() -> Node {
Node::Any
}
}
pub trait TemplateType: Describe + serde::Serialize + Send + Sync + 'static {
const KEY: &'static str;
const DESCRIPTION: &'static str;
fn example() -> Self;
fn defaults() -> Vec<DefaultTemplate>;
}
#[derive(Debug, Clone)]
pub struct TypeInfo {
pub key: &'static str,
pub description: &'static str,
pub variables: Vec<Field>,
pub(crate) example: fn() -> serde_json::Result<serde_json::Value>,
pub(crate) defaults: fn() -> Vec<DefaultTemplate>,
}
impl TypeInfo {
pub fn example(&self) -> laravel::Result<serde_json::Value> {
(self.example)()
.map_err(|e| laravel::Error::msg(format!("the example of `{}` doesn't serialize: {e}", self.key)))
}
#[must_use]
pub fn defaults(&self) -> Vec<DefaultTemplate> {
(self.defaults)()
}
#[must_use]
pub fn recipients(&self) -> Vec<String> {
let mut paths = Vec::new();
collect_recipients(&self.variables, "", &mut paths);
paths
}
#[must_use]
pub fn variable(&self, path: &str) -> Option<Node> {
let mut node = Node::Object(self.variables.clone());
for part in path.split('.') {
let fields = node.fields()?;
node = fields.into_iter().find(|f| f.name == part)?.node;
}
Some(node)
}
pub fn to_json(&self) -> laravel::Result<serde_json::Value> {
Ok(serde_json::json!({
"key": self.key,
"description": self.description,
"variables": fields_json(&self.variables, ""),
"recipients": self.recipients(),
"example": self.example()?,
}))
}
}
fn collect_recipients(fields: &[Field], prefix: &str, paths: &mut Vec<String>) {
for field in fields {
let path = join(prefix, field.name);
match field.node.required() {
Node::Recipient => paths.push(path),
Node::List(item) if *item.required() == Node::Recipient => paths.push(path),
Node::Object(inner) => collect_recipients(inner, &path, paths),
_ => {}
}
}
}
pub(crate) fn join(prefix: &str, name: &str) -> String {
if prefix.is_empty() {
name.to_owned()
} else {
format!("{prefix}.{name}")
}
}
#[derive(Serialize)]
struct FieldJson {
name: &'static str,
path: String,
#[serde(rename = "type")]
kind: &'static str,
description: &'static str,
optional: bool,
#[serde(skip_serializing_if = "Option::is_none")]
item: Option<Box<NodeJson>>,
#[serde(skip_serializing_if = "Option::is_none")]
fields: Option<Vec<FieldJson>>,
}
#[derive(Serialize)]
struct NodeJson {
#[serde(rename = "type")]
kind: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
item: Option<Box<NodeJson>>,
#[serde(skip_serializing_if = "Option::is_none")]
fields: Option<Vec<FieldJson>>,
}
fn fields_json(fields: &[Field], prefix: &str) -> Vec<FieldJson> {
fields
.iter()
.map(|field| {
let path = join(prefix, field.name);
let (item, fields) = children(&field.node, &path);
FieldJson {
name: field.name,
kind: field.node.type_name(),
description: field.description,
optional: matches!(field.node, Node::Optional(_)),
path,
item,
fields,
}
})
.collect()
}
fn children(node: &Node, path: &str) -> (Option<Box<NodeJson>>, Option<Vec<FieldJson>>) {
match node.required() {
Node::List(item) => {
let (inner_item, inner_fields) = children(item, "item");
let json = NodeJson {
kind: item.type_name(),
item: inner_item,
fields: inner_fields,
};
(Some(Box::new(json)), None)
}
other => (None, other.fields().map(|fields| fields_json(&fields, path))),
}
}
#[doc(hidden)]
pub struct Registration {
key: &'static str,
description: &'static str,
describe: fn() -> Node,
example: fn() -> serde_json::Result<serde_json::Value>,
defaults: fn() -> Vec<DefaultTemplate>,
}
impl Registration {
#[must_use]
pub const fn of<T: TemplateType>() -> Self {
Self {
key: T::KEY,
description: T::DESCRIPTION,
describe: T::describe,
example: example_of::<T>,
defaults: T::defaults,
}
}
pub(crate) fn info(&self) -> TypeInfo {
let variables = match (self.describe)() {
Node::Object(fields) => fields,
_ => Vec::new(),
};
TypeInfo {
key: self.key,
description: self.description,
variables,
example: self.example,
defaults: self.defaults,
}
}
}
fn example_of<T: TemplateType>() -> serde_json::Result<serde_json::Value> {
serde_json::to_value(T::example())
}
inventory::collect!(Registration);
#[must_use]
pub fn types() -> Vec<TypeInfo> {
let mut types: Vec<TypeInfo> = inventory::iter::<Registration>().map(Registration::info).collect();
types.sort_by_key(|t| t.key);
types.dedup_by_key(|t| t.key);
types
}
#[must_use]
pub fn find_type(key: &str) -> Option<TypeInfo> {
inventory::iter::<Registration>()
.find(|r| r.key == key)
.map(Registration::info)
}
#[must_use]
pub fn type_of<T: TemplateType>() -> TypeInfo {
Registration::of::<T>().info()
}