1use std::fmt;
40
41use serde_json::{Map, Value};
42
43use super::{DocMeta, MetaAuthor, MetaPlace, MetaText};
44
45pub const TITLE_KEY: &str = "title";
47
48pub const AUTHOR_KEY: &str = "author";
51
52pub const DATE_KEY: &str = "date";
54
55pub const NAME_KEY: &str = "name";
57
58pub const AFFILIATION_KEY: &str = "affiliation";
61
62pub const EMAIL_KEY: &str = "email";
65
66pub const NOTE_KEY: &str = "note";
69
70pub fn metadata_schema() -> Value {
77 let text = || serde_json::json!({ "type": ["string", "number", "boolean"] });
78 let texts = |description: &str| {
79 serde_json::json!({
80 "description": description,
81 "anyOf": [text(), { "type": "array", "items": text() }],
82 })
83 };
84 let entry = serde_json::json!({
85 "anyOf": [
86 text(),
87 {
88 "type": "object",
89 "properties": {
90 NAME_KEY: {
91 "description": "The author's name, a text in FLM.",
92 "type": ["string", "number", "boolean"],
93 },
94 AFFILIATION_KEY: texts("The author's affiliations: one text in FLM, or a list of texts."),
95 EMAIL_KEY: {
96 "description": "The author's email address, a plain text, not FLM.",
97 "type": ["string", "number", "boolean"],
98 },
99 NOTE_KEY: texts("The notes about the author: one text in FLM, or a list of texts."),
100 },
101 "required": [NAME_KEY],
102 },
103 ],
104 });
105 serde_json::json!({
106 "type": "object",
107 "description": "The metadata of the document: its title, its authors, its date, and any other key, \
108 whose value is kept as written.",
109 "properties": {
110 TITLE_KEY: {
111 "description": "The title of the document, a text in FLM.",
112 "type": ["string", "number", "boolean"],
113 },
114 AUTHOR_KEY: {
115 "description": "The authors of the document: one author, or a list of authors. An author is \
116 a text in FLM, the author's name, or a map with the author's `name` and, as the author \
117 wishes, `affiliation`, `email` and `note`.",
118 "anyOf": [entry.clone(), { "type": "array", "items": entry }],
119 },
120 DATE_KEY: {
121 "description": "The date of the document, a text in FLM, as the author writes it.",
122 "type": ["string", "number", "boolean"],
123 },
124 },
125 })
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Hash)]
133pub struct MetaPath {
134 pub key: String,
136 pub steps: Vec<MetaStep>,
139}
140
141impl MetaPath {
142 pub fn of(key: impl Into<String>) -> MetaPath {
144 MetaPath { key: key.into(), steps: Vec::new() }
145 }
146
147 pub fn then(&self, step: MetaStep) -> MetaPath {
149 let mut path = self.clone();
150 path.steps.push(step);
151 path
152 }
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Hash)]
158pub enum MetaStep {
159 Index(usize),
161 Key(String),
163}
164
165impl fmt::Display for MetaPath {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.write_str(&self.key)?;
168 for step in &self.steps {
169 match step {
170 MetaStep::Index(index) => write!(f, ".{index}")?,
171 MetaStep::Key(key) => write!(f, ".{key}")?,
172 }
173 }
174 Ok(())
175 }
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct MetaDataError {
183 pub path: MetaPath,
185 pub detail: String,
187}
188
189impl fmt::Display for MetaDataError {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.write_str(&self.detail)
192 }
193}
194
195impl std::error::Error for MetaDataError {}
196
197impl DocMeta {
198 pub fn from_data(
235 data: &Map<String, Value>,
236 place_of: impl Fn(&MetaPath) -> Option<MetaPlace>,
237 ) -> Result<DocMeta, Vec<MetaDataError>> {
238 let reader = Reader { place_of: &place_of };
239 let mut meta = DocMeta::default();
240 let mut errors = Vec::new();
241 for (key, value) in data {
242 let path = MetaPath::of(key.as_str());
243 match key.as_str() {
244 TITLE_KEY => meta.title = reader.text(&path, value, &mut errors),
245 DATE_KEY => meta.date = reader.text(&path, value, &mut errors),
246 AUTHOR_KEY => meta.authors = reader.authors(&path, value, &mut errors),
247 _ => {
248 meta.other.insert(key.clone(), value.clone());
249 }
250 }
251 }
252 if errors.is_empty() { Ok(meta) } else { Err(errors) }
253 }
254}
255
256struct Reader<'p> {
259 place_of: &'p dyn Fn(&MetaPath) -> Option<MetaPlace>,
260}
261
262impl Reader<'_> {
263 fn text(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Option<MetaText> {
267 let text = match value {
268 Value::String(text) => text.clone(),
269 Value::Number(number) => number.to_string(),
270 Value::Bool(value) => value.to_string(),
271 _ => {
272 errors.push(MetaDataError {
273 path: path.clone(),
274 detail: format!("‘{path}’ must be a text, a number or a truth value"),
275 });
276 return None;
277 }
278 };
279 let text = MetaText::new(text);
280 Some(match (self.place_of)(path) {
281 Some(place) => text.at(place),
282 None => text,
283 })
284 }
285
286 fn texts(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Vec<MetaText> {
288 match value {
289 Value::Array(items) => items
290 .iter()
291 .enumerate()
292 .filter_map(|(index, item)| self.text(&path.then(MetaStep::Index(index)), item, errors))
293 .collect(),
294 Value::Object(_) | Value::Null => {
295 errors.push(MetaDataError {
296 path: path.clone(),
297 detail: format!("‘{path}’ must be a text or a list of texts"),
298 });
299 Vec::new()
300 }
301 _ => self.text(path, value, errors).into_iter().collect(),
302 }
303 }
304
305 fn authors(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Vec<MetaAuthor> {
308 match value {
309 Value::Array(items) => items
310 .iter()
311 .enumerate()
312 .filter_map(|(index, item)| self.author(&path.then(MetaStep::Index(index)), item, errors))
313 .collect(),
314 Value::Null => {
315 errors.push(MetaDataError {
316 path: path.clone(),
317 detail: format!("‘{path}’ must be a name, a map with the key ‘{NAME_KEY}’, or a list of these"),
318 });
319 Vec::new()
320 }
321 _ => self.author(path, value, errors).into_iter().collect(),
322 }
323 }
324
325 fn author(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Option<MetaAuthor> {
329 let entries = match value {
330 Value::Object(entries) => entries,
331 Value::Array(_) | Value::Null => {
332 errors.push(MetaDataError {
333 path: path.clone(),
334 detail: format!("‘{path}’ must be a name or a map with the key ‘{NAME_KEY}’"),
335 });
336 return None;
337 }
338 _ => return self.text(path, value, errors).map(MetaAuthor::new),
339 };
340 let at = |key: &str| path.then(MetaStep::Key(key.to_string()));
341 let Some(name) = entries.get(NAME_KEY) else {
342 errors.push(MetaDataError { path: path.clone(), detail: format!("Missing key ‘{NAME_KEY}’ in ‘{path}’") });
343 return None;
344 };
345 let mut author = MetaAuthor::new(self.text(&at(NAME_KEY), name, errors)?);
346 for (key, value) in entries {
347 match key.as_str() {
348 NAME_KEY => {}
349 AFFILIATION_KEY => author.affiliations = self.texts(&at(key), value, errors),
350 EMAIL_KEY => author.email = self.text(&at(key), value, errors),
351 NOTE_KEY => author.notes = self.texts(&at(key), value, errors),
352 _ => {
353 author.other.insert(key.clone(), value.clone());
354 }
355 }
356 }
357 Some(author)
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 fn read(data: Value) -> Result<DocMeta, Vec<MetaDataError>> {
366 DocMeta::from_data(data.as_object().unwrap(), |_| None)
367 }
368
369 #[test]
370 fn an_author_is_a_text_a_list_of_texts_or_a_list_with_maps() {
371 let meta = read(serde_json::json!({"author": "Ada", "date": 2026, "draft": true})).unwrap();
372 assert_eq!(meta.authors, [MetaAuthor::new(MetaText::new("Ada"))]);
373 assert_eq!(meta.date, Some(MetaText::new("2026")));
374 assert_eq!(meta.other["draft"], Value::Bool(true));
375 let meta = read(serde_json::json!({"author": ["Ada", "Grace"]})).unwrap();
376 assert_eq!(meta.authors.len(), 2);
377 let meta = read(serde_json::json!({"author": [
378 {"name": "Ada", "affiliation": ["U. of X", "I. of Y"], "email": "ada@example.com",
379 "note": "Corresponding author", "orcid": "0000"},
380 "Grace",
381 ]}))
382 .unwrap();
383 let ada = MetaAuthor::new(MetaText::new("Ada"))
384 .affiliation(MetaText::new("U. of X"))
385 .affiliation(MetaText::new("I. of Y"))
386 .email(MetaText::new("ada@example.com"))
387 .note(MetaText::new("Corresponding author"))
388 .other("orcid", serde_json::json!("0000"));
389 assert_eq!(meta.authors, [ada, MetaAuthor::new(MetaText::new("Grace"))]);
390 }
391
392 #[test]
393 fn a_value_of_another_shape_and_an_author_without_a_name_are_refused_at_their_paths() {
394 let errors = read(serde_json::json!({
395 "title": ["a"],
396 "author": ["Ada", {"x": 1}, {"name": "Grace", "affiliation": {"y": 2}}],
397 }))
398 .unwrap_err();
399 let paths: Vec<String> = errors.iter().map(|error| error.path.to_string()).collect();
400 assert_eq!(paths.len(), 3, "{paths:?}");
401 assert!(paths.contains(&String::from("title")));
402 assert!(paths.contains(&String::from("author.1")));
403 assert!(paths.contains(&String::from("author.2.affiliation")));
404 }
405}