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(ev) => to_string_pretty(&ev).unwrap_or_else(|_| EMPTY_JSON_OBJECT.to_string()),
535            None => format!("{{\"revision\":{}}}", hub.revision()),
536        };
537        write_http_response(&mut stream, MIME_JSON, payload.as_bytes(), head_only);
538        return;
539    }
540    let decoded_path: String = percent_decode_path(path_only);
541    let stripped_path: &str = strip_base_prefix(&decoded_path, ctx.get_base_url());
542    if let Some(file_path) = resolve_static_file(ctx.get_out_dir(), stripped_path)
543        && let Ok(bytes) = fs::read(&file_path)
544    {
545        let mime: &str = mime_type_for_path(&file_path);
546        write_http_response(&mut stream, mime, &bytes, head_only);
547        return;
548    }
549    drop(stream.write_all(HTTP_404_RESP.as_bytes()));
550}
551
552/// Streams live Server-Sent Events (`event: reload` / `ota` / `error`) whenever `hub` increments revision.
553///
554/// # Arguments
555///
556/// - `TcpStream` - Long-lived client TCP stream.
557/// - `&Arc<HmrHub>` - Shared HMR hub.
558fn serve_sse_stream(mut stream: TcpStream, hub: &Arc<HmrHub>) {
559    if stream.write_all(HTTP_SSE_HEADERS.as_bytes()).is_err() || stream.flush().is_err() {
560        return;
561    }
562    let mut last_sent_rev: u64 = hub.revision();
563    let mut idle_ticks: u32 = 0;
564    while hub.is_running() {
565        thread::sleep(Duration::from_millis(50));
566        let cur_rev: u64 = hub.revision();
567        if cur_rev != last_sent_rev {
568            last_sent_rev = cur_rev;
569            idle_ticks = 0;
570            if let Some(ev) = hub.current_event() {
571                let ev_name: &str = match ev.get_kind() {
572                    HmrEventKind::Reload => HMR_EVENT_RELOAD,
573                    HmrEventKind::OtaUpdate => HMR_EVENT_OTA,
574                    HmrEventKind::BuildError => HMR_EVENT_ERROR,
575                };
576                let data: String = to_string_pretty(&ev)
577                    .unwrap_or_else(|_| format!("{{\"revision\":{cur_rev}}}"))
578                    .replace('\n', " ");
579                let frame: String = format!("event: {ev_name}\ndata: {data}\n\n");
580                if stream.write_all(frame.as_bytes()).is_err() || stream.flush().is_err() {
581                    return;
582                }
583            }
584        } else {
585            idle_ticks += 1;
586            if idle_ticks >= 100 {
587                idle_ticks = 0;
588                if stream.write_all(SSE_PING_LINE.as_bytes()).is_err() || stream.flush().is_err() {
589                    return;
590                }
591            }
592        }
593    }
594}
595
596/// Writes an HTTP/1.1 200 response with CORS and no-cache headers, omitting the body on `HEAD` requests.
597///
598/// # Arguments
599///
600/// - `&mut TcpStream` - Client socket.
601/// - `&str` - Content-Type header value.
602/// - `&[u8]` - Response payload bytes.
603/// - `bool` - When `true`, writes headers only (`HEAD`).
604fn write_http_response(stream: &mut TcpStream, mime: &str, body: &[u8], head_only: bool) {
605    let header: String = format!(
606        "{HTTP_200_PREFIX}{mime}{HTTP_CORS_HEADERS}{}{HTTP_CONN_CLOSE_SEP}",
607        body.len()
608    );
609    drop(stream.write_all(header.as_bytes()));
610    if !head_only {
611        drop(stream.write_all(body));
612    }
613    drop(stream.flush());
614}
615
616/// Strips a configured `base_url` prefix from an incoming request path when present.
617///
618/// # Arguments
619///
620/// - `&'a str` - Percent-decoded HTTP request path.
621/// - `&str` - Configured base URL prefix (for example `""` or `"/docs"`).
622///
623/// # Returns
624///
625/// - `&'a str` - Relative path rooted at the output directory.
626fn strip_base_prefix<'a>(path: &'a str, base_url: &str) -> &'a str {
627    let normalized: &str = base_url.trim_matches('/');
628    if normalized.is_empty() {
629        return path;
630    }
631    let trimmed: &str = path.trim_start_matches('/');
632    if let Some(rest) = trimmed.strip_prefix(normalized)
633        && (rest.is_empty() || rest.starts_with('/'))
634    {
635        return rest;
636    }
637    path
638}
639
640/// Decodes `%XX` percent-encoded byte sequences in a URL path into UTF-8 text.
641///
642/// # Arguments
643///
644/// - `&str` - Raw URL path component.
645///
646/// # Returns
647///
648/// - `String` - Decoded UTF-8 URL path.
649fn percent_decode_path(input: &str) -> String {
650    if !input.contains('%') {
651        return input.to_string();
652    }
653    let bytes: &[u8] = input.as_bytes();
654    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
655    let mut i: usize = 0;
656    while i < bytes.len() {
657        if bytes[i] == ASCII_PERCENT
658            && i + 2 < bytes.len()
659            && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
660        {
661            out.push((hi << 4) | lo);
662            i += 3;
663            continue;
664        }
665        out.push(bytes[i]);
666        i += 1;
667    }
668    String::from_utf8(out).unwrap_or_else(|_| input.to_string())
669}
670
671/// Converts a single ASCII hexadecimal byte into its 4-bit value.
672///
673/// # Arguments
674///
675/// - `u8` - Candidate ASCII hex byte.
676///
677/// # Returns
678///
679/// - `Option<u8>` - Numeric nibble (`0..=15`) when valid.
680fn hex_nibble(byte: u8) -> Option<u8> {
681    match byte {
682        ASCII_DIGIT_ZERO..=ASCII_DIGIT_NINE => Some(byte - ASCII_DIGIT_ZERO),
683        ASCII_LOWER_A..=ASCII_LOWER_F => Some(byte - ASCII_LOWER_A + 10),
684        ASCII_UPPER_A..=ASCII_UPPER_F => Some(byte - ASCII_UPPER_A + 10),
685        _ => None,
686    }
687}
688
689/// Resolves an HTTP request path safely within `out_dir` supporting clean URLs and `index.html` fallbacks.
690///
691/// # Arguments
692///
693/// - `&Path` - Served output directory root.
694/// - `&str` - Sanitized URL path component.
695///
696/// # Returns
697///
698/// - `Option<PathBuf>` - Existing file path inside `out_dir`, if found.
699fn resolve_static_file(out_dir: &Path, url_path: &str) -> Option<PathBuf> {
700    let trimmed: &str = url_path.trim_matches('/');
701    let mut safe_rel: PathBuf = PathBuf::new();
702    for seg in trimmed.split('/') {
703        if seg.is_empty() || seg == "." || seg == ".." {
704            continue;
705        }
706        safe_rel.push(seg);
707    }
708    if safe_rel.as_os_str().is_empty() {
709        let root_idx: PathBuf = out_dir.join(INDEX_HTML_NAME);
710        return root_idx.is_file().then_some(root_idx);
711    }
712    let direct: PathBuf = out_dir.join(&safe_rel);
713    if direct.is_file() {
714        return Some(direct);
715    }
716    let clean_idx: PathBuf = direct.join(INDEX_HTML_NAME);
717    if clean_idx.is_file() {
718        return Some(clean_idx);
719    }
720    let html_file: PathBuf = out_dir.join(format!("{}.html", safe_rel.display()));
721    if html_file.is_file() {
722        return Some(html_file);
723    }
724    None
725}
726
727/// Determines the HTTP `Content-Type` header for a static file path by extension.
728///
729/// # Arguments
730///
731/// - `&Path` - File path.
732///
733/// # Returns
734///
735/// - `&'static str` - Appropriate MIME type string.
736#[must_use]
737pub fn mime_type_for_path(path: &Path) -> &'static str {
738    let Some(ext) = path.extension().and_then(|s: &OsStr| s.to_str()) else {
739        return MIME_OCTET;
740    };
741    if ext.eq_ignore_ascii_case(EXT_HTML) {
742        MIME_HTML
743    } else if ext.eq_ignore_ascii_case(EXT_JSON) {
744        MIME_JSON
745    } else if ext.eq_ignore_ascii_case(EXT_XML) {
746        MIME_XML
747    } else if ext.eq_ignore_ascii_case(EXT_CSS) {
748        MIME_CSS
749    } else if ext.eq_ignore_ascii_case(EXT_WASM) {
750        MIME_WASM
751    } else if ext.eq_ignore_ascii_case(EXT_SVG) {
752        MIME_SVG
753    } else if ext.eq_ignore_ascii_case(EXT_PNG) {
754        MIME_PNG
755    } else if ext.eq_ignore_ascii_case(EXT_JPG) || ext.eq_ignore_ascii_case(EXT_JPEG) {
756        MIME_JPEG
757    } else if ext.eq_ignore_ascii_case(EXT_WEBP) {
758        MIME_WEBP
759    } else {
760        MIME_OCTET
761    }
762}
763
764/// Recursively populates `entries` with modification stamps for all watched files under `dir`.
765///
766/// # Arguments
767///
768/// - `&Path` - Current directory to scan.
769/// - `&[&str]` - Allowed lowercase file extensions.
770/// - `Option<&Path>` - Optional canonical output directory excluded from watching.
771/// - `Option<&Path>` - Canonical path of `dir` when `exclude_dir` lies within `dir`.
772/// - `bool` - Whether non-symlink child directories must be tested against `exclude_dir`.
773/// - `&mut BTreeMap<PathBuf, FileStamp>` - Accumulator map.
774///
775/// # Returns
776///
777/// - `io::Result<()>` - Scan result.
778pub(crate) fn scan_dir_stamps(
779    dir: &Path,
780    allowed_exts: &[&str],
781    exclude_dir: Option<&Path>,
782    canon_dir: Option<&Path>,
783    check_real_exclude: bool,
784    entries: &mut BTreeMap<PathBuf, FileStamp>,
785) -> io::Result<()> {
786    for entry_res in fs::read_dir(dir)? {
787        let entry: DirEntry = entry_res?;
788        let path: PathBuf = entry.path();
789        if let Ok(ft) = entry.file_type() {
790            if ft.is_dir() {
791                let file_name: OsString = entry.file_name();
792                let name: Cow<'_, str> = file_name.to_string_lossy();
793                if should_skip_watch_dir(&name) {
794                    continue;
795                }
796                if check_real_exclude && let Some(excluded) = exclude_dir {
797                    if let Some(cur_canon) = canon_dir {
798                        let child_canon: PathBuf = cur_canon.join(&file_name);
799                        if child_canon == excluded || child_canon.starts_with(excluded) {
800                            continue;
801                        }
802                        let recurse_check: bool = excluded.starts_with(&child_canon);
803                        let next_canon: Option<&Path> =
804                            recurse_check.then_some(child_canon.as_path());
805                        scan_dir_stamps(
806                            &path,
807                            allowed_exts,
808                            exclude_dir,
809                            next_canon,
810                            recurse_check,
811                            entries,
812                        )?;
813                        continue;
814                    }
815                    let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
816                    if canon == excluded || canon.starts_with(excluded) {
817                        continue;
818                    }
819                }
820                scan_dir_stamps(
821                    &path,
822                    allowed_exts,
823                    exclude_dir,
824                    None,
825                    check_real_exclude,
826                    entries,
827                )?;
828                continue;
829            }
830            if ft.is_file() {
831                if has_allowed_extension(&path, allowed_exts)
832                    && let Ok(meta) = entry.metadata()
833                {
834                    let _: Option<FileStamp> = entries.insert(path, stamp_from_metadata(&meta));
835                }
836                continue;
837            }
838        }
839        let Ok(meta) = fs::metadata(&path) else {
840            continue;
841        };
842        if meta.is_dir() {
843            let file_name: OsString = entry.file_name();
844            let name: Cow<'_, str> = file_name.to_string_lossy();
845            if should_skip_watch_dir(&name) {
846                continue;
847            }
848            if let Some(excluded) = exclude_dir {
849                let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
850                if canon == excluded || canon.starts_with(excluded) {
851                    continue;
852                }
853                let recurse_check: bool = excluded.starts_with(&canon);
854                let next_canon: Option<&Path> = recurse_check.then_some(canon.as_path());
855                scan_dir_stamps(
856                    &path,
857                    allowed_exts,
858                    exclude_dir,
859                    next_canon,
860                    recurse_check,
861                    entries,
862                )?;
863                continue;
864            }
865            scan_dir_stamps(&path, allowed_exts, None, None, false, entries)?;
866        } else if meta.is_file() && has_allowed_extension(&path, allowed_exts) {
867            let _: Option<FileStamp> = entries.insert(path, stamp_from_metadata(&meta));
868        }
869    }
870    Ok(())
871}
872
873/// Returns `true` when directory `name` should be excluded from file watching.
874///
875/// # Arguments
876///
877/// - `&str` - Directory name.
878///
879/// # Returns
880///
881/// - `bool` - Whether the watcher skips this directory.
882fn should_skip_watch_dir(name: &str) -> bool {
883    name.starts_with('.')
884        || WATCH_IGNORED_DIRS
885            .iter()
886            .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
887}
888
889/// Returns `true` when `path` has an extension listed in `allowed_exts`.
890///
891/// # Arguments
892///
893/// - `&Path` - Candidate file path.
894/// - `&[&str]` - Allowed lowercase extensions.
895///
896/// # Returns
897///
898/// - `bool` - Whether the file should be watched.
899fn has_allowed_extension(path: &Path, allowed_exts: &[&str]) -> bool {
900    path.extension()
901        .and_then(|s: &OsStr| s.to_str())
902        .is_some_and(|ext: &str| {
903            allowed_exts
904                .iter()
905                .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
906        })
907}
908
909/// Extracts a deterministic `FileStamp` from filesystem `Metadata`.
910///
911/// # Arguments
912///
913/// - `&Metadata` - File metadata.
914///
915/// # Returns
916///
917/// - `FileStamp` - Modification timestamp and byte size pair.
918fn stamp_from_metadata(meta: &Metadata) -> FileStamp {
919    let nanos: u128 = meta
920        .modified()
921        .ok()
922        .and_then(|t: SystemTime| t.duration_since(UNIX_EPOCH).ok())
923        .map(|d: Duration| d.as_nanos())
924        .unwrap_or(0);
925    FileStamp::new(nanos, meta.len())
926}