use crate::error::PackageError;
use boon::{Compiler, Schemas};
use serde_json::Value;
use std::sync::OnceLock;
const MANIFEST_SCHEMA: &str = include_str!("../schema/manifest.schema.json");
const NODES_SCHEMA: &str = include_str!("../schema/nodes.schema.json");
const STYLES_SCHEMA: &str = include_str!("../schema/styles.schema.json");
const VISUAL_SCHEMA: &str = include_str!("../schema/visual_primitives.schema.json");
const SIGNATURES_SCHEMA: &str = include_str!("../schema/signatures.schema.json");
pub fn bundled_schema_files() -> Vec<(&'static str, &'static str)> {
crate::paths::FORMAT_SCHEMA_FILES
.iter()
.copied()
.zip([
MANIFEST_SCHEMA,
NODES_SCHEMA,
STYLES_SCHEMA,
VISUAL_SCHEMA,
SIGNATURES_SCHEMA,
])
.collect()
}
struct Compiled {
schemas: Schemas,
manifest: boon::SchemaIndex,
nodes: boon::SchemaIndex,
styles: boon::SchemaIndex,
signatures: boon::SchemaIndex,
}
fn compiled() -> Result<&'static Compiled, PackageError> {
static CELL: OnceLock<Result<Compiled, String>> = OnceLock::new();
match CELL.get_or_init(build) {
Ok(c) => Ok(c),
Err(e) => Err(PackageError::Other(format!("schema compiler: {e}"))),
}
}
fn build() -> Result<Compiled, String> {
let mut schemas = Schemas::new();
let mut compiler = Compiler::new();
for (url, text) in [
("k2f://schema/manifest.schema.json", MANIFEST_SCHEMA),
("k2f://schema/nodes.schema.json", NODES_SCHEMA),
("k2f://schema/styles.schema.json", STYLES_SCHEMA),
("k2f://schema/visual_primitives.schema.json", VISUAL_SCHEMA),
("k2f://schema/signatures.schema.json", SIGNATURES_SCHEMA),
] {
let value: Value = serde_json::from_str(text).map_err(|e| format!("{url}: {e}"))?;
compiler
.add_resource(url, value)
.map_err(|e| format!("add {url}: {e}"))?;
}
let manifest = compiler
.compile("k2f://schema/manifest.schema.json", &mut schemas)
.map_err(|e| format!("compile manifest: {e}"))?;
let nodes = compiler
.compile("k2f://schema/nodes.schema.json", &mut schemas)
.map_err(|e| format!("compile nodes: {e}"))?;
let styles = compiler
.compile("k2f://schema/styles.schema.json", &mut schemas)
.map_err(|e| format!("compile styles: {e}"))?;
let signatures = compiler
.compile("k2f://schema/signatures.schema.json", &mut schemas)
.map_err(|e| format!("compile signatures: {e}"))?;
Ok(Compiled {
schemas,
manifest,
nodes,
styles,
signatures,
})
}
fn validate_against(
index: boon::SchemaIndex,
instance: &Value,
label: &str,
) -> Result<(), PackageError> {
let compiled = compiled()?;
compiled.schemas.validate(instance, index).map_err(|e| {
PackageError::SchemaInvalid(crate::schema_error::format_schema_error(label, &e))
})
}
pub fn validate_manifest_json(v: &Value) -> Result<(), PackageError> {
validate_against(compiled()?.manifest, v, "manifest.json")
}
pub fn validate_root_json(v: &Value) -> Result<(), PackageError> {
validate_against(compiled()?.nodes, v, "content/root.json")
}
pub fn validate_content_json(v: &Value, label: &str) -> Result<(), PackageError> {
validate_against(compiled()?.nodes, v, label)
}
pub fn validate_theme_json(v: &Value) -> Result<(), PackageError> {
validate_against(compiled()?.styles, v, "styles/theme.json")
}
pub fn validate_signatures_json(v: &Value) -> Result<(), PackageError> {
validate_against(compiled()?.signatures, v, "signatures/v1.json")
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn extra_field_on_node_is_schema_invalid() {
let node = json!({
"id": "root",
"role": "body",
"content": { "type": "text", "value": "hi" },
"bogus": true
});
let err = validate_root_json(&node).unwrap_err();
assert!(
err.to_string().contains(crate::CODE_SCHEMA_INVALID),
"got {err}"
);
}
#[test]
fn hyphenated_node_id_is_schema_invalid() {
let node = json!({
"id": "clause-4",
"role": "body",
"content": { "type": "text", "value": "hi" }
});
let err = validate_root_json(&node).unwrap_err();
assert!(
err.to_string().contains(crate::CODE_SCHEMA_INVALID),
"got {err}"
);
}
#[test]
fn include_stub_in_container_children_is_valid() {
let node = json!({
"id": "root",
"role": "document",
"content": {
"type": "container",
"value": {
"children": [
{ "include": "content/ch01.json" }
]
}
}
});
validate_root_json(&node).unwrap();
}
#[test]
fn bundled_schemas_are_format_five_only() {
let names: Vec<_> = bundled_schema_files().iter().map(|(p, _)| *p).collect();
assert_eq!(names, crate::paths::FORMAT_SCHEMA_FILES.to_vec());
assert!(!names.iter().any(|p| p.contains("agent")));
assert!(!crate::paths::is_schema_path("schema/agent_v0.schema.json"));
assert!(!crate::paths::is_schema_path(
"schema/agent_invoice.schema.json"
));
assert!(crate::paths::is_schema_path("schema/nodes.schema.json"));
}
#[test]
fn grid_optional_null_gaps_and_cell_align_are_valid() {
let node = json!({
"id": "root",
"role": "document",
"content": {
"type": "container",
"value": {
"children": [{
"id": "root.grid",
"role": "body",
"content": {
"type": "container",
"value": { "children": [] }
},
"layout": {
"type": "grid",
"columns": [{ "pt": 100000 }],
"rows": [{ "pt": 100000 }],
"gap": 0,
"row_gap": null,
"column_gap": null,
"cell_align": null
}
}]
}
}
});
validate_root_json(&node).unwrap();
}
#[test]
fn grid_omitted_gaps_are_valid() {
let node = json!({
"id": "root",
"role": "document",
"content": {
"type": "container",
"value": {
"children": [{
"id": "root.grid",
"role": "body",
"content": {
"type": "container",
"value": { "children": [] }
},
"layout": {
"type": "grid",
"columns": [{ "fr": 1 }],
"rows": [{ "pt": 50000 }],
"gap": 8000
}
}]
}
}
});
validate_root_json(&node).unwrap();
}
#[test]
fn grid_optional_width_height_is_valid() {
let node = json!({
"id": "root",
"role": "document",
"content": {
"type": "container",
"value": {
"children": [{
"id": "root.grid",
"role": "body",
"content": {
"type": "container",
"value": { "children": [] }
},
"layout": {
"type": "grid",
"columns": [{ "fr": 1 }],
"rows": [{ "fr": 1 }, { "pt": 40000 }],
"gap": 0,
"height": 540000,
"width": 960000
}
}]
}
}
});
validate_root_json(&node).unwrap();
}
#[test]
fn grid_omitted_rows_are_valid() {
let node = json!({
"id": "root",
"role": "document",
"content": {
"type": "container",
"value": {
"children": [{
"id": "root.grid",
"role": "body",
"content": {
"type": "container",
"value": {
"children": [
{
"id": "root.grid.a",
"role": "body",
"content": { "type": "text", "value": "a" }
},
{
"id": "root.grid.b",
"role": "body",
"content": { "type": "text", "value": "b" }
}
]
}
},
"layout": {
"type": "grid",
"columns": [{ "fr": 1 }, { "fr": 1 }]
}
}]
}
}
});
validate_root_json(&node).unwrap();
}
#[test]
fn signatures_schema_rejects_version_two_extra_field_and_empty_list() {
let valid = json!({
"version": 1,
"signatures": [{
"alg": "ed25519",
"public_key": "aa".repeat(32),
"signature": "bb".repeat(64),
"signed_at": 1_704_067_200
}]
});
validate_signatures_json(&valid).unwrap();
let mut v2 = valid.clone();
v2["version"] = json!(2);
assert!(validate_signatures_json(&v2).is_err());
let mut extra = valid.clone();
extra["signatures"][0]["note"] = json!("x");
assert!(validate_signatures_json(&extra).is_err());
let empty = json!({ "version": 1, "signatures": [] });
assert!(validate_signatures_json(&empty).is_err());
}
#[test]
fn container_role_may_omit_text_fields() {
let theme = json!({
"palette": { "ink": "#111111" },
"roles": {
"default": {
"font_family": "default",
"font_size": 12000,
"line_height_mult": 1200,
"color": "ink"
},
"rule": {
"box_decoration": { "padding_pt": 0 }
}
}
});
validate_theme_json(&theme).unwrap();
}
#[test]
fn stack_layout_may_omit_type() {
let node = json!({
"id": "root",
"role": "document",
"content": {
"type": "container",
"value": {
"children": [{
"id": "root.rule",
"role": "rule",
"content": { "type": "container", "value": {} },
"layout": { "height": 1500 }
}]
}
}
});
validate_root_json(&node).unwrap();
}
#[test]
fn image_path_error_is_compact_and_names_src() {
let node = json!({
"id": "root",
"role": "image",
"content": {
"type": "image",
"value": {
"path": "assets/images/dot.png",
"width": 24000,
"height": 24000
}
}
});
let err = validate_root_json(&node).unwrap_err().to_string();
assert!(err.contains(crate::CODE_SCHEMA_INVALID), "got {err}");
assert!(err.contains("path"), "got {err}");
assert!(err.contains("src"), "got {err}");
assert!(
err.len() < 800,
"oneOf dump should be summarized, got {} chars: {err}",
err.len()
);
}
#[test]
fn malformed_table_header_rows_does_not_report_table_reference() {
let node = json!({
"id": "root",
"role": "document",
"content": {
"type": "container",
"value": {
"children": [{
"id": "root.t",
"role": "table",
"content": {
"type": "table",
"value": {
"column_widths": [{ "fr": 1 }],
"header_rows": [[{
"id": "root.t.h0",
"role": "table_header_cell",
"content": { "type": "text", "value": "A" }
}]],
"data": {
"type": "inline",
"rows": [[{
"id": "root.t.r0c0",
"role": "table_row_cell",
"content": { "type": "text", "value": "x" }
}]]
}
}
}
}]
}
}
});
let err = validate_root_json(&node).unwrap_err().to_string();
assert!(err.contains(crate::CODE_SCHEMA_INVALID), "got {err}");
assert!(
err.contains("header_rows"),
"should name the bad field, got {err}"
);
assert!(
!err.contains("table_reference"),
"must not pick the sibling content tag, got {err}"
);
}
#[test]
fn malformed_grid_track_does_not_report_stack_or_overlay() {
let node = json!({
"id": "root",
"role": "document",
"content": {
"type": "container",
"value": {
"children": [{
"id": "root.grid",
"role": "body",
"content": {
"type": "container",
"value": { "children": [] }
},
"layout": {
"type": "grid",
"columns": [{ "fr": 1.5 }]
}
}]
}
}
});
let err = validate_root_json(&node).unwrap_err().to_string();
assert!(err.contains(crate::CODE_SCHEMA_INVALID), "got {err}");
assert!(
!err.to_lowercase().contains("stack"),
"must not pick a sibling layout tag, got {err}"
);
assert!(
!err.contains("overlay"),
"must not pick a sibling layout tag, got {err}"
);
}
#[test]
fn padding_pt_accepts_trbl_array() {
let theme = json!({
"palette": { "ink": "#111111" },
"roles": {
"default": {
"font_family": "default",
"font_size": 12000,
"line_height_mult": 1200,
"color": "ink",
"box_decoration": { "padding_pt": [1000, 2000, 3000, 4000] }
}
}
});
validate_theme_json(&theme).unwrap();
}
#[test]
fn form_field_node_is_schema_valid() {
let node = json!({
"id": "app.applicant.full_name",
"role": "form_field",
"variant": "underline",
"break_inside": "avoid",
"content": {
"type": "form_field",
"value": {
"kind": "text",
"value": "",
"placeholder": "Full legal name",
"width": 220000,
"lines": 1
}
}
});
validate_root_json(&node).unwrap();
}
#[test]
fn form_field_unknown_kind_is_schema_invalid() {
let node = json!({
"id": "app.name",
"role": "form_field",
"content": {
"type": "form_field",
"value": { "kind": "dropdown", "value": "" }
}
});
let err = validate_root_json(&node).unwrap_err().to_string();
assert!(err.contains(crate::CODE_SCHEMA_INVALID), "got {err}");
}
#[test]
fn official_blank_theme_accepts_form_field_role() {
let theme: Value = serde_json::from_str(include_str!(
"../../../templates/blank/styles/theme.json"
))
.unwrap();
assert!(theme["roles"]["form_field"]["variants"]["underline"].is_object());
validate_theme_json(&theme).unwrap();
}
}