1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
4use std::sync::Arc;
5
6use serde::Serialize;
7
8use crate::Recipient;
9use crate::defaults::DefaultTemplate;
10
11#[derive(Debug, Clone, PartialEq)]
13pub enum Node {
14 Text,
16 Number,
18 Bool,
20 Date,
22 Recipient,
24 Optional(Box<Node>),
26 List(Box<Node>),
28 Object(Vec<Field>),
30 Any,
32}
33
34#[derive(Debug, Clone, PartialEq)]
36pub struct Field {
37 pub name: &'static str,
39 pub description: &'static str,
41 pub node: Node,
43}
44
45impl Field {
46 #[must_use]
48 pub fn new(name: &'static str, description: &'static str, node: Node) -> Self {
49 Self {
50 name,
51 description,
52 node,
53 }
54 }
55}
56
57impl Node {
58 #[must_use]
60 pub fn required(&self) -> &Node {
61 match self {
62 Node::Optional(inner) => inner.required(),
63 other => other,
64 }
65 }
66
67 #[must_use]
69 pub fn fields(&self) -> Option<Vec<Field>> {
70 match self.required() {
71 Node::Object(fields) => Some(fields.clone()),
72 Node::Recipient => Some(recipient_fields()),
73 _ => None,
74 }
75 }
76
77 #[must_use]
79 pub fn type_name(&self) -> &'static str {
80 match self.required() {
81 Node::Text => "text",
82 Node::Number => "number",
83 Node::Bool => "bool",
84 Node::Date => "date",
85 Node::Recipient => "recipient",
86 Node::List(_) => "list",
87 Node::Object(_) => "object",
88 Node::Any | Node::Optional(_) => "any",
89 }
90 }
91}
92
93fn recipient_fields() -> Vec<Field> {
94 vec![
95 Field::new("email", "Email address", Node::Text),
96 Field::new("name", "Name", Node::Optional(Box::new(Node::Text))),
97 Field::new(
98 "locale",
99 "Preferred language, such as `uk` or `en`",
100 Node::Optional(Box::new(Node::Text)),
101 ),
102 ]
103}
104
105pub trait Describe {
108 fn describe() -> Node;
110}
111
112macro_rules! describe_as {
113 ($node:expr => $($ty:ty),* $(,)?) => {
114 $(impl Describe for $ty {
115 fn describe() -> Node {
116 $node
117 }
118 })*
119 };
120}
121
122describe_as!(Node::Text => String, str, char, std::borrow::Cow<'_, str>);
123describe_as!(Node::Number => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64);
124describe_as!(Node::Bool => bool);
125describe_as!(Node::Recipient => Recipient);
126describe_as!(Node::Any => serde_json::Value);
127describe_as!(Node::Date => laravel::time::Timestamp, laravel::time::ZonedDateTime, laravel::time::civil::Date,
128 laravel::time::civil::DateTime, chrono::NaiveDate, chrono::NaiveDateTime);
129
130impl<Tz: chrono::TimeZone> Describe for chrono::DateTime<Tz> {
131 fn describe() -> Node {
132 Node::Date
133 }
134}
135
136impl<T: Describe + ?Sized> Describe for &T {
137 fn describe() -> Node {
138 T::describe()
139 }
140}
141
142impl<T: Describe + ?Sized> Describe for Box<T> {
143 fn describe() -> Node {
144 T::describe()
145 }
146}
147
148impl<T: Describe + ?Sized> Describe for Arc<T> {
149 fn describe() -> Node {
150 T::describe()
151 }
152}
153
154impl<T: Describe> Describe for Option<T> {
155 fn describe() -> Node {
156 Node::Optional(Box::new(T::describe()))
157 }
158}
159
160macro_rules! describe_list {
161 ($($ty:ty),*) => {
162 $(impl<T: Describe> Describe for $ty {
163 fn describe() -> Node {
164 Node::List(Box::new(T::describe()))
165 }
166 })*
167 };
168}
169
170describe_list!(Vec<T>, [T], VecDeque<T>, BTreeSet<T>, HashSet<T>);
171
172impl<T: Describe, const N: usize> Describe for [T; N] {
173 fn describe() -> Node {
174 Node::List(Box::new(T::describe()))
175 }
176}
177
178impl<K, V: Describe> Describe for BTreeMap<K, V> {
179 fn describe() -> Node {
180 Node::Any
181 }
182}
183
184impl<K, V: Describe, S> Describe for HashMap<K, V, S> {
185 fn describe() -> Node {
186 Node::Any
187 }
188}
189
190pub trait TemplateType: Describe + serde::Serialize + Send + Sync + 'static {
194 const KEY: &'static str;
196 const DESCRIPTION: &'static str;
198
199 fn example() -> Self;
201
202 fn defaults() -> Vec<DefaultTemplate>;
204}
205
206#[derive(Debug, Clone)]
208pub struct TypeInfo {
209 pub key: &'static str,
211 pub description: &'static str,
213 pub variables: Vec<Field>,
215 pub(crate) example: fn() -> serde_json::Result<serde_json::Value>,
216 pub(crate) defaults: fn() -> Vec<DefaultTemplate>,
217}
218
219impl TypeInfo {
220 pub fn example(&self) -> laravel::Result<serde_json::Value> {
226 (self.example)()
227 .map_err(|e| laravel::Error::msg(format!("the example of `{}` doesn't serialize: {e}", self.key)))
228 }
229
230 #[must_use]
232 pub fn defaults(&self) -> Vec<DefaultTemplate> {
233 (self.defaults)()
234 }
235
236 #[must_use]
239 pub fn recipients(&self) -> Vec<String> {
240 let mut paths = Vec::new();
241 collect_recipients(&self.variables, "", &mut paths);
242 paths
243 }
244
245 #[must_use]
247 pub fn variable(&self, path: &str) -> Option<Node> {
248 let mut node = Node::Object(self.variables.clone());
249 for part in path.split('.') {
250 let fields = node.fields()?;
251 node = fields.into_iter().find(|f| f.name == part)?.node;
252 }
253 Some(node)
254 }
255
256 pub fn to_json(&self) -> laravel::Result<serde_json::Value> {
263 Ok(serde_json::json!({
264 "key": self.key,
265 "description": self.description,
266 "variables": fields_json(&self.variables, ""),
267 "recipients": self.recipients(),
268 "example": self.example()?,
269 }))
270 }
271}
272
273fn collect_recipients(fields: &[Field], prefix: &str, paths: &mut Vec<String>) {
274 for field in fields {
275 let path = join(prefix, field.name);
276 match field.node.required() {
277 Node::Recipient => paths.push(path),
278 Node::List(item) if *item.required() == Node::Recipient => paths.push(path),
279 Node::Object(inner) => collect_recipients(inner, &path, paths),
280 _ => {}
281 }
282 }
283}
284
285pub(crate) fn join(prefix: &str, name: &str) -> String {
286 if prefix.is_empty() {
287 name.to_owned()
288 } else {
289 format!("{prefix}.{name}")
290 }
291}
292
293#[derive(Serialize)]
294struct FieldJson {
295 name: &'static str,
296 path: String,
297 #[serde(rename = "type")]
298 kind: &'static str,
299 description: &'static str,
300 optional: bool,
301 #[serde(skip_serializing_if = "Option::is_none")]
302 item: Option<Box<NodeJson>>,
303 #[serde(skip_serializing_if = "Option::is_none")]
304 fields: Option<Vec<FieldJson>>,
305}
306
307#[derive(Serialize)]
308struct NodeJson {
309 #[serde(rename = "type")]
310 kind: &'static str,
311 #[serde(skip_serializing_if = "Option::is_none")]
312 item: Option<Box<NodeJson>>,
313 #[serde(skip_serializing_if = "Option::is_none")]
314 fields: Option<Vec<FieldJson>>,
315}
316
317fn fields_json(fields: &[Field], prefix: &str) -> Vec<FieldJson> {
318 fields
319 .iter()
320 .map(|field| {
321 let path = join(prefix, field.name);
322 let (item, fields) = children(&field.node, &path);
323 FieldJson {
324 name: field.name,
325 kind: field.node.type_name(),
326 description: field.description,
327 optional: matches!(field.node, Node::Optional(_)),
328 path,
329 item,
330 fields,
331 }
332 })
333 .collect()
334}
335
336fn children(node: &Node, path: &str) -> (Option<Box<NodeJson>>, Option<Vec<FieldJson>>) {
338 match node.required() {
339 Node::List(item) => {
340 let (inner_item, inner_fields) = children(item, "item");
341 let json = NodeJson {
342 kind: item.type_name(),
343 item: inner_item,
344 fields: inner_fields,
345 };
346 (Some(Box::new(json)), None)
347 }
348 other => (None, other.fields().map(|fields| fields_json(&fields, path))),
349 }
350}
351
352#[doc(hidden)]
353pub struct Registration {
354 key: &'static str,
355 description: &'static str,
356 describe: fn() -> Node,
357 example: fn() -> serde_json::Result<serde_json::Value>,
358 defaults: fn() -> Vec<DefaultTemplate>,
359}
360
361impl Registration {
362 #[must_use]
363 pub const fn of<T: TemplateType>() -> Self {
364 Self {
365 key: T::KEY,
366 description: T::DESCRIPTION,
367 describe: T::describe,
368 example: example_of::<T>,
369 defaults: T::defaults,
370 }
371 }
372
373 pub(crate) fn info(&self) -> TypeInfo {
374 let variables = match (self.describe)() {
375 Node::Object(fields) => fields,
376 _ => Vec::new(),
377 };
378 TypeInfo {
379 key: self.key,
380 description: self.description,
381 variables,
382 example: self.example,
383 defaults: self.defaults,
384 }
385 }
386}
387
388fn example_of<T: TemplateType>() -> serde_json::Result<serde_json::Value> {
389 serde_json::to_value(T::example())
390}
391
392inventory::collect!(Registration);
393
394#[must_use]
396pub fn types() -> Vec<TypeInfo> {
397 let mut types: Vec<TypeInfo> = inventory::iter::<Registration>().map(Registration::info).collect();
398 types.sort_by_key(|t| t.key);
399 types.dedup_by_key(|t| t.key);
400 types
401}
402
403#[must_use]
405pub fn find_type(key: &str) -> Option<TypeInfo> {
406 inventory::iter::<Registration>()
407 .find(|r| r.key == key)
408 .map(Registration::info)
409}
410
411#[must_use]
413pub fn type_of<T: TemplateType>() -> TypeInfo {
414 Registration::of::<T>().info()
415}