ayun_view/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
pub mod config;
mod instance;

use ayun_core::{traits::ErrorTrait, Error, Result};
use std::{collections::HashMap, ops::Deref};
use tera::Tera;

pub struct View {
    inner: Tera,
    config: config::View,
}

impl View {
    pub fn try_from_config(config: config::View) -> Result<Self, Error> {
        let mut tera = Tera::new(&config.path).map_err(Error::wrap)?;

        tera.register_function("asset", asset(config.asset.url.to_owned()));
        tera.register_function("vite", vite(config.asset.url.to_owned()));

        Ok(Self {
            inner: tera,
            config,
        })
    }

    pub fn config(self) -> config::View {
        self.config
    }
}

fn asset(url: String) -> impl tera::Function {
    Box::new(
        move |args: &HashMap<String, serde_json::Value>| -> tera::Result<serde_json::Value> {
            let resource = match args.get("resource") {
                Some(val) => match serde_json::from_value::<String>(val.clone()) {
                    Ok(v) => v,
                    Err(_) => {
                        let msg = format!(
                            "Function `asset` received resource={} but `resource` can only be a \
                             string",
                            val
                        );

                        tracing::error!(err.msg = msg, "error");
                        return Err(tera::Error::msg(msg));
                    }
                },
                None => {
                    let msg = "Function `asset` didn't receive a `resource` argument";

                    tracing::error!(err.msg = msg, "error");
                    return Err(tera::Error::msg(msg));
                }
            };

            Ok(serde_json::Value::String(format!("{}/{}", url, resource)))
        },
    )
}

fn vite(url: String) -> impl tera::Function {
    Box::new(
        move |args: &HashMap<String, serde_json::Value>| -> tera::Result<serde_json::Value> {
            let entry = match args.get("entry") {
                Some(val) => match serde_json::from_value::<String>(val.clone()) {
                    Ok(v) => v,
                    Err(_) => {
                        let msg = format!(
                            "Function `vite` received entry={} but `entry` can only be a string",
                            val
                        );

                        tracing::error!(err.msg = msg, "error");
                        return Err(tera::Error::msg(msg));
                    }
                },
                None => {
                    let msg = "Function `vite` didn't receive a `entry` argument";

                    tracing::error!(err.msg = msg, "error");
                    return Err(tera::Error::msg(msg));
                }
            };

            // dev
            if std::path::Path::new("public/hot").exists() {
                let dev = format!(
                    r#"<script type="module" src="http://localhost:5173/@vite/client"></script>
                   <script type="module" src="http://localhost:5173/{}"></script>"#,
                    &entry
                );

                return Ok(serde_json::Value::String(dev));
            }

            // build
            let manifest = match std::fs::read_to_string("public/build/manifest.json").ok() {
                None => {
                    let msg = format!(
                        "Vite manifest not found at `{}`",
                        "public/build/manifest.json"
                    );

                    tracing::error!(err.msg = msg, "error");
                    return Err(tera::Error::msg(msg));
                }
                Some(content) => {
                    match serde_json::from_str::<serde_json::Value>(&content)?.get(&entry) {
                        None => {
                            let msg = format!("Vite manifest entry not found at `{}`", &entry);

                            tracing::error!(err.msg = msg, "error");
                            return Err(tera::Error::msg(msg));
                        }
                        Some(val) => {
                            if let Some(is_entry) = val.get("isEntry") {
                                if !is_entry.as_bool().ok_or_else(|| {
                                    tera::Error::msg("Failed to parse `isEntry` as bool")
                                })? {
                                    let msg =
                                        format!("Vite manifest entry `{}` is not an entry", &entry);

                                    tracing::error!(err.msg = msg, "error");
                                    return Err(tera::Error::msg(msg));
                                }
                            }

                            val.clone()
                        }
                    }
                }
            };

            let mut resources = String::new();
            if let Some(css) = manifest.get("css") {
                for css in css
                    .as_array()
                    .ok_or_else(|| tera::Error::msg("Failed to parse `css` as array"))?
                {
                    resources.push_str(&format!(
                        r#"<link rel="stylesheet" href="{}/build/{}">"#,
                        url,
                        css.as_str()
                            .ok_or_else(|| tera::Error::msg("Failed to parse `css` as string"))?
                    ));
                }
            }

            if let Some(js) = manifest.get("file") {
                resources.push_str(&format!(
                    r#"<script type="module" src="{}/build/{}"></script>"#,
                    url,
                    js.as_str()
                        .ok_or_else(|| tera::Error::msg("Failed to parse `file` as string"))?
                ));
            }

            Ok(serde_json::Value::String(resources))
        },
    )
}

impl Deref for View {
    type Target = Tera;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}