Skip to main content

euv_cli/server/
fn.rs

1use super::*;
2
3/// Sets the global application state.
4///
5/// # Arguments
6///
7/// - `Arc<AppState>` - The shared application state to store globally.
8///
9/// # Returns
10///
11/// - `Result<(), EuvError>` - Indicates success or failure of the initialization.
12pub(crate) fn set_global_state(state: Arc<AppState>) -> Result<(), EuvError> {
13    APP_STATE.set(state).map_err(|_: Arc<AppState>| {
14        EuvError::Message(String::from("Global state already initialized"))
15    })
16}
17
18/// Retrieves the global application state.
19///
20/// # Returns
21///
22/// - `Option<Arc<AppState>>` - The global state if initialized.
23pub(crate) fn get_global_state() -> Option<Arc<AppState>> {
24    APP_STATE.get().cloned()
25}
26
27/// Resolves the bootstrap script body to inline into the generated HTML.
28///
29/// When JS bridge inlining is enabled and the `pkg/<name>.js` file is present
30/// after a successful `wasm-pack` build, reads the bridge, strips its
31/// top-level `import` statements, inlines the 2 snippet helper modules, and
32/// wraps everything in a synchronous IIFE that fetches the wasm and calls
33/// `main()`. The result is zero extra HTTP requests for the JS bridge file
34/// and no ES module graph parsing on the critical path.
35///
36/// When inlining is disabled (env var or missing `pkg/<name>.js` file),
37/// returns the classic `<script type="module">` import fallback so the
38/// page still boots.
39async fn resolve_inline_js(config: &HtmlConfig) -> String {
40    if inline_bridge_disabled() {
41        return build_module_fallback_bridge(config.get_import_path());
42    }
43    let pkg_dir: PathBuf = config.get_serving_root().join(PKG_DIR_NAME);
44    let js_name: String = config
45        .get_import_path()
46        .rsplit('/')
47        .next()
48        .unwrap_or("")
49        .to_string();
50    if js_name.is_empty() {
51        return build_module_fallback_bridge(config.get_import_path());
52    }
53    let js_path: PathBuf = pkg_dir.join(&js_name);
54    if !js_path.exists() {
55        return build_module_fallback_bridge(config.get_import_path());
56    }
57    let wasm_url: String = if let Some(stem) = js_name.strip_suffix(".js") {
58        format!("pkg/{stem}_bg.wasm")
59    } else {
60        config.get_import_path().replace(".js", "_bg.wasm")
61    };
62    match build_inline_bridge(&pkg_dir, &js_name, &wasm_url).await {
63        Ok(snippet) => snippet,
64        Err(error) => {
65            log::warn!("Falling back to module import bridge: {error}");
66            build_module_fallback_bridge(config.get_import_path())
67        }
68    }
69}
70
71/// Generates `index.html` based on the build profile.
72///
73/// Uses `INDEX_HTML_RELEASE` when `is_release` is `true` (no live-reload script),
74/// otherwise uses `INDEX_HTML_DEV` (includes live-reload instrumentation).
75///
76/// The wasm-bindgen JS bridge is **inlined** into the HTML at build time
77/// (Rust reads `pkg/<name>.js`, strips its top-level `import` statements,
78/// inlines the 2 snippet helpers, and wraps the body in a synchronous IIFE)
79/// so the browser incurs zero extra HTTP requests for the JS bridge file
80/// and skips ES module graph parsing. Set the `EUV_NO_INLINE_BRIDGE` env
81/// var to opt out.
82///
83/// Then writes the template with the import path placeholder replaced to disk.
84///
85/// # Arguments
86///
87/// - `&HtmlConfig` - The HTML generation configuration.
88///
89/// # Returns
90///
91/// - `Result<String, EuvError>` - The generated HTML content written to disk.
92pub(crate) async fn generate_html(config: &HtmlConfig) -> Result<String, EuvError> {
93    let template_content: String = if let Some(custom_path) = config.try_get_custom_index_html() {
94        let bytes: Vec<u8> =
95            read(custom_path)
96                .await
97                .map_err(|error: io::Error| EuvError::IoPath {
98                    message: String::from("Failed to read custom index.html"),
99                    path: custom_path.to_path_buf(),
100                    error,
101                })?;
102        String::from_utf8(bytes).map_err(|error: FromUtf8Error| EuvError::Utf8 {
103            message: String::from("Custom index.html is not valid UTF-8"),
104            error,
105        })?
106    } else if config.get_is_release() {
107        INDEX_HTML_RELEASE.to_string()
108    } else {
109        INDEX_HTML_DEV.to_string()
110    };
111    let inline_js: String = resolve_inline_js(config).await;
112    let html: String = template_content
113        .replace(IMPORT_PATH_PLACEHOLDER, config.get_import_path())
114        .replace(RELOAD_ROUTE_PLACEHOLDER, RELOAD_ROUTE)
115        .replace(INLINE_JS_PLACEHOLDER, &inline_js);
116    let index_path: PathBuf = config.get_serving_root().join(INDEX_HTML_FILE_NAME);
117    create_dir_all(config.get_serving_root())
118        .await
119        .map_err(|error: io::Error| EuvError::Io {
120            message: String::from("Failed to create static directory"),
121            error,
122        })?;
123    write(&index_path, &html)
124        .await
125        .map_err(|error: io::Error| EuvError::Io {
126            message: String::from("Failed to write index.html"),
127            error,
128        })?;
129    Ok(html)
130}
131
132/// Resolves the effective www directory, handling wasm-pack nested output.
133///
134/// # Arguments
135///
136/// - `&Path` - The candidate www directory path.
137///
138/// # Returns
139///
140/// - `PathBuf` - The resolved www directory containing `index.html`.
141pub async fn resolve_www_dir(www_dir: &Path) -> PathBuf {
142    if metadata(www_dir.join(INDEX_HTML_FILE_NAME)).await.is_ok() {
143        return www_dir.to_path_buf();
144    }
145    let parent_name: Option<&str> = www_dir
146        .file_name()
147        .and_then(|file_name_os_str: &ffi::OsStr| file_name_os_str.to_str());
148    if let Some(name) = parent_name {
149        let nested: PathBuf = www_dir.join(name);
150        if metadata(nested.join(INDEX_HTML_FILE_NAME)).await.is_ok() {
151            return nested;
152        }
153    }
154    www_dir.to_path_buf()
155}
156
157/// Resolves the pkg directory for serving WASM artifacts.
158///
159/// Delegates to `resolve_out_dir` which respects `--out-dir`
160/// from wasm-pack args or defaults to `{www_dir}/pkg`.
161///
162/// # Arguments
163///
164/// - `&ModeArgs` - The CLI arguments for resolving out_dir.
165///
166/// # Returns
167///
168/// - `PathBuf` - The resolved pkg directory containing WASM build artifacts.
169pub fn resolve_pkg_dir(args: &ModeArgs) -> PathBuf {
170    resolve_out_dir(args)
171}
172
173/// Resolves a file path within a base directory with path-traversal protection.
174///
175/// Canonicalizes both the file path and the base directory, then verifies
176/// that the canonical file path starts with the canonical base directory.
177///
178/// # Arguments
179///
180/// - `&Path` - The base directory to resolve within.
181/// - `&str` - The relative path to the file.
182///
183/// # Returns
184///
185/// - `Option<PathBuf>` - The resolved file path if valid, `None` otherwise.
186pub async fn resolve_file_in_base(base: &Path, path: &str) -> Option<PathBuf> {
187    let file_path: PathBuf = base.join(path);
188    let canonical_path: PathBuf = canonicalize(&file_path).await.ok()?;
189    let base_canonical: PathBuf = canonicalize(base).await.ok()?;
190    canonical_path
191        .starts_with(&base_canonical)
192        .then_some(file_path)
193}