Skip to main content

euv_cli/hot/
fn.rs

1use super::*;
2
3/// Builds a complete static documentation site from all `.md` files beneath `src_dir` into `out_dir`.
4///
5/// # Arguments
6///
7/// - `&Path` - Project or Markdown source root directory.
8/// - `&Path` - Destination output directory.
9/// - `&DocsBuildOptions` - Site title, base URL, clean URL, asset copy, and optional dev HMR configuration.
10///
11/// # Returns
12///
13/// - `io::Result<GeneratedSiteReport>` - Summary report of generated pages or I/O error.
14pub fn build_docs_site(
15    src_dir: &Path,
16    out_dir: &Path,
17    options: &DocsBuildOptions,
18) -> io::Result<GeneratedSiteReport> {
19    build_docs_bundle(src_dir, out_dir, options)
20}
21
22/// Compiles a fresh signed Dynamic WASM OTA hot-update bundle for version `version`.
23///
24/// # Arguments
25///
26/// - `u64` - Monotonic OTA bundle version number.
27/// - `&str` - Human-readable title embedded into the executable `.wasm` module.
28/// - `Vec<String>` - Source file paths triggering this hot update.
29///
30/// # Returns
31///
32/// - `OtaBundleState` - Signed manifest and executable `.wasm` bytes.
33#[must_use]
34pub fn build_dev_ota_state(
35    version: u64,
36    title: &str,
37    changed_files: Vec<String>,
38) -> OtaBundleState {
39    let accent_hex: u32 = if version.is_multiple_of(2) {
40        0x2563EB
41    } else {
42        0x059669
43    };
44    let wasm_bytes: Vec<u8> = build_partial_widget_wasm(title, version, accent_hex);
45    let checksum: u64 = compute_wasm_checksum(&wasm_bytes);
46    let signature: String = compute_wasm_signature(&wasm_bytes, version, OTA_DEV_SIGNING_KEY);
47    let manifest: OtaManifest = OtaManifest::new(
48        version,
49        OTA_SLOT_DEV.to_string(),
50        OTA_MODULE_ENDPOINT.to_string(),
51        checksum,
52        signature,
53        wasm_bytes.len(),
54        changed_files,
55    );
56    OtaBundleState::new(manifest, wasm_bytes)
57}
58
59/// Injects the dev-only SSE hot-reload script right before `</body>` in an HTML document.
60///
61/// # Arguments
62///
63/// - `&str` - Original HTML source string.
64/// - `&str` - SSE HMR endpoint URL path.
65///
66/// # Returns
67///
68/// - `String` - HTML document containing the live-reload client snippet.
69#[must_use]
70pub fn inject_dev_hmr_into_html(html: &str, hmr_endpoint: &str) -> String {
71    if html.contains(hmr_endpoint) {
72        return html.to_string();
73    }
74    let snippet: String = format!("{DEV_HMR_SCRIPT_PREFIX}{hmr_endpoint}{DEV_HMR_SCRIPT_SUFFIX}");
75    if let Some(pos) = html.rfind(HTML_BODY_CLOSE_TAG) {
76        let mut out: String = String::with_capacity(html.len() + snippet.len());
77        out.push_str(&html[..pos]);
78        out.push_str(&snippet);
79        out.push_str(&html[pos..]);
80        out
81    } else {
82        format!("{html}{snippet}")
83    }
84}
85
86/// Starts a live HTTP, SSE hot-reload, file-watcher, and Dynamic WASM OTA dev server in background threads.
87///
88/// # Arguments
89///
90/// - `DevServerConfig` - Full dev server configuration.
91///
92/// # Returns
93///
94/// - `io::Result<DevServerHandle>` - Running server handle or startup error.
95pub fn start_dev_server(config: DevServerConfig) -> io::Result<DevServerHandle> {
96    let is_process_target: bool = matches!(
97        config.get_target(),
98        DevTargetArg::Native | DevTargetArg::Tui | DevTargetArg::Cli
99    );
100    if !is_process_target {
101        fs::create_dir_all(config.get_out_dir())?;
102    }
103    let mut initial_pages: usize = 0;
104    let mode_label: String = match config.get_target() {
105        DevTargetArg::Docs => {
106            let docs_opts: DocsBuildOptions = docs_options_for_dev(&config);
107            let report: GeneratedSiteReport =
108                build_docs_site(config.get_src_dir(), config.get_out_dir(), &docs_opts)?;
109            initial_pages = report.get_page_count();
110            MODE_LABEL_DOCS.to_string()
111        }
112        DevTargetArg::Web => {
113            rebuild_web_dev_bundle(&config)?;
114            MODE_LABEL_WEB.to_string()
115        }
116        DevTargetArg::Native => MODE_LABEL_NATIVE.to_string(),
117        DevTargetArg::Tui => MODE_LABEL_TUI.to_string(),
118        DevTargetArg::Cli => MODE_LABEL_CLI.to_string(),
119        DevTargetArg::Harmony => MODE_LABEL_HARMONY.to_string(),
120        DevTargetArg::Wearable => MODE_LABEL_WEARABLE.to_string(),
121        DevTargetArg::Miniapp => MODE_LABEL_MINIAPP.to_string(),
122        DevTargetArg::Quickapp => MODE_LABEL_QUICKAPP.to_string(),
123    };
124    let initial_ota: OtaBundleState = build_dev_ota_state(1, OTA_INITIAL_TITLE, Vec::new());
125    let hub: Arc<HmrHub> = Arc::new(HmrHub::new(initial_ota));
126    let bind_addr: String = format!("{}:{}", config.get_host(), config.get_port());
127    let listener: TcpListener = TcpListener::bind(&bind_addr)?;
128    let address: SocketAddr = listener.local_addr()?;
129    listener.set_nonblocking(true)?;
130    let serve_ctx: HttpServeContext = HttpServeContext {
131        out_dir: config.get_out_dir().clone(),
132        base_url: config.get_base_url().clone(),
133        enable_ota: config.get_enable_ota(),
134        hub: Arc::clone(&hub),
135    };
136    let http_thread: JoinHandle<()> = thread::spawn(move || {
137        run_http_accept_loop(listener, serve_ctx);
138    });
139    let watch_hub: Arc<HmrHub> = Arc::clone(&hub);
140    let watch_cfg: DevServerConfig = config.clone();
141    let dev_url: String = format!("http://{address}");
142    let watch_thread: JoinHandle<()> = thread::spawn(move || {
143        run_watch_rebuild_loop(watch_cfg, dev_url, watch_hub);
144    });
145    Ok(DevServerHandle {
146        address,
147        out_dir: config.get_out_dir().clone(),
148        mode: mode_label,
149        page_count: initial_pages,
150        hub,
151        http_thread: Some(http_thread),
152        watch_thread: Some(watch_thread),
153    })
154}
155
156/// Starts the dev server and either exits immediately (`once=true`) or serves continuously until interrupted.
157///
158/// # Arguments
159///
160/// - `DevServerConfig` - Dev server configuration.
161///
162/// # Returns
163///
164/// - `io::Result<DevServerReport>` - Server startup summary report or I/O error.
165pub fn run_dev_blocking(config: DevServerConfig) -> io::Result<DevServerReport> {
166    let once: bool = config.get_once();
167    let mut handle: DevServerHandle = start_dev_server(config)?;
168    let report: DevServerReport = handle.report();
169    if once {
170        handle.shutdown();
171        return Ok(report);
172    }
173    eprintln!(
174        "[euv-dev] mode={} url={} hmr={} ota={}",
175        report.get_mode(),
176        report.get_url(),
177        report.get_hmr_url(),
178        report.get_ota_manifest_url()
179    );
180    while handle.hub.is_running() {
181        thread::sleep(Duration::from_millis(250));
182    }
183    handle.shutdown();
184    Ok(report)
185}
186
187/// Constructs `DocsBuildOptions` wired for live dev hot reload from a `DevServerConfig`.
188///
189/// # Arguments
190///
191/// - `&DevServerConfig` - Active dev server configuration.
192///
193/// # Returns
194///
195/// - `DocsBuildOptions` - Populated docs build options with dev HMR endpoint.
196fn docs_options_for_dev(config: &DevServerConfig) -> DocsBuildOptions {
197    let mut opts: DocsBuildOptions = DocsBuildOptions::default();
198    opts.set_title(config.try_get_title().clone())
199        .set_base_url(config.get_base_url().clone())
200        .set_hmr_endpoint(Some(HMR_ENDPOINT.to_string()))
201        .set_assets_root(Some(config.get_src_dir().clone()))
202        .set_clean_urls(true);
203    opts
204}
205
206/// Runs the non-blocking HTTP accept loop dispatching static files, SSE `/__euv_hmr`, and OTA endpoints.
207///
208/// # Arguments
209///
210/// - `TcpListener` - Bound non-blocking TCP listener.
211/// - `HttpServeContext` - Output directory, base prefix, OTA gate, and shared HMR hub.
212fn run_http_accept_loop(listener: TcpListener, ctx: HttpServeContext) {
213    while ctx.get_hub().is_running() {
214        match listener.accept() {
215            Ok((stream, _)) => {
216                if !ctx.get_hub().is_running() {
217                    break;
218                }
219                let conn_ctx: HttpServeContext = ctx.clone();
220                drop(thread::spawn(move || {
221                    serve_http_connection(stream, &conn_ctx);
222                }));
223            }
224            Err(err) if err.kind() == ErrorKind::WouldBlock => {
225                thread::sleep(Duration::from_millis(20));
226            }
227            Err(_) => {
228                thread::sleep(Duration::from_millis(50));
229            }
230        }
231    }
232}
233
234/// Runs the recursive file watcher loop rebuilding docs, web bundles, or native binaries on file changes.
235///
236/// # Arguments
237///
238/// - `DevServerConfig` - Active dev server configuration.
239/// - `String` - Base HTTP URL of the active dev server forwarded to native child processes.
240/// - `Arc<HmrHub>` - Shared HMR and OTA hub.
241fn run_watch_rebuild_loop(config: DevServerConfig, dev_url: String, hub: Arc<HmrHub>) {
242    let allowed_exts: &[&str] = match config.get_target() {
243        DevTargetArg::Docs => &WATCH_EXTS_DOCS,
244        _ => &WATCH_EXTS_CODE,
245    };
246    let is_process_target: bool = matches!(
247        config.get_target(),
248        DevTargetArg::Native | DevTargetArg::Tui | DevTargetArg::Cli
249    );
250    let exclude_out: Option<&Path> = if is_process_target {
251        None
252    } else {
253        Some(config.get_out_dir().as_path())
254    };
255    let mut prev_snap: WatchSnapshot =
256        WatchSnapshot::scan_excluding(config.get_src_dir(), allowed_exts, exclude_out)
257            .unwrap_or_default();
258    let mut native_child: Option<Child> = if is_process_target && !config.get_once() {
259        spawn_native_app_child(&config, &dev_url).ok()
260    } else {
261        None
262    };
263    let poll_dur: Duration = Duration::from_millis(config.get_poll_ms().clamp(50, 5000));
264    while hub.is_running() {
265        thread::sleep(poll_dur);
266        if !hub.is_running() {
267            break;
268        }
269        let Ok(next_snap) =
270            WatchSnapshot::scan_excluding(config.get_src_dir(), allowed_exts, exclude_out)
271        else {
272            continue;
273        };
274        let changes: FileChangeSet = prev_snap.diff(&next_snap);
275        if changes.is_empty() {
276            continue;
277        }
278        prev_snap = next_snap;
279        let changed_files: Vec<String> = changes.all_paths();
280        match config.get_target() {
281            DevTargetArg::Docs => {
282                let docs_opts: DocsBuildOptions = docs_options_for_dev(&config);
283                match build_docs_site(config.get_src_dir(), config.get_out_dir(), &docs_opts) {
284                    Ok(report) => {
285                        let next_ver: u64 = hub.revision() + 1;
286                        if config.get_enable_ota() {
287                            let ota_title: String = format!(
288                                "Docs Hot Update v{next_ver} ({} pages)",
289                                report.get_page_count()
290                            );
291                            hub.set_ota_state(build_dev_ota_state(
292                                next_ver,
293                                &ota_title,
294                                changed_files.clone(),
295                            ));
296                        }
297                        let _: u64 = hub.publish(
298                            HmrEventKind::Reload,
299                            format!("{MSG_DOCS_REBUILT} ({} pages)", report.get_page_count()),
300                            changed_files,
301                        );
302                    }
303                    Err(err) => {
304                        let _: u64 =
305                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
306                    }
307                }
308            }
309            DevTargetArg::Web => match rebuild_web_dev_bundle(&config) {
310                Ok(()) => {
311                    let next_ver: u64 = hub.revision() + 1;
312                    if config.get_enable_ota() {
313                        let ota_title: String = format!("Web WASM Hot Update v{next_ver}");
314                        hub.set_ota_state(build_dev_ota_state(
315                            next_ver,
316                            &ota_title,
317                            changed_files.clone(),
318                        ));
319                    }
320                    let _: u64 = hub.publish(
321                        HmrEventKind::Reload,
322                        MSG_WEB_REBUILT.to_string(),
323                        changed_files,
324                    );
325                }
326                Err(err) => {
327                    let _: u64 =
328                        hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
329                }
330            },
331            DevTargetArg::Native | DevTargetArg::Tui | DevTargetArg::Cli => {
332                if let Some(mut old_child) = native_child.take() {
333                    drop(old_child.kill());
334                    drop(old_child.wait());
335                }
336                match spawn_native_app_child(&config, &dev_url) {
337                    Ok(child) => {
338                        native_child = Some(child);
339                        let next_ver: u64 = hub.revision() + 1;
340                        if config.get_enable_ota() {
341                            let ota_title: String = format!("Native OTA Hot Update v{next_ver}");
342                            hub.set_ota_state(build_dev_ota_state(
343                                next_ver,
344                                &ota_title,
345                                changed_files.clone(),
346                            ));
347                        }
348                        let _: u64 = hub.publish(
349                            HmrEventKind::OtaUpdate,
350                            MSG_NATIVE_RESTARTED.to_string(),
351                            changed_files,
352                        );
353                    }
354                    Err(err) => {
355                        let _: u64 =
356                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
357                    }
358                }
359            }
360            DevTargetArg::Harmony
361            | DevTargetArg::Wearable
362            | DevTargetArg::Miniapp
363            | DevTargetArg::Quickapp => {
364                let next_ver: u64 = hub.revision() + 1;
365                if config.get_enable_ota() {
366                    let ota_title: String =
367                        format!("{:?} OTA Hot Update v{next_ver}", config.get_target());
368                    hub.set_ota_state(build_dev_ota_state(
369                        next_ver,
370                        &ota_title,
371                        changed_files.clone(),
372                    ));
373                }
374                let _: u64 = hub.publish(
375                    HmrEventKind::OtaUpdate,
376                    MSG_NATIVE_RESTARTED.to_string(),
377                    changed_files,
378                );
379            }
380        }
381    }
382    if let Some(mut child) = native_child.take() {
383        drop(child.kill());
384        drop(child.wait());
385    }
386}
387
388/// Rebuilds the WebAssembly bundle into `config.out_dir` and injects the dev SSE hot-reload script.
389///
390/// # Arguments
391///
392/// - `&DevServerConfig` - Active web dev configuration.
393///
394/// # Returns
395///
396/// - `io::Result<()>` - Build result.
397fn rebuild_web_dev_bundle(config: &DevServerConfig) -> io::Result<()> {
398    let out_dir: &Path = config.get_out_dir();
399    let mut wp_args: Vec<String> = vec![
400        ARG_BUILD.to_string(),
401        ARG_TARGET.to_string(),
402        ARG_TARGET_WEB.to_string(),
403        ARG_OUT_DIR.to_string(),
404        out_dir.display().to_string(),
405    ];
406    if config.get_release() {
407        wp_args.push(ARG_RELEASE.to_string());
408    }
409    let output: Output = Command::new(BIN_WASM_PACK)
410        .args(&wp_args)
411        .current_dir(config.get_src_dir())
412        .output()?;
413    if !output.status.success() {
414        let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
415        return Err(Error::other(format!("{ERR_STEP_FAILED}: {stderr}")));
416    }
417    if out_dir.exists() {
418        let index_path: PathBuf = package_zero_js_web_bundle(out_dir, WEB_BUNDLE_TITLE)?;
419        let html: String = fs::read_to_string(&index_path)?;
420        let with_hmr: String = inject_dev_hmr_into_html(&html, HMR_ENDPOINT);
421        fs::write(&index_path, with_hmr)?;
422    }
423    Ok(())
424}
425
426/// Spawns a fresh native `cargo run` child process with live HMR/OTA endpoint env vars.
427///
428/// # Arguments
429///
430/// - `&DevServerConfig` - Active native dev configuration.
431/// - `&str` - Base HTTP URL of the active dev server.
432///
433/// # Returns
434///
435/// - `io::Result<Child>` - Spawned child process handle or error.
436fn spawn_native_app_child(config: &DevServerConfig, dev_url: &str) -> io::Result<Child> {
437    let step: BuildStep = resolve_run_step(
438        TargetArg::Native,
439        config.get_render(),
440        config.get_release(),
441        config.try_get_package().as_deref(),
442    );
443    let mut cmd: Command = Command::new(step.get_program());
444    let _: &mut Command = cmd
445        .args(step.get_args())
446        .current_dir(config.get_src_dir())
447        .stdin(Stdio::null())
448        .env(ENV_DEV_URL, dev_url)
449        .env(ENV_HMR_URL, format!("{dev_url}{HMR_ENDPOINT}"));
450    if config.get_enable_ota() {
451        let _: &mut Command = cmd
452            .env(
453                ENV_OTA_MANIFEST_URL,
454                format!("{dev_url}{OTA_MANIFEST_ENDPOINT}"),
455            )
456            .env(
457                ENV_OTA_MODULE_URL,
458                format!("{dev_url}{OTA_MODULE_ENDPOINT}"),
459            );
460    }
461    cmd.spawn()
462}
463
464/// Handles a single incoming HTTP/1.1 connection for static files, SSE `/__euv_hmr`, or Dynamic WASM OTA.
465///
466/// # Arguments
467///
468/// - `TcpStream` - Connected client socket.
469/// - `&HttpServeContext` - Output directory, base prefix, OTA gate, and shared HMR hub.
470fn serve_http_connection(mut stream: TcpStream, ctx: &HttpServeContext) {
471    drop(stream.set_nonblocking(false));
472    drop(stream.set_read_timeout(Some(Duration::from_secs(3))));
473    let req_line: String = {
474        let mut reader: BufReader<&TcpStream> = BufReader::new(&stream);
475        let mut line: String = String::new();
476        if reader.read_line(&mut line).is_err() || line.is_empty() {
477            return;
478        }
479        let mut header_count: usize = 0;
480        while header_count < 64 {
481            let mut hdr: String = String::new();
482            match reader.read_line(&mut hdr) {
483                Ok(0) => break,
484                Ok(_) if hdr == "\r\n" || hdr == "\n" => break,
485                Ok(_) => header_count += 1,
486                Err(_) => break,
487            }
488        }
489        line
490    };
491    let mut parts: SplitWhitespace<'_> = req_line.split_whitespace();
492    let method: &str = parts.next().unwrap_or("");
493    let raw_target: &str = parts.next().unwrap_or("/");
494    if method.eq_ignore_ascii_case(HTTP_METHOD_OPTIONS) {
495        drop(stream.write_all(HTTP_204_OPTIONS_RESP.as_bytes()));
496        drop(stream.flush());
497        return;
498    }
499    let head_only: bool = method.eq_ignore_ascii_case(HTTP_METHOD_HEAD);
500    let path_only: &str = raw_target.split('?').next().unwrap_or("/");
501    let hub: &Arc<HmrHub> = ctx.get_hub();
502    if path_only == HMR_ENDPOINT {
503        serve_sse_stream(stream, hub);
504        return;
505    }
506    if path_only == OTA_MANIFEST_ENDPOINT {
507        if ctx.get_enable_ota()
508            && let Some(ota) = hub.ota_snapshot()
509            && let Ok(json) = to_string_pretty(ota.get_manifest())
510        {
511            write_http_response(&mut stream, MIME_JSON, json.as_bytes(), head_only);
512            return;
513        }
514        drop(stream.write_all(HTTP_404_RESP.as_bytes()));
515        return;
516    }
517    if path_only == OTA_MODULE_ENDPOINT {
518        if ctx.get_enable_ota()
519            && let Some(ota) = hub.ota_snapshot()
520        {
521            write_http_response(
522                &mut stream,
523                MIME_WASM,
524                ota.get_wasm_bytes().as_slice(),
525                head_only,
526            );
527            return;
528        }
529        drop(stream.write_all(HTTP_404_RESP.as_bytes()));
530        return;
531    }
532    if path_only == DEV_STATUS_ENDPOINT {
533        let payload: String = match hub.current_event() {
534            Some(ui_event) => {
535                to_string_pretty(&ui_event).unwrap_or_else(|_| EMPTY_JSON_OBJECT.to_string())
536            }
537            None => format!("{{\"revision\":{}}}", hub.revision()),
538        };
539        write_http_response(&mut stream, MIME_JSON, payload.as_bytes(), head_only);
540        return;
541    }
542    let decoded_path: String = percent_decode_path(path_only);
543    let stripped_path: &str = strip_base_prefix(&decoded_path, ctx.get_base_url());
544    if let Some(file_path) = resolve_static_file(ctx.get_out_dir(), stripped_path)
545        && let Ok(bytes) = fs::read(&file_path)
546    {
547        let mime: &str = mime_type_for_path(&file_path);
548        write_http_response(&mut stream, mime, &bytes, head_only);
549        return;
550    }
551    drop(stream.write_all(HTTP_404_RESP.as_bytes()));
552}
553
554/// Streams live Server-Sent Events (`event: reload` / `ota` / `error`) whenever `hub` increments revision.
555///
556/// # Arguments
557///
558/// - `TcpStream` - Long-lived client TCP stream.
559/// - `&Arc<HmrHub>` - Shared HMR hub.
560fn serve_sse_stream(mut stream: TcpStream, hub: &Arc<HmrHub>) {
561    if stream.write_all(HTTP_SSE_HEADERS.as_bytes()).is_err() || stream.flush().is_err() {
562        return;
563    }
564    let mut last_sent_rev: u64 = hub.revision();
565    let mut idle_ticks: u32 = 0;
566    while hub.is_running() {
567        thread::sleep(Duration::from_millis(50));
568        let cur_rev: u64 = hub.revision();
569        if cur_rev != last_sent_rev {
570            last_sent_rev = cur_rev;
571            idle_ticks = 0;
572            if let Some(ui_event) = hub.current_event() {
573                let ev_name: &str = match ui_event.get_kind() {
574                    HmrEventKind::Reload => HMR_EVENT_RELOAD,
575                    HmrEventKind::OtaUpdate => HMR_EVENT_OTA,
576                    HmrEventKind::BuildError => HMR_EVENT_ERROR,
577                };
578                let data: String = to_string_pretty(&ui_event)
579                    .unwrap_or_else(|_| format!("{{\"revision\":{cur_rev}}}"))
580                    .replace('\n', " ");
581                let frame: String = format!("event: {ev_name}\ndata: {data}\n\n");
582                if stream.write_all(frame.as_bytes()).is_err() || stream.flush().is_err() {
583                    return;
584                }
585            }
586        } else {
587            idle_ticks += 1;
588            if idle_ticks >= 100 {
589                idle_ticks = 0;
590                if stream.write_all(SSE_PING_LINE.as_bytes()).is_err() || stream.flush().is_err() {
591                    return;
592                }
593            }
594        }
595    }
596}
597
598/// Writes an HTTP/1.1 200 response with CORS and no-cache headers, omitting the body on `HEAD` requests.
599///
600/// # Arguments
601///
602/// - `&mut TcpStream` - Client socket.
603/// - `&str` - Content-Type header value.
604/// - `&[u8]` - Response payload bytes.
605/// - `bool` - When `true`, writes headers only (`HEAD`).
606fn write_http_response(stream: &mut TcpStream, mime: &str, body: &[u8], head_only: bool) {
607    let header: String = format!(
608        "{HTTP_200_PREFIX}{mime}{HTTP_CORS_HEADERS}{}{HTTP_CONN_CLOSE_SEP}",
609        body.len()
610    );
611    drop(stream.write_all(header.as_bytes()));
612    if !head_only {
613        drop(stream.write_all(body));
614    }
615    drop(stream.flush());
616}
617
618/// Strips a configured `base_url` prefix from an incoming request path when present.
619///
620/// # Arguments
621///
622/// - `&'a str` - Percent-decoded HTTP request path.
623/// - `&str` - Configured base URL prefix (for example `""` or `"/docs"`).
624///
625/// # Returns
626///
627/// - `&'a str` - Relative path rooted at the output directory.
628fn strip_base_prefix<'a>(path: &'a str, base_url: &str) -> &'a str {
629    let normalized: &str = base_url.trim_matches('/');
630    if normalized.is_empty() {
631        return path;
632    }
633    let trimmed: &str = path.trim_start_matches('/');
634    if let Some(rest) = trimmed.strip_prefix(normalized)
635        && (rest.is_empty() || rest.starts_with('/'))
636    {
637        return rest;
638    }
639    path
640}
641
642/// Decodes `%XX` percent-encoded byte sequences in a URL path into UTF-8 text.
643///
644/// # Arguments
645///
646/// - `&str` - Raw URL path component.
647///
648/// # Returns
649///
650/// - `String` - Decoded UTF-8 URL path.
651fn percent_decode_path(input: &str) -> String {
652    if !input.contains('%') {
653        return input.to_string();
654    }
655    let bytes: &[u8] = input.as_bytes();
656    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
657    let mut item_index: usize = 0;
658    while item_index < bytes.len() {
659        if bytes[item_index] == ASCII_PERCENT
660            && item_index + 2 < bytes.len()
661            && let (Some(hi), Some(lo)) = (
662                hex_nibble(bytes[item_index + 1]),
663                hex_nibble(bytes[item_index + 2]),
664            )
665        {
666            out.push((hi << 4) | lo);
667            item_index += 3;
668            continue;
669        }
670        out.push(bytes[item_index]);
671        item_index += 1;
672    }
673    String::from_utf8(out).unwrap_or_else(|_| input.to_string())
674}
675
676/// Converts a single ASCII hexadecimal byte into its 4-bit value.
677///
678/// # Arguments
679///
680/// - `u8` - Candidate ASCII hex byte.
681///
682/// # Returns
683///
684/// - `Option<u8>` - Numeric nibble (`0..=15`) when valid.
685fn hex_nibble(byte: u8) -> Option<u8> {
686    match byte {
687        ASCII_DIGIT_ZERO..=ASCII_DIGIT_NINE => Some(byte - ASCII_DIGIT_ZERO),
688        ASCII_LOWER_A..=ASCII_LOWER_F => Some(byte - ASCII_LOWER_A + 10),
689        ASCII_UPPER_A..=ASCII_UPPER_F => Some(byte - ASCII_UPPER_A + 10),
690        _ => None,
691    }
692}
693
694/// Resolves an HTTP request path safely within `out_dir` supporting clean URLs and `index.html` fallbacks.
695///
696/// # Arguments
697///
698/// - `&Path` - Served output directory root.
699/// - `&str` - Sanitized URL path component.
700///
701/// # Returns
702///
703/// - `Option<PathBuf>` - Existing file path inside `out_dir`, if found.
704fn resolve_static_file(out_dir: &Path, url_path: &str) -> Option<PathBuf> {
705    let trimmed: &str = url_path.trim_matches('/');
706    let mut safe_rel: PathBuf = PathBuf::new();
707    for seg in trimmed.split('/') {
708        if seg.is_empty() || seg == "." || seg == ".." {
709            continue;
710        }
711        safe_rel.push(seg);
712    }
713    if safe_rel.as_os_str().is_empty() {
714        let root_idx: PathBuf = out_dir.join(INDEX_HTML_NAME);
715        return root_idx.is_file().then_some(root_idx);
716    }
717    let direct: PathBuf = out_dir.join(&safe_rel);
718    if direct.is_file() {
719        return Some(direct);
720    }
721    let clean_idx: PathBuf = direct.join(INDEX_HTML_NAME);
722    if clean_idx.is_file() {
723        return Some(clean_idx);
724    }
725    let html_file: PathBuf = out_dir.join(format!("{}.html", safe_rel.display()));
726    if html_file.is_file() {
727        return Some(html_file);
728    }
729    None
730}
731
732/// Determines the HTTP `Content-Type` header for a static file path by extension.
733///
734/// # Arguments
735///
736/// - `&Path` - File path.
737///
738/// # Returns
739///
740/// - `&'static str` - Appropriate MIME type string.
741#[must_use]
742pub fn mime_type_for_path(path: &Path) -> &'static str {
743    let Some(ext) = path
744        .extension()
745        .and_then(|source_val: &OsStr| source_val.to_str())
746    else {
747        return MIME_OCTET;
748    };
749    if ext.eq_ignore_ascii_case(EXT_HTML) {
750        MIME_HTML
751    } else if ext.eq_ignore_ascii_case(EXT_JSON) {
752        MIME_JSON
753    } else if ext.eq_ignore_ascii_case(EXT_XML) {
754        MIME_XML
755    } else if ext.eq_ignore_ascii_case(EXT_CSS) {
756        MIME_CSS
757    } else if ext.eq_ignore_ascii_case(EXT_WASM) {
758        MIME_WASM
759    } else if ext.eq_ignore_ascii_case(EXT_SVG) {
760        MIME_SVG
761    } else if ext.eq_ignore_ascii_case(EXT_PNG) {
762        MIME_PNG
763    } else if ext.eq_ignore_ascii_case(EXT_JPG) || ext.eq_ignore_ascii_case(EXT_JPEG) {
764        MIME_JPEG
765    } else if ext.eq_ignore_ascii_case(EXT_WEBP) {
766        MIME_WEBP
767    } else {
768        MIME_OCTET
769    }
770}
771
772/// Recursively populates `entries` with modification stamps for all watched files under `dir`.
773///
774/// # Arguments
775///
776/// - `&Path` - Current directory to scan.
777/// - `&[&str]` - Allowed lowercase file extensions.
778/// - `Option<&Path>` - Optional canonical output directory excluded from watching.
779/// - `Option<&Path>` - Canonical path of `dir` when `exclude_dir` lies within `dir`.
780/// - `bool` - Whether non-symlink child directories must be tested against `exclude_dir`.
781/// - `&mut BTreeMap<PathBuf, FileStamp>` - Accumulator map.
782///
783/// # Returns
784///
785/// - `io::Result<()>` - Scan result.
786pub(crate) fn scan_dir_stamps(
787    dir: &Path,
788    allowed_exts: &[&str],
789    exclude_dir: Option<&Path>,
790    canon_dir: Option<&Path>,
791    check_real_exclude: bool,
792    entries: &mut BTreeMap<PathBuf, FileStamp>,
793) -> io::Result<()> {
794    for entry_res in fs::read_dir(dir)? {
795        let entry: DirEntry = entry_res?;
796        let path: PathBuf = entry.path();
797        if let Ok(ft) = entry.file_type() {
798            if ft.is_dir() {
799                let file_name: OsString = entry.file_name();
800                let name: Cow<'_, str> = file_name.to_string_lossy();
801                if should_skip_watch_dir(&name) {
802                    continue;
803                }
804                if check_real_exclude && let Some(excluded) = exclude_dir {
805                    if let Some(cur_canon) = canon_dir {
806                        let child_canon: PathBuf = cur_canon.join(&file_name);
807                        if child_canon == excluded || child_canon.starts_with(excluded) {
808                            continue;
809                        }
810                        let recurse_check: bool = excluded.starts_with(&child_canon);
811                        let next_canon: Option<&Path> =
812                            recurse_check.then_some(child_canon.as_path());
813                        scan_dir_stamps(
814                            &path,
815                            allowed_exts,
816                            exclude_dir,
817                            next_canon,
818                            recurse_check,
819                            entries,
820                        )?;
821                        continue;
822                    }
823                    let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
824                    if canon == excluded || canon.starts_with(excluded) {
825                        continue;
826                    }
827                }
828                scan_dir_stamps(
829                    &path,
830                    allowed_exts,
831                    exclude_dir,
832                    None,
833                    check_real_exclude,
834                    entries,
835                )?;
836                continue;
837            }
838            if ft.is_file() {
839                if has_allowed_extension(&path, allowed_exts)
840                    && let Ok(meta) = entry.metadata()
841                {
842                    let _: Option<FileStamp> = entries.insert(path, stamp_from_metadata(&meta));
843                }
844                continue;
845            }
846        }
847        let Ok(meta) = fs::metadata(&path) else {
848            continue;
849        };
850        if meta.is_dir() {
851            let file_name: OsString = entry.file_name();
852            let name: Cow<'_, str> = file_name.to_string_lossy();
853            if should_skip_watch_dir(&name) {
854                continue;
855            }
856            if let Some(excluded) = exclude_dir {
857                let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
858                if canon == excluded || canon.starts_with(excluded) {
859                    continue;
860                }
861                let recurse_check: bool = excluded.starts_with(&canon);
862                let next_canon: Option<&Path> = recurse_check.then_some(canon.as_path());
863                scan_dir_stamps(
864                    &path,
865                    allowed_exts,
866                    exclude_dir,
867                    next_canon,
868                    recurse_check,
869                    entries,
870                )?;
871                continue;
872            }
873            scan_dir_stamps(&path, allowed_exts, None, None, false, entries)?;
874        } else if meta.is_file() && has_allowed_extension(&path, allowed_exts) {
875            let _: Option<FileStamp> = entries.insert(path, stamp_from_metadata(&meta));
876        }
877    }
878    Ok(())
879}
880
881/// Returns `true` when directory `name` should be excluded from file watching.
882///
883/// # Arguments
884///
885/// - `&str` - Directory name.
886///
887/// # Returns
888///
889/// - `bool` - Whether the watcher skips this directory.
890fn should_skip_watch_dir(name: &str) -> bool {
891    name.starts_with('.')
892        || WATCH_IGNORED_DIRS
893            .iter()
894            .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
895}
896
897/// Returns `true` when `path` has an extension listed in `allowed_exts`.
898///
899/// # Arguments
900///
901/// - `&Path` - Candidate file path.
902/// - `&[&str]` - Allowed lowercase extensions.
903///
904/// # Returns
905///
906/// - `bool` - Whether the file should be watched.
907fn has_allowed_extension(path: &Path, allowed_exts: &[&str]) -> bool {
908    path.extension()
909        .and_then(|source_val: &OsStr| source_val.to_str())
910        .is_some_and(|ext: &str| {
911            allowed_exts
912                .iter()
913                .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
914        })
915}
916
917/// Extracts a deterministic `FileStamp` from filesystem `Metadata`.
918///
919/// # Arguments
920///
921/// - `&Metadata` - File metadata.
922///
923/// # Returns
924///
925/// - `FileStamp` - Modification timestamp and byte size pair.
926fn stamp_from_metadata(meta: &Metadata) -> FileStamp {
927    let nanos: u128 = meta
928        .modified()
929        .ok()
930        .and_then(|blend_factor: SystemTime| blend_factor.duration_since(UNIX_EPOCH).ok())
931        .map(|delta_val: Duration| delta_val.as_nanos())
932        .unwrap_or(0);
933    FileStamp::new(nanos, meta.len())
934}