citum-schema-style 0.78.0

Citum style schema types and styling engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
SPDX-License-Identifier: MIT OR Apache-2.0
SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
*/

//! Style registry — discovery and alias resolution for citation styles.

#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::OnceLock;

static DEFAULT_REGISTRY: OnceLock<StyleRegistry> = OnceLock::new();

/// Tier classification for a style in the registry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum StyleKind {
    /// Complete style that serves as an inheritance root.
    Base,
    /// Organizational adaptation of a base style (publisher, society, standards body).
    Profile,
    /// Pure alias pointing to a profile or base style.
    Journal,
    /// Standalone style with no aliases and no inheritance role.
    Independent,
}

/// A single entry in a style registry.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct RegistryEntry {
    /// Canonical style ID, must match the key used in `get_embedded_style`.
    pub id: String,
    /// Short aliases that resolve to this entry (default empty).
    #[serde(default)]
    pub aliases: Vec<String>,
    /// Name of an embedded style (present for the default registry).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub builtin: Option<String>,
    /// Relative path to a YAML file (used in local registries).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
    /// HTTP URL to a YAML style file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Human-readable title from the style metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Human-readable description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Subject/domain classification tags (default empty).
    #[serde(default)]
    pub fields: Vec<String>,
    /// Tier classification (base, profile, journal, independent).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<StyleKind>,
}

/// A registry of citation styles with alias resolution.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct StyleRegistry {
    /// Version identifier for the registry format.
    pub version: String,
    /// List of style entries in the registry.
    pub styles: Vec<RegistryEntry>,
}

impl StyleRegistry {
    /// Resolve a name or alias to the matching registry entry.
    ///
    /// Checks `id` first, then searches aliases.
    pub fn resolve(&self, name: &str) -> Option<&RegistryEntry> {
        // Check exact ID match
        if let Some(entry) = self.styles.iter().find(|e| e.id == name) {
            return Some(entry);
        }
        // Check aliases
        self.styles
            .iter()
            .find(|e| e.aliases.iter().any(|a| a == name))
    }

    /// All canonical style IDs in the registry.
    pub fn all_ids(&self) -> impl Iterator<Item = &str> {
        self.styles.iter().map(|e| e.id.as_str())
    }

    /// Merge another registry over self (self wins on ID conflict).
    ///
    /// Entries from `base` are included first. If an entry in `self`
    /// has the same ID as one in `base`, the entry from `self` replaces it.
    /// New entries from `self` are appended.
    #[must_use]
    #[allow(clippy::indexing_slicing, reason = "pos is found via .position()")]
    pub fn merge_over(&self, base: &StyleRegistry) -> StyleRegistry {
        let mut result = base.clone();
        for entry in &self.styles {
            if let Some(pos) = result.styles.iter().position(|e| e.id == entry.id) {
                result.styles[pos] = entry.clone();
            } else {
                result.styles.push(entry.clone());
            }
        }
        result
    }

    /// Build a registry from embedded style name and alias slices.
    ///
    /// Used to construct the default registry from hardcoded embedded data.
    pub fn from_slices(names: &[&str], aliases: &[(&str, &str)]) -> Self {
        let mut styles = Vec::new();

        // Create entries for each embedded style name.
        for name in names {
            let style_aliases: Vec<String> = aliases
                .iter()
                .filter(|(_, full)| full == name)
                .map(|(alias, _)| (*alias).to_string())
                .collect();

            styles.push(RegistryEntry {
                id: (*name).to_string(),
                aliases: style_aliases,
                builtin: Some((*name).to_string()),
                path: None,
                url: None,
                title: None,
                description: None,
                fields: Vec::new(),
                kind: None,
            });
        }

        StyleRegistry {
            version: "1".to_string(),
            styles,
        }
    }

