use std::collections::BTreeMap;
use std::sync::Arc;
use mlua::{AnyUserData, Function, Lua, Table, Value};
mod coerce;
mod compile;
mod engine;
pub(crate) mod exemplars;
pub(crate) mod file;
pub(crate) mod format;
mod lua;
pub(crate) mod media;
pub(crate) mod message;
mod presets;
pub(crate) mod schema_json;
mod shorthand;
#[cfg(test)]
mod tests;
pub use coerce::{TextValue, coerce_for_fuzzing};
pub use engine::{ErrorEntry, ValidationError};
pub use file::{FileInfo, LuaFile, SaveResolver};
use format::FormatRule;
pub(crate) use lua::{LuaSchema, create_validate_table};
use message::{AppMessages, Param, Template};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
String,
Number,
Integer,
Boolean,
Array,
Table,
Map,
Any,
File,
}
impl Kind {
fn parse(name: &str) -> Option<Self> {
Some(match name {
"string" => Self::String,
"number" => Self::Number,
"integer" => Self::Integer,
"boolean" => Self::Boolean,
"array" => Self::Array,
"table" => Self::Table,
"map" => Self::Map,
"any" => Self::Any,
"file" => Self::File,
_ => None?,
})
}
pub(crate) fn name(self) -> &'static str {
match self {
Self::String => "string",
Self::Number => "number",
Self::Integer => "integer",
Self::Boolean => "boolean",
Self::Array => "array",
Self::Table => "table",
Self::Map => "map",
Self::Any => "any",
Self::File => "file",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Literal {
Str(String),
Num(f64),
Bool(bool),
}
impl Literal {
fn matches(&self, value: &Value) -> bool {
match (self, value) {
(Self::Str(s), Value::String(v)) => v.as_bytes().as_ref() == s.as_bytes(),
(Self::Num(n), Value::Integer(i)) => *n == *i as f64,
(Self::Num(n), Value::Number(f)) => n == f,
(Self::Bool(b), Value::Boolean(v)) => b == v,
_ => false,
}
}
fn param(&self) -> Param {
match self {
Self::Str(s) => Param::Str(s.clone()),
Self::Num(n) => Param::Num(*n),
Self::Bool(b) => Param::Bool(*b),
}
}
fn to_lua(&self, lua: &Lua) -> mlua::Result<Value> {
self.param().to_lua(lua)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Case {
Lower,
Upper,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum TimeBound {
Now,
Literal(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TypePattern {
Any,
Family(String),
Exact(String),
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Aspect {
min: f64,
max: f64,
label: String,
}
#[derive(Debug, Clone)]
pub(crate) struct FileRule {
min_bytes: u64,
types: Vec<TypePattern>,
allow_executables: bool,
extensions: Vec<String>,
match_extension: bool,
filename: Option<Arc<Rule>>,
min_width: Option<u32>,
max_width: Option<u32>,
min_height: Option<u32>,
max_height: Option<u32>,
max_pixels: Option<u64>,
aspect: Option<Aspect>,
utf8: bool,
}
impl FileRule {
fn wants_dimensions(&self) -> bool {
self.min_width.is_some()
|| self.max_width.is_some()
|| self.min_height.is_some()
|| self.max_height.is_some()
|| self.max_pixels.is_some()
|| self.aspect.is_some()
}
}
#[derive(Debug, Clone)]
pub(crate) struct Rule {
kind: Kind,
required: bool,
default: Option<Literal>,
equals: Option<Literal>,
one_of: Option<Vec<Literal>>,
not_one_of: Option<Vec<Literal>>,
label: Option<String>,
message: Option<Template>,
messages: BTreeMap<String, Template>,
check: Option<Function>,
transform: Option<Function>,
description: Option<String>,
trim: bool,
case: Option<Case>,
min_len: Option<usize>,
max_len: Option<usize>,
len: Option<usize>,
format: Option<FormatRule>,
starts_with: Option<String>,
ends_with: Option<String>,
contains: Option<String>,
does_not_contain: Option<String>,
after: Option<TimeBound>,
before: Option<TimeBound>,
min: Option<f64>,
max: Option<f64>,
exclusive_min: Option<f64>,
exclusive_max: Option<f64>,
multiple_of: Option<f64>,
decimals: Option<u32>,
items: Option<Arc<Rule>>,
min_items: Option<usize>,
max_items: Option<usize>,
unique: bool,
contains_item: Option<Literal>,
contains_any: Option<Vec<Literal>>,
contains_all: Option<Vec<Literal>>,
max_total_bytes: Option<u64>,
fields: Option<Arc<SchemaDef>>,
keys: Option<Arc<Rule>>,
values: Option<Arc<Rule>>,
min_keys: Option<usize>,
max_keys: Option<usize>,
max_bytes: Option<u64>,
file: Option<FileRule>,
}
#[derive(Debug, Clone)]
pub(crate) struct Group {
fields: Vec<String>,
message: Option<Template>,
}
#[derive(Debug, Clone)]
pub(crate) struct CheckDef {
description: String,
func: Function,
message: Option<Template>,
}
#[derive(Debug, Clone)]
pub(crate) struct SchemaDef {
fields: Vec<(String, Arc<Rule>)>,
title: Option<String>,
strict: bool,
messages: BTreeMap<String, Template>,
at_least_one: Vec<Group>,
mutually_exclusive: Vec<Group>,
dependent_required: Vec<(String, Group)>,
equal_fields: Vec<Group>,
ordered: Vec<Group>,
checks: Vec<CheckDef>,
}
impl SchemaDef {
fn rule(&self, name: &str) -> Option<&Arc<Rule>> {
self.fields.iter().find(|(n, _)| n == name).map(|(_, r)| r)
}
fn has_file_rules(&self) -> bool {
self.fields.iter().any(|(_, r)| r.mentions_file())
}
}
impl Rule {
fn mentions_file(&self) -> bool {
self.kind == Kind::File
|| self.items.as_ref().is_some_and(|r| r.mentions_file())
|| self.fields.as_ref().is_some_and(|s| s.has_file_rules())
}
}
#[derive(Debug, Clone)]
pub struct CompiledSchema(Arc<SchemaDef>);
impl CompiledSchema {
pub fn has_file_rules(&self) -> bool {
self.0.has_file_rules()
}
pub fn field_names(&self) -> Vec<&str> {
self.0.fields.iter().map(|(n, _)| n.as_str()).collect()
}
pub fn is_array_field(&self, name: &str) -> bool {
self.0.rule(name).is_some_and(|r| r.kind == Kind::Array)
}
pub fn is_file_field(&self, name: &str) -> bool {
self.0.rule(name).is_some_and(|r| {
r.kind == Kind::File || r.items.as_ref().is_some_and(|i| i.kind == Kind::File)
})
}
pub fn file_max_bytes(&self, name: &str) -> Option<u64> {
let rule = self.0.rule(name)?;
match rule.kind {
Kind::File => rule.max_bytes,
Kind::Array => rule.items.as_ref().and_then(|i| i.max_bytes),
_ => None,
}
}
pub fn strict(&self) -> bool {
self.0.strict
}
pub fn title(&self) -> Option<&str> {
self.0.title.as_deref()
}
pub fn json_schema(
&self,
components: &mut schema_json::Components,
) -> Result<serde_json::Value, String> {
schema_json::export(&self.0, components)
}
pub async fn check(
&self,
lua: &Lua,
value: Value,
strict: Option<bool>,
) -> mlua::Result<Result<Table, ValidationError>> {
engine::run(lua, &self.0, value, strict).await
}
pub async fn check_text(
&self,
lua: &Lua,
pairs: Vec<(String, TextValue)>,
strict: Option<bool>,
) -> mlua::Result<Result<Table, ValidationError>> {
let value = coerce::build_table(lua, &self.0, pairs)?;
engine::run(lua, &self.0, Value::Table(value), strict).await
}
}
pub fn compile_schema(lua: &Lua, value: Value, what: &str) -> mlua::Result<CompiledSchema> {
match value {
Value::UserData(ud) if ud.is::<LuaSchema>() => {
Ok(CompiledSchema(ud.borrow::<LuaSchema>()?.0.clone()))
}
Value::Table(fields) => Ok(CompiledSchema(Arc::new(compile::compile_schema(
lua, &fields, None, what,
)?))),
other => Err(mlua::Error::RuntimeError(format!(
"{what} must be a schema or a table of rules, got {}",
other.type_name()
))),
}
}
pub fn compile_text_schema(lua: &Lua, value: Value, what: &str) -> mlua::Result<CompiledSchema> {
let schema = compile_schema(lua, value, what)?;
for (name, rule) in &schema.0.fields {
let nested = match rule.kind {
Kind::Table | Kind::Map | Kind::Any | Kind::File => true,
Kind::Array => rule.items.as_ref().is_some_and(|i| {
matches!(
i.kind,
Kind::Table | Kind::Map | Kind::Any | Kind::File | Kind::Array
)
}),
_ => false,
};
if nested {
return Err(mlua::Error::RuntimeError(format!(
"{what}: field `{name}` has type `{}`, which text input cannot carry \
(a query string, form field or header is a string or a list of them)",
rule.kind.name()
)));
}
}
Ok(schema)
}
pub fn compile_file_rule(lua: &Lua, value: Value, what: &str) -> mlua::Result<CompiledSchema> {
let fields = lua.create_table()?;
fields.set("file", value)?;
let schema = compile::compile_schema(lua, &fields, None, what)?;
match schema.rule("file") {
Some(rule) if rule.kind == Kind::File => Ok(CompiledSchema(Arc::new(schema))),
_ => Err(mlua::Error::RuntimeError(format!(
"{what} must be a `file` rule"
))),
}
}
#[derive(Debug, Clone)]
pub enum DocSchema {
Fields(CompiledSchema),
Rule(CompiledSchema),
}
impl DocSchema {
pub fn json_schema(
&self,
components: &mut schema_json::Components,
) -> Result<serde_json::Value, String> {
match self {
Self::Fields(schema) => schema.json_schema(components),
Self::Rule(wrapper) => {
let mut exported = wrapper.json_schema(components)?;
match exported
.get_mut("properties")
.and_then(|p| p.get_mut("value"))
{
Some(value) => Ok(value.take()),
None => Err("the rule wrapper lost its `value` property".into()),
}
}
}
}
}
pub fn compile_doc_schema(lua: &Lua, value: Value, what: &str) -> mlua::Result<DocSchema> {
if let Value::Table(table) = &value
&& let Value::String(_) = table.get::<Value>("type")?
{
let fields = lua.create_table()?;
fields.set("value", value)?;
let schema = compile::compile_schema(lua, &fields, None, what)?;
return Ok(DocSchema::Rule(CompiledSchema(Arc::new(schema))));
}
Ok(DocSchema::Fields(compile_schema(lua, value, what)?))
}
pub fn freeze_messages(lua: &Lua) {
if let Some(mut app) = lua.app_data_mut::<AppMessages>() {
app.frozen = true;
} else {
lua.set_app_data(AppMessages {
frozen: true,
..Default::default()
});
}
}
fn schema_of(ud: &AnyUserData) -> Option<Arc<SchemaDef>> {
ud.borrow::<LuaSchema>().ok().map(|s| s.0.clone())
}