1use serde::{Deserialize, Deserializer, Serialize};
12
13#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum FieldType {
17 #[default]
19 Any,
20 Text,
21 Secret,
25 RichText,
27 Int,
28 Float,
29 Bool,
30 Date,
32 Time,
34 Identifier,
36 #[serde(alias = "principal")]
40 Actor,
41 Resource(String),
43 Named(String),
45 Json,
48 Option(Box<FieldType>),
50 List(Box<FieldType>),
51 Set(Box<FieldType>),
53 Collection(Box<FieldType>),
55 Map(Box<FieldType>),
57 Union(Vec<FieldType>),
59 Reactions,
62 Outbox(Box<FieldType>),
65 Duration,
68}
69
70impl FieldType {
71 #[must_use]
73 pub const fn is_any(&self) -> bool {
74 matches!(self, Self::Any)
75 }
76
77 #[must_use]
79 pub const fn is_outbox(&self) -> bool {
80 matches!(self, Self::Outbox(_))
81 }
82
83 #[must_use]
85 pub const fn is_reactions(&self) -> bool {
86 matches!(self, Self::Reactions)
87 }
88
89 #[must_use]
93 pub fn from_rust_text(text: &str) -> Self {
94 let head = text.split('<').next().unwrap_or_default().trim();
95 match head.rsplit("::").next() {
96 Some("Outbox") if text.contains('<') => Self::Outbox(Box::new(Self::Any)),
97 Some("Reactions") => Self::Reactions,
98 _ => Self::Any,
99 }
100 }
101
102 #[must_use]
106 pub fn renamed(&self, renames: &std::collections::BTreeMap<String, String>) -> Self {
107 let inner = |ty: &Self| Box::new(ty.renamed(renames));
108 match self {
109 Self::Named(name) => renames
110 .get(name)
111 .map_or_else(|| self.clone(), |name| Self::Named(name.clone())),
112 Self::Option(ty) => Self::Option(inner(ty)),
113 Self::List(ty) => Self::List(inner(ty)),
114 Self::Set(ty) => Self::Set(inner(ty)),
115 Self::Collection(ty) => Self::Collection(inner(ty)),
116 Self::Map(ty) => Self::Map(inner(ty)),
117 Self::Outbox(ty) => Self::Outbox(inner(ty)),
118 Self::Union(cases) => {
119 Self::Union(cases.iter().map(|case| case.renamed(renames)).collect())
120 }
121 other => other.clone(),
122 }
123 }
124
125 #[must_use]
128 pub fn from_schema(schema: &serde_json::Value) -> Self {
129 use serde_json::Value;
130 let Some(node) = schema.as_object() else {
131 return Self::Any;
132 };
133 if let Some(kind) = node
134 .get(crate::params::RESOURCE_KIND_ANNOTATION)
135 .and_then(Value::as_str)
136 {
137 return Self::Resource(kind.to_owned());
138 }
139 for key in ["anyOf", "oneOf"] {
140 if let Some(alternatives) = node.get(key).and_then(Value::as_array) {
141 let is_null = |alternative: &Value| {
142 alternative.get("type").and_then(Value::as_str) == Some("null")
143 };
144 let present: Vec<&Value> =
145 alternatives.iter().filter(|item| !is_null(item)).collect();
146 if let [one] = present.as_slice()
147 && present.len() < alternatives.len()
148 {
149 return Self::Option(Box::new(Self::from_schema(one)));
150 }
151 return Self::Any;
152 }
153 }
154 let types: Vec<&str> = match node.get("type") {
155 Some(Value::String(one)) => vec![one.as_str()],
156 Some(Value::Array(many)) => many.iter().filter_map(Value::as_str).collect(),
157 _ => Vec::new(),
158 };
159 let nullable = types.contains(&"null");
160 let present: Vec<&str> = types.into_iter().filter(|ty| *ty != "null").collect();
161 let ty = match present.as_slice() {
162 ["string"] => match node.get("format").and_then(Value::as_str) {
163 Some("date") => Self::Date,
164 Some("date-time") => Self::Time,
165 Some("uri") => Self::Identifier,
166 _ => Self::Text,
167 },
168 ["integer"] => Self::Int,
169 ["number"] => Self::Float,
170 ["boolean"] => Self::Bool,
171 ["array"] => {
172 let item = node.get("items").map_or(Self::Any, Self::from_schema);
173 if node.get("uniqueItems").and_then(Value::as_bool) == Some(true) {
174 Self::Set(Box::new(item))
175 } else {
176 Self::List(Box::new(item))
177 }
178 }
179 ["object"] => match node.get("additionalProperties") {
180 Some(item @ Value::Object(_)) if node.get("properties").is_none() => {
181 Self::Map(Box::new(Self::from_schema(item)))
182 }
183 _ => Self::Any,
184 },
185 _ => Self::Any,
186 };
187 if nullable && ty != Self::Any {
188 Self::Option(Box::new(ty))
189 } else {
190 ty
191 }
192 }
193}
194
195pub(crate) fn field_type_or_text<'de, D: Deserializer<'de>>(
198 deserializer: D,
199) -> Result<FieldType, D::Error> {
200 #[derive(Deserialize)]
201 #[serde(untagged)]
202 enum Written {
203 Typed(FieldType),
204 Text(String),
205 }
206 Ok(match Written::deserialize(deserializer)? {
207 Written::Typed(ty) => ty,
208 Written::Text(text) => FieldType::from_rust_text(&text),
209 })
210}
211
212#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
216pub struct NamedType {
217 pub name: String,
218 #[serde(default, skip_serializing_if = "String::is_empty")]
219 pub doc: String,
220 #[serde(default, skip_serializing_if = "Vec::is_empty")]
221 pub fields: Vec<TypeField>,
222 #[serde(default, skip_serializing_if = "Vec::is_empty")]
223 pub cases: Vec<TypeCase>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub tag: Option<String>,
229}
230
231impl NamedType {
232 #[must_use]
234 pub const fn is_enum(&self) -> bool {
235 !self.cases.is_empty()
236 }
237}
238
239#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
241pub struct TypeField {
242 pub name: String,
243 #[serde(rename = "type", deserialize_with = "field_type_or_text")]
244 pub ty: FieldType,
245 #[serde(default, skip_serializing_if = "String::is_empty")]
246 pub title: String,
247}
248
249#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
251pub struct TypeCase {
252 pub name: String,
253 #[serde(default, skip_serializing_if = "String::is_empty")]
255 pub label: String,
256 #[serde(default, skip_serializing_if = "Vec::is_empty")]
257 pub fields: Vec<TypeField>,
258}
259
260#[derive(Debug, Default)]
263pub struct TypeSet {
264 declared: Vec<(String, NamedType)>,
267}
268
269impl TypeSet {
270 #[must_use]
271 pub fn new() -> Self {
272 Self::default()
273 }
274
275 pub fn named(
279 &mut self,
280 identity: &str,
281 name: &str,
282 build: impl FnOnce(&mut Self) -> NamedType,
283 ) -> FieldType {
284 if let Some((_, declared)) = self.declared.iter().find(|(id, _)| id == identity) {
285 return FieldType::Named(declared.name.clone());
286 }
287 let mut unique = name.to_owned();
288 let mut number = 2_u32;
289 while self.declared.iter().any(|(_, ty)| ty.name == unique) {
290 unique = format!("{name}{number}");
291 number = number.saturating_add(1);
292 }
293 let at = self.declared.len();
296 self.declared.push((
297 identity.to_owned(),
298 NamedType {
299 name: unique.clone(),
300 ..NamedType::default()
301 },
302 ));
303 let mut body = build(self);
304 body.name.clone_from(&unique);
305 if let Some((_, slot)) = self.declared.get_mut(at) {
306 *slot = body;
307 }
308 FieldType::Named(unique)
309 }
310
311 pub fn tag(&mut self, ty: &FieldType, tag: &str) {
313 let FieldType::Named(name) = ty else { return };
314 if let Some((_, declared)) = self.declared.iter_mut().find(|(_, ty)| ty.name == *name) {
315 declared.tag = Some(tag.to_owned());
316 }
317 }
318
319 #[must_use]
321 pub fn get(&self, name: &str) -> Option<&NamedType> {
322 self.declared
323 .iter()
324 .map(|(_, ty)| ty)
325 .find(|ty| ty.name == name)
326 }
327
328 #[must_use]
330 pub fn into_types(self) -> Vec<NamedType> {
331 let mut types: Vec<NamedType> = self.declared.into_iter().map(|(_, ty)| ty).collect();
332 types.sort_by(|a, b| a.name.cmp(&b.name));
333 types
334 }
335}
336
337#[must_use]
340pub fn label_of(name: &str) -> String {
341 let words = name.replace(['_', '-'], " ");
342 let mut chars = words.trim().chars();
343 chars.next().map_or_else(String::new, |first| {
344 first.to_uppercase().chain(chars).collect()
345 })
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 tilo_test_env::scenario! {
353 fn a_field_type_reads_and_declares_its_schema;
354
355 phase a_type_reads_from_the_vocabulary_or_older_rust_text;
356 {
357 #[derive(Deserialize)]
358 struct Field {
359 #[serde(deserialize_with = "field_type_or_text")]
360 ty: FieldType,
361 }
362 let read = |json: &str| {
363 serde_json::from_str::<Field>(json).map_or(FieldType::Any, |field| field.ty)
364 };
365 assert_eq!(read(r#"{"ty": "text"}"#), FieldType::Text);
366 assert_eq!(
367 read(r#"{"ty": {"option": {"named": "Channel"}}}"#),
368 FieldType::Option(Box::new(FieldType::Named("Channel".into())))
369 );
370 assert_eq!(read(r#"{"ty": "String"}"#), FieldType::Any);
371 assert_eq!(
372 read(r#"{"ty": "ui::tilo_resource::Reactions"}"#),
373 FieldType::Reactions
374 );
375 assert!(read(r#"{"ty": "Outbox<Upload>"}"#).is_outbox());
376 assert_eq!(
377 read(r#"{"ty": {"option": "principal"}}"#),
378 FieldType::Option(Box::new(FieldType::Actor))
379 );
380 }
381
382 phase a_type_used_twice_is_declared_once_and_names_stay_unique;
383 {
384 let mut types = TypeSet::new();
385 let record = |name: &str| NamedType {
386 name: name.into(),
387 ..NamedType::default()
388 };
389 let first = types.named("a::Step", "Step", |_| record("Step"));
390 let again = types.named("a::Step", "Step", |_| unreachable!());
391 let other = types.named("b::Step", "Step", |_| record("Step"));
392 assert_eq!(first, again);
393 assert_eq!(other, FieldType::Named("Step2".into()));
394 let names: Vec<String> = types.into_types().into_iter().map(|ty| ty.name).collect();
395 assert_eq!(names, ["Step", "Step2"]);
396 }
397
398 phase a_schema_tells_what_it_can;
399 {
400 let ty = FieldType::from_schema(&serde_json::json!({"type": ["string", "null"]}));
401 assert_eq!(ty, FieldType::Option(Box::new(FieldType::Text)));
402 let ty = FieldType::from_schema(
403 &serde_json::json!({"type": "array", "items": {"type": "integer"}}),
404 );
405 assert_eq!(ty, FieldType::List(Box::new(FieldType::Int)));
406 }
407 }
408}