feat(docgen): add MDX output format for Astro Starlight

Add new --format mdx option to generate Astro Starlight-compatible
MDX documentation from JSON Schema.

Features:
- New MdxGenerator with Tera templates (mdx_base.md, mdx_macros.md)
- Custom heading IDs using {#anchor} syntax for reliable deep linking
- Starlight Badge components for required/optional/deprecated markers
- MDX escape filter for curly braces in descriptions
- Reuses existing schema preparation from prepare.rs

Changes:
- src/mdx_generator.rs: New MDX generation module
- src/templates/mdx_base.md: Base MDX template with frontmatter
- src/templates/mdx_macros.md: Tera macros for MDX rendering
- src/lib.rs: Add generate_mdx() public API and MdxOptions
- src/main.rs: Add --format argument (html/mdx)
- src/prepare.rs: Fix oneOf variant usage anchors for bare $ref

The MDX output integrates with Starlight's TOC generation via
remark-custom-heading-id plugin and produces valid MDX that passes
mdxlint validation.
This commit is contained in:
LGUG2Z committed 2025-12-26 10:22:04 -08:00
1 parent 855f6b2592
commit 23a86d0efa
6 files changed
+1277 -10

No files matched your search

+20
View File
@@ -32,12 +32,14 @@
mod generator;
pub mod identifiers;
mod mdx_generator;
mod prepare;
pub use generator::Generator;
pub use identifiers::CSS;
pub use identifiers::IDS;
pub use identifiers::TYPE_CLASSES;
pub use mdx_generator::MdxGenerator;
use schemars::Schema;
use serde_json::Value;
@@ -49,6 +51,15 @@ pub struct Options {
pub title_override: Option<String>,
}
/// Options for MDX generation
#[derive(Debug, Clone, Default)]
pub struct MdxOptions {
/// Override the schema title
pub title_override: Option<String>,
/// Override the schema description (used in frontmatter)
pub description_override: Option<String>,
}
/// Error type for documentation generation
#[derive(Debug, thiserror::Error)]
pub enum Error {
@@ -68,6 +79,15 @@ pub fn generate_html(schema: &Schema, options: &Options) -> Result<String, Error
generator.generate(schema, options)
}
/// Generate MDX documentation from a schema
///
/// This generates an MDX document suitable for use with Astro Starlight.
/// The output includes YAML frontmatter and uses Starlight components.
pub fn generate_mdx(schema: &Schema, options: &MdxOptions) -> Result<String, Error> {
let generator = MdxGenerator::new()?;
generator.generate(schema, options)
}
/// Extension trait for convenient access to common schema properties
///
/// Since `schemars::Schema` is a wrapper around `serde_json::Value`,
+40 -9
View File
@@ -1,24 +1,45 @@
#![warn(clippy::all)]
use clap::Parser;
use clap::ValueEnum;
use schemars_docgen::MdxOptions;
use schemars_docgen::Options;
use schemars_docgen::generate_html;
use schemars_docgen::generate_mdx;
use std::path::PathBuf;
/// Output format for documentation generation
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
enum Format {
/// HTML output (self-contained single file)
#[default]
Html,
/// MDX output for Astro Starlight
Mdx,
}
#[derive(Parser)]
#[command(name = "schemars-docgen")]
#[command(about = "Generate HTML documentation from JSON Schema")]
#[command(about = "Generate documentation from JSON Schema")]
struct Cli {
/// Input JSON Schema file
input: PathBuf,
/// Output HTML file
/// Output file (defaults to input filename with appropriate extension)
#[arg(short, long)]
output: Option<PathBuf>,
/// Schema title (overrides schema title from the schema)
/// Output format
#[arg(short, long, default_value = "html")]
format: Format,
/// Schema title (overrides title from the schema)
#[arg(short, long)]
title: Option<String>,
/// Schema description (overrides description from the schema, MDX only)
#[arg(short, long)]
description: Option<String>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -27,19 +48,29 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let schema_json = std::fs::read_to_string(&cli.input)?;
let schema: schemars::Schema = serde_json::from_str(&schema_json)?;
let options = Options {
title_override: cli.title,
let (output, extension) = match cli.format {
Format::Html => {
let options = Options {
title_override: cli.title,
};
(generate_html(&schema, &options)?, "html")
}
Format::Mdx => {
let options = MdxOptions {
title_override: cli.title,
description_override: cli.description,
};
(generate_mdx(&schema, &options)?, "mdx")
}
};
let html = generate_html(&schema, &options)?;
let output_path = cli.output.unwrap_or_else(|| {
let mut path = cli.input.clone();
path.set_extension("html");
path.set_extension(extension);
path
});
std::fs::write(&output_path, html)?;
std::fs::write(&output_path, output)?;
println!("Generated documentation: {}", output_path.display());
Ok(())
+806
View File
@@ -0,0 +1,806 @@
//! MDX generation using Tera templates for Astro Starlight
use crate::Error;
use crate::MdxOptions;
use crate::prepare::NavigationData;
use crate::prepare::build_navigation;
use crate::prepare::embed_usages_in_defs;
use crate::prepare::prepare_for_template;
use crate::prepare::strip_markdown;
use schemars::Schema;
use serde_json::Value;
use std::collections::HashMap;
use tera::Context;
use tera::Tera;
/// Tera filter to escape curly braces for MDX
///
/// MDX interprets `{` and `}` as JSX expressions. This filter escapes them
/// so they render as literal text, which is necessary for descriptions
/// containing JSON code blocks.
fn mdx_escape(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
match value {
Value::String(s) => {
let escaped = s.replace('{', "\\{").replace('}', "\\}");
Ok(Value::String(escaped))
}
_ => Ok(value.clone()),
}
}
/// MDX documentation generator for Astro Starlight
pub struct MdxGenerator {
tera: Tera,
}
impl MdxGenerator {
/// Create a new MDX generator with embedded templates
pub fn new() -> Result<Self, Error> {
let mut tera = Tera::default();
// Register custom filters
tera.register_filter("mdx_escape", mdx_escape);
// Add MDX-specific templates
// Order matters: macros must be added before base which imports them
tera.add_raw_template("mdx_macros.md", include_str!("templates/mdx_macros.md"))?;
tera.add_raw_template("mdx_base.md", include_str!("templates/mdx_base.md"))?;
Ok(Self { tera })
}
/// Generate MDX documentation from a schema
pub fn generate(&self, schema: &Schema, options: &MdxOptions) -> Result<String, Error> {
// Prepare the schema for template rendering (reuse existing preparation logic)
let mut prepared_schema = prepare_for_template(schema.as_value());
// Build navigation data from the prepared schema
let navigation = build_navigation(&prepared_schema);
// Embed usages directly into $defs
embed_usages_in_defs(&mut prepared_schema, &navigation.usages);
// Build the template context
let context = self.build_context(&prepared_schema, &navigation, options)?;
// Render the MDX template
let mdx = self.tera.render("mdx_base.md", &context)?;
Ok(mdx)
}
/// Build the Tera context from schema and options
fn build_context(
&self,
schema: &Value,
navigation: &NavigationData,
options: &MdxOptions,
) -> Result<Context, Error> {
let mut context = Context::new();
// Title: use override, then schema title, then fallback
let title = options
.title_override
.clone()
.or_else(|| {
schema
.get("title")
.and_then(|v| v.as_str())
.map(String::from)
})
.unwrap_or_else(|| "Schema Documentation".to_string());
// Strip markdown for plain text title (for frontmatter)
let title_plain = strip_markdown(&title);
context.insert("title", &title_plain);
// Description: use override, then schema description, then title
let description = options
.description_override
.clone()
.or_else(|| {
schema
.get("description")
.and_then(|v| v.as_str())
.map(String::from)
})
.or_else(|| Some(title_plain.clone()))
.unwrap_or_default();
// Strip markdown and sanitize for YAML frontmatter
let description_plain = strip_markdown(&description)
.replace(['\n', '\r'], " ")
.replace('"', "'"); // Replace double quotes with single quotes for YAML safety
// Truncate very long descriptions for frontmatter
let description_truncated = if description_plain.len() > 200 {
format!("{}...", &description_plain[..197])
} else {
description_plain
};
context.insert("description", &description_truncated);
// The full schema for property rendering
context.insert("schema", schema);
// Navigation data
context.insert("navigation", navigation);
// Type usages for "Usages" section in type definitions
context.insert("usages", &navigation.usages);
// Display names for wrapper types (type_name -> display_name)
context.insert("display_names", &navigation.display_names);
// Build required set for the root schema
let required_set: Vec<String> = schema
.get("required")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
context.insert("required_set", &required_set);
Ok(context)
}
}
impl Default for MdxGenerator {
fn default() -> Self {
Self::new().expect("Failed to create default MDX generator")
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn make_schema(value: Value) -> Schema {
serde_json::from_value(value).unwrap()
}
#[test]
fn test_mdx_generator_new() {
let generator = MdxGenerator::new();
assert!(generator.is_ok());
}
#[test]
fn test_generate_simple_schema() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "TestConfig",
"description": "A test configuration",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name"
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options);
assert!(mdx.is_ok());
let mdx = mdx.unwrap();
// Check frontmatter
assert!(mdx.contains("---"), "Should have frontmatter delimiters");
assert!(
mdx.contains("title: \"TestConfig\""),
"Should have title in frontmatter"
);
// Check content
assert!(mdx.contains("name"), "Should contain property name");
assert!(
mdx.contains("The name"),
"Should contain property description"
);
}
#[test]
fn test_generate_with_title_override() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "OriginalTitle",
"type": "object"
}));
let options = MdxOptions {
title_override: Some("Custom Title".to_string()),
..Default::default()
};
let mdx = generator.generate(&schema, &options).unwrap();
assert!(mdx.contains("title: \"Custom Title\""));
assert!(!mdx.contains("title: \"OriginalTitle\""));
}
#[test]
fn test_generate_with_description_override() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"description": "Original description",
"type": "object"
}));
let options = MdxOptions {
description_override: Some("Custom description".to_string()),
..Default::default()
};
let mdx = generator.generate(&schema, &options).unwrap();
assert!(mdx.contains("description: \"Custom description\""));
}
#[test]
fn test_frontmatter_generation() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "My Schema",
"description": "Schema description",
"type": "object"
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Frontmatter should be at the start
assert!(mdx.starts_with("---"), "MDX should start with frontmatter");
// Should have closing delimiter
let parts: Vec<&str> = mdx.splitn(3, "---").collect();
assert!(
parts.len() >= 3,
"Should have opening and closing frontmatter delimiters"
);
}
#[test]
fn test_component_imports() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"field": { "type": "string" }
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should import Badge component from Starlight
assert!(
mdx.contains("import { Badge }") || mdx.contains("import {Badge}"),
"Should import Badge component"
);
assert!(
mdx.contains("@astrojs/starlight/components"),
"Should import from Starlight"
);
}
#[test]
fn test_heading_structure() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"alpha": { "type": "string" },
"beta": { "type": "number" }
},
"$defs": {
"MyType": { "type": "string" }
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should have H2 for main sections
assert!(
mdx.contains("## Configuration"),
"Should have Configuration H2"
);
assert!(
mdx.contains("## Type Definitions"),
"Should have Type Definitions H2"
);
// Should have H3 for properties and types (using markdown headings with custom IDs)
assert!(mdx.contains("### alpha {#alpha}"), "Should have alpha H3");
assert!(mdx.contains("### beta {#beta}"), "Should have beta H3");
assert!(
mdx.contains("### MyType {#mytype}"),
"Should have MyType H3"
);
}
#[test]
fn test_primitive_type_badges() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"str_field": { "type": "string" },
"num_field": { "type": "number" },
"int_field": { "type": "integer" },
"bool_field": { "type": "boolean" }
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Primitive types should be shown as inline code
assert!(mdx.contains("`string`"), "Should show string type");
assert!(mdx.contains("`number`"), "Should show number type");
assert!(mdx.contains("`integer`"), "Should show integer type");
assert!(mdx.contains("`boolean`"), "Should show boolean type");
}
#[test]
fn test_required_property_badge() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"required": ["name"],
"properties": {
"name": { "type": "string" }
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Required properties should have a Badge
assert!(
mdx.contains("Badge") && mdx.contains("required"),
"Should have required badge"
);
}
#[test]
fn test_deprecated_property_badge() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"old_field": {
"type": "string",
"deprecated": true
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Deprecated properties should have a Badge
assert!(
mdx.contains("Badge") && mdx.contains("deprecated"),
"Should have deprecated badge"
);
}
#[test]
fn test_optional_property_badge() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"maybe_name": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
]
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Option<T> pattern should show optional badge
assert!(
mdx.contains("optional"),
"Should have optional badge for Option<T>"
);
}
#[test]
fn test_ref_type_links() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"$defs": {
"MyType": { "type": "string" }
},
"properties": {
"field": { "$ref": "#/$defs/MyType" }
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should have a link to the type definition
assert!(
mdx.contains("[MyType](#mytype)") || mdx.contains("[`MyType`](#mytype)"),
"Should have link to type definition"
);
}
#[test]
fn test_enum_values() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["active", "inactive", "pending"]
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should list enum values
assert!(mdx.contains("active"), "Should contain enum value 'active'");
assert!(
mdx.contains("inactive"),
"Should contain enum value 'inactive'"
);
assert!(
mdx.contains("pending"),
"Should contain enum value 'pending'"
);
}
#[test]
fn test_oneof_variants() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"choice": {
"oneOf": [
{ "type": "string", "const": "A", "description": "Option A" },
{ "type": "string", "const": "B", "description": "Option B" }
]
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show variants
assert!(
mdx.contains("Option A") || mdx.contains("\"A\""),
"Should contain variant A"
);
assert!(
mdx.contains("Option B") || mdx.contains("\"B\""),
"Should contain variant B"
);
}
#[test]
fn test_anyof_variants() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"value": {
"anyOf": [
{ "type": "string" },
{ "type": "number" },
{ "type": "boolean" }
]
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show all variant types
assert!(mdx.contains("string"), "Should contain string variant");
assert!(mdx.contains("number"), "Should contain number variant");
assert!(mdx.contains("boolean"), "Should contain boolean variant");
}
#[test]
fn test_array_type_with_items() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"items": {
"type": "array",
"items": { "type": "string" }
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show array type
assert!(mdx.contains("array"), "Should contain array type");
assert!(mdx.contains("string"), "Should contain item type");
}
#[test]
fn test_format_constraint() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email"
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show format constraint
assert!(mdx.contains("email"), "Should show format constraint");
}
#[test]
fn test_pattern_constraint() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"code": {
"type": "string",
"pattern": "^[A-Z]{3}$"
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show pattern constraint
assert!(mdx.contains("^[A-Z]{3}$"), "Should show pattern constraint");
}
#[test]
fn test_min_max_constraints() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"age": {
"type": "integer",
"minimum": 0,
"maximum": 120
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show min/max constraints
assert!(mdx.contains("0"), "Should show minimum");
assert!(mdx.contains("120"), "Should show maximum");
}
#[test]
fn test_usage_links() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"$defs": {
"SharedType": { "type": "string", "description": "A shared type" }
},
"properties": {
"field1": { "$ref": "#/$defs/SharedType" },
"field2": { "$ref": "#/$defs/SharedType" }
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Type definition should have usage links
assert!(
mdx.contains("field1") && mdx.contains("field2"),
"Should show where the type is used"
);
}
#[test]
fn test_anchor_link_format() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"$defs": {
"MyType": { "type": "string" }
},
"properties": {
"field": { "$ref": "#/$defs/MyType" }
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Anchor links should be lowercase
assert!(mdx.contains("#mytype"), "Anchor links should be lowercase");
}
#[test]
fn test_wrapper_types() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"$defs": {
"InnerType": { "type": "string" },
"WrapperType": {
"anyOf": [
{
"type": "object",
"additionalProperties": { "$ref": "#/$defs/InnerType" }
},
{ "$ref": "#/$defs/InnerType" }
]
}
},
"properties": {
"config": { "$ref": "#/$defs/WrapperType" }
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Wrapper types should show inner type
assert!(
mdx.contains("InnerType") || mdx.contains("innertype"),
"Should show inner type for wrapper"
);
}
#[test]
fn test_option_t_pattern() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"optional_value": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
]
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show optional badge, not enum variants
assert!(mdx.contains("optional"), "Should show optional badge");
// Should show the actual type
assert!(mdx.contains("string"), "Should show string type");
}
#[test]
fn test_allof_schemas() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"combined": {
"allOf": [
{ "type": "object", "properties": { "name": { "type": "string" } } },
{ "type": "object", "properties": { "age": { "type": "integer" } } }
]
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show allOf content
assert!(
mdx.contains("name"),
"Should show first allOf schema properties"
);
assert!(
mdx.contains("age"),
"Should show second allOf schema properties"
);
}
#[test]
fn test_homogeneous_tuple() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"point": {
"type": "array",
"prefixItems": [
{ "type": "number" },
{ "type": "number" }
],
"minItems": 2,
"maxItems": 2
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// Should show compact tuple notation
assert!(
mdx.contains("float; 2")
|| mdx.contains("number; 2")
|| mdx.contains("[float; 2]")
|| mdx.contains("[number; 2]"),
"Should show compact tuple notation"
);
}
#[test]
fn test_string_enum_detection() {
let generator = MdxGenerator::new().unwrap();
let schema = make_schema(json!({
"title": "Test",
"type": "object",
"properties": {
"mode": {
"oneOf": [
{ "type": "string", "const": "A", "description": "Mode A" },
{ "type": "string", "const": "B", "description": "Mode B" }
]
}
}
}));
let options = MdxOptions::default();
let mdx = generator.generate(&schema, &options).unwrap();
// String enum should be detected
assert!(
mdx.contains("enum") || mdx.contains("Enum"),
"Should detect string enum pattern"
);
}
}
+10 -1
View File
@@ -681,7 +681,16 @@ fn collect_config_usages(
// e.g., KomorebiTheme.oneOf[0].bar_accent -> "komorebitheme-oneof[0]-bar_accent"
// Note: Keep [N] for variant indices, but remove empty [] from array notation
let clean_path = type_relative_path.replace("[]", "");
if clean_path.is_empty() {
// If the path is ONLY a variant index (e.g., "oneOf[1]"), the $ref is at variant root.
// In this case, link to the parent type, not the non-existent variant anchor.
// The template doesn't render separate heading IDs for bare $ref variants.
let is_variant_root_ref = (clean_path.starts_with("oneOf[")
|| clean_path.starts_with("anyOf[")
|| clean_path.starts_with("allOf["))
&& !clean_path.contains('.');
if clean_path.is_empty() || is_variant_root_ref {
make_anchor(parent_type)
} else {
make_anchor(&format!("{}.{}", parent_type, clean_path))
+24
View File
@@ -0,0 +1,24 @@
{%- import "mdx_macros.md" as macros -%}
---
title: "{{ title }}"
description: "{{ description }}"
---
import { Badge } from '@astrojs/starlight/components';
## Configuration
{% if schema.properties %}
{% for prop_name, prop in schema.properties -%}
{%- set is_required = prop_name in required_set -%}
{{ macros::render_property(name=prop_name, node=prop, required=is_required, depth=0, path=prop_name) }}
{% endfor %}
{% else %}
*No configuration properties defined.*
{% endif %}
{% if schema["$defs"] %}
## Type Definitions
{% for def_name, def in schema["$defs"] -%}
{{ macros::render_definition(def_name=def_name, def=def) }}
{% endfor %}
{% endif %}
+377
View File
@@ -0,0 +1,377 @@
{# MDX Macros for Astro Starlight documentation generation #}
{# These macros mirror the HTML macro logic for consistent output #}
{# Render the type badge for a schema - outputs inline code or links #}
{% macro render_type_badge(node) %}
{%- if node["$ref"] -%}
{%- set ref_name = node["$ref"] | replace(from="#/$defs/", to="") -%}
{%- set display = display_names[ref_name] | default(value=ref_name) -%}
{%- if schema["$defs"][ref_name] -%}
{%- set ref_def = schema["$defs"][ref_name] -%}
[`{{ display }}`](#{{ ref_name | lower }}){% if ref_def._wrapper_inner %} {{ self::render_type_badge(node=ref_def._wrapper_inner) }}{% endif -%}
{%- else -%}
`$ref`
{%- endif -%}
{%- elif node.type -%}
{%- if node.type is string -%}
{%- if node.type == "array" and node.prefixItems -%}
{# Check if all prefixItems have the same type (homogeneous tuple) #}
{%- set first_type = node.prefixItems | first -%}
{%- set_global is_homogeneous = true -%}
{%- for item in node.prefixItems -%}
{%- if item.type is defined and first_type.type is defined -%}
{%- if item.type != first_type.type -%}
{%- set_global is_homogeneous = false -%}
{%- endif -%}
{%- else -%}
{%- set_global is_homogeneous = false -%}
{%- endif -%}
{%- endfor -%}
{%- if is_homogeneous and first_type.type -%}
`array` {% if first_type.type == "number" %}`[float; {{ node.prefixItems | length }}]`{% else %}`[{{ first_type.type }}; {{ node.prefixItems | length }}]`{% endif %}
{%- else -%}
`array` `tuple`
{%- endif -%}
{%- elif node.type == "array" and node.items -%}
`array` {{ self::render_type_badge(node=node.items) }}
{%- else -%}
`{{ node.type }}`
{%- endif -%}
{%- else -%}
{# Check for Option<T> pattern: type array with exactly 2 types where one is null #}
{%- if node.type | length == 2 and "null" in node.type -%}
<Badge text="optional" variant="note" /> {% for t in node.type %}{% if t != "null" %}{% if t == "array" and node.items %}`array` {{ self::render_type_badge(node=node.items) }}{% else %}`{{ t }}`{% endif %}{% endif %}{% endfor %}
{%- else -%}
{% for t in node.type %}`{{ t }}` {% endfor %}
{%- endif -%}
{%- endif -%}
{%- elif node.anyOf -%}
{# Check for wrapper type pattern first #}
{%- if node._wrapper_type -%}
{{ self::render_type_badge(node=node._wrapper_inner) }}
{%- elif node.anyOf | length == 2 -%}
{%- set first = node.anyOf | first -%}
{%- set second = node.anyOf | last -%}
{%- if second.type and second.type == "null" -%}
<Badge text="optional" variant="note" /> {{ self::render_type_badge(node=first) }}
{%- elif first.type and first.type == "null" -%}
<Badge text="optional" variant="note" /> {{ self::render_type_badge(node=second) }}
{%- else -%}
{# Check if all variants are string const (enum pattern) #}
{%- set_global is_string_enum = true -%}
{%- for variant in node.anyOf -%}
{%- if variant.type and variant.type == "string" and variant.const -%}
{%- else -%}
{%- set_global is_string_enum = false -%}
{%- endif -%}
{%- endfor -%}
{%- if is_string_enum -%}
`string` `enum`
{%- else -%}
`enum`
{%- endif -%}
{%- endif -%}
{%- else -%}
{# Check if all variants are string const (enum pattern) #}
{%- set_global is_string_enum = true -%}
{%- for variant in node.anyOf -%}
{%- if variant.type and variant.type == "string" and variant.const -%}
{%- else -%}
{%- set_global is_string_enum = false -%}
{%- endif -%}
{%- endfor -%}
{%- if is_string_enum -%}
`string` `enum`
{%- else -%}
`enum`
{%- endif -%}
{%- endif -%}
{%- elif node.oneOf -%}
{# Check if all variants are string const (enum pattern) #}
{%- set_global is_string_enum = true -%}
{%- for variant in node.oneOf -%}
{%- if variant.type and variant.type == "string" and variant.const -%}
{%- else -%}
{%- set_global is_string_enum = false -%}
{%- endif -%}
{%- endfor -%}
{%- if is_string_enum -%}
`string` `enum`
{%- else -%}
`enum`
{%- endif -%}
{%- elif node.allOf -%}
`allOf`
{%- elif node.const -%}
`const`
{%- elif node.enum -%}
`enum`
{%- endif -%}
{% endmacro render_type_badge %}
{# Render constraints like min, max, pattern, format #}
{% macro render_constraints(node) %}
{# Check if this is a homogeneous tuple - skip minItems/maxItems if so #}
{%- set_global skip_item_constraints = false -%}
{%- if node.prefixItems -%}
{%- set first_type = node.prefixItems | first -%}
{%- set_global is_homogeneous = true -%}
{%- for item in node.prefixItems -%}
{%- if item.type is defined and first_type.type is defined -%}
{%- if item.type != first_type.type -%}
{%- set_global is_homogeneous = false -%}
{%- endif -%}
{%- else -%}
{%- set_global is_homogeneous = false -%}
{%- endif -%}
{%- endfor -%}
{%- if is_homogeneous and first_type.type -%}
{%- set_global skip_item_constraints = true -%}
{%- endif -%}
{%- endif -%}
{%- if node.format or node.pattern or node.minimum is defined or node.maximum is defined or node.minLength is defined or node.maxLength is defined or (node.minItems is defined and not skip_item_constraints) or (node.maxItems is defined and not skip_item_constraints) %}
{% if node.format %}- **Format:** `{{ node.format }}`
{% endif %}{% if node.pattern %}- **Pattern:** `{{ node.pattern }}`
{% endif %}{% if node.minimum is defined %}- **Minimum:** {{ node.minimum }}
{% endif %}{% if node.maximum is defined %}- **Maximum:** {{ node.maximum }}
{% endif %}{% if node.minLength is defined %}- **Min length:** {{ node.minLength }}
{% endif %}{% if node.maxLength is defined %}- **Max length:** {{ node.maxLength }}
{% endif %}{% if node.minItems is defined and not skip_item_constraints %}- **Min items:** {{ node.minItems }}
{% endif %}{% if node.maxItems is defined and not skip_item_constraints %}- **Max items:** {{ node.maxItems }}
{% endif %}
{%- endif -%}
{% endmacro render_constraints %}
{# Render the body of a schema (properties, items, variants, etc.) #}
{% macro render_schema_body(node, depth, path) %}
{%- if depth < 10 -%}
{%- if node["$ref"] -%}
{# Reference only, already shown as type badge #}
{%- elif node.properties -%}
{%- set required_arr = node.required | default(value=[]) -%}
<details>
<summary>Properties ({{ node.properties | length }})</summary>
{% for prop_name, prop in node.properties -%}
{%- set is_required = prop_name in required_arr -%}
{{ self::render_nested_property(name=prop_name, node=prop, required=is_required, depth=depth + 1, path=path ~ "." ~ prop_name) }}
{% endfor %}
</details>
{%- elif node.patternProperties -%}
{% for pattern, prop in node.patternProperties %}
{# Convert known patterns to friendly type names #}
{# Note: patterns use single backslash in the parsed JSON value #}
{% if pattern == "^\d+$" or pattern == "^[0-9]+$" or pattern == "^-?\d+$" or pattern == "^-?[0-9]+$" -%}
**Key:** `"<integer>"` **→** {{ self::render_type_badge(node=prop) }}
{% elif pattern == ".*" or pattern == "^.*$" -%}
**Key:** `"<string>"` **→** {{ self::render_type_badge(node=prop) }}
{% else -%}
**Pattern:** `{{ pattern }}` **→** {{ self::render_type_badge(node=prop) }}
{% endif %}
{% if prop.description_html %}{{ prop.description_html | striptags | mdx_escape }}{% endif %}
{{ self::render_schema_body(node=prop, depth=depth + 1, path=path ~ ".[key]") }}
{% endfor %}
{%- elif node.items -%}
{%- if node.items["$ref"] -%}
{# Already shown in type badge #}
{%- elif node.items.type and node.items.type is string -%}
{# Simple type - already shown in type badge #}
{%- else -%}
<details>
<summary>Array Items</summary>
{{ self::render_schema(node=node.items, depth=depth + 1, path=path ~ "[]") }}
</details>
{%- endif -%}
{%- elif node.prefixItems -%}
{# Check if homogeneous tuple #}
{%- set first_type = node.prefixItems | first -%}
{%- set_global is_homogeneous = true -%}
{%- for item in node.prefixItems -%}
{%- if item.type is defined and first_type.type is defined -%}
{%- if item.type != first_type.type -%}
{%- set_global is_homogeneous = false -%}
{%- endif -%}
{%- else -%}
{%- set_global is_homogeneous = false -%}
{%- endif -%}
{%- endfor -%}
{%- if is_homogeneous and first_type.type -%}
{# Homogeneous tuple - already shown as [T; N] in badge #}
{%- else -%}
<details>
<summary>Tuple Items ({{ node.prefixItems | length }})</summary>
{% for item in node.prefixItems %}
**[{{ loop.index0 }}]** {{ self::render_schema(node=item, depth=depth + 1, path=path ~ "[" ~ loop.index0 ~ "]") }}
{% endfor %}
</details>
{%- endif -%}
{%- elif node.anyOf -%}
{# Check for wrapper type pattern first #}
{%- if node._wrapper_type -%}
{{ self::render_schema_body(node=node._wrapper_inner, depth=depth, path=path) }}
{%- elif node.anyOf | length == 2 -%}
{%- set first = node.anyOf | first -%}
{%- set second = node.anyOf | last -%}
{%- if second.type and second.type == "null" -%}
{{ self::render_schema_body(node=first, depth=depth, path=path) }}
{%- elif first.type and first.type == "null" -%}
{{ self::render_schema_body(node=second, depth=depth, path=path) }}
{%- else -%}
<details>
<summary>Enum variants ({{ node.anyOf | length }})</summary>
{% for variant in node.anyOf %}
---
{{ self::render_schema(node=variant, depth=depth + 1, path=path ~ ".anyOf[" ~ loop.index0 ~ "]") }}
{% endfor %}
</details>
{%- endif -%}
{%- else -%}
<details>
<summary>Enum variants ({{ node.anyOf | length }})</summary>
{% for variant in node.anyOf %}
---
{{ self::render_schema(node=variant, depth=depth + 1, path=path ~ ".anyOf[" ~ loop.index0 ~ "]") }}
{% endfor %}
</details>
{%- endif -%}
{%- elif node.oneOf -%}
<details>
<summary>Enum variants ({{ node.oneOf | length }})</summary>
{% for variant in node.oneOf %}
---
{{ self::render_schema(node=variant, depth=depth + 1, path=path ~ ".oneOf[" ~ loop.index0 ~ "]") }}
{% endfor %}
</details>
{%- elif node.allOf -%}
<details>
<summary>All of ({{ node.allOf | length }} schemas)</summary>
{% for variant in node.allOf %}
---
{{ self::render_schema(node=variant, depth=depth + 1, path=path ~ ".allOf[" ~ loop.index0 ~ "]") }}
{% endfor %}
</details>
{%- elif node.enum -%}
<details>
<summary>Enum variants ({{ node.enum | length }})</summary>
{% for value in node.enum %}- `{{ value | json_encode() }}`
{% endfor %}
</details>
{%- elif node.const -%}
**Value:** `{{ node.const | json_encode() }}`
{%- endif -%}
{%- if node.additionalProperties and node.additionalProperties is object -%}
<details>
<summary>Additional Properties</summary>
{{ self::render_schema(node=node.additionalProperties, depth=depth + 1, path=path ~ ".[*]") }}
</details>
{%- endif -%}
{%- endif -%}
{% endmacro render_schema_body %}
{# Render a schema without property wrapper #}
{% macro render_schema(node, depth, path) %}
{%- if depth < 10 -%}
{{ self::render_type_badge(node=node) }}{% if node.description_html %} - {{ node.description_html | striptags | mdx_escape }}{% endif %}
{{ self::render_constraints(node=node) }}
{%- if node.default %}
**Default:** `{{ node.default | json_encode() }}`
{% endif -%}
{{ self::render_schema_body(node=node, depth=depth, path=path) }}
{%- endif -%}
{% endmacro render_schema %}
{# Render a nested property (used within details blocks) #}
{% macro render_nested_property(name, node, required, depth, path) %}
{%- if depth < 10 -%}
{%- set anchor = path | lower | replace(from=".", to="-") -%}
#### {{ name }} {{"{"}}#{{ anchor }}{{"}"}}
{% if required %}<Badge text="required" variant="success" /> {% endif %}{% if node.deprecated %}<Badge text="deprecated" variant="danger" /> {% endif %}{{ self::render_type_badge(node=node) }}
{% if node.description_html %}{{ node.description_html | striptags | mdx_escape }}{% endif %}
{{ self::render_constraints(node=node) }}
{%- if node.default %}
**Default:** `{{ node.default | json_encode() }}`
{% endif -%}
{{ self::render_schema_body(node=node, depth=depth, path=path) }}
{%- endif -%}
{% endmacro render_nested_property %}
{# Render a top-level property as H3 #}
{% macro render_property(name, node, required, depth, path) %}
{%- if depth < 10 -%}
{%- set anchor = path | lower | replace(from=".", to="-") -%}
### {{ name }} {{"{"}}#{{ anchor }}{{"}"}}
{% if required %}<Badge text="required" variant="success" /> {% endif %}{% if node.deprecated %}<Badge text="deprecated" variant="danger" /> {% endif %}{{ self::render_type_badge(node=node) }}
{% if node.description_html %}{{ node.description_html | striptags | mdx_escape }}{% endif %}
{{ self::render_constraints(node=node) }}
{%- if node.default %}
**Default:** `{{ node.default | json_encode() }}`
{% endif -%}
{{ self::render_schema_body(node=node, depth=depth, path=path) }}
---
{%- endif -%}
{% endmacro render_property %}
{# Render usages section for a type definition #}
{% macro render_usages(def) %}
{%- if def._usages and (def._usages.config_usages | length > 0 or def._usages.type_references | length > 0) -%}
#### Usages
{% if def._usages.config_usages | length > 0 -%}
**Configuration:**
{% for usage in def._usages.config_usages %}- [`{{ usage.path }}`](#{{ usage.anchor }})
{% endfor %}
{% endif %}
{% if def._usages.type_references | length > 0 -%}
**Referenced by:**
{% for ref in def._usages.type_references %}{%- set ref_display = display_names[ref.type_name] | default(value=ref.type_name) -%}
- [`{{ ref_display }}`](#{{ ref.anchor }})
{% endfor %}
{% endif %}
{%- endif -%}
{% endmacro render_usages %}
{# Render a type definition as H3 #}
{% macro render_definition(def_name, def) %}
{%- set anchor = def_name | lower | replace(from=".", to="-") -%}
### {{ def._display_name | default(value=def_name) }} {{"{"}}#{{ anchor }}{{"}"}}
{{ self::render_type_badge(node=def) }}
{% if def.description_html %}{{ def.description_html | striptags | mdx_escape }}{% endif %}
{{ self::render_constraints(node=def) }}
{{ self::render_schema_body(node=def, depth=0, path=def_name) }}
{{ self::render_usages(def=def) }}
---
{% endmacro render_definition %}