vibe/web_runtime/form_state/
mod.rs1pub mod history_crdt;
15pub mod lifecycle;
16pub mod serialize_privacy;
17
18use std::collections::BTreeMap;
19
20use crate::error::{DiagCode, Diagnostic};
21use crate::span::Span;
22use crate::value::Value;
23
24pub(crate) const MAX_HISTORY_LEN: usize = 64;
26
27pub(crate) const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
29
30pub(crate) const FNV_PRIME: u64 = 0x100000001b3;
32
33pub fn call_form_state(
35 path: &str,
36 args: &[Value],
37 span: Span,
38) -> Result<Option<Value>, Diagnostic> {
39 if let Some(res) = lifecycle::call_lifecycle(path, args, span)? {
40 return Ok(Some(res));
41 }
42 if let Some(res) = history_crdt::call_history_crdt(path, args, span)? {
43 return Ok(Some(res));
44 }
45 if let Some(res) = serialize_privacy::call_serialize_privacy(path, args, span)? {
46 return Ok(Some(res));
47 }
48 Ok(None)
49}
50
51pub(crate) fn fnv1a_64(bytes: &[u8]) -> u64 {
52 let mut h = FNV_OFFSET_BASIS;
53 for &b in bytes {
54 h ^= b as u64;
55 h = h.wrapping_mul(FNV_PRIME);
56 }
57 h
58}
59
60pub(crate) fn push_bounded(list: &mut Vec<Value>, item: Value) {
61 if list.len() >= MAX_HISTORY_LEN {
62 list.remove(0);
63 }
64 list.push(item);
65}
66
67pub(crate) fn get_sub_record(rec: &BTreeMap<String, Value>, key: &str) -> BTreeMap<String, Value> {
68 match rec.get(key) {
69 Some(Value::Record(sub)) => sub.clone(),
70 _ => BTreeMap::new(),
71 }
72}
73
74pub(crate) fn get_sub_list(rec: &BTreeMap<String, Value>, key: &str) -> Vec<Value> {
75 match rec.get(key) {
76 Some(Value::List(items)) => items.clone(),
77 _ => Vec::new(),
78 }
79}
80
81pub(crate) fn extract_schema_base(form: &BTreeMap<String, Value>) -> String {
82 let base = match form.get("schema_iri") {
83 Some(Value::Iri(s)) | Some(Value::String(s)) => s.as_str(),
84 _ => "https://qualia.world/ontology/form#",
85 };
86 if base.ends_with('#') || base.ends_with('/') {
87 base.to_string()
88 } else {
89 format!("{base}#")
90 }
91}
92
93pub(crate) fn extract_str(
94 args: &[Value],
95 idx: usize,
96 ctx: &str,
97 span: Span,
98) -> Result<String, Diagnostic> {
99 match args.get(idx) {
100 Some(Value::String(s)) | Some(Value::Iri(s)) => Ok(s.clone()),
101 _ => Err(Diagnostic::new(
102 DiagCode::E100,
103 span,
104 format!("{ctx}: argument #{idx} must be a string"),
105 )),
106 }
107}
108
109pub(crate) fn extract_i64(
110 args: &[Value],
111 idx: usize,
112 ctx: &str,
113 span: Span,
114) -> Result<i64, Diagnostic> {
115 args.get(idx).and_then(Value::as_i64).ok_or_else(|| {
116 Diagnostic::new(
117 DiagCode::E100,
118 span,
119 format!("{ctx}: argument #{idx} must be an integer"),
120 )
121 })
122}
123
124pub(crate) fn extract_record(
125 args: &[Value],
126 idx: usize,
127 ctx: &str,
128 span: Span,
129) -> Result<BTreeMap<String, Value>, Diagnostic> {
130 match args.get(idx) {
131 Some(Value::Record(map)) => Ok(map.clone()),
132 _ => Err(Diagnostic::new(
133 DiagCode::E100,
134 span,
135 format!("{ctx}: argument #{idx} must be a record"),
136 )),
137 }
138}