use std::fmt;
use serde_json::{Map, Value};
use super::{DocMeta, MetaAuthor, MetaPlace, MetaText};
pub const TITLE_KEY: &str = "title";
pub const AUTHOR_KEY: &str = "author";
pub const DATE_KEY: &str = "date";
pub const NAME_KEY: &str = "name";
pub const AFFILIATION_KEY: &str = "affiliation";
pub const EMAIL_KEY: &str = "email";
pub const NOTE_KEY: &str = "note";
pub fn metadata_schema() -> Value {
let text = || serde_json::json!({ "type": ["string", "number", "boolean"] });
let texts = |description: &str| {
serde_json::json!({
"description": description,
"anyOf": [text(), { "type": "array", "items": text() }],
})
};
let entry = serde_json::json!({
"anyOf": [
text(),
{
"type": "object",
"properties": {
NAME_KEY: {
"description": "The author's name, a text in FLM.",
"type": ["string", "number", "boolean"],
},
AFFILIATION_KEY: texts("The author's affiliations: one text in FLM, or a list of texts."),
EMAIL_KEY: {
"description": "The author's email address, a plain text, not FLM.",
"type": ["string", "number", "boolean"],
},
NOTE_KEY: texts("The notes about the author: one text in FLM, or a list of texts."),
},
"required": [NAME_KEY],
},
],
});
serde_json::json!({
"type": "object",
"description": "The metadata of the document: its title, its authors, its date, and any other key, \
whose value is kept as written.",
"properties": {
TITLE_KEY: {
"description": "The title of the document, a text in FLM.",
"type": ["string", "number", "boolean"],
},
AUTHOR_KEY: {
"description": "The authors of the document: one author, or a list of authors. An author is \
a text in FLM, the author's name, or a map with the author's `name` and, as the author \
wishes, `affiliation`, `email` and `note`.",
"anyOf": [entry.clone(), { "type": "array", "items": entry }],
},
DATE_KEY: {
"description": "The date of the document, a text in FLM, as the author writes it.",
"type": ["string", "number", "boolean"],
},
},
})
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MetaPath {
pub key: String,
pub steps: Vec<MetaStep>,
}
impl MetaPath {
pub fn of(key: impl Into<String>) -> MetaPath {
MetaPath { key: key.into(), steps: Vec::new() }
}
pub fn then(&self, step: MetaStep) -> MetaPath {
let mut path = self.clone();
path.steps.push(step);
path
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MetaStep {
Index(usize),
Key(String),
}
impl fmt::Display for MetaPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.key)?;
for step in &self.steps {
match step {
MetaStep::Index(index) => write!(f, ".{index}")?,
MetaStep::Key(key) => write!(f, ".{key}")?,
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetaDataError {
pub path: MetaPath,
pub detail: String,
}
impl fmt::Display for MetaDataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl std::error::Error for MetaDataError {}
impl DocMeta {
pub fn from_data(
data: &Map<String, Value>,
place_of: impl Fn(&MetaPath) -> Option<MetaPlace>,
) -> Result<DocMeta, Vec<MetaDataError>> {
let reader = Reader { place_of: &place_of };
let mut meta = DocMeta::default();
let mut errors = Vec::new();
for (key, value) in data {
let path = MetaPath::of(key.as_str());
match key.as_str() {
TITLE_KEY => meta.title = reader.text(&path, value, &mut errors),
DATE_KEY => meta.date = reader.text(&path, value, &mut errors),
AUTHOR_KEY => meta.authors = reader.authors(&path, value, &mut errors),
_ => {
meta.other.insert(key.clone(), value.clone());
}
}
}
if errors.is_empty() { Ok(meta) } else { Err(errors) }
}
}
struct Reader<'p> {
place_of: &'p dyn Fn(&MetaPath) -> Option<MetaPlace>,
}
impl Reader<'_> {
fn text(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Option<MetaText> {
let text = match value {
Value::String(text) => text.clone(),
Value::Number(number) => number.to_string(),
Value::Bool(value) => value.to_string(),
_ => {
errors.push(MetaDataError {
path: path.clone(),
detail: format!("‘{path}’ must be a text, a number or a truth value"),
});
return None;
}
};
let text = MetaText::new(text);
Some(match (self.place_of)(path) {
Some(place) => text.at(place),
None => text,
})
}
fn texts(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Vec<MetaText> {
match value {
Value::Array(items) => items
.iter()
.enumerate()
.filter_map(|(index, item)| self.text(&path.then(MetaStep::Index(index)), item, errors))
.collect(),
Value::Object(_) | Value::Null => {
errors.push(MetaDataError {
path: path.clone(),
detail: format!("‘{path}’ must be a text or a list of texts"),
});
Vec::new()
}
_ => self.text(path, value, errors).into_iter().collect(),
}
}
fn authors(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Vec<MetaAuthor> {
match value {
Value::Array(items) => items
.iter()
.enumerate()
.filter_map(|(index, item)| self.author(&path.then(MetaStep::Index(index)), item, errors))
.collect(),
Value::Null => {
errors.push(MetaDataError {
path: path.clone(),
detail: format!("‘{path}’ must be a name, a map with the key ‘{NAME_KEY}’, or a list of these"),
});
Vec::new()
}
_ => self.author(path, value, errors).into_iter().collect(),
}
}
fn author(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Option<MetaAuthor> {
let entries = match value {
Value::Object(entries) => entries,
Value::Array(_) | Value::Null => {
errors.push(MetaDataError {
path: path.clone(),
detail: format!("‘{path}’ must be a name or a map with the key ‘{NAME_KEY}’"),
});
return None;
}
_ => return self.text(path, value, errors).map(MetaAuthor::new),
};
let at = |key: &str| path.then(MetaStep::Key(key.to_string()));
let Some(name) = entries.get(NAME_KEY) else {
errors.push(MetaDataError { path: path.clone(), detail: format!("Missing key ‘{NAME_KEY}’ in ‘{path}’") });
return None;
};
let mut author = MetaAuthor::new(self.text(&at(NAME_KEY), name, errors)?);
for (key, value) in entries {
match key.as_str() {
NAME_KEY => {}
AFFILIATION_KEY => author.affiliations = self.texts(&at(key), value, errors),
EMAIL_KEY => author.email = self.text(&at(key), value, errors),
NOTE_KEY => author.notes = self.texts(&at(key), value, errors),
_ => {
author.other.insert(key.clone(), value.clone());
}
}
}
Some(author)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn read(data: Value) -> Result<DocMeta, Vec<MetaDataError>> {
DocMeta::from_data(data.as_object().unwrap(), |_| None)
}
#[test]
fn an_author_is_a_text_a_list_of_texts_or_a_list_with_maps() {
let meta = read(serde_json::json!({"author": "Ada", "date": 2026, "draft": true})).unwrap();
assert_eq!(meta.authors, [MetaAuthor::new(MetaText::new("Ada"))]);
assert_eq!(meta.date, Some(MetaText::new("2026")));
assert_eq!(meta.other["draft"], Value::Bool(true));
let meta = read(serde_json::json!({"author": ["Ada", "Grace"]})).unwrap();
assert_eq!(meta.authors.len(), 2);
let meta = read(serde_json::json!({"author": [
{"name": "Ada", "affiliation": ["U. of X", "I. of Y"], "email": "ada@example.com",
"note": "Corresponding author", "orcid": "0000"},
"Grace",
]}))
.unwrap();
let ada = MetaAuthor::new(MetaText::new("Ada"))
.affiliation(MetaText::new("U. of X"))
.affiliation(MetaText::new("I. of Y"))
.email(MetaText::new("ada@example.com"))
.note(MetaText::new("Corresponding author"))
.other("orcid", serde_json::json!("0000"));
assert_eq!(meta.authors, [ada, MetaAuthor::new(MetaText::new("Grace"))]);
}
#[test]
fn a_value_of_another_shape_and_an_author_without_a_name_are_refused_at_their_paths() {
let errors = read(serde_json::json!({
"title": ["a"],
"author": ["Ada", {"x": 1}, {"name": "Grace", "affiliation": {"y": 2}}],
}))
.unwrap_err();
let paths: Vec<String> = errors.iter().map(|error| error.path.to_string()).collect();
assert_eq!(paths.len(), 3, "{paths:?}");
assert!(paths.contains(&String::from("title")));
assert!(paths.contains(&String::from("author.1")));
assert!(paths.contains(&String::from("author.2.affiliation")));
}
}