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 {
113 self.precompress = precompress;
114 self
115 }
116
117 pub fn precompress_in_release(self) -> Self {
124 self.precompress(!cfg!(debug_assertions))
125 }
126
127 pub fn build(self) -> Result<MountConfig, ErrorCode> {
128 let mut config = MountConfig::new(
129 self.mount_point,
130 self.dest_dir,
131 self.env,
132 self.wasm_preload,
133 self.disable_hydration,
134 )?;
135 config.ssr_fetch_base = self.ssr_fetch_base;
136 config.ssr_cookies = self.ssr_cookies;
137 config.ssr_fetch_cookies = self.ssr_fetch_cookies;
138 config.pretty_html = self.pretty_html;
139 config.precompress = self.precompress;
140 Ok(config)
141 }
142}
143
144#[derive(Clone, Debug)]
145pub struct MountConfig {
146 mount_point: String,
148 dest_dir: String,
150 run_js: String,
152 wasm_path: String,
154 pub env: Arc<HashMap<String, String>>,
157 pub wasm_preload: bool,
159 pub disable_hydration: bool,
161 pub ssr_fetch_base: Option<String>,
163 pub ssr_cookies: Vec<String>,
165 pub ssr_fetch_cookies: Vec<String>,
167 pub pretty_html: bool,
169 pub precompress: bool,
171}
172
173impl MountConfig {
174 pub fn new(
175 public_mount_point: impl Into<String>,
176 dest_dir: impl Into<String>,
177 env: Vec<(String, String)>,
178 wasm_preload: bool,
179 disable_hydration: bool,
180 ) -> Result<MountConfig, ErrorCode> {
181 let dest_dir = dest_dir.into();
182 let index_model = read_index(&dest_dir)?;
183
184 let mut config = MountConfig {
185 dest_dir,
186 mount_point: public_mount_point.into(),
187 run_js: index_model.run_js,
188 wasm_path: index_model.wasm,
189 env: Arc::default(),
190 wasm_preload,
191 disable_hydration,
192 ssr_fetch_base: None,
193 ssr_cookies: vec![],
194 ssr_fetch_cookies: vec![],
195 pretty_html: false,
196 precompress: false,
197 };
198
199 let mut env: HashMap<String, String> = env.into_iter().collect();
203 env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
204 env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
205 config.env = Arc::new(env);
206
207 Ok(config)
208 }
209
210 pub fn mount_point(&self) -> &str {
211 self.mount_point.as_str()
212 }
213
214 pub fn dest_dir(&self) -> &str {
215 self.dest_dir.trim_start_matches("./")
216 }
217
218 pub fn dest_http_root(&self) -> String {
219 Path::new(&self.mount_point)
220 .join(self.dest_dir())
221 .components()
222 .as_path()
223 .to_string_lossy()
224 .into_owned()
225 }
226
227 pub fn get_wasm_http_path(&self) -> String {
228 self.translate_to_http(&self.wasm_path)
229 }
230
231 pub fn get_run_js_http_path(&self) -> String {
232 self.translate_to_http(&self.run_js)
233 }
234
235 pub fn get_wasm_fs_path(&self) -> String {
236 self.translate_to_fs(&self.wasm_path)
237 }
238
239 fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
240 let fs_path = fs_path.into();
241 fs_path.replace(
242 VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
243 &self.dest_http_root(),
244 )
245 }
246
247 fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
248 let http_path = http_path.into();
249 replace_prefix(&self.dest_dir, &http_path)
250 }
251}
252
253fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
254 let index_path = Path::new(dest_dir).join("index.json");
255 let index_html = match std::fs::read_to_string(&index_path) {
256 Ok(data) => data,
257 Err(err) => {
258 log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
259 return Err(ErrorCode::ServeCantReadIndexFile);
260 }
261 };
262
263 serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
264 log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
265 ErrorCode::ServeCantReadIndexFile
266 })
267}
268
269fn replace_prefix(dest_dir: &str, path: &str) -> String {
270 if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
271 path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
273 } else {
274 path.to_string()
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
282
283 use super::{MountConfig, MountConfigBuilder, replace_prefix};
284
285 #[test]
286 fn html_is_indented_only_when_asked() -> std::io::Result<()> {
287 let dest_dir = std::env::temp_dir().join(format!("vertigo-pretty-{}", std::process::id()));
288 std::fs::create_dir_all(&dest_dir)?;
289 std::fs::write(
290 dest_dir.join("index.json"),
291 r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
292 )?;
293
294 let builder = || MountConfigBuilder::new("/", dest_dir.to_string_lossy());
295 let (Ok(default), Ok(pretty)) = (builder().build(), builder().pretty_html(true).build())
296 else {
297 panic!("index.json in {dest_dir:?} should read");
298 };
299
300 assert!(!default.pretty_html);
301 assert!(pretty.pretty_html);
302
303 std::fs::remove_dir_all(&dest_dir)
304 }
305
306 #[test]
307 fn precompress_in_release_follows_the_build() {
308 let builder = MountConfigBuilder::new("/", "build").precompress_in_release();
309
310 assert_eq!(builder.precompress, !cfg!(debug_assertions));
312 }
313
314 #[test]
315 fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
316 let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
317 std::fs::create_dir_all(&dest_dir)?;
318 std::fs::write(
319 dest_dir.join("index.json"),
320 r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
321 )?;
322
323 let Ok(config) = MountConfig::new(
324 "/panel",
325 dest_dir.to_string_lossy(),
326 vec![
327 ("api_url".into(), "/api".into()),
328 ("vertigo-mount-point".into(), "/elsewhere".into()),
330 ],
331 false,
332 false,
333 ) else {
334 panic!("index.json in {dest_dir:?} should read");
335 };
336
337 assert_eq!(config.env["api_url"], "/api");
338 assert_eq!(config.env["vertigo-mount-point"], "/panel");
339 assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
340
341 std::fs::remove_dir_all(&dest_dir)
342 }
343
344 #[test]
345 fn test_replace_prefix() {
346 assert_eq!(
347 replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
348 "build/vertigo_demo.33.wasm".to_string()
349 );
350
351 assert_eq!(
352 replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
353 "build/vertigo_demo.33.wasm".to_string()
354 );
355
356 assert_eq!(
357 replace_prefix(
358 "demo_build",
359 &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
360 ),
361 "demo_build/vertigo_demo.33.wasm".to_string()
362 );
363 }
364}