vld_app/tauri.rs
1//! # `vld_app::tauri` — Tauri IPC validation for `vld`
2//!
3//! Validate [Tauri](https://tauri.app/) IPC commands, events, state, plugin
4//! config and channel messages with `vld` schemas.
5//!
6//! No dependency on `tauri`: the crate only needs `vld`, `serde` and
7//! `serde_json`; add `tauri` to your app separately.
8//!
9//! | Item | Use |
10//! |------|-----|
11//! | [`validate`] | Validate a `serde_json::Value` (commands, events, state, config, channel messages) |
12//! | [`validate_args`] | Parse and validate a raw JSON string |
13//! | [`VldTauriError`] | Serializable error for `#[tauri::command]` results |
14//! | [`VldPayload<T>`] | `Deserialize` wrapper that validates |
15//! | [`VldEvent<T>`] | Type alias of [`VldPayload<T>`] for event payloads |
16//!
17//! Issue paths have no leading dot (`name`, `user.email`, `items[0]`).
18//!
19//! Guide: <https://s00d.github.io/vld/integrations/ui/tauri>
20//!
21//! # Usage patterns
22//!
23//! ## IPC commands — explicit validation (recommended)
24//!
25//! Accept `serde_json::Value` and validate manually.
26//! The frontend receives structured error JSON on failure.
27//!
28//! ```rust,ignore
29//! use vld_app::tauri::prelude::*;
30//!
31//! vld::schema! {
32//! #[derive(Debug, Clone, serde::Serialize)]
33//! pub struct CreateUser {
34//! pub name: String => vld::string().min(2).max(50),
35//! pub email: String => vld::string().email(),
36//! }
37//! }
38//!
39//! #[tauri::command]
40//! fn create_user(payload: serde_json::Value) -> Result<String, VldTauriError> {
41//! let user = validate::<CreateUser>(payload)?;
42//! Ok(format!("Created {}", user.name))
43//! }
44//! ```
45//!
46//! ## IPC commands — auto-validated payload
47//!
48//! `VldPayload<T>` implements `Deserialize` and validates during
49//! deserialization. If validation fails, Tauri reports an argument
50//! deserialization error carrying the validation message as a string (not a
51//! structured [`VldTauriError`]).
52//!
53//! ```rust,ignore
54//! #[tauri::command]
55//! fn create_user(payload: VldPayload<CreateUser>) -> Result<String, VldTauriError> {
56//! Ok(format!("Created {}", payload.name))
57//! }
58//! ```
59//!
60//! ## Event payloads
61//!
62//! Validate data from `emit()`/`listen()`:
63//!
64//! ```rust,ignore
65//! use tauri::{Emitter, Listener};
66//!
67//! // Backend: validate incoming event from frontend
68//! app.listen("user:update", |event| {
69//! let payload: serde_json::Value = serde_json::from_str(event.payload()).unwrap();
70//! match validate::<UserUpdate>(payload) {
71//! Ok(update) => println!("Valid update: {:?}", update),
72//! Err(e) => eprintln!("Bad event: {e}"),
73//! }
74//! });
75//!
76//! // Or validate while deserializing (VldEvent<T> is VldPayload<T>):
77//! let event: VldEvent<UserUpdate> = serde_json::from_str(event.payload()).unwrap();
78//! ```
79//!
80//! ## State validation at init
81//!
82//! ```rust,ignore
83//! let config_json = std::fs::read_to_string("config.json").unwrap();
84//! let config = validate::<AppConfig>(
85//! serde_json::from_str(&config_json).unwrap()
86//! ).expect("Invalid app config");
87//! app.manage(config);
88//! ```
89//!
90//! ## Plugin config validation
91//!
92//! ```rust,ignore
93//! let plugin_cfg: serde_json::Value = /* from tauri.conf.json */;
94//! let cfg = validate::<MyPluginConfig>(plugin_cfg)
95//! .expect("Invalid plugin config");
96//! ```
97//!
98//! ## Channel message validation
99//!
100//! ```rust,ignore
101//! #[tauri::command]
102//! fn stream(channel: Channel<serde_json::Value>) -> Result<(), VldTauriError> {
103//! let msg = ProgressUpdate { percent: 50, status: "working".into() };
104//! let validated = validate::<ProgressUpdate>(
105//! serde_json::to_value(&msg).unwrap()
106//! )?;
107//! channel.send(serde_json::to_value(&validated).unwrap()).unwrap();
108//! Ok(())
109//! }
110//! ```
111//!
112//! # Frontend usage (TypeScript)
113//!
114//! ```javascript,ignore
115//! import { invoke } from '@tauri-apps/api/core';
116//!
117//! interface VldError {
118//! error: string;
119//! issues: Array<{
120//! path: string;
121//! message: string;
122//! code: string; // "too_small", "invalid_type", a rule key, …
123//! params: Record<string, string>; // { minimum: "2", origin: "string", … }
124//! }>;
125//! }
126//!
127//! try {
128//! const result = await invoke('create_user', {
129//! payload: { name: 'Alice', email: 'alice@example.com' }
130//! });
131//! } catch (err) {
132//! const vldErr = err as VldError;
133//! for (const issue of vldErr.issues) {
134//! // vue-i18n: messages like `vld: { too_small: "At least {minimum}" }`
135//! console.error(`${issue.path}: ${t(`vld.${issue.code}`, issue.params)}`);
136//! }
137//! }
138//! ```
139
140use std::collections::BTreeMap;
141
142use serde::{Deserialize, Serialize};
143use vld::schema::VldParse;
144
145// ---------------------------------------------------------------------------
146// Error type
147// ---------------------------------------------------------------------------
148
149/// Single validation issue, serialised for the frontend.
150///
151/// `code` and `params` are what a frontend i18n library needs to render its
152/// own message: with vue-i18n, `t(`vld.${issue.code}`, issue.params)` and a
153/// `vld.too_small` message such as `"At least {minimum}"`.
154#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
155pub struct TauriIssue {
156 /// Path of the failing field, e.g. `name`, `user.email`, `items[0]`.
157 pub path: String,
158 /// Human-readable error message.
159 pub message: String,
160 /// Issue code ([`IssueCode::key`](vld::error::IssueCode::key)):
161 /// `too_small`, `invalid_type`, a rule key, …; `invalid_json` / `custom`
162 /// for errors not produced by a schema.
163 #[serde(default)]
164 pub code: String,
165 /// Template parameters of the code
166 /// ([`IssueCode::params`](vld::error::IssueCode::params)): `minimum`,
167 /// `origin`, `expected`, …
168 #[serde(default)]
169 pub params: BTreeMap<String, String>,
170}
171
172impl TauriIssue {
173 fn plain(code: &str, message: String) -> Self {
174 Self {
175 path: String::new(),
176 message,
177 code: code.into(),
178 params: BTreeMap::new(),
179 }
180 }
181}
182
183/// Serializable error type for Tauri IPC commands, events, and channel
184/// messages.
185///
186/// Tauri requires command error types to implement `Serialize`.
187/// `VldTauriError` serialises as:
188///
189/// ```json
190/// {
191/// "error": "Validation failed",
192/// "issues": [
193/// {
194/// "path": "name",
195/// "message": "String must be at least 2 characters",
196/// "code": "too_small",
197/// "params": { "inclusive": "true", "minimum": "2", "origin": "string" }
198/// }
199/// ]
200/// }
201/// ```
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct VldTauriError {
204 /// Error category string (e.g. `"Validation failed"`, `"Invalid JSON"`).
205 pub error: String,
206 /// List of individual validation issues.
207 pub issues: Vec<TauriIssue>,
208}
209
210impl VldTauriError {
211 /// Create from a [`VldError`](vld::error::VldError).
212 pub fn from_vld(e: &vld::error::VldError) -> Self {
213 let issues = e
214 .issues
215 .iter()
216 .map(|i| TauriIssue {
217 path: vld::error::format_path(&i.path),
218 message: i.message.clone(),
219 code: i.code.key().to_string(),
220 params: i
221 .code
222 .params()
223 .into_iter()
224 .map(|(k, v)| (k.to_string(), v))
225 .collect(),
226 })
227 .collect();
228 Self {
229 error: "Validation failed".into(),
230 issues,
231 }
232 }
233
234 /// Build a JSON-parse error.
235 pub fn json_parse_error(msg: impl std::fmt::Display) -> Self {
236 Self {
237 error: "Invalid JSON".into(),
238 issues: vec![TauriIssue::plain("invalid_json", msg.to_string())],
239 }
240 }
241
242 /// Build a generic error with a custom category.
243 pub fn custom(error: impl Into<String>, message: impl Into<String>) -> Self {
244 Self {
245 error: error.into(),
246 issues: vec![TauriIssue::plain("custom", message.into())],
247 }
248 }
249
250 /// `true` if the error contains any issues.
251 pub fn has_issues(&self) -> bool {
252 !self.issues.is_empty()
253 }
254
255 /// Number of issues.
256 pub fn issue_count(&self) -> usize {
257 self.issues.len()
258 }
259}
260
261impl std::fmt::Display for VldTauriError {
262 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263 write!(f, "{}: {} issue(s)", self.error, self.issues.len())
264 }
265}
266
267impl std::error::Error for VldTauriError {}
268
269impl From<vld::error::VldError> for VldTauriError {
270 fn from(e: vld::error::VldError) -> Self {
271 Self::from_vld(&e)
272 }
273}
274
275// ---------------------------------------------------------------------------
276// Core validate function
277// ---------------------------------------------------------------------------
278
279/// Validate a `serde_json::Value` against a `vld` schema.
280///
281/// General-purpose entry-point used by all specialised helpers.
282///
283/// # Example
284///
285/// ```rust
286/// use vld_app::tauri::validate;
287///
288/// vld::schema! {
289/// #[derive(Debug)]
290/// struct Greet {
291/// name: String => vld::string().min(1),
292/// }
293/// }
294///
295/// let val = serde_json::json!({"name": "Alice"});
296/// let g = validate::<Greet>(val).unwrap();
297/// assert_eq!(g.name, "Alice");
298/// ```
299pub fn validate<T: VldParse>(value: serde_json::Value) -> Result<T, VldTauriError> {
300 T::vld_parse_value(&value).map_err(VldTauriError::from)
301}
302
303/// Validate a raw JSON string against a `vld` schema.
304///
305/// Convenience wrapper — parses the string first, then validates.
306///
307/// # Example
308///
309/// ```rust
310/// use vld_app::tauri::validate_args;
311///
312/// vld::schema! {
313/// #[derive(Debug)]
314/// struct Ping {
315/// msg: String => vld::string().min(1),
316/// }
317/// }
318///
319/// let p = validate_args::<Ping>(r#"{"msg":"pong"}"#).unwrap();
320/// assert_eq!(p.msg, "pong");
321/// ```
322pub fn validate_args<T: VldParse>(json_str: &str) -> Result<T, VldTauriError> {
323 let value: serde_json::Value =
324 serde_json::from_str(json_str).map_err(VldTauriError::json_parse_error)?;
325 validate(value)
326}
327
328// ---------------------------------------------------------------------------
329// VldPayload<T> — auto-validating wrapper for command args
330// ---------------------------------------------------------------------------
331
332/// Auto-validating wrapper for Tauri **command parameters**.
333///
334/// Implements [`Deserialize`] — on deserialization the incoming JSON is
335/// validated through `T::vld_parse_value()`. If validation fails,
336/// deserialization returns a `serde::de::Error` with the full message.
337///
338/// Implements [`Deref`](std::ops::Deref) to `T` so fields are accessible
339/// directly.
340///
341/// # Example
342///
343/// ```rust,ignore
344/// #[tauri::command]
345/// fn greet(payload: VldPayload<GreetArgs>) -> Result<String, VldTauriError> {
346/// Ok(format!("Hello, {}!", payload.name))
347/// }
348/// ```
349pub struct VldPayload<T>(pub T);
350
351impl<T> std::ops::Deref for VldPayload<T> {
352 type Target = T;
353 fn deref(&self) -> &T {
354 &self.0
355 }
356}
357
358impl<T> std::ops::DerefMut for VldPayload<T> {
359 fn deref_mut(&mut self) -> &mut T {
360 &mut self.0
361 }
362}
363
364impl<T: std::fmt::Debug> std::fmt::Debug for VldPayload<T> {
365 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366 f.debug_tuple("VldPayload").field(&self.0).finish()
367 }
368}
369
370impl<T: Clone> Clone for VldPayload<T> {
371 fn clone(&self) -> Self {
372 Self(self.0.clone())
373 }
374}
375
376impl<'de, T: VldParse> Deserialize<'de> for VldPayload<T> {
377 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
378 where
379 D: serde::Deserializer<'de>,
380 {
381 let value = serde_json::Value::deserialize(deserializer)?;
382 T::vld_parse_value(&value).map(VldPayload).map_err(|e| {
383 let msg = format_vld_error_inline(&e);
384 serde::de::Error::custom(msg)
385 })
386 }
387}
388
389// ---------------------------------------------------------------------------
390// VldEvent<T> — auto-validating wrapper for event payloads
391// ---------------------------------------------------------------------------
392
393/// Auto-validating wrapper for Tauri **event payloads** — the same type as
394/// [`VldPayload<T>`], named for data received via `Listener::listen()`.
395///
396/// Since 0.5 this is a type alias: construct / match it as `VldPayload(x)`.
397///
398/// # Example
399///
400/// ```rust,ignore
401/// app.listen("settings:changed", |event| {
402/// if let Ok(s) = serde_json::from_str::<VldEvent<Settings>>(event.payload()) {
403/// println!("New settings: {:?}", s.0);
404/// }
405/// });
406/// ```
407pub type VldEvent<T> = VldPayload<T>;
408
409// ---------------------------------------------------------------------------
410// Internal helpers
411// ---------------------------------------------------------------------------
412
413fn format_vld_error_inline(e: &vld::error::VldError) -> String {
414 let issues: Vec<String> = vld::error::flatten_issues(e)
415 .into_iter()
416 .map(|(path, message)| {
417 if path.is_empty() {
418 message
419 } else {
420 format!("{path}: {message}")
421 }
422 })
423 .collect();
424 format!("Validation failed: {}", issues.join("; "))
425}
426
427// ---------------------------------------------------------------------------
428// Prelude
429// ---------------------------------------------------------------------------
430
431/// Prelude — import everything you need.
432pub mod prelude {
433 pub use super::{TauriIssue, VldEvent, VldPayload, VldTauriError, validate, validate_args};
434 pub use vld::prelude::*;
435}