pub mod json;
pub mod regexp;
pub mod value;
pub use regexp::{JsMatch, JsRegExp};
pub use value::{TagValue, Value};
use crate::ast::{Function, Node, PathSegment};
use crate::next::transformer::ResolvedNode;
use crate::types::{MarkdocError, Result, Scalar, ValidationError, ValidationLevel};
use indexmap::IndexMap;
use std::borrow::Cow;
use std::fmt;
use std::sync::{Arc, LazyLock};
pub type TransformFn = Arc<dyn Fn(&ResolvedNode<'_>, &Config) -> Result<Value> + Send + Sync>;
pub type ValidateFn =
Arc<dyn Fn(&Node, &ValidationContext<'_>) -> Result<Vec<ValidationError>> + Send + Sync>;
pub type AttributeValidateFn = Arc<
dyn Fn(&Scalar, &ValidationContext<'_>, &str) -> Result<Vec<ValidationError>> + Send + Sync,
>;
pub type FunctionTransformFn = Arc<dyn Fn(&Value, &Config) -> Result<Value> + Send + Sync>;
pub type FunctionValidateFn =
Arc<dyn Fn(&Function, &ValidationContext<'_>) -> Result<Vec<ValidationError>> + Send + Sync>;
pub type MatchesFn = Arc<dyn Fn(&ValidationContext<'_>) -> Matches + Send + Sync>;
pub type VariablesFn = Arc<dyn Fn(&[PathSegment]) -> Value + Send + Sync>;
#[derive(Clone, Copy)]
pub struct ValidationContext<'a> {
pub config: &'a Config,
pub parents: &'a [&'a Node],
}
#[derive(Clone, Default)]
pub struct Config {
pub nodes: IndexMap<String, Option<Schema>>,
pub tags: IndexMap<String, Option<Schema>>,
pub variables: Option<Variables>,
pub functions: IndexMap<String, Option<ConfigFunction>>,
pub partials: Option<IndexMap<String, Partial>>,
pub partials_null: bool,
pub validation: Validation,
}
#[derive(Clone)]
pub enum Variables {
Value(Value),
Fn(VariablesFn),
}
#[derive(Debug, Clone, Default)]
pub struct Validation {
pub validate_functions: bool,
pub environment: Option<String>,
}
#[derive(Debug, Clone)]
pub enum Partial {
Node(Arc<Node>),
Nodes(Arc<Vec<Node>>),
Value(Value),
}
#[derive(Clone, Default)]
pub struct Schema {
pub render: Option<Value>,
pub children: Option<Value>,
pub attributes: Option<IndexMap<String, SchemaAttribute>>,
pub slots: Option<IndexMap<String, SchemaSlot>>,
pub self_closing: bool,
pub inline: Option<Value>,
pub transform: Option<TransformFn>,
pub validate: Option<ValidateFn>,
pub description: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SchemaKind {
#[default]
Object,
Truthy,
Falsy,
Null,
}
impl SchemaKind {
pub fn is_falsy(self) -> bool {
matches!(self, SchemaKind::Falsy | SchemaKind::Null)
}
pub fn read(self, field: &str) -> std::result::Result<(), String> {
match self {
SchemaKind::Null => Err(format!(
"TypeError: Cannot read properties of null (reading '{field}')"
)),
_ => Ok(()),
}
}
}
#[derive(Clone, Default)]
pub struct SchemaAttribute {
pub kind: SchemaKind,
pub attr_type: Option<TypeSpec>,
pub render: Option<Value>,
pub default: Option<Value>,
pub required: bool,
pub matches: Option<Matches>,
pub validate: Option<AttributeValidateFn>,
pub error_level: Option<ValidationLevel>,
pub description: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct SchemaSlot {
pub kind: SchemaKind,
pub render: Option<Value>,
pub required: bool,
}
#[derive(Clone, Default)]
pub struct ConfigFunction {
pub returns: Option<Vec<TypeSpec>>,
pub parameters: Option<IndexMap<String, SchemaAttribute>>,
pub transform: Option<FunctionTransformFn>,
pub validate: Option<FunctionValidateFn>,
pub description: Option<String>,
}
#[derive(Clone)]
pub enum TypeSpec {
Falsy,
Name(String),
Builtin(BuiltinType),
Markdoc(MarkdocType),
Custom(Arc<dyn CustomType>),
Union(Vec<TypeSpec>),
Value(Value),
Realm(crate::next::realm::Builtin),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuiltinType {
String,
Number,
Boolean,
Object,
Array,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MarkdocType {
Class,
Id,
ConditionalAttributeType,
PartialFile,
}
pub trait CustomType: Send + Sync {
fn name(&self) -> &str;
fn transform(&self, value: Value, config: &Config) -> Option<Result<Value>> {
let _ = (value, config);
None
}
fn validate(
&self,
value: &Scalar,
cx: &ValidationContext<'_>,
key: &str,
) -> Option<Result<Vec<ValidationError>>> {
let _ = (value, cx, key);
None
}
}
#[derive(Clone)]
pub enum Matches {
Array(Vec<Value>),
RegExp(Arc<JsRegExp>),
Fn(MatchesFn),
Call(crate::next::realm::Builtin),
Other,
}
impl BuiltinType {
pub fn name(self) -> &'static str {
match self {
BuiltinType::String => "String",
BuiltinType::Number => "Number",
BuiltinType::Boolean => "Boolean",
BuiltinType::Object => "Object",
BuiltinType::Array => "Array",
}
}
pub fn from_name(name: &str) -> Option<BuiltinType> {
Some(match name {
"String" => BuiltinType::String,
"Number" => BuiltinType::Number,
"Boolean" => BuiltinType::Boolean,
"Object" => BuiltinType::Object,
"Array" => BuiltinType::Array,
_ => return None,
})
}
}
impl MarkdocType {
pub fn name(self) -> &'static str {
match self {
MarkdocType::Class => "Class",
MarkdocType::Id => "Id",
MarkdocType::ConditionalAttributeType => "ConditionalAttributeType",
MarkdocType::PartialFile => "PartialFile",
}
}
pub fn transform(self, value: Value) -> Option<Value> {
match self {
MarkdocType::Class => Some(class_transform(value)),
_ => None,
}
}
pub fn validate(
self,
value: &Scalar,
config: &Config,
key: &str,
) -> std::result::Result<Vec<ValidationError>, String> {
Ok(match self {
MarkdocType::Class => class_validate(value, key),
MarkdocType::Id => id_validate(value),
MarkdocType::ConditionalAttributeType => conditional_validate(value, key),
MarkdocType::PartialFile => {
crate::next::tags::partial::partial_file_validate(value, config)?
}
})
}
}
impl TypeSpec {
pub fn is_function(&self) -> bool {
match self {
TypeSpec::Builtin(_) | TypeSpec::Markdoc(_) | TypeSpec::Custom(_) => true,
TypeSpec::Realm(b) => b.is_callable(),
_ => false,
}
}
pub fn identical(&self, other: &TypeSpec) -> bool {
match (self, other) {
(TypeSpec::Name(a), TypeSpec::Name(b)) => a == b,
(TypeSpec::Builtin(a), TypeSpec::Builtin(b)) => a == b,
(TypeSpec::Markdoc(a), TypeSpec::Markdoc(b)) => a == b,
(TypeSpec::Realm(a), TypeSpec::Realm(b)) => a == b,
(TypeSpec::Custom(a), TypeSpec::Custom(b)) => {
std::ptr::addr_eq(Arc::as_ptr(a), Arc::as_ptr(b))
}
(TypeSpec::Value(a), TypeSpec::Value(b)) => value::strict_equals(a, b),
_ => false,
}
}
}
impl fmt::Debug for TypeSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TypeSpec::Falsy => f.write_str("Falsy"),
TypeSpec::Name(n) => write!(f, "Name({n:?})"),
TypeSpec::Builtin(b) => write!(f, "Builtin({})", b.name()),
TypeSpec::Markdoc(m) => write!(f, "Markdoc({})", m.name()),
TypeSpec::Custom(c) => write!(f, "Custom({})", c.name()),
TypeSpec::Union(types) => f.debug_tuple("Union").field(types).finish(),
TypeSpec::Value(v) => f.debug_tuple("Value").field(v).finish(),
TypeSpec::Realm(b) => write!(f, "Realm({b:?})"),
}
}
}
impl fmt::Debug for Matches {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Matches::Array(values) => f.debug_tuple("Array").field(values).finish(),
Matches::RegExp(r) => write!(f, "RegExp({})", r.to_js_string()),
Matches::Fn(_) => f.write_str("Fn(<function>)"),
Matches::Call(b) => write!(f, "Call({b:?})"),
Matches::Other => f.write_str("Other"),
}
}
}
fn function_marker<T>(f: &Option<T>) -> Option<&'static str> {
f.as_ref().map(|_| "<function>")
}
impl fmt::Debug for Schema {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Schema")
.field("render", &self.render)
.field("children", &self.children)
.field("attributes", &self.attributes)
.field("slots", &self.slots)
.field("self_closing", &self.self_closing)
.field("inline", &self.inline)
.field("transform", &function_marker(&self.transform))
.field("validate", &function_marker(&self.validate))
.finish()
}
}
impl fmt::Debug for SchemaAttribute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SchemaAttribute")
.field("attr_type", &self.attr_type)
.field("render", &self.render)
.field("default", &self.default)
.field("required", &self.required)
.field("matches", &self.matches)
.field("validate", &function_marker(&self.validate))
.field("error_level", &self.error_level)
.finish()
}
}
impl fmt::Debug for ConfigFunction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConfigFunction")
.field("returns", &self.returns)
.field("parameters", &self.parameters)
.field("transform", &function_marker(&self.transform))
.field("validate", &function_marker(&self.validate))
.finish()
}
}
impl fmt::Debug for Variables {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Variables::Value(v) => f.debug_tuple("Value").field(v).finish(),
Variables::Fn(_) => f.write_str("Fn(<function>)"),
}
}
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Config")
.field("nodes", &self.nodes)
.field("tags", &self.tags)
.field("variables", &self.variables)
.field("functions", &self.functions)
.field("partials", &self.partials)
.field("validation", &self.validation)
.finish()
}
}
#[derive(Debug)]
pub enum Found<'a, T> {
Own(&'a T),
Inherited,
Missing,
}
pub fn inherited(key: &str) -> Value {
crate::next::realm::inherited_by_plain_object(key).unwrap_or(Value::Undefined)
}
pub fn lookup<'a, T>(map: &'a IndexMap<String, T>, key: &str) -> Found<'a, T> {
match map.get(key) {
Some(v) => Found::Own(v),
None if value::is_object_prototype_name(key) => Found::Inherited,
None => Found::Missing,
}
}
pub fn is_undefined_in<T>(map: &IndexMap<String, T>, key: &str) -> bool {
matches!(lookup(map, key), Found::Missing)
}
pub fn loose_equals_false(value: &Value) -> std::result::Result<bool, String> {
Ok(match value {
Value::Undefined | Value::Null => false,
Value::Boolean(b) => !*b,
Value::Number(n) => *n == 0.0,
Value::String(s) => string_to_number(s) == 0.0,
Value::Array(_) | Value::Object(_) | Value::Tag(_) | Value::Builtin(_) => {
loose_equals_false(&value::to_primitive(value, value::Hint::Default)?)?
}
})
}
fn string_to_number(s: &value::JsString) -> f64 {
crate::markdown_it::js::string_to_number(&s.to_utf16())
}
pub fn renders<'a>(
attr: &'a SchemaAttribute,
key: &'a str,
) -> std::result::Result<Option<Cow<'a, str>>, String> {
attr.kind.read("render")?;
if let Some(r) = &attr.render
&& loose_equals_false(r)?
{
return Ok(None);
}
Ok(match &attr.render {
Some(Value::String(name)) => Some(name.to_string_lossy()),
_ => Some(Cow::Borrowed(key)),
})
}
impl SchemaSlot {
pub fn renders<'a>(
&'a self,
key: &'a str,
) -> std::result::Result<Option<Cow<'a, str>>, String> {
self.kind.read("render")?;
Ok(match &self.render {
Some(Value::Boolean(false)) => None,
Some(Value::String(name)) => Some(name.to_string_lossy()),
_ => Some(Cow::Borrowed(key)),
})
}
}
impl Schema {
pub fn allows_child(&self, child_type: &str) -> Option<std::result::Result<bool, String>> {
let children = self.children.as_ref()?;
Some(match children {
Value::Array(items) => Ok(items
.present()
.any(|(_, item)| item.as_str() == Some(child_type))),
Value::String(s) => {
let needle: Vec<u16> = child_type.encode_utf16().collect();
Ok(needle.is_empty() || s.to_utf16().windows(needle.len()).any(|w| w == needle))
}
_ => Err("TypeError: schema.children.includes is not a function".into()),
})
}
}
fn error(id: &str, level: ValidationLevel, message: String) -> ValidationError {
ValidationError {
id: id.into(),
level,
message,
location: None,
raw: None,
span: None,
}
}
fn is_js_object(value: &Scalar) -> bool {
matches!(
value,
Scalar::Null
| Scalar::Array(_)
| Scalar::Object(_)
| Scalar::Variable(_)
| Scalar::Function(_)
| Scalar::Tag(_)
| Scalar::Js(_)
)
}
pub fn class_validate(value: &Scalar, key: &str) -> Vec<ValidationError> {
if matches!(value, Scalar::String(_)) || is_js_object(value) {
return Vec::new();
}
vec![error(
"attribute-type-invalid",
ValidationLevel::Error,
format!("Attribute '{key}' must be type 'string | object'"),
)]
}
pub fn class_transform(value: Value) -> Value {
if !value.to_boolean() || matches!(value, Value::String(_)) {
return value;
}
let classes: Vec<String> = value::own_entries(&value)
.into_iter()
.filter(|(_, v)| v.to_boolean())
.map(|(k, _)| k)
.collect();
Value::string(classes.join(" "))
}
pub fn id_validate(value: &Scalar) -> Vec<ValidationError> {
if let Scalar::String(s) = value
&& s.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
{
return Vec::new();
}
vec![error(
"attribute-value-invalid",
ValidationLevel::Error,
"The 'id' attribute must start with a letter".into(),
)]
}
pub fn conditional_validate(value: &Scalar, key: &str) -> Vec<ValidationError> {
if matches!(value, Scalar::Boolean(_)) || is_js_object(value) {
return Vec::new();
}
vec![error(
"attribute-type-invalid",
ValidationLevel::Error,
format!(
"Attribute '{key}' must be type 'boolean | object' (null or undefined are also allowed)"
),
)]
}
fn names(list: &[&str]) -> Option<Value> {
Some(Value::array(
list.iter().map(|s| Value::string(*s)).collect(),
))
}
fn attrs(list: Vec<(&str, SchemaAttribute)>) -> Option<IndexMap<String, SchemaAttribute>> {
let mut out = IndexMap::new();
for (k, v) in list {
crate::types::js_insert(&mut out, k, v);
}
Some(out)
}
fn attr(t: BuiltinType) -> SchemaAttribute {
SchemaAttribute {
attr_type: Some(TypeSpec::Builtin(t)),
..Default::default()
}
}
fn hidden(mut a: SchemaAttribute) -> SchemaAttribute {
a.render = Some(Value::Boolean(false));
a
}
fn required(mut a: SchemaAttribute) -> SchemaAttribute {
a.required = true;
a
}
fn render_as(mut a: SchemaAttribute, name: &str) -> SchemaAttribute {
a.render = Some(Value::string(name));
a
}
fn render(name: &str) -> Option<Value> {
Some(Value::string(name))
}
fn transform_fn(f: fn(&ResolvedNode<'_>, &Config) -> Result<Value>) -> Option<TransformFn> {
Some(Arc::new(f))
}
pub fn document() -> Schema {
Schema {
render: render("article"),
children: names(&[
"heading",
"paragraph",
"image",
"table",
"tag",
"fence",
"blockquote",
"comment",
"list",
"hr",
]),
attributes: attrs(vec![(
"frontmatter",
SchemaAttribute {
render: Some(Value::Boolean(false)),
..Default::default()
},
)]),
..Default::default()
}
}
#[inline(never)]
fn tag_value(
name: impl Into<value::JsString>,
attributes: value::Object,
children: Vec<Value>,
) -> Value {
TagValue::new(Value::String(name.into()), attributes, children).into()
}
pub fn heading() -> Schema {
Schema {
children: names(&["inline"]),
attributes: attrs(vec![("level", required(hidden(attr(BuiltinType::Number))))]),
transform: transform_fn(|node, config| {
let level = node.attribute("level")?;
let name = value::JsString::from("h")
.concat(&level.to_js_string().map_err(MarkdocError::TransformError)?);
let attributes = node.transform_attributes(config)?;
let children = node.transform_children(config)?;
Ok(tag_value(name, attributes, children))
}),
..Default::default()
}
}
pub fn paragraph() -> Schema {
Schema {
render: render("p"),
children: names(&["inline"]),
..Default::default()
}
}
pub fn image() -> Schema {
Schema {
render: render("img"),
attributes: attrs(vec![
("src", required(attr(BuiltinType::String))),
("alt", attr(BuiltinType::String)),
("title", attr(BuiltinType::String)),
]),
..Default::default()
}
}
pub fn fence() -> Schema {
let mut process = hidden(attr(BuiltinType::Boolean));
process.default = Some(Value::Boolean(true));
Schema {
render: render("pre"),
attributes: attrs(vec![
("content", required(hidden(attr(BuiltinType::String)))),
(
"language",
render_as(attr(BuiltinType::String), "data-language"),
),
("process", process),
]),
transform: transform_fn(|node, config| {
let _level = crate::next::transformer::charge(crate::next::transformer::cost::FENCE)?;
let attributes = node.transform_attributes(config)?;
let children = if !node.children.is_empty() {
node.transform_children(config)?
} else {
vec![node.attribute("content")?]
};
Ok(TagValue::new("pre", attributes, children).into())
}),
..Default::default()
}
}
pub fn blockquote() -> Schema {
Schema {
render: render("blockquote"),
children: names(&[
"heading",
"paragraph",
"image",
"table",
"tag",
"fence",
"blockquote",
"list",
"hr",
]),
..Default::default()
}
}
pub fn item() -> Schema {
Schema {
render: render("li"),
children: names(&[
"inline",
"heading",
"paragraph",
"image",
"table",
"tag",
"fence",
"blockquote",
"list",
"hr",
]),
..Default::default()
}
}
pub fn list() -> Schema {
Schema {
children: names(&["item"]),
attributes: attrs(vec![
("ordered", required(hidden(attr(BuiltinType::Boolean)))),
("start", attr(BuiltinType::Number)),
("marker", hidden(attr(BuiltinType::String))),
]),
transform: transform_fn(|node, config| {
let head = list_head(node, config)?;
let children = crate::next::transformer::children(node, config)?;
let (name, attributes) = *head;
Ok(tag_value(name, attributes, children))
}),
..Default::default()
}
}
#[inline(never)]
#[allow(clippy::type_complexity)]
fn list_head(
node: &ResolvedNode<'_>,
config: &Config,
) -> Result<Box<(&'static str, value::Object)>> {
let ordered = node.attribute("ordered")?.to_boolean();
Ok(Box::new((
if ordered { "ol" } else { "ul" },
node.transform_attributes(config)?,
)))
}
pub fn hr() -> Schema {
Schema {
render: render("hr"),
..Default::default()
}
}
pub fn table() -> Schema {
Schema {
render: render("table"),
..Default::default()
}
}
pub fn td() -> Schema {
Schema {
render: render("td"),
children: names(&[
"inline",
"heading",
"paragraph",
"image",
"table",
"tag",
"fence",
"blockquote",
"list",
"hr",
]),
attributes: attrs(vec![
("align", attr(BuiltinType::String)),
("colspan", render_as(attr(BuiltinType::Number), "colSpan")),
("rowspan", render_as(attr(BuiltinType::Number), "rowSpan")),
]),
..Default::default()
}
}
pub fn th() -> Schema {
Schema {
render: render("th"),
attributes: attrs(vec![
("width", attr(BuiltinType::String)),
("align", attr(BuiltinType::String)),
("colspan", render_as(attr(BuiltinType::Number), "colSpan")),
("rowspan", render_as(attr(BuiltinType::Number), "rowSpan")),
]),
..Default::default()
}
}
pub fn tr() -> Schema {
Schema {
render: render("tr"),
children: names(&["th", "td"]),
..Default::default()
}
}
pub fn tbody() -> Schema {
Schema {
render: render("tbody"),
children: names(&["tr", "tag"]),
..Default::default()
}
}
pub fn thead() -> Schema {
Schema {
render: render("thead"),
children: names(&["tr"]),
..Default::default()
}
}
pub fn strong() -> Schema {
Schema {
render: render("strong"),
children: names(&["em", "s", "link", "code", "text", "tag"]),
attributes: attrs(vec![("marker", hidden(attr(BuiltinType::String)))]),
..Default::default()
}
}
pub fn em() -> Schema {
Schema {
render: render("em"),
children: names(&["strong", "s", "link", "code", "text", "tag"]),
attributes: attrs(vec![("marker", hidden(attr(BuiltinType::String)))]),
..Default::default()
}
}
pub fn s() -> Schema {
Schema {
render: render("s"),
children: names(&["strong", "em", "link", "code", "text", "tag"]),
..Default::default()
}
}
pub fn inline() -> Schema {
Schema {
children: names(&[
"strong",
"em",
"s",
"code",
"text",
"tag",
"link",
"image",
"hardbreak",
"softbreak",
"comment",
]),
..Default::default()
}
}
pub fn link() -> Schema {
Schema {
render: render("a"),
children: names(&["strong", "em", "s", "code", "text", "tag"]),
attributes: attrs(vec![
("href", required(attr(BuiltinType::String))),
("title", attr(BuiltinType::String)),
]),
..Default::default()
}
}
pub fn code() -> Schema {
Schema {
render: render("code"),
attributes: attrs(vec![(
"content",
required(hidden(attr(BuiltinType::String))),
)]),
transform: transform_fn(|node, config| {
let attributes = node.transform_attributes(config)?;
let content = node.attribute("content")?;
Ok(TagValue::new("code", attributes, vec![content]).into())
}),
..Default::default()
}
}
pub fn text() -> Schema {
Schema {
attributes: attrs(vec![("content", required(attr(BuiltinType::String)))]),
transform: transform_fn(|node, _config| node.attribute("content")),
..Default::default()
}
}
pub fn hardbreak() -> Schema {
Schema {
render: render("br"),
..Default::default()
}
}
pub fn softbreak() -> Schema {
Schema {
transform: transform_fn(|_node, _config| Ok(Value::string(" "))),
..Default::default()
}
}
pub fn comment() -> Schema {
Schema {
attributes: attrs(vec![("content", required(attr(BuiltinType::String)))]),
..Default::default()
}
}
pub fn error_schema() -> Schema {
Schema::default()
}
pub fn node() -> Schema {
Schema::default()
}
static DEFAULT_NODES: LazyLock<IndexMap<String, Option<Schema>>> = LazyLock::new(|| {
[
("blockquote", blockquote()),
("code", code()),
("comment", comment()),
("document", document()),
("em", em()),
("error", error_schema()),
("fence", fence()),
("hardbreak", hardbreak()),
("heading", heading()),
("hr", hr()),
("image", image()),
("inline", inline()),
("item", item()),
("link", link()),
("list", list()),
("node", node()),
("paragraph", paragraph()),
("s", s()),
("softbreak", softbreak()),
("strong", strong()),
("table", table()),
("tbody", tbody()),
("td", td()),
("text", text()),
("th", th()),
("thead", thead()),
("tr", tr()),
]
.into_iter()
.map(|(name, schema)| (name.to_string(), Some(schema)))
.collect()
});
pub fn default_nodes() -> &'static IndexMap<String, Option<Schema>> {
&DEFAULT_NODES
}
pub fn global_attributes() -> &'static IndexMap<String, SchemaAttribute> {
static GLOBAL: LazyLock<IndexMap<String, SchemaAttribute>> = LazyLock::new(|| {
let mut out = IndexMap::new();
out.insert(
"class".to_string(),
SchemaAttribute {
attr_type: Some(TypeSpec::Markdoc(MarkdocType::Class)),
render: Some(Value::Boolean(true)),
..Default::default()
},
);
out.insert(
"id".to_string(),
SchemaAttribute {
attr_type: Some(TypeSpec::Markdoc(MarkdocType::Id)),
render: Some(Value::Boolean(true)),
..Default::default()
},
);
out
});
&GLOBAL
}
pub fn merged_attributes(schema: Option<&Schema>) -> IndexMap<String, SchemaAttribute> {
let mut out = global_attributes().clone();
if let Some(attributes) = schema.and_then(|s| s.attributes.as_ref()) {
for (k, v) in attributes {
crate::types::js_insert(&mut out, k.clone(), v.clone());
}
}
out
}
impl Config {
pub fn new() -> Self {
Self::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_reads_loose_equality() {
let a = |r: Option<Value>| SchemaAttribute {
render: r,
..Default::default()
};
let renders =
|attr: &SchemaAttribute, key| renders(attr, key).unwrap().map(Cow::into_owned);
assert_eq!(renders(&a(None), "k").as_deref(), Some("k"));
assert_eq!(
renders(&a(Some(Value::Boolean(true))), "k").as_deref(),
Some("k")
);
assert_eq!(
renders(&a(Some(Value::string("x"))), "k").as_deref(),
Some("x")
);
for hidden in [
Value::Boolean(false),
Value::Number(0.0),
Value::string(""),
Value::string("0"),
Value::string(" 0x0 "),
Value::array(vec![]),
] {
assert_eq!(renders(&a(Some(hidden.clone())), "k"), None, "{hidden:?}");
}
assert_eq!(renders(&a(Some(Value::Null)), "k").as_deref(), Some("k"));
let slot = SchemaSlot {
render: Some(Value::string("")),
..SchemaSlot::default()
};
assert_eq!(slot.renders("k").unwrap().as_deref(), Some(""));
}
#[test]
fn class_transform_joins_truthy_keys() {
let mut o = IndexMap::new();
o.insert("a".to_string(), Value::Boolean(true));
o.insert("b".to_string(), Value::Number(0.0));
o.insert("c".to_string(), Value::string("x"));
assert_eq!(class_transform(Value::object(o)).as_str(), Some("a c"));
assert!(matches!(
class_transform(Value::Number(0.0)),
Value::Number(_)
));
assert_eq!(class_transform(Value::Number(5.0)).as_str(), Some(""));
assert_eq!(
class_transform(Value::array(vec![Value::Boolean(true), Value::Null])).as_str(),
Some("0")
);
}
#[test]
fn a_config_can_be_shared_between_threads() {
fn send_sync<T: Send + Sync>() {}
send_sync::<Config>();
send_sync::<Value>();
}
#[test]
fn inherited_names_are_found() {
let map: IndexMap<String, i32> = IndexMap::new();
assert!(matches!(lookup(&map, "toString"), Found::Inherited));
assert!(matches!(lookup(&map, "foo"), Found::Missing));
assert!(!is_undefined_in(&map, "constructor"));
}
}