    /// Load the embedded default registry from the compiled-in YAML data.
    ///
    /// # Panics
    /// Panics only if the embedded YAML is malformed (should never happen in
    /// a correctly built binary).
    #[allow(
        clippy::expect_used,
        clippy::panic,
        reason = "Embedded registry must be valid at runtime"
    )]
    pub fn load_default() -> Self {
        DEFAULT_REGISTRY
            .get_or_init(|| {
                let bytes = include_bytes!("../embedded/registry/default.yaml");
                let registry: Self = serde_yaml::from_slice(bytes)
                    .expect("embedded registry/default.yaml is valid YAML");
                registry
                    .validate_sources()
                    .expect("embedded registry/default.yaml has valid style sources");
                for entry in &registry.styles {
                    if entry.kind == Some(StyleKind::Profile)
                        && let Some(name) = &entry.builtin
                        && let Some(style) = crate::embedded::get_embedded_style(name)
                    {
                        let style = style.expect("embedded profile style should parse");
                        style.validate_profile_shape().unwrap_or_else(|err| {
                            panic!("embedded profile `{name}` violates profile contract: {err}")
                        });
                    }
                }
                registry
            })
            .clone()
    }

    /// Load a registry from a YAML file on disk.
    ///
    /// # Errors
    /// Returns an error if the file cannot be read or if the YAML cannot be parsed.
    /// Also returns an error if any entry does not have exactly one of
    /// `builtin`, `path`, or `url`.
    pub fn load_from_file(path: &std::path::Path) -> Result<Self, Box<dyn std::error::Error>> {
        let content = std::fs::read(path)?;
        let registry: Self = serde_yaml::from_slice(&content)?;
        registry.validate_sources()?;
        Ok(registry)
    }

    /// Validate that each entry declares exactly one loadable style source.
    ///
    /// # Errors
    /// Returns an error if any entry has no source or multiple sources.
    pub fn validate_sources(&self) -> Result<(), Box<dyn std::error::Error>> {
        for entry in &self.styles {
            let source_count = usize::from(entry.builtin.is_some())
                + usize::from(entry.path.is_some())
                + usize::from(entry.url.is_some());
            if source_count != 1 {
                return Err(format!(
                    "Registry entry '{}' must have exactly one of 'builtin', 'path', or 'url'",
                    entry.id
                )
                .into());
            }
        }
        Ok(())
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::todo,
    clippy::unimplemented,
    clippy::unreachable,
    clippy::get_unwrap,
    reason = "Panicking is acceptable and often desired in tests."
)]
mod tests {
    use super::*;

    #[test]
    fn test_resolve_exact_id() {
        let registry = StyleRegistry {
            version: "1".to_string(),
            styles: vec![RegistryEntry {
                id: "apa-7th".to_string(),
                aliases: vec!["apa".to_string()],
                builtin: Some("apa-7th".to_string()),
                path: None,
                url: None,
                title: None,
                description: Some("APA 7th edition".to_string()),
                fields: vec!["psychology".to_string()],
                kind: None,
            }],
        };

        assert!(registry.resolve("apa-7th").is_some());
        assert_eq!(registry.resolve("apa-7th").unwrap().id, "apa-7th");
    }

    #[test]
    fn test_resolve_alias() {
        let registry = StyleRegistry {
            version: "1".to_string(),
            styles: vec![RegistryEntry {
                id: "apa-7th".to_string(),
                aliases: vec!["apa".to_string()],
                builtin: Some("apa-7th".to_string()),
                path: None,
                url: None,
                title: None,
                description: Some("APA 7th edition".to_string()),
                fields: vec!["psychology".to_string()],
                kind: None,
            }],
        };

        assert!(registry.resolve("apa").is_some());
        assert_eq!(registry.resolve("apa").unwrap().id, "apa-7th");
    }

    #[test]
    fn test_all_ids() {
        let registry = StyleRegistry {
            version: "1".to_string(),
            styles: vec![
                RegistryEntry {
                    id: "apa-7th".to_string(),
                    aliases: vec!["apa".to_string()],
                    builtin: Some("apa-7th".to_string()),
                    path: None,
                    url: None,
                    title: None,
                    description: None,
                    fields: vec![],
                    kind: None,
                },
                RegistryEntry {
                    id: "mla".to_string(),
                    aliases: vec![],
                    builtin: Some("mla".to_string()),
                    path: None,
                    url: None,
                    title: None,
                    description: None,
                    fields: vec![],
                    kind: None,
                },
            ],
        };

        let ids: Vec<_> = registry.all_ids().collect();
        assert_eq!(ids, vec!["apa-7th", "mla"]);
    }

