Skip to main content

mla_titlecase/
plugin.rs

1//! Versioned plugin schema shared by the library and CLI.
2
3use serde::{Deserialize, Serialize};
4
5use crate::{error::Result, lexicon::ExternalLexicons, util::normalize::lookup_key, Error};
6
7/// Current stable plugin schema version.
8pub const PLUGIN_SCHEMA_VERSION: u32 = 1;
9
10/// Top-level plugin document.
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12pub struct LexiconPlugin {
13    /// Provenance and compatibility metadata.
14    pub metadata: PluginMetadata,
15    /// Plugin payload.
16    pub payload: PluginPayload,
17}
18
19impl LexiconPlugin {
20    /// Returns the payload kind.
21    #[must_use]
22    pub fn payload_kind(&self) -> PluginPayloadKind {
23        self.payload.kind()
24    }
25
26    /// Validates the plugin contents.
27    pub fn validate(&self) -> Result<()> {
28        self.metadata.validate()?;
29        self.payload.validate()
30    }
31
32    /// Registers the plugin into an [`ExternalLexicons`] container.
33    pub fn register_into(&self, external: &mut ExternalLexicons) -> Result<()> {
34        self.validate()?;
35        external.register_plugin(self)
36    }
37}
38
39/// Provenance and compatibility metadata for a plugin.
40#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
41pub struct PluginMetadata {
42    /// Stable schema version.
43    pub schema_version: u32,
44    /// Plugin revision chosen by the producer.
45    pub plugin_version: u32,
46    /// Source identifier such as `scowl` or `stopwords-iso`.
47    pub source_id: String,
48    /// Optional upstream source version.
49    pub source_version: Option<String>,
50    /// Optional upstream URL.
51    pub upstream_url: Option<String>,
52    /// Producer timestamp string.
53    pub prepared_at: String,
54    /// Optional checksum covering the generated artifact.
55    pub checksum: Option<String>,
56    /// Human-readable license summary.
57    pub license_summary: String,
58    /// Optional notice text to preserve in downstream artifacts.
59    pub notice: Option<String>,
60}
61
62impl PluginMetadata {
63    /// Returns minimal metadata for ad-hoc plugins.
64    #[must_use]
65    pub fn new(source_id: impl Into<String>, license_summary: impl Into<String>) -> Self {
66        Self {
67            schema_version: PLUGIN_SCHEMA_VERSION,
68            plugin_version: 1,
69            source_id: source_id.into(),
70            source_version: None,
71            upstream_url: None,
72            prepared_at: "unknown".to_string(),
73            checksum: None,
74            license_summary: license_summary.into(),
75            notice: None,
76        }
77    }
78
79    /// Validates the metadata fields.
80    pub fn validate(&self) -> Result<()> {
81        if self.schema_version != PLUGIN_SCHEMA_VERSION {
82            return Err(Error::UnsupportedVersion {
83                found: self.schema_version,
84                expected: PLUGIN_SCHEMA_VERSION,
85            });
86        }
87
88        if self.source_id.trim().is_empty() {
89            return Err(Error::InvalidData("plugin source_id cannot be empty".to_string()));
90        }
91
92        if self.license_summary.trim().is_empty() {
93            return Err(Error::InvalidData("plugin license_summary cannot be empty".to_string()));
94        }
95
96        Ok(())
97    }
98}
99
100/// Payload kinds supported by the plugin format.
101#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
102#[serde(rename_all = "kebab-case")]
103pub enum PluginPayloadKind {
104    /// Case-insensitive word membership.
105    WordSet,
106    /// Canonical spellings keyed by lowercase lookup keys.
107    CanonicalMap,
108    /// Canonical spellings keyed by normalized multiword phrases.
109    MultiwordMap,
110    /// Ranked or commonness-ordered words.
111    RankedWords,
112    /// Protected spellings keyed by lowercase lookup keys.
113    ProtectedSpellings,
114}
115
116impl PluginPayloadKind {
117    pub(crate) const fn tag(self) -> u8 {
118        match self {
119            Self::WordSet => 1,
120            Self::CanonicalMap => 2,
121            Self::MultiwordMap => 3,
122            Self::RankedWords => 4,
123            Self::ProtectedSpellings => 5,
124        }
125    }
126
127    pub(crate) fn from_tag(tag: u8) -> Result<Self> {
128        match tag {
129            1 => Ok(Self::WordSet),
130            2 => Ok(Self::CanonicalMap),
131            3 => Ok(Self::MultiwordMap),
132            4 => Ok(Self::RankedWords),
133            5 => Ok(Self::ProtectedSpellings),
134            _ => Err(Error::InvalidData(format!("unknown plugin payload tag {tag}"))),
135        }
136    }
137}
138
139/// Key/value entry used by canonical and protected payloads.
140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
141pub struct MapEntry {
142    /// Case-insensitive lookup key.
143    pub key: String,
144    /// Canonical output spelling.
145    pub value: String,
146}
147
148/// Ranked word entry used by ranked payloads.
149#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
150pub struct RankedEntry {
151    /// Case-insensitive lookup key.
152    pub word: String,
153    /// Rank or commonness score.
154    pub rank: u64,
155}
156
157/// Supported plugin payload values.
158#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
159#[serde(tag = "kind", rename_all = "kebab-case")]
160pub enum PluginPayload {
161    /// Case-insensitive word membership.
162    WordSet {
163        /// Stored words.
164        words: Vec<String>,
165    },
166    /// Canonical spellings keyed by lowercase lookup keys.
167    CanonicalMap {
168        /// Stored key/value entries.
169        entries: Vec<MapEntry>,
170    },
171    /// Canonical spellings keyed by normalized multiword phrases.
172    MultiwordMap {
173        /// Stored key/value entries.
174        entries: Vec<MapEntry>,
175    },
176    /// Ranked words keyed by lowercase lookup keys.
177    RankedWords {
178        /// Stored ranked entries.
179        entries: Vec<RankedEntry>,
180    },
181    /// Protected spellings keyed by lowercase lookup keys.
182    ProtectedSpellings {
183        /// Stored key/value entries.
184        entries: Vec<MapEntry>,
185    },
186}
187
188impl PluginPayload {
189    /// Returns the payload kind.
190    #[must_use]
191    pub fn kind(&self) -> PluginPayloadKind {
192        match self {
193            Self::WordSet { .. } => PluginPayloadKind::WordSet,
194            Self::CanonicalMap { .. } => PluginPayloadKind::CanonicalMap,
195            Self::MultiwordMap { .. } => PluginPayloadKind::MultiwordMap,
196            Self::RankedWords { .. } => PluginPayloadKind::RankedWords,
197            Self::ProtectedSpellings { .. } => PluginPayloadKind::ProtectedSpellings,
198        }
199    }
200
201    /// Returns the number of stored entries.
202    #[must_use]
203    pub fn len(&self) -> usize {
204        match self {
205            Self::WordSet { words } => words.len(),
206            Self::CanonicalMap { entries }
207            | Self::MultiwordMap { entries }
208            | Self::ProtectedSpellings { entries } => entries.len(),
209            Self::RankedWords { entries } => entries.len(),
210        }
211    }
212
213    /// Returns whether the payload is empty.
214    #[must_use]
215    pub fn is_empty(&self) -> bool {
216        self.len() == 0
217    }
218
219    pub(crate) fn validate(&self) -> Result<()> {
220        match self {
221            Self::WordSet { words } => validate_words(words),
222            Self::CanonicalMap { entries } | Self::ProtectedSpellings { entries } => {
223                validate_map_entries(entries)
224            }
225            Self::MultiwordMap { entries } => validate_multiword_entries(entries),
226            Self::RankedWords { entries } => validate_ranked_entries(entries),
227        }
228    }
229}
230
231fn validate_words(words: &[String]) -> Result<()> {
232    let mut seen = std::collections::BTreeSet::new();
233    for word in words {
234        let key = lookup_key(word);
235        if key.is_empty() {
236            return Err(Error::InvalidData("word-set entries cannot be empty".to_string()));
237        }
238        if !seen.insert(key) {
239            return Err(Error::InvalidData("word-set entries must be unique".to_string()));
240        }
241    }
242    Ok(())
243}
244
245fn validate_map_entries(entries: &[MapEntry]) -> Result<()> {
246    let mut seen = std::collections::BTreeSet::new();
247    for entry in entries {
248        let key = lookup_key(&entry.key);
249        if key.is_empty() || entry.value.trim().is_empty() {
250            return Err(Error::InvalidData(
251                "map entries require non-empty keys and values".to_string(),
252            ));
253        }
254        if !seen.insert(key) {
255            return Err(Error::InvalidData("map entries must be unique".to_string()));
256        }
257    }
258    Ok(())
259}
260
261fn validate_multiword_entries(entries: &[MapEntry]) -> Result<()> {
262    validate_map_entries(entries)?;
263    for entry in entries {
264        if !entry.key.contains(' ') {
265            return Err(Error::InvalidData(
266                "multiword-map entries require keys containing at least one space".to_string(),
267            ));
268        }
269    }
270    Ok(())
271}
272
273fn validate_ranked_entries(entries: &[RankedEntry]) -> Result<()> {
274    let mut seen = std::collections::BTreeSet::new();
275    for entry in entries {
276        let key = lookup_key(&entry.word);
277        if key.is_empty() {
278            return Err(Error::InvalidData(
279                "ranked-word entries require a non-empty word".to_string(),
280            ));
281        }
282        if !seen.insert(key) {
283            return Err(Error::InvalidData("ranked-word entries must be unique".to_string()));
284        }
285    }
286    Ok(())
287}
288
289#[cfg(test)]
290mod tests {
291    use super::{
292        LexiconPlugin, MapEntry, PluginMetadata, PluginPayload, PluginPayloadKind, RankedEntry,
293    };
294    use crate::ExternalLexicons;
295
296    #[test]
297    fn validates_payloads() {
298        let plugin = LexiconPlugin {
299            metadata: PluginMetadata::new("fixture", "MIT"),
300            payload: PluginPayload::CanonicalMap {
301                entries: vec![MapEntry { key: "github".to_string(), value: "GitHub".to_string() }],
302            },
303        };
304
305        assert_eq!(plugin.payload_kind(), PluginPayloadKind::CanonicalMap);
306        assert!(plugin.validate().is_ok());
307    }
308
309    #[test]
310    fn rejects_duplicate_words() {
311        let plugin = LexiconPlugin {
312            metadata: PluginMetadata::new("fixture", "MIT"),
313            payload: PluginPayload::WordSet { words: vec!["and".to_string(), "AND".to_string()] },
314        };
315
316        assert!(plugin.validate().is_err());
317    }
318
319    #[test]
320    fn validates_ranked_entries() {
321        let plugin = LexiconPlugin {
322            metadata: PluginMetadata::new("fixture", "MIT"),
323            payload: PluginPayload::RankedWords {
324                entries: vec![RankedEntry { word: "common".to_string(), rank: 7 }],
325            },
326        };
327
328        assert!(plugin.validate().is_ok());
329    }
330
331    #[test]
332    fn validates_multiword_entries() {
333        let plugin = LexiconPlugin {
334            metadata: PluginMetadata::new("fixture", "MIT"),
335            payload: PluginPayload::MultiwordMap {
336                entries: vec![MapEntry {
337                    key: "new york city".to_string(),
338                    value: "New York City".to_string(),
339                }],
340            },
341        };
342
343        assert!(plugin.validate().is_ok());
344    }
345
346    #[test]
347    fn registers_plugins_into_external_lexicons() {
348        let plugin = LexiconPlugin {
349            metadata: PluginMetadata::new("fixture", "MIT"),
350            payload: PluginPayload::ProtectedSpellings {
351                entries: vec![MapEntry { key: "github".to_string(), value: "GitHub".to_string() }],
352            },
353        };
354        let mut lexicons = ExternalLexicons::default();
355
356        plugin.register_into(&mut lexicons).unwrap();
357
358        assert_eq!(lexicons.protected_spelling("github"), Some("GitHub"));
359    }
360}