1use crate::ViewError;
4
5#[derive(Clone, Debug, Eq, PartialEq)]
7pub struct AssetConfig {
8 base: String,
9}
10
11impl Default for AssetConfig {
12 fn default() -> Self {
13 Self {
14 base: "/assets".to_owned(),
15 }
16 }
17}
18
19impl AssetConfig {
20 #[must_use]
22 pub fn with_base(base: impl Into<String>) -> Self {
23 Self { base: base.into() }
24 }
25
26 pub fn join(&self, relative: &str) -> Result<String, ViewError> {
35 let trimmed = relative.trim().trim_start_matches('/');
36 if trimmed.is_empty() {
37 return Ok(normalize_base(&self.base));
38 }
39 let (file_part, query) = match trimmed.split_once('?') {
40 Some((file, q)) => (file, Some(q)),
41 None => (trimmed, None),
42 };
43 if file_part.is_empty() || file_part.contains("..") || file_part.contains(':') {
44 return Err(ViewError::msg(format!("unsafe asset path `{relative}`")));
45 }
46 for part in file_part.split('/') {
47 if part.is_empty() || part == "." {
48 return Err(ViewError::msg(format!("unsafe asset path `{relative}`")));
49 }
50 }
51 let base = normalize_base(&self.base);
52 let joined = format!("{base}/{file_part}");
53 Ok(match query {
54 Some(q) => format!("{joined}?{q}"),
55 None => joined,
56 })
57 }
58}
59
60pub fn asset(relative: &str) -> Result<String, ViewError> {
66 AssetConfig::default().join(relative)
67}
68
69fn normalize_base(base: &str) -> String {
70 let trimmed = base.trim().trim_end_matches('/');
71 if trimmed.is_empty() {
72 return String::new();
73 }
74 if trimmed.starts_with('/') {
75 trimmed.to_owned()
76 } else {
77 format!("/{trimmed}")
78 }
79}