Skip to main content

vertigo_cli/serve/
mount_path.rs

1#![allow(clippy::question_mark)]
2use std::{collections::HashMap, path::Path, sync::Arc};
3use vertigo::dev::{
4    VERTIGO_MOUNT_POINT_ENV, VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, VERTIGO_PUBLIC_PATH_ENV,
5};
6
7use crate::commons::{ErrorCode, models::IndexModel};
8
9pub struct MountConfigBuilder {
10    pub mount_point: String,
11    pub dest_dir: String,
12    pub env: Vec<(String, String)>,
13    pub wasm_preload: bool,
14    pub disable_hydration: bool,
15    pub ssr_fetch_base: Option<String>,
16    pub ssr_cookies: Vec<String>,
17    pub pretty_html: bool,
18}
19
20impl MountConfigBuilder {
21    pub fn new(mount_point: impl Into<String>, dest_dir: impl Into<String>) -> MountConfigBuilder {
22        MountConfigBuilder {
23            mount_point: mount_point.into(),
24            dest_dir: dest_dir.into(),
25            env: vec![],
26            wasm_preload: false,
27            disable_hydration: false,
28            ssr_fetch_base: None,
29            ssr_cookies: vec![],
30            pretty_html: false,
31        }
32    }
33
34    pub fn envs(mut self, envs: Vec<(String, String)>) -> Self {
35        self.env = envs;
36        self
37    }
38
39    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
40        self.env.push((key.into(), value.into()));
41        self
42    }
43
44    pub fn wasm_preload(mut self, wasm_preload: bool) -> Self {
45        self.wasm_preload = wasm_preload;
46        self
47    }
48
49    pub fn disable_hydration(mut self, disable_hydration: bool) -> Self {
50        self.disable_hydration = disable_hydration;
51        self
52    }
53
54    /// Origin against which SSR resolves relative fetch URLs (`/api/posts`), e.g. `http://127.0.0.1:8080`.
55    ///
56    /// Without it, fetching a relative URL during SSR fails.
57    pub fn ssr_fetch_base(mut self, origin: impl Into<String>) -> Self {
58        self.ssr_fetch_base = Some(origin.into());
59        self
60    }
61
62    /// A cookie the app may read with `get_driver().cookie_get()` while the server renders the
63    /// page, f. ex. the language the user picked, so the page comes rendered as the browser will
64    /// show it. Others read as empty there, as they always did.
65    ///
66    /// Only for a cookie the browser shows the app too: not `HttpOnly`. The `Cookie` header doesn't
67    /// tell which are, and the server would render what the browser can't.
68    pub fn ssr_cookie(mut self, name: impl Into<String>) -> Self {
69        self.ssr_cookies.push(name.into());
70        self
71    }
72
73    /// Indent the server-rendered HTML, to read it in the page source.
74    ///
75    /// Off by default: the indentation is whitespace between elements, which the app's own tree
76    /// doesn't have - until the app starts it shows as gaps between inline elements, and
77    /// hydration then takes it out, one node at a time.
78    pub fn pretty_html(mut self, pretty_html: bool) -> Self {
79        self.pretty_html = pretty_html;
80        self
81    }
82
83    pub fn build(self) -> Result<MountConfig, ErrorCode> {
84        let mut config = MountConfig::new(
85            self.mount_point,
86            self.dest_dir,
87            self.env,
88            self.wasm_preload,
89            self.disable_hydration,
90        )?;
91        config.ssr_fetch_base = self.ssr_fetch_base;
92        config.ssr_cookies = self.ssr_cookies;
93        config.pretty_html = self.pretty_html;
94        Ok(config)
95    }
96}
97
98#[derive(Clone, Debug)]
99pub struct MountConfig {
100    /// Mount point in URL
101    mount_point: String,
102    /// Build destination directory (where wasm file and wasm_run.js are stored)
103    dest_dir: String,
104    /// waasm_run.js taken from index.json
105    run_js: String,
106    /// path to wasm-file taken from index.json
107    wasm_path: String,
108    /// Environment variables passed to WASM runtime - together with the mount point and the
109    /// public path of the build (`vertigo-mount-point`, `vertigo-public-path`)
110    pub env: Arc<HashMap<String, String>>,
111    /// Whether to preload wasm script using <link rel="preload">
112    pub wasm_preload: bool,
113    /// Whether to disable hydration
114    pub disable_hydration: bool,
115    /// See [`MountConfigBuilder::ssr_fetch_base`]
116    pub ssr_fetch_base: Option<String>,
117    /// See [`MountConfigBuilder::ssr_cookie`]
118    pub ssr_cookies: Vec<String>,
119    /// See [`MountConfigBuilder::pretty_html`]
120    pub pretty_html: bool,
121}
122
123impl MountConfig {
124    pub fn new(
125        public_mount_point: impl Into<String>,
126        dest_dir: impl Into<String>,
127        env: Vec<(String, String)>,
128        wasm_preload: bool,
129        disable_hydration: bool,
130    ) -> Result<MountConfig, ErrorCode> {
131        let dest_dir = dest_dir.into();
132        let index_model = read_index(&dest_dir)?;
133
134        let mut config = MountConfig {
135            dest_dir,
136            mount_point: public_mount_point.into(),
137            run_js: index_model.run_js,
138            wasm_path: index_model.wasm,
139            env: Arc::default(),
140            wasm_preload,
141            disable_hydration,
142            ssr_fetch_base: None,
143            ssr_cookies: vec![],
144            pretty_html: false,
145        };
146
147        // The app gets them wherever it runs - in the browser as `data-env-*`, during SSR from
148        // the host - so both sides build the same paths (`Driver::route_to_public`,
149        // `Driver::public_build_path`)
150        let mut env: HashMap<String, String> = env.into_iter().collect();
151        env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
152        env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
153        config.env = Arc::new(env);
154
155        Ok(config)
156    }
157
158    pub fn mount_point(&self) -> &str {
159        self.mount_point.as_str()
160    }
161
162    pub fn dest_dir(&self) -> &str {
163        self.dest_dir.trim_start_matches("./")
164    }
165
166    pub fn dest_http_root(&self) -> String {
167        Path::new(&self.mount_point)
168            .join(self.dest_dir())
169            .components()
170            .as_path()
171            .to_string_lossy()
172            .into_owned()
173    }
174
175    pub fn get_wasm_http_path(&self) -> String {
176        self.translate_to_http(&self.wasm_path)
177    }
178
179    pub fn get_run_js_http_path(&self) -> String {
180        self.translate_to_http(&self.run_js)
181    }
182
183    pub fn get_wasm_fs_path(&self) -> String {
184        self.translate_to_fs(&self.wasm_path)
185    }
186
187    fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
188        let fs_path = fs_path.into();
189        fs_path.replace(
190            VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
191            &self.dest_http_root(),
192        )
193    }
194
195    fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
196        let http_path = http_path.into();
197        replace_prefix(&self.dest_dir, &http_path)
198    }
199}
200
201fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
202    let index_path = Path::new(dest_dir).join("index.json");
203    let index_html = match std::fs::read_to_string(&index_path) {
204        Ok(data) => data,
205        Err(err) => {
206            log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
207            return Err(ErrorCode::ServeCantReadIndexFile);
208        }
209    };
210
211    serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
212        log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
213        ErrorCode::ServeCantReadIndexFile
214    })
215}
216
217fn replace_prefix(dest_dir: &str, path: &str) -> String {
218    if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
219        // Dynamic path resolution
220        path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
221    } else {
222        // Static path resolution
223        path.to_string()
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
230
231    use super::{MountConfig, MountConfigBuilder, replace_prefix};
232
233    #[test]
234    fn html_is_indented_only_when_asked() -> std::io::Result<()> {
235        let dest_dir = std::env::temp_dir().join(format!("vertigo-pretty-{}", std::process::id()));
236        std::fs::create_dir_all(&dest_dir)?;
237        std::fs::write(
238            dest_dir.join("index.json"),
239            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
240        )?;
241
242        let builder = || MountConfigBuilder::new("/", dest_dir.to_string_lossy());
243        let (Ok(default), Ok(pretty)) = (builder().build(), builder().pretty_html(true).build())
244        else {
245            panic!("index.json in {dest_dir:?} should read");
246        };
247
248        assert!(!default.pretty_html);
249        assert!(pretty.pretty_html);
250
251        std::fs::remove_dir_all(&dest_dir)
252    }
253
254    #[test]
255    fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
256        let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
257        std::fs::create_dir_all(&dest_dir)?;
258        std::fs::write(
259            dest_dir.join("index.json"),
260            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
261        )?;
262
263        let Ok(config) = MountConfig::new(
264            "/panel",
265            dest_dir.to_string_lossy(),
266            vec![
267                ("api_url".into(), "/api".into()),
268                // the server knows better where it mounted the app
269                ("vertigo-mount-point".into(), "/elsewhere".into()),
270            ],
271            false,
272            false,
273        ) else {
274            panic!("index.json in {dest_dir:?} should read");
275        };
276
277        assert_eq!(config.env["api_url"], "/api");
278        assert_eq!(config.env["vertigo-mount-point"], "/panel");
279        assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
280
281        std::fs::remove_dir_all(&dest_dir)
282    }
283
284    #[test]
285    fn test_replace_prefix() {
286        assert_eq!(
287            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
288            "build/vertigo_demo.33.wasm".to_string()
289        );
290
291        assert_eq!(
292            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
293            "build/vertigo_demo.33.wasm".to_string()
294        );
295
296        assert_eq!(
297            replace_prefix(
298                "demo_build",
299                &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
300            ),
301            "demo_build/vertigo_demo.33.wasm".to_string()
302        );
303    }
304}