    #[test]
    fn test_merge_over() {
        let base = StyleRegistry {
            version: "1".to_string(),
            styles: vec![RegistryEntry {
                id: "apa-7th".to_string(),
                aliases: vec!["apa".to_string()],
                builtin: Some("apa-7th".to_string()),
                path: None,
                url: None,
                title: None,
                description: Some("APA 7th edition".to_string()),
                fields: vec!["psychology".to_string()],
                kind: None,
            }],
        };

        let custom = StyleRegistry {
            version: "1".to_string(),
            styles: vec![
                RegistryEntry {
                    id: "custom-style".to_string(),
                    aliases: vec!["custom".to_string()],
                    path: Some(PathBuf::from("custom.yaml")),
                    builtin: None,
                    url: None,
                    title: None,
                    description: Some("Custom style".to_string()),
                    fields: vec![],
                    kind: None,
                },
                RegistryEntry {
                    id: "apa-7th".to_string(),
                    aliases: vec!["apa".to_string()],
                    builtin: Some("apa-7th".to_string()),
                    path: None,
                    url: None,
                    title: None,
                    description: Some("APA 7th edition (modified)".to_string()),
                    fields: vec!["psychology".to_string(), "custom".to_string()],
                    kind: None,
                },
            ],
        };

        let merged = custom.merge_over(&base);

        assert_eq!(merged.styles.len(), 2);
        assert!(merged.resolve("custom").is_some());
        assert_eq!(
            merged.resolve("apa-7th").unwrap().description,
            Some("APA 7th edition (modified)".to_string())
        );
    }

    #[test]
    fn test_from_slices() {
        let names = &["apa-7th", "mla"];
        let aliases = &[("apa", "apa-7th"), ("mla", "mla")];

        let registry = StyleRegistry::from_slices(names, aliases);

        assert_eq!(registry.styles.len(), 2);
        assert_eq!(registry.resolve("apa").unwrap().id, "apa-7th");
        assert_eq!(registry.resolve("mla").unwrap().id, "mla");
    }

    #[test]
    fn test_load_default_keeps_profiles_valid() {
        let registry = StyleRegistry::load_default();
        let entry = registry
            .resolve("elsevier-harvard")
            .expect("elsevier-harvard should exist");
        assert_eq!(entry.kind, Some(StyleKind::Profile));
    }

    #[test]
    fn default_registry_exposes_gb_t_7714_heads_but_hides_the_family_base() {
        let registry = StyleRegistry::load_default();
        let public_heads = [
            "gb-t-7714-2025-numeric",
            "gb-t-7714-2025-author-date",
            "gb-t-7714-2025-note",
        ];

        for id in public_heads {
            let entry = registry
                .resolve(id)
                .unwrap_or_else(|| panic!("{id} should be discoverable"));
            assert_eq!(entry.id, id);
            assert_eq!(entry.builtin.as_deref(), Some(id));
            assert_eq!(entry.kind, Some(StyleKind::Base));
        }

        for alias in ["gb-t-7714-2025", "gb7714-2025"] {
            assert_eq!(
                registry.resolve(alias).map(|entry| entry.id.as_str()),
                Some("gb-t-7714-2025-numeric")
            );
        }
        assert!(
            registry.resolve("gb-t-7714-2025-base").is_none(),
            "the hidden family base should not appear in public discovery"
        );
    }

    #[test]
    fn test_load_default_contains_embedded_and_core_http_entries() {
        let registry = StyleRegistry::load_default();
        let embedded = registry.resolve("apa-7th").expect("apa-7th should exist");
        assert_eq!(embedded.builtin.as_deref(), Some("apa-7th"));

        let core_http = registry.resolve("alpha").expect("alpha should exist");
        assert_eq!(
            core_http.url.as_deref(),
            Some("https://raw.githubusercontent.com/citum/citum-core/main/styles/alpha.yaml")
        );
    }
}