1use std::collections::HashMap;
6
7use serde::Deserialize;
8
9use crate::core::error::{CatalogError, Result};
10
11use super::{
12 CATALOG_DATA, Catalog, CatalogEntry, EnumDomain, EnumMember, Kind, Locale,
13 LocalizedStringEntry, ParamCoercions, Provenance, TargetMeta,
14};
15
16#[derive(Deserialize)]
17#[serde(rename_all = "camelCase")]
18struct CatalogFile {
19 schema_version: u32,
20 locales: Vec<String>,
21 target: TargetMeta,
22 provenance: Provenance,
23 #[serde(default)]
25 version: Option<String>,
26 #[serde(default)]
28 digest: Option<String>,
29 #[serde(default)]
30 structural: Vec<EntryFile>,
31 #[serde(default)]
32 actions: Vec<EntryFile>,
33 #[serde(default)]
34 values: Vec<EntryFile>,
35 #[serde(default)]
36 events: Vec<EntryFile>,
37 #[serde(default)]
38 operators: Vec<EntryFile>,
39 #[serde(default)]
40 settings: Vec<EntryFile>,
41 #[serde(default)]
42 localized_strings: Vec<LocalizedStringFile>,
43 #[serde(default)]
44 enums: Vec<EnumFile>,
45}
46
47#[derive(Deserialize)]
48#[serde(rename_all = "camelCase")]
49struct EntryFile {
50 id: String,
51 aliases: HashMap<String, AliasFile>,
52 #[serde(default)]
53 params: Vec<String>,
54 #[serde(default)]
56 param_names: Vec<String>,
57 #[serde(default)]
58 param_aliases: Vec<HashMap<String, AliasFile>>,
59 #[serde(default)]
62 param_domains: Vec<Option<String>>,
63 #[serde(default)]
70 param_defaults: Vec<Option<String>>,
71 #[serde(default)]
72 param_types: Vec<Option<String>>,
73 #[serde(default)]
74 param_coercions: Vec<Option<ParamCoercions>>,
75 #[serde(default)]
76 return_type: Option<String>,
77 #[serde(default)]
78 variadic: bool,
79}
80
81#[derive(Deserialize)]
82struct LocalizedStringFile {
83 id: String,
84 aliases: HashMap<String, AliasFile>,
85}
86
87#[derive(Deserialize)]
88struct EnumFile {
89 domain: String,
90 #[serde(default)]
91 aliases: HashMap<String, AliasFile>,
92 members: Vec<MemberFile>,
93}
94
95#[derive(Deserialize)]
96struct MemberFile {
97 id: String,
98 aliases: HashMap<String, AliasFile>,
99}
100
101#[derive(Debug, Deserialize)]
106#[serde(untagged)]
107enum AliasFile {
108 One(String),
109 Many(Vec<String>),
110}
111
112impl AliasFile {
113 fn into_spellings(self, id: &str, locale: &str) -> Result<Vec<String>> {
114 let spellings = match self {
115 AliasFile::One(spelling) => vec![spelling],
116 AliasFile::Many(spellings) => spellings,
117 };
118 if spellings.is_empty() || spellings.iter().any(String::is_empty) {
119 return Err(CatalogError::validation(format!(
120 "catalog entry '{}' declares an empty alias for locale '{}'",
121 id, locale
122 )));
123 }
124 Ok(spellings)
125 }
126}
127impl Catalog {
128 pub fn load(json: &str) -> Result<Catalog> {
131 let catalog = Self::load_unverified(json)?;
132 if let Some(declared) = &catalog.catalog_digest {
133 let computed = content_digest(json)?;
134 if declared != &computed {
135 return Err(CatalogError::validation(format!(
136 "catalog digest mismatch: declared '{declared}', content '{computed}' — \
137 run the catalog pipeline (workshop-catalog-gen build)"
138 )));
139 }
140 }
141 Ok(catalog)
142 }
143
144 pub fn load_unverified(json: &str) -> Result<Catalog> {
147 let file: CatalogFile = serde_json::from_str(json)
148 .map_err(|error| CatalogError::malformed(format!("catalog data: {error}")))?;
149 if file.schema_version != 1 {
150 return Err(CatalogError::malformed(format!(
151 "unsupported catalog schemaVersion {}",
152 file.schema_version
153 )));
154 }
155 let locales: Vec<Locale> = file.locales.iter().map(|s| Locale::new(s)).collect();
156 if locales.is_empty() {
157 return Err(CatalogError::malformed(
158 "catalog declares no locales".to_string(),
159 ));
160 }
161
162 let mut catalog = Catalog {
163 schema_version: file.schema_version,
164 locales,
165 target: file.target,
166 provenance: file.provenance,
167 catalog_version: file.version.unwrap_or_else(|| "dev".to_string()),
168 catalog_digest: file.digest,
169 entries: Vec::new(),
170 localized_strings: Vec::new(),
171 enums: Vec::new(),
172 by_id: Default::default(),
173 alias_to_entry: HashMap::new(),
174 localized_string_by_id: HashMap::new(),
175 localized_string_alias: HashMap::new(),
176 enum_by_domain: HashMap::new(),
177 enum_alias_to_domain: HashMap::new(),
178 enum_alias_to_member: HashMap::new(),
179 bare_member_index: HashMap::new(),
180 };
181
182 for (kind, items) in [
183 (Kind::Structural, file.structural),
184 (Kind::Action, file.actions),
185 (Kind::Value, file.values),
186 (Kind::Event, file.events),
187 (Kind::Operator, file.operators),
188 (Kind::Setting, file.settings),
189 ] {
190 for item in items {
191 catalog.insert_entry(kind, item)?;
192 }
193 }
194 for item in file.localized_strings {
195 catalog.insert_localized_string(item)?;
196 }
197 for domain in file.enums {
198 catalog.insert_enum(domain)?;
199 }
200 for domain in &catalog.enums {
201 for member in &domain.members {
202 for (locale, spellings) in &member.aliases {
203 for spelling in spellings {
204 catalog
205 .bare_member_index
206 .entry(locale.clone())
207 .or_default()
208 .entry(spelling.clone())
209 .or_default()
210 .push((domain.domain.clone(), member.member.clone()));
211 }
212 }
213 }
214 }
215 catalog.validate_param_domains()?;
216 Ok(catalog)
217 }
218
219 pub fn builtin() -> Result<Catalog> {
221 Self::load(CATALOG_DATA)
222 }
223 fn insert_entry(&mut self, kind: Kind, item: EntryFile) -> Result<()> {
224 let index = self.entries.len();
225 let aliases = self.collect_aliases(
226 &item.id,
227 &format!("entry '{}'", item.id),
228 item.aliases,
229 true,
230 |catalog, locale, spelling| {
231 let locale_map = catalog.alias_to_entry.entry(locale.clone()).or_default();
232 if locale_map[kind.as_index()].contains_key(spelling) {
233 return Err(CatalogError::validation(format!(
234 "duplicate {} alias '{spelling}' for locale '{locale}'",
235 kind.as_str()
236 )));
237 }
238 locale_map[kind.as_index()].insert(spelling.to_string(), index);
239 Ok(())
240 },
241 )?;
242 if self.by_id[kind.as_index()].contains_key(&item.id) {
243 return Err(CatalogError::validation(format!(
244 "duplicate {} id '{}'",
245 kind.as_str(),
246 item.id
247 )));
248 }
249 let param_names = match item.param_names {
254 names if names.is_empty() => None,
255 names if names.len() != item.params.len() => {
256 return Err(CatalogError::validation(format!(
257 "{} '{}' declares {} param names for {} params",
258 kind.as_str(),
259 item.id,
260 names.len(),
261 item.params.len()
262 )));
263 }
264 names if names == item.params => None,
265 names => Some(names),
266 };
267 self.by_id[kind.as_index()].insert(item.id.clone(), index);
268 let item_id = item.id.clone();
269 self.entries.push(CatalogEntry {
270 id: item.id,
271 kind,
272 params: item.params,
273 param_names,
274 param_aliases: item
275 .param_aliases
276 .into_iter()
277 .map(|aliases| {
278 aliases
279 .into_iter()
280 .map(|(locale, alias)| {
281 let locale_key = Locale::new(&locale);
282 let spellings = alias.into_spellings(&item_id, locale_key.as_str())?;
283 Ok((locale_key, spellings))
284 })
285 .collect::<Result<HashMap<_, _>>>()
286 })
287 .collect::<Result<Vec<_>>>()?,
288 param_domains: item.param_domains,
289 param_defaults: item.param_defaults,
290 param_types: item.param_types,
291 param_coercions: item.param_coercions,
292 return_type: item.return_type,
293 variadic: item.variadic,
294 aliases,
295 });
296 Ok(())
297 }
298
299 fn insert_localized_string(&mut self, item: LocalizedStringFile) -> Result<()> {
300 if self.localized_string_by_id.contains_key(&item.id) {
301 return Err(CatalogError::validation(format!(
302 "duplicate localized string id '{}'",
303 item.id
304 )));
305 }
306 let index = self.localized_strings.len();
307 let aliases = self.collect_aliases(
308 &item.id,
309 &format!("localized string '{}'", item.id),
310 item.aliases,
311 true,
312 |catalog, locale, spelling| {
313 let locale_map = catalog
314 .localized_string_alias
315 .entry(locale.clone())
316 .or_default();
317 if locale_map.contains_key(spelling) {
318 return Err(CatalogError::validation(format!(
319 "duplicate localized string alias '{spelling}' for locale '{locale}'"
320 )));
321 }
322 locale_map.insert(spelling.to_string(), index);
323 Ok(())
324 },
325 )?;
326 self.localized_string_by_id.insert(item.id.clone(), index);
327 self.localized_strings.push(LocalizedStringEntry {
328 id: item.id,
329 aliases,
330 });
331 Ok(())
332 }
333
334 fn validate_param_domains(&self) -> Result<()> {
336 for entry in &self.entries {
337 for (name, count) in [
338 ("parameter alias sets", entry.param_aliases.len()),
339 ("param domains", entry.param_domains.len()),
340 ("param defaults", entry.param_defaults.len()),
341 ("param types", entry.param_types.len()),
342 ("param coercions", entry.param_coercions.len()),
343 ] {
344 if count > entry.params.len() {
345 return Err(CatalogError::validation(format!(
346 "{} '{}' declares more {name} than params",
347 entry.kind.as_str(),
348 entry.id
349 )));
350 }
351 }
352 if entry.kind != Kind::Value && entry.return_type.is_some() {
353 return Err(CatalogError::validation(format!(
354 "{} '{}' declares a return type but is not a value",
355 entry.kind.as_str(),
356 entry.id
357 )));
358 }
359 for domain in entry.param_domains.iter().flatten() {
360 if !self.enum_by_domain.contains_key(domain) {
361 return Err(CatalogError::validation(format!(
362 "{} '{}' declares undeclared enum domain '{domain}'",
363 entry.kind.as_str(),
364 entry.id
365 )));
366 }
367 }
368 for aliases in &entry.param_aliases {
369 for locale in aliases.keys() {
370 if !self.locales.contains(locale) {
371 return Err(CatalogError::validation(format!(
372 "{} '{}' declares parameter alias for undeclared locale '{}'",
373 entry.kind.as_str(),
374 entry.id,
375 locale
376 )));
377 }
378 }
379 }
380 }
381 Ok(())
382 }
383
384 fn insert_enum(&mut self, domain: EnumFile) -> Result<()> {
385 let domain_index = self.enums.len();
386 if self.enum_by_domain.contains_key(&domain.domain) {
387 return Err(CatalogError::validation(format!(
388 "duplicate enum domain '{}'",
389 domain.domain
390 )));
391 }
392 let primary = self.locales[0].clone();
393 let mut domain_aliases = self.collect_aliases(
394 &domain.domain,
395 &format!("enum domain '{}'", domain.domain),
396 domain.aliases,
397 false,
398 |catalog, locale, spelling| {
399 let locale_map = catalog
400 .enum_alias_to_domain
401 .entry(locale.clone())
402 .or_default();
403 if let Some(existing) = locale_map.get(spelling) {
404 return Err(CatalogError::validation(format!(
405 "duplicate enum domain alias '{spelling}' for '{existing}' and '{}' in locale '{locale}'",
406 domain.domain
407 )));
408 }
409 locale_map.insert(spelling.to_string(), domain.domain.clone());
410 Ok(())
411 },
412 )?;
413 domain_aliases
414 .entry(primary.clone())
415 .or_insert_with(|| vec![domain.domain.clone()]);
416 self.enum_alias_to_domain
417 .entry(primary.clone())
418 .or_default()
419 .entry(domain.domain.clone())
420 .or_insert_with(|| domain.domain.clone());
421 let mut members = Vec::new();
422 for (member_index, member) in domain.members.into_iter().enumerate() {
423 let aliases = self.collect_aliases(
424 &member.id,
425 &format!("enum {}::{}", domain.domain, member.id),
426 member.aliases,
427 true,
428 |catalog, locale, spelling| {
429 let domain_map = catalog
430 .enum_alias_to_member
431 .entry(locale.clone())
432 .or_default()
433 .entry(domain.domain.clone())
434 .or_default();
435 if domain_map.contains_key(spelling) {
436 return Err(CatalogError::validation(format!(
437 "duplicate enum alias '{spelling}' in '{}' for locale '{locale}'",
438 domain.domain
439 )));
440 }
441 domain_map.insert(spelling.to_string(), (domain_index, member_index));
442 Ok(())
443 },
444 )?;
445 members.push(EnumMember {
446 member: member.id,
447 aliases,
448 });
449 }
450 self.enum_by_domain
451 .insert(domain.domain.clone(), domain_index);
452 self.enums.push(EnumDomain {
453 domain: domain.domain,
454 aliases: domain_aliases,
455 members,
456 });
457 Ok(())
458 }
459
460 fn collect_aliases(
465 &mut self,
466 id: &str,
467 label: &str,
468 aliases: HashMap<String, AliasFile>,
469 require_primary: bool,
470 mut register: impl FnMut(&mut Self, &Locale, &str) -> Result<()>,
471 ) -> Result<HashMap<Locale, Vec<String>>> {
472 let mut collected = HashMap::new();
473 for (locale_str, alias_file) in aliases {
474 let locale = Locale::new(&locale_str);
475 if !self.locales.contains(&locale) {
476 return Err(CatalogError::validation(format!(
477 "{label} declares alias for undeclared locale '{locale}'"
478 )));
479 }
480 let spellings = alias_file.into_spellings(id, locale.as_str())?;
481 for spelling in &spellings {
482 register(self, &locale, spelling)?;
483 }
484 collected.insert(locale, spellings);
485 }
486 let primary = &self.locales[0];
487 if require_primary && !collected.contains_key(primary) {
488 return Err(CatalogError::validation(format!(
489 "{label} is missing a '{primary}' alias"
490 )));
491 }
492 Ok(collected)
493 }
494}
495
496pub fn canonicalize(json: &str) -> Result<String> {
502 Catalog::load_unverified(json)?;
504 let value: serde_json::Value = serde_json::from_str(json)
505 .map_err(|error| CatalogError::malformed(format!("catalog data: {error}")))?;
506 pretty_json(&value)
507}
508
509pub fn build_canonical(json: &str) -> Result<String> {
513 let mut value: serde_json::Value = serde_json::from_str(json)
514 .map_err(|error| CatalogError::malformed(format!("catalog data: {error}")))?;
515 let digest = content_digest(json)?;
516 if let Some(object) = value.as_object_mut() {
517 object.insert("digest".to_string(), serde_json::Value::String(digest));
518 }
519 let output = pretty_json(&value)?;
520 Catalog::load(&output)?;
523 Ok(output)
524}
525
526pub fn content_digest(json: &str) -> Result<String> {
531 let mut value: serde_json::Value = serde_json::from_str(json)
532 .map_err(|error| CatalogError::malformed(format!("catalog data: {error}")))?;
533 if let Some(object) = value.as_object_mut() {
534 object.remove("digest");
535 }
536 let canonical = pretty_json(&value)?;
537 use sha2::{Digest, Sha256};
538 let mut hasher = Sha256::new();
539 hasher.update(canonical.trim_end().as_bytes());
540 Ok(format!("{:x}", hasher.finalize()))
541}
542
543fn pretty_json(value: &serde_json::Value) -> Result<String> {
546 serde_json::to_string_pretty(value)
547 .map(|mut out| {
548 out.push('\n');
549 out
550 })
551 .map_err(|error| CatalogError::malformed(format!("cannot serialize catalog: {error}")))
552}