1use std::collections::BTreeMap;
28use std::fmt::Write as _;
29use std::path::{Component, Path, PathBuf};
30
31use base64::Engine as _;
32use prost_reflect::DescriptorPool;
33use serde_json::Value;
34use sha2::{Digest, Sha256};
35
36use crate::authoring::{RawType, SchemasSection, TypeRef};
37use crate::diag::{Diagnostic, Report};
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
41pub enum SchemaKind {
42 Protobuf,
43 JsonSchema,
44 Packed,
47}
48
49impl SchemaKind {
50 #[must_use]
51 pub fn as_str(self) -> &'static str {
52 match self {
53 Self::Protobuf => "protobuf",
54 Self::JsonSchema => "jsonschema",
55 Self::Packed => "packed",
56 }
57 }
58}
59
60#[derive(Debug, Clone, PartialEq)]
62pub struct Artifact {
63 pub kind: SchemaKind,
64 pub name: String,
67 pub data: ArtifactData,
68}
69
70#[derive(Debug, Clone, PartialEq)]
71pub enum ArtifactData {
72 Protobuf(Vec<u8>),
74 Json(Value),
76}
77
78impl Artifact {
79 #[must_use]
81 pub fn id(&self) -> String {
82 match &self.data {
83 ArtifactData::Protobuf(b) => sha256_id(b),
84 ArtifactData::Json(v) => sha256_id(&jcs(v)),
85 }
86 }
87
88 #[must_use]
91 pub fn data_value(&self) -> Value {
92 match &self.data {
93 ArtifactData::Protobuf(b) => {
94 Value::String(base64::engine::general_purpose::STANDARD.encode(b))
95 }
96 ArtifactData::Json(v) => v.clone(),
97 }
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
103pub enum TypeId {
104 Protobuf {
105 name: String,
106 schema: String,
107 },
108 JsonSchema {
109 name: String,
110 schema: String,
111 },
112 Packed {
114 name: String,
115 schema: String,
116 },
117 Raw {
118 media_type: String,
119 media_param: Option<String>,
120 },
121}
122
123impl TypeId {
124 #[must_use]
125 pub fn kind_str(&self) -> &'static str {
126 match self {
127 Self::Protobuf { .. } => "protobuf",
128 Self::JsonSchema { .. } => "jsonschema",
129 Self::Packed { .. } => "packed",
130 Self::Raw { .. } => "raw",
131 }
132 }
133 #[must_use]
134 pub fn is_json(&self) -> bool {
135 matches!(self, Self::JsonSchema { .. })
136 }
137 #[must_use]
138 pub fn is_packed(&self) -> bool {
139 matches!(self, Self::Packed { .. })
140 }
141}
142
143struct ProtoFile {
144 name: String,
146 pool: DescriptorPool,
147 artifact: String,
148}
149
150struct JsonFile {
151 stem: String,
152 doc: Value,
153 artifact: String,
154}
155
156struct PackedFile {
157 stem: String,
158 doc: crate::packed::PackedDoc,
159 artifact: String,
160}
161
162pub struct SchemaSet {
164 artifacts: BTreeMap<String, Artifact>,
165 proto: Vec<ProtoFile>,
166 json: Vec<JsonFile>,
167 packed: Vec<PackedFile>,
168 proto_failed: bool,
171 json_failed: bool,
172 packed_failed: bool,
173}
174
175const WELL_KNOWN: &[(&str, &[&str])] = &[
177 ("google/protobuf/any.proto", &["Any"]),
178 ("google/protobuf/duration.proto", &["Duration"]),
179 ("google/protobuf/empty.proto", &["Empty"]),
180 ("google/protobuf/field_mask.proto", &["FieldMask"]),
181 (
182 "google/protobuf/struct.proto",
183 &["Struct", "Value", "ListValue"],
184 ),
185 ("google/protobuf/timestamp.proto", &["Timestamp"]),
186 (
187 "google/protobuf/wrappers.proto",
188 &[
189 "DoubleValue",
190 "FloatValue",
191 "Int64Value",
192 "UInt64Value",
193 "Int32Value",
194 "UInt32Value",
195 "BoolValue",
196 "StringValue",
197 "BytesValue",
198 ],
199 ),
200];
201
202impl SchemaSet {
203 pub fn load(dir: &Path, sec: &SchemasSection, report: &mut Report) -> Self {
205 let mut set = Self {
206 artifacts: BTreeMap::new(),
207 proto: Vec::new(),
208 json: Vec::new(),
209 packed: Vec::new(),
210 proto_failed: false,
211 json_failed: false,
212 packed_failed: false,
213 };
214 set.load_proto(dir, sec, report);
215 set.load_json(dir, sec, report);
216 set.load_packed(dir, sec, report);
217 set
218 }
219
220 fn load_packed(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
225 for f in &sec.packed {
226 let at = format!("schemas.packed {f:?}");
227 let doc = match std::fs::read_to_string(dir.join(f)) {
228 Ok(text) => match crate::strict::parse_json(&text) {
229 Ok(v) => v,
230 Err(e) => {
231 report.push(Diagnostic::error(
232 "E029",
233 at,
234 format!("is not valid JSON: {e}"),
235 ));
236 self.packed_failed = true;
237 continue;
238 }
239 },
240 Err(e) => {
241 report.push(Diagnostic::error(
242 "E029",
243 at,
244 format!("cannot be read: {e}"),
245 ));
246 self.packed_failed = true;
247 continue;
248 }
249 };
250 if let Some(n) = unsafe_integer(&doc) {
251 report.push(Diagnostic::error(
252 "E028",
253 at.clone(),
254 format!("{n} is outside ±(2^53−1), so the artifact has no portable id"),
255 ));
256 }
257 let stem = file_stem(f);
258 if self.packed.iter().any(|p| p.stem == stem) {
259 report.push(Diagnostic::error(
260 "E024",
261 at,
262 format!(
263 "a second listed packed file has the stem {stem:?}; stems are unique per contract"
264 ),
265 ));
266 continue;
267 }
268 let art = Artifact {
269 kind: SchemaKind::Packed,
270 name: stem.clone(),
271 data: ArtifactData::Json(doc.clone()),
272 };
273 let id = art.id();
274 let taken = self
275 .json
276 .iter()
277 .map(|j| (&j.artifact, &j.stem))
278 .chain(self.packed.iter().map(|p| (&p.artifact, &p.stem)))
279 .find(|(a, _)| **a == id);
280 if let Some((_, first)) = taken {
281 report.push(Diagnostic::error(
282 "E024",
283 at,
284 format!("the same document as {first:?} (one id); list it once"),
285 ));
286 continue;
287 }
288 let read = crate::packed::PackedDoc::read(&doc);
289 for x in &read.findings {
290 let place = if x.at.is_empty() {
291 at.clone()
292 } else {
293 format!("{at} {}", x.at)
294 };
295 report.push(Diagnostic::error(x.code, place, x.message.clone()));
296 }
297 self.artifacts.insert(id.clone(), art);
298 self.packed.push(PackedFile {
299 stem,
300 doc: read,
301 artifact: id,
302 });
303 }
304 }
305
306 #[must_use]
309 pub fn packed_layout(&self, t: &TypeId) -> Option<&crate::packed::Layout> {
310 let TypeId::Packed { name, schema } = t else {
311 return None;
312 };
313 self.packed
314 .iter()
315 .find(|p| &p.artifact == schema)?
316 .doc
317 .types
318 .get(name)?
319 .as_ref()
320 }
321
322 fn load_proto(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
323 if sec.protobuf.is_empty() {
324 return;
325 }
326 let includes: Vec<PathBuf> = match &sec.proto_include {
327 Some(v) => v.iter().map(|p| dir.join(p)).collect(),
328 None if dir.join("proto").is_dir() => vec![dir.join("proto")],
329 None => vec![dir.to_path_buf()],
330 };
331 for f in &sec.protobuf {
332 let at = format!("schemas.protobuf {f:?}");
333 let compiled = protox::Compiler::new(&includes).and_then(|mut c| {
334 c.include_imports(true).include_source_info(false);
335 c.open_file(dir.join(f))?;
336 Ok(c)
337 });
338 let c = match compiled {
339 Ok(c) => c,
340 Err(e) => {
341 report.push(Diagnostic::error(
342 "E029",
343 at,
344 format!("does not compile: {e}"),
345 ));
346 self.proto_failed = true;
347 continue;
348 }
349 };
350 let Some(name) = c
351 .files()
352 .find(|m| !m.is_import())
353 .map(|m| m.name().to_owned())
354 else {
355 report.push(Diagnostic::error("E029", at, "compiled to no file"));
356 self.proto_failed = true;
357 continue;
358 };
359 let art = Artifact {
360 kind: SchemaKind::Protobuf,
361 name: name.clone(),
362 data: ArtifactData::Protobuf(c.encode_file_descriptor_set()),
363 };
364 let id = art.id();
365 self.artifacts.insert(id.clone(), art);
366 self.proto.push(ProtoFile {
367 name,
368 pool: c.descriptor_pool(),
369 artifact: id,
370 });
371 }
372 }
373
374 fn load_json(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
375 let mut paths = Vec::new();
376 for f in &sec.jsonschema {
377 let at = format!("schemas.jsonschema {f:?}");
378 let path = dir.join(f);
379 let doc = match std::fs::read_to_string(&path) {
380 Ok(text) => match crate::strict::parse_json(&text) {
381 Ok(v) => v,
382 Err(e) => {
383 report.push(Diagnostic::error(
384 "E029",
385 at,
386 format!("is not valid JSON: {e}"),
387 ));
388 self.json_failed = true;
389 continue;
390 }
391 },
392 Err(e) => {
393 report.push(Diagnostic::error(
394 "E029",
395 at,
396 format!("cannot be read: {e}"),
397 ));
398 self.json_failed = true;
399 continue;
400 }
401 };
402 if let Some(n) = unsafe_integer(&doc) {
403 report.push(Diagnostic::error(
404 "E028",
405 at.clone(),
406 format!("{n} is outside ±(2^53−1), so the artifact has no portable id"),
407 ));
408 }
409 let mut refused = std::collections::BTreeSet::new();
410 refused_keywords(&doc, &mut refused);
411 for k in refused {
412 report.push(Diagnostic::error(
413 "E037",
414 at.clone(),
415 format!("keyword {k:?} is outside the zk2 JSON Schema subset"),
416 ));
417 }
418 let stem = file_stem(f);
419 if self.json.iter().any(|j| j.stem == stem) {
420 report.push(Diagnostic::error(
421 "E024",
422 at,
423 format!(
424 "a second listed file has the stem {stem:?}; stems are unique per contract"
425 ),
426 ));
427 continue;
428 }
429 let art = Artifact {
430 kind: SchemaKind::JsonSchema,
431 name: stem.clone(),
432 data: ArtifactData::Json(doc.clone()),
433 };
434 let id = art.id();
435 if let Some(first) = self.json.iter().find(|j| j.artifact == id) {
440 report.push(Diagnostic::error(
441 "E024",
442 at,
443 format!(
444 "the same document as {:?} (one id); list it once",
445 first.stem
446 ),
447 ));
448 continue;
449 }
450 self.artifacts.insert(id.clone(), art);
451 self.json.push(JsonFile {
452 stem,
453 doc,
454 artifact: id,
455 });
456 paths.push((f.clone(), normalize(&path)));
457 }
458 for (i, (f, path)) in paths.iter().enumerate() {
460 let mut refs = Vec::new();
461 collect_refs(&self.json[i].doc, &mut refs);
462 for r in refs {
463 let at = format!("schemas.jsonschema {f:?}");
464 let (file_part, pointer) = r.split_once('#').unwrap_or((r.as_str(), ""));
465 let target = if file_part.is_empty() {
466 Some(i)
467 } else if file_part.contains(':') {
468 None
469 } else {
470 let p = normalize(&path.parent().unwrap_or(Path::new("")).join(file_part));
471 paths.iter().position(|(_, q)| *q == p)
472 };
473 let Some(t) = target else {
474 report.push(Diagnostic::error(
475 "E032",
476 at,
477 format!("$ref {r:?} points outside the listed files"),
478 ));
479 continue;
480 };
481 if !pointer.is_empty() && self.json[t].doc.pointer(pointer).is_none() {
482 report.push(Diagnostic::error(
483 "E032",
484 at,
485 format!("$ref {r:?} points at a missing definition"),
486 ));
487 }
488 }
489 }
490 }
491
492 pub fn resolve(&mut self, r: &TypeRef, at: &str, report: &mut Report) -> Option<TypeId> {
494 match r {
495 TypeRef::Raw(raw) => resolve_raw(raw, at, report),
496 TypeRef::Named(s) => {
497 if let Some(rest) = s.strip_prefix("json:") {
498 self.resolve_json(s, rest, at, report)
499 } else if let Some(rest) = s.strip_prefix("packed:") {
500 self.resolve_packed(s, rest, at, report)
501 } else {
502 self.resolve_proto(s, at, report)
503 }
504 }
505 }
506 }
507
508 fn resolve_json(
509 &self,
510 full: &str,
511 rest: &str,
512 at: &str,
513 report: &mut Report,
514 ) -> Option<TypeId> {
515 let (stem, name) = match rest.split_once('#') {
516 Some((stem, name)) => (Some(stem), name),
517 None => (None, rest),
518 };
519 let has = |j: &JsonFile| j.doc.get("$defs").and_then(|d| d.get(name)).is_some();
520 let found: Vec<&JsonFile> = self
521 .json
522 .iter()
523 .filter(|j| stem.is_none_or(|s| j.stem == s) && has(j))
524 .collect();
525 match found.as_slice() {
526 [j] => Some(TypeId::JsonSchema {
527 name: name.to_owned(),
528 schema: j.artifact.clone(),
529 }),
530 [] => {
531 if !self.json_failed {
532 report.push(Diagnostic::error(
533 "E023",
534 at,
535 format!("{full:?}: no listed JSON Schema file defines $defs/{name}"),
536 ));
537 }
538 None
539 }
540 many => {
541 let stems: Vec<&str> = many.iter().map(|j| j.stem.as_str()).collect();
542 report.push(Diagnostic::error(
543 "E024",
544 at,
545 format!("{full:?} is defined in {stems:?}; qualify it as json:<stem>#{name}"),
546 ));
547 None
548 }
549 }
550 }
551
552 fn resolve_packed(
553 &self,
554 full: &str,
555 rest: &str,
556 at: &str,
557 report: &mut Report,
558 ) -> Option<TypeId> {
559 let (stem, name) = match rest.split_once('#') {
560 Some((stem, name)) => (Some(stem), name),
561 None => (None, rest),
562 };
563 let found: Vec<&PackedFile> = self
564 .packed
565 .iter()
566 .filter(|p| stem.is_none_or(|s| p.stem == s) && p.doc.types.contains_key(name))
567 .collect();
568 match found.as_slice() {
569 [p] => Some(TypeId::Packed {
570 name: name.to_owned(),
571 schema: p.artifact.clone(),
572 }),
573 [] => {
574 if !self.packed_failed {
575 report.push(Diagnostic::error(
576 "E023",
577 at,
578 format!("{full:?}: no listed packed file defines types/{name}"),
579 ));
580 }
581 None
582 }
583 many => {
584 let stems: Vec<&str> = many.iter().map(|p| p.stem.as_str()).collect();
585 report.push(Diagnostic::error(
586 "E024",
587 at,
588 format!("{full:?} is defined in {stems:?}; qualify it as packed:<stem>#{name}"),
589 ));
590 None
591 }
592 }
593 }
594
595 fn resolve_proto(&mut self, name: &str, at: &str, report: &mut Report) -> Option<TypeId> {
596 let found: Vec<&ProtoFile> = self
597 .proto
598 .iter()
599 .filter(|p| {
600 p.pool
601 .get_message_by_name(name)
602 .is_some_and(|m| m.parent_file().name() == p.name)
603 })
604 .collect();
605 match found.as_slice() {
606 [p] => {
607 return Some(TypeId::Protobuf {
608 name: name.to_owned(),
609 schema: p.artifact.clone(),
610 });
611 }
612 [] => {}
613 _ => {
614 report.push(Diagnostic::error(
615 "E023",
616 at,
617 format!("{name:?} is defined by more than one listed .proto file"),
618 ));
619 return None;
620 }
621 }
622 if let Some(short) = name.strip_prefix("google.protobuf.")
623 && let Some((file, _)) = WELL_KNOWN.iter().find(|(_, ms)| ms.contains(&short))
624 {
625 return self.well_known(file, name);
626 }
627 if !self.proto_failed {
628 let hint = if self
629 .proto
630 .iter()
631 .any(|p| p.pool.get_message_by_name(name).is_some())
632 {
633 " (it is defined by an imported file: list that file)"
634 } else {
635 ""
636 };
637 report.push(Diagnostic::error(
638 "E023",
639 at,
640 format!("{name:?}: no listed .proto file defines this message{hint}"),
641 ));
642 }
643 None
644 }
645
646 fn well_known(&mut self, file: &str, name: &str) -> Option<TypeId> {
647 if let Some(p) = self.proto.iter().find(|p| p.name == file) {
648 return Some(TypeId::Protobuf {
649 name: name.to_owned(),
650 schema: p.artifact.clone(),
651 });
652 }
653 let mut c = protox::Compiler::new::<_, &Path>([]).ok()?;
654 c.include_imports(true).include_source_info(false);
655 c.open_file(file).ok()?;
656 let art = Artifact {
657 kind: SchemaKind::Protobuf,
658 name: file.to_owned(),
659 data: ArtifactData::Protobuf(c.encode_file_descriptor_set()),
660 };
661 let id = art.id();
662 self.artifacts.insert(id.clone(), art);
663 self.proto.push(ProtoFile {
664 name: file.to_owned(),
665 pool: c.descriptor_pool(),
666 artifact: id.clone(),
667 });
668 Some(TypeId::Protobuf {
669 name: name.to_owned(),
670 schema: id,
671 })
672 }
673
674 #[must_use]
677 pub fn field_names(&self, t: &TypeId) -> Option<Vec<String>> {
678 match t {
679 TypeId::Protobuf { name, schema } => {
680 let p = self.proto.iter().find(|p| &p.artifact == schema)?;
681 let m = p.pool.get_message_by_name(name)?;
682 Some(m.fields().map(|f| f.name().to_owned()).collect())
683 }
684 TypeId::JsonSchema { name, schema } => {
685 let j = self.json.iter().find(|j| &j.artifact == schema)?;
686 let props = j
687 .doc
688 .get("$defs")?
689 .get(name)?
690 .get("properties")?
691 .as_object()?;
692 Some(props.keys().cloned().collect())
693 }
694 TypeId::Packed { .. } | TypeId::Raw { .. } => None,
695 }
696 }
697
698 #[must_use]
700 pub fn artifacts(&self) -> &BTreeMap<String, Artifact> {
701 &self.artifacts
702 }
703}
704
705fn resolve_raw(raw: &RawType, at: &str, report: &mut Report) -> Option<TypeId> {
706 if !is_media_type(&raw.raw) {
707 report.push(Diagnostic::error(
708 "E023",
709 at,
710 format!(
711 "{:?} is not a lowercase media type <type>/<subtype> or family <type>/*",
712 raw.raw
713 ),
714 ));
715 return None;
716 }
717 Some(TypeId::Raw {
718 media_type: raw.raw.clone(),
719 media_param: raw.media_param.clone(),
720 })
721}
722
723fn is_media_type(s: &str) -> bool {
724 let tok = |t: &str| {
725 let mut cs = t.chars();
726 cs.next()
727 .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
728 && cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "!#$&-^_.+".contains(c))
729 };
730 match s.split_once('/') {
731 Some((t, sub)) => tok(t) && (sub == "*" || tok(sub)),
732 None => false,
733 }
734}
735
736fn file_stem(f: &str) -> String {
737 let base = f.rsplit('/').next().unwrap_or(f);
738 base.strip_suffix(".json").unwrap_or(base).to_owned()
739}
740
741fn normalize(p: &Path) -> PathBuf {
744 let mut out = PathBuf::new();
745 for c in p.components() {
746 match c {
747 Component::CurDir => {}
748 Component::ParentDir => {
749 if !out.pop() {
750 out.push("..");
751 }
752 }
753 other => out.push(other),
754 }
755 }
756 out
757}
758
759pub(crate) fn visit_schemas<'a>(
766 schema: &'a Value,
767 f: &mut dyn FnMut(&'a serde_json::Map<String, Value>),
768) {
769 let Value::Object(m) = schema else { return };
770 f(m);
771 for (k, v) in m {
772 match (k.as_str(), v) {
773 ("properties" | "$defs", Value::Object(subs)) => {
774 subs.values().for_each(|s| visit_schemas(s, f));
775 }
776 ("prefixItems" | "oneOf" | "anyOf", Value::Array(subs)) => {
777 subs.iter().for_each(|s| visit_schemas(s, f));
778 }
779 ("items" | "additionalProperties", sub) => visit_schemas(sub, f),
780 _ => {}
781 }
782 }
783}
784
785fn collect_refs(v: &Value, out: &mut Vec<String>) {
787 visit_schemas(v, &mut |m| {
788 if let Some(Value::String(r)) = m.get("$ref") {
789 out.push(r.clone());
790 }
791 });
792}
793
794#[must_use]
799pub fn jcs(v: &Value) -> Vec<u8> {
800 serde_json_canonicalizer::to_vec(v).expect("a serde_json::Value always serializes")
801}
802
803#[must_use]
805pub fn sha256_id(bytes: &[u8]) -> String {
806 let digest = Sha256::digest(bytes);
807 let mut s = String::with_capacity(71);
808 s.push_str("sha256:");
809 for b in digest {
810 let _ = write!(s, "{b:02x}");
811 }
812 s
813}
814
815pub(crate) fn unsafe_integer(v: &Value) -> Option<String> {
820 match v {
821 Value::Number(n) => crate::canonical::outside_safe_range(n).then(|| n.to_string()),
822 Value::Array(a) => a.iter().find_map(unsafe_integer),
823 Value::Object(m) => m.values().find_map(unsafe_integer),
824 _ => None,
825 }
826}
827
828const SUBSET: &[&str] = &[
831 "type",
832 "properties",
833 "required",
834 "additionalProperties",
835 "items",
836 "prefixItems",
837 "enum",
838 "const",
839 "minimum",
840 "maximum",
841 "exclusiveMinimum",
842 "exclusiveMaximum",
843 "minLength",
844 "maxLength",
845 "minItems",
846 "maxItems",
847 "$ref",
848 "oneOf",
849 "anyOf",
850];
851const ANNOTATIONS: &[&str] = &[
852 "$schema",
853 "$id",
854 "$defs",
855 "$comment",
856 "title",
857 "description",
858 "default",
859 "examples",
860 "format",
861 "deprecated",
862 "readOnly",
863 "writeOnly",
864];
865
866fn refused_keywords(schema: &Value, out: &mut std::collections::BTreeSet<String>) {
870 visit_schemas(schema, &mut |m| {
871 for k in m.keys() {
872 if !SUBSET.contains(&k.as_str()) && !ANNOTATIONS.contains(&k.as_str()) {
873 out.insert(k.clone());
874 }
875 }
876 });
877}
878
879#[cfg(test)]
880mod tests {
881 use super::*;
882
883 #[test]
884 fn media_types() {
885 for ok in [
886 "image/jpeg",
887 "video/*",
888 "application/vnd.foo+cbor",
889 "audio/l16",
890 ] {
891 assert!(is_media_type(ok), "{ok}");
892 }
893 for bad in ["image", "Image/jpeg", "*/*", "image/", "image/jpeg; q=1"] {
894 assert!(!is_media_type(bad), "{bad}");
895 }
896 }
897
898 #[test]
899 fn well_known_types_compile_on_demand() {
900 let mut report = Report::default();
901 let mut set = SchemaSet::load(Path::new("."), &SchemasSection::default(), &mut report);
902 let t = set
903 .resolve(
904 &TypeRef::Named("google.protobuf.Empty".into()),
905 "x",
906 &mut report,
907 )
908 .unwrap();
909 assert!(report.0.is_empty(), "{report}");
910 let TypeId::Protobuf { schema, .. } = t else {
911 panic!()
912 };
913 assert_eq!(set.artifacts()[&schema].name, "google/protobuf/empty.proto");
914 assert!(
915 set.resolve(
916 &TypeRef::Named("google.protobuf.Nope".into()),
917 "x",
918 &mut report
919 )
920 .is_none()
921 );
922 assert_eq!(report.codes(), ["E023"]);
923 }
924
925 #[test]
929 fn a_listed_file_with_a_taken_id_is_e024() {
930 let dir = std::env::temp_dir().join(format!("zk2-schema-ids-{}", std::process::id()));
931 std::fs::create_dir_all(&dir).unwrap();
932 std::fs::write(
933 dir.join("a.json"),
934 r#"{"$defs": {"X": {"type": "string"}}}"#,
935 )
936 .unwrap();
937 std::fs::write(
938 dir.join("b.json"),
939 "{\"$defs\":{\"X\":{\"type\":\"string\"}}}\n",
940 )
941 .unwrap();
942 std::fs::write(
943 dir.join("c.json"),
944 r#"{"$defs": {"Y": {"$ref": "a.json#/$defs/X"}}}"#,
945 )
946 .unwrap();
947 let sec = SchemasSection {
948 jsonschema: vec!["a.json".into(), "b.json".into(), "c.json".into()],
949 ..SchemasSection::default()
950 };
951 let mut report = Report::default();
952 let set = SchemaSet::load(&dir, &sec, &mut report);
953 std::fs::remove_dir_all(&dir).unwrap();
954 assert_eq!(report.codes(), ["E024"], "{report}");
955 let names: Vec<&str> = set.artifacts().values().map(|a| a.name.as_str()).collect();
956 assert_eq!(names.len(), 2);
957 assert!(names.contains(&"a") && names.contains(&"c"), "{names:?}");
958 }
959
960 #[test]
961 fn normalize_folds_dots() {
962 assert_eq!(
963 normalize(Path::new("a/./b/../c.json")),
964 PathBuf::from("a/c.json")
965 );
966 assert_eq!(normalize(Path::new("../x")), PathBuf::from("../x"));
967 }
968}