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 ssr_fetch_cookies: Vec<String>,
18 pub pretty_html: bool,
19 pub precompress: bool,
20}
21
22impl MountConfigBuilder {
23 pub fn new(mount_point: impl Into<String>, dest_dir: impl Into<String>) -> MountConfigBuilder {
24 MountConfigBuilder {
25 mount_point: mount_point.into(),
26 dest_dir: dest_dir.into(),
27 env: vec![],
28 wasm_preload: false,
29 disable_hydration: false,
30 ssr_fetch_base: None,
31 ssr_cookies: vec![],
32 ssr_fetch_cookies: vec![],
33 pretty_html: false,
34 precompress: false,
35 }
36 }
37
38 pub fn envs(mut self, envs: Vec<(String, String)>) -> Self {
39 self.env = envs;
40 self
41 }
42
43 pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
44 self.env.push((key.into(), value.into()));
45 self
46 }
47
48 pub fn wasm_preload(mut self, wasm_preload: bool) -> Self {
49 self.wasm_preload = wasm_preload;
50 self
51 }
52
53 pub fn disable_hydration(mut self, disable_hydration: bool) -> Self {
54 self.disable_hydration = disable_hydration;
55 self
56 }
57
58 pub fn ssr_fetch_base(mut self, origin: impl Into<String>) -> Self {
62 self.ssr_fetch_base = Some(origin.into());
63 self
64 }
65
66 pub fn ssr_cookie(mut self, name: impl Into<String>) -> Self {
73 self.ssr_cookies.push(name.into());
74 self
75 }
76
77 pub fn ssr_fetch_cookie(mut self, name: impl Into<String>) -> Self {
87 self.ssr_fetch_cookies.push(name.into());
88 self
89 }
90
91 pub fn pretty_html(mut self, pretty_html: bool) -> Self {
97 self.pretty_html = pretty_html;
98 self
99 }
100
101 pub fn precompress(mut self, precompress: bool) -> Self {
110 self.precompress = precompress;
111 self
112 }
113
114 pub fn precompress_in_release(self) -> Self {
121 self.precompress(!cfg!(debug_assertions))
122 }
123
124 pub fn build(self) -> Result<MountConfig, ErrorCode> {
125 let mut config = MountConfig::new(
126 self.mount_point,
127 self.dest_dir,
128 self.env,
129 self.wasm_preload,
130 self.disable_hydration,
131 )?;
132 config.ssr_fetch_base = self.ssr_fetch_base;
133 config.ssr_cookies = self.ssr_cookies;
134 config.ssr_fetch_cookies = self.ssr_fetch_cookies;
135 config.pretty_html = self.pretty_html;
136 config.precompress = self.precompress;
137 Ok(config)
138 }
139}
140
141#[derive(Clone, Debug)]
142pub struct MountConfig {
143 mount_point: String,
145 dest_dir: String,
147 run_js: String,
149 wasm_path: String,
151 pub env: Arc<HashMap<String, String>>,
154 pub wasm_preload: bool,
156 pub disable_hydration: bool,
158 pub ssr_fetch_base: Option<String>,
160 pub ssr_cookies: Vec<String>,
162 pub ssr_fetch_cookies: Vec<String>,
164 pub pretty_html: bool,
166 pub precompress: bool,
168}
169
170impl MountConfig {
171 pub fn new(
172 public_mount_point: impl Into<String>,
173 dest_dir: impl Into<String>,
174 env: Vec<(String, String)>,
175 wasm_preload: bool,
176 disable_hydration: bool,
177 ) -> Result<MountConfig, ErrorCode> {
178 let dest_dir = dest_dir.into();
179 let index_model = read_index(&dest_dir)?;
180
181 let mut config = MountConfig {
182 dest_dir,
183 mount_point: public_mount_point.into(),
184 run_js: index_model.run_js,
185 wasm_path: index_model.wasm,
186 env: Arc::default(),
187 wasm_preload,
188 disable_hydration,
189 ssr_fetch_base: None,
190 ssr_cookies: vec![],
191 ssr_fetch_cookies: vec![],
192 pretty_html: false,
193 precompress: false,
194 };
195
196 let mut env: HashMap<String, String> = env.into_iter().collect();
200 env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
201 env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
202 config.env = Arc::new(env);
203
204 Ok(config)
205 }
206
207 pub fn mount_point(&self) -> &str {
208 self.mount_point.as_str()
209 }
210
211 pub fn dest_dir(&self) -> &str {
212 self.dest_dir.trim_start_matches("./")
213 }
214
215 pub fn dest_http_root(&self) -> String {
216 Path::new(&self.mount_point)
217 .join(self.dest_dir())
218 .components()
219 .as_path()
220 .to_string_lossy()
221 .into_owned()
222 }
223
224 pub fn get_wasm_http_path(&self) -> String {
225 self.translate_to_http(&self.wasm_path)
226 }
227
228 pub fn get_run_js_http_path(&self) -> String {
229 self.translate_to_http(&self.run_js)
230 }
231
232 pub fn get_wasm_fs_path(&self) -> String {
233 self.translate_to_fs(&self.wasm_path)
234 }
235
236 fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
237 let fs_path = fs_path.into();
238 fs_path.replace(
239 VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
240 &self.dest_http_root(),
241 )
242 }
243
244 fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
245 let http_path = http_path.into();
246 replace_prefix(&self.dest_dir, &http_path)
247 }
248}
249
250fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
251 let index_path = Path::new(dest_dir).join("index.json");
252 let index_html = match std::fs::read_to_string(&index_path) {
253 Ok(data) => data,
254 Err(err) => {
255 log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
256 return Err(ErrorCode::ServeCantReadIndexFile);
257 }
258 };
259
260 serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
261 log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
262 ErrorCode::ServeCantReadIndexFile
263 })
264}
265
266fn replace_prefix(dest_dir: &str, path: &str) -> String {
267 if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
268 path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
270 } else {
271 path.to_string()
273 }
274}
275
276#[cfg(test)]
277mod tests {
278 use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
279
280 use super::{MountConfig, MountConfigBuilder, replace_prefix};
281
282 #[test]
283 fn html_is_indented_only_when_asked() -> std::io::Result<()> {
284 let dest_dir = std::env::temp_dir().join(format!("vertigo-pretty-{}", std::process::id()));
285 std::fs::create_dir_all(&dest_dir)?;
286 std::fs::write(
287 dest_dir.join("index.json"),
288 r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
289 )?;
290
291 let builder = || MountConfigBuilder::new("/", dest_dir.to_string_lossy());
292 let (Ok(default), Ok(pretty)) = (builder().build(), builder().pretty_html(true).build())
293 else {
294 panic!("index.json in {dest_dir:?} should read");
295 };
296
297 assert!(!default.pretty_html);
298 assert!(pretty.pretty_html);
299
300 std::fs::remove_dir_all(&dest_dir)
301 }
302
303 #[test]
304 fn precompress_in_release_follows_the_build() {
305 let builder = MountConfigBuilder::new("/", "build").precompress_in_release();
306
307 assert_eq!(builder.precompress, !cfg!(debug_assertions));
309 }
310
311 #[test]
312 fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
313 let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
314 std::fs::create_dir_all(&dest_dir)?;
315 std::fs::write(
316 dest_dir.join("index.json"),
317 r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
318 )?;
319
320 let Ok(config) = MountConfig::new(
321 "/panel",
322 dest_dir.to_string_lossy(),
323 vec![
324 ("api_url".into(), "/api".into()),
325 ("vertigo-mount-point".into(), "/elsewhere".into()),
327 ],
328 false,
329 false,
330 ) else {
331 panic!("index.json in {dest_dir:?} should read");
332 };
333
334 assert_eq!(config.env["api_url"], "/api");
335 assert_eq!(config.env["vertigo-mount-point"], "/panel");
336 assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
337
338 std::fs::remove_dir_all(&dest_dir)
339 }
340
341 #[test]
342 fn test_replace_prefix() {
343 assert_eq!(
344 replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
345 "build/vertigo_demo.33.wasm".to_string()
346 );
347
348 assert_eq!(
349 replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
350 "build/vertigo_demo.33.wasm".to_string()
351 );
352
353 assert_eq!(
354 replace_prefix(
355 "demo_build",
356 &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
357 ),
358 "demo_build/vertigo_demo.33.wasm".to_string()
359 );
360 }
361}