1use std::collections::BTreeMap;
24use std::sync::Arc;
25
26use mlua::{AnyUserData, Function, Lua, Table, Value};
27
28mod coerce;
29mod compile;
30mod engine;
31pub(crate) mod exemplars;
32pub(crate) mod file;
33pub(crate) mod format;
34mod lua;
35pub(crate) mod media;
36pub(crate) mod message;
37mod presets;
38pub(crate) mod schema_json;
39mod shorthand;
40#[cfg(test)]
41mod tests;
42
43pub use coerce::{TextValue, coerce_for_fuzzing};
44pub use engine::{ErrorEntry, ValidationError};
45pub use file::{FileInfo, LuaFile, SaveResolver};
46use format::FormatRule;
47pub(crate) use lua::{LuaSchema, create_validate_table};
48use message::{AppMessages, Param, Template};
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub(crate) enum Kind {
53 String,
54 Number,
55 Integer,
56 Boolean,
57 Array,
58 Table,
59 Map,
60 Any,
61 File,
62}
63
64impl Kind {
65 fn parse(name: &str) -> Option<Self> {
66 Some(match name {
67 "string" => Self::String,
68 "number" => Self::Number,
69 "integer" => Self::Integer,
70 "boolean" => Self::Boolean,
71 "array" => Self::Array,
72 "table" => Self::Table,
73 "map" => Self::Map,
74 "any" => Self::Any,
75 "file" => Self::File,
76 _ => None?,
77 })
78 }
79
80 pub(crate) fn name(self) -> &'static str {
81 match self {
82 Self::String => "string",
83 Self::Number => "number",
84 Self::Integer => "integer",
85 Self::Boolean => "boolean",
86 Self::Array => "array",
87 Self::Table => "table",
88 Self::Map => "map",
89 Self::Any => "any",
90 Self::File => "file",
91 }
92 }
93}
94
95#[derive(Debug, Clone, PartialEq)]
97pub(crate) enum Literal {
98 Str(String),
99 Num(f64),
100 Bool(bool),
101}
102
103impl Literal {
104 fn matches(&self, value: &Value) -> bool {
105 match (self, value) {
106 (Self::Str(s), Value::String(v)) => v.as_bytes().as_ref() == s.as_bytes(),
107 (Self::Num(n), Value::Integer(i)) => *n == *i as f64,
108 (Self::Num(n), Value::Number(f)) => n == f,
109 (Self::Bool(b), Value::Boolean(v)) => b == v,
110 _ => false,
111 }
112 }
113
114 fn param(&self) -> Param {
115 match self {
116 Self::Str(s) => Param::Str(s.clone()),
117 Self::Num(n) => Param::Num(*n),
118 Self::Bool(b) => Param::Bool(*b),
119 }
120 }
121
122 fn to_lua(&self, lua: &Lua) -> mlua::Result<Value> {
123 self.param().to_lua(lua)
124 }
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub(crate) enum Case {
130 Lower,
131 Upper,
132}
133
134#[derive(Debug, Clone, PartialEq)]
136pub(crate) enum TimeBound {
137 Now,
138 Literal(String),
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub(crate) enum TypePattern {
144 Any,
146 Family(String),
148 Exact(String),
149}
150
151#[derive(Debug, Clone, PartialEq)]
153pub(crate) struct Aspect {
154 min: f64,
155 max: f64,
156 label: String,
157}
158
159#[derive(Debug, Clone)]
161pub(crate) struct FileRule {
162 min_bytes: u64,
163 types: Vec<TypePattern>,
164 allow_executables: bool,
165 extensions: Vec<String>,
166 match_extension: bool,
167 filename: Option<Arc<Rule>>,
168 min_width: Option<u32>,
169 max_width: Option<u32>,
170 min_height: Option<u32>,
171 max_height: Option<u32>,
172 max_pixels: Option<u64>,
173 aspect: Option<Aspect>,
174 utf8: bool,
175}
176
177impl FileRule {
178 fn wants_dimensions(&self) -> bool {
179 self.min_width.is_some()
180 || self.max_width.is_some()
181 || self.min_height.is_some()
182 || self.max_height.is_some()
183 || self.max_pixels.is_some()
184 || self.aspect.is_some()
185 }
186}
187
188#[derive(Debug, Clone)]
190pub(crate) struct Rule {
191 kind: Kind,
192 required: bool,
193 default: Option<Literal>,
194 equals: Option<Literal>,
195 one_of: Option<Vec<Literal>>,
196 not_one_of: Option<Vec<Literal>>,
197 label: Option<String>,
198 message: Option<Template>,
200 messages: BTreeMap<String, Template>,
202 check: Option<Function>,
203 transform: Option<Function>,
206 description: Option<String>,
208 trim: bool,
210 case: Option<Case>,
211 min_len: Option<usize>,
212 max_len: Option<usize>,
213 len: Option<usize>,
214 format: Option<FormatRule>,
215 starts_with: Option<String>,
216 ends_with: Option<String>,
217 contains: Option<String>,
218 does_not_contain: Option<String>,
219 after: Option<TimeBound>,
220 before: Option<TimeBound>,
221 min: Option<f64>,
223 max: Option<f64>,
224 exclusive_min: Option<f64>,
225 exclusive_max: Option<f64>,
226 multiple_of: Option<f64>,
227 decimals: Option<u32>,
228 items: Option<Arc<Rule>>,
230 min_items: Option<usize>,
231 max_items: Option<usize>,
232 unique: bool,
233 contains_item: Option<Literal>,
234 contains_any: Option<Vec<Literal>>,
235 contains_all: Option<Vec<Literal>>,
236 max_total_bytes: Option<u64>,
237 fields: Option<Arc<SchemaDef>>,
239 keys: Option<Arc<Rule>>,
241 values: Option<Arc<Rule>>,
242 min_keys: Option<usize>,
243 max_keys: Option<usize>,
244 max_bytes: Option<u64>,
246 file: Option<FileRule>,
247}
248
249#[derive(Debug, Clone)]
251pub(crate) struct Group {
252 fields: Vec<String>,
253 message: Option<Template>,
254}
255
256#[derive(Debug, Clone)]
258pub(crate) struct CheckDef {
259 description: String,
260 func: Function,
261 message: Option<Template>,
262}
263
264#[derive(Debug, Clone)]
266pub(crate) struct SchemaDef {
267 fields: Vec<(String, Arc<Rule>)>,
268 title: Option<String>,
270 strict: bool,
271 messages: BTreeMap<String, Template>,
272 at_least_one: Vec<Group>,
273 mutually_exclusive: Vec<Group>,
274 dependent_required: Vec<(String, Group)>,
275 equal_fields: Vec<Group>,
276 ordered: Vec<Group>,
277 checks: Vec<CheckDef>,
278}
279
280impl SchemaDef {
281 fn rule(&self, name: &str) -> Option<&Arc<Rule>> {
282 self.fields.iter().find(|(n, _)| n == name).map(|(_, r)| r)
283 }
284
285 fn has_file_rules(&self) -> bool {
286 self.fields.iter().any(|(_, r)| r.mentions_file())
287 }
288}
289
290impl Rule {
291 fn mentions_file(&self) -> bool {
292 self.kind == Kind::File
293 || self.items.as_ref().is_some_and(|r| r.mentions_file())
294 || self.fields.as_ref().is_some_and(|s| s.has_file_rules())
295 }
296}
297
298#[derive(Debug, Clone)]
301pub struct CompiledSchema(Arc<SchemaDef>);
302
303impl CompiledSchema {
304 pub fn has_file_rules(&self) -> bool {
306 self.0.has_file_rules()
307 }
308
309 pub fn field_names(&self) -> Vec<&str> {
311 self.0.fields.iter().map(|(n, _)| n.as_str()).collect()
312 }
313
314 pub fn is_array_field(&self, name: &str) -> bool {
317 self.0.rule(name).is_some_and(|r| r.kind == Kind::Array)
318 }
319
320 pub fn is_file_field(&self, name: &str) -> bool {
322 self.0.rule(name).is_some_and(|r| {
323 r.kind == Kind::File || r.items.as_ref().is_some_and(|i| i.kind == Kind::File)
324 })
325 }
326
327 pub fn file_max_bytes(&self, name: &str) -> Option<u64> {
330 let rule = self.0.rule(name)?;
331 match rule.kind {
332 Kind::File => rule.max_bytes,
333 Kind::Array => rule.items.as_ref().and_then(|i| i.max_bytes),
334 _ => None,
335 }
336 }
337
338 pub fn strict(&self) -> bool {
340 self.0.strict
341 }
342
343 pub fn title(&self) -> Option<&str> {
346 self.0.title.as_deref()
347 }
348
349 pub fn json_schema(
354 &self,
355 components: &mut schema_json::Components,
356 ) -> Result<serde_json::Value, String> {
357 schema_json::export(&self.0, components)
358 }
359
360 pub async fn check(
364 &self,
365 lua: &Lua,
366 value: Value,
367 strict: Option<bool>,
368 ) -> mlua::Result<Result<Table, ValidationError>> {
369 engine::run(lua, &self.0, value, strict).await
370 }
371
372 pub async fn check_text(
375 &self,
376 lua: &Lua,
377 pairs: Vec<(String, TextValue)>,
378 strict: Option<bool>,
379 ) -> mlua::Result<Result<Table, ValidationError>> {
380 let value = coerce::build_table(lua, &self.0, pairs)?;
381 engine::run(lua, &self.0, Value::Table(value), strict).await
382 }
383}
384
385pub fn compile_schema(lua: &Lua, value: Value, what: &str) -> mlua::Result<CompiledSchema> {
389 match value {
390 Value::UserData(ud) if ud.is::<LuaSchema>() => {
391 Ok(CompiledSchema(ud.borrow::<LuaSchema>()?.0.clone()))
392 }
393 Value::Table(fields) => Ok(CompiledSchema(Arc::new(compile::compile_schema(
394 lua, &fields, None, what,
395 )?))),
396 other => Err(mlua::Error::RuntimeError(format!(
397 "{what} must be a schema or a table of rules, got {}",
398 other.type_name()
399 ))),
400 }
401}
402
403pub fn compile_text_schema(lua: &Lua, value: Value, what: &str) -> mlua::Result<CompiledSchema> {
407 let schema = compile_schema(lua, value, what)?;
408 for (name, rule) in &schema.0.fields {
409 let nested = match rule.kind {
410 Kind::Table | Kind::Map | Kind::Any | Kind::File => true,
411 Kind::Array => rule.items.as_ref().is_some_and(|i| {
412 matches!(
413 i.kind,
414 Kind::Table | Kind::Map | Kind::Any | Kind::File | Kind::Array
415 )
416 }),
417 _ => false,
418 };
419 if nested {
420 return Err(mlua::Error::RuntimeError(format!(
421 "{what}: field `{name}` has type `{}`, which text input cannot carry \
422 (a query string, form field or header is a string or a list of them)",
423 rule.kind.name()
424 )));
425 }
426 }
427 Ok(schema)
428}
429
430pub fn compile_file_rule(lua: &Lua, value: Value, what: &str) -> mlua::Result<CompiledSchema> {
433 let fields = lua.create_table()?;
434 fields.set("file", value)?;
435 let schema = compile::compile_schema(lua, &fields, None, what)?;
436 match schema.rule("file") {
437 Some(rule) if rule.kind == Kind::File => Ok(CompiledSchema(Arc::new(schema))),
438 _ => Err(mlua::Error::RuntimeError(format!(
439 "{what} must be a `file` rule"
440 ))),
441 }
442}
443
444#[derive(Debug, Clone)]
449pub enum DocSchema {
450 Fields(CompiledSchema),
452 Rule(CompiledSchema),
454}
455
456impl DocSchema {
457 pub fn json_schema(
459 &self,
460 components: &mut schema_json::Components,
461 ) -> Result<serde_json::Value, String> {
462 match self {
463 Self::Fields(schema) => schema.json_schema(components),
464 Self::Rule(wrapper) => {
465 let mut exported = wrapper.json_schema(components)?;
466 match exported
467 .get_mut("properties")
468 .and_then(|p| p.get_mut("value"))
469 {
470 Some(value) => Ok(value.take()),
471 None => Err("the rule wrapper lost its `value` property".into()),
472 }
473 }
474 }
475 }
476}
477
478pub fn compile_doc_schema(lua: &Lua, value: Value, what: &str) -> mlua::Result<DocSchema> {
482 if let Value::Table(table) = &value
483 && let Value::String(_) = table.get::<Value>("type")?
484 {
485 let fields = lua.create_table()?;
486 fields.set("value", value)?;
487 let schema = compile::compile_schema(lua, &fields, None, what)?;
488 return Ok(DocSchema::Rule(CompiledSchema(Arc::new(schema))));
489 }
490 Ok(DocSchema::Fields(compile_schema(lua, value, what)?))
491}
492
493pub fn freeze_messages(lua: &Lua) {
496 if let Some(mut app) = lua.app_data_mut::<AppMessages>() {
497 app.frozen = true;
498 } else {
499 lua.set_app_data(AppMessages {
500 frozen: true,
501 ..Default::default()
502 });
503 }
504}
505
506fn schema_of(ud: &AnyUserData) -> Option<Arc<SchemaDef>> {
509 ud.borrow::<LuaSchema>().ok().map(|s| s.0.clone())
510}