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/// Resolves the active v1 OTA store directory for `config` (defaults to `<out_dir>/.euv-updates`).
87///
88/// # Arguments
89///
90/// - `&DevServerConfig` - Active dev server configuration.
91///
92/// # Returns
93///
94/// - `PathBuf` - Local update store root path.
95#[must_use]
96pub fn resolve_dev_ota_store_dir(config: &DevServerConfig) -> PathBuf {
97    match config.try_get_ota_store_dir() {
98        Some(explicit) => explicit.clone(),
99        None => config.get_out_dir().join(DEV_OTA_STORE_SUBDIR),
100    }
101}
102
103/// Resolves the effective `(project, channel, signing_key)` tuple for `config`, applying sensible dev defaults when empty.
104///
105/// # Arguments
106///
107/// - `&DevServerConfig` - Active dev server configuration.
108///
109/// # Returns
110///
111/// - `(String, String, String)` - Non-empty `(project, channel, signing_key)` triple.
112#[must_use]
113pub fn resolve_dev_ota_identity(config: &DevServerConfig) -> (String, String, String) {
114    let project: String = if config.get_ota_project().trim().is_empty() {
115        DEFAULT_DEV_OTA_PROJECT.to_string()
116    } else {
117        config.get_ota_project().trim().to_string()
118    };
119    let channel: String = if config.get_ota_channel().trim().is_empty() {
120        DEFAULT_DEV_OTA_CHANNEL.to_string()
121    } else {
122        config.get_ota_channel().trim().to_string()
123    };
124    let signing_key: String = if config.get_ota_signing_key().trim().is_empty() {
125        OTA_DEV_SIGNING_KEY.to_string()
126    } else {
127        config.get_ota_signing_key().clone()
128    };
129    (project, channel, signing_key)
130}
131
132/// Computes the exact environment variables injected into native/mobile/web child processes launched by `euv dev`.
133///
134/// # Arguments
135///
136/// - `&DevServerConfig` - Active dev server configuration.
137/// - `&str` - Bound base HTTP URL of the live dev server.
138///
139/// # Returns
140///
141/// - `Vec<(String, String)>` - Ordered `(key, value)` environment variable pairs.
142#[must_use]
143pub fn build_child_dev_env(config: &DevServerConfig, dev_url: &str) -> Vec<(String, String)> {
144    let mut vars: Vec<(String, String)> = vec![
145        (ENV_DEV_URL.to_string(), dev_url.to_string()),
146        (ENV_HMR_URL.to_string(), format!("{dev_url}{HMR_ENDPOINT}")),
147    ];
148    if config.get_enable_ota() {
149        let (_project, channel, signing_key): (String, String, String) =
150            resolve_dev_ota_identity(config);
151        let cache_dir: PathBuf =
152            resolve_dev_ota_store_dir(config).join(DEV_OTA_CLIENT_CACHE_SUBDIR);
153        vars.push((ENV_EUV_UPDATE_URL.to_string(), dev_url.to_string()));
154        vars.push((ENV_EUV_UPDATE_CHANNEL.to_string(), channel));
155        vars.push((ENV_DEV_UPDATE_SIGNING_KEY.to_string(), signing_key));
156        vars.push((
157            ENV_EUV_UPDATE_CACHE_DIR.to_string(),
158            cache_dir.display().to_string(),
159        ));
160        vars.push((
161            ENV_OTA_MANIFEST_URL.to_string(),
162            format!("{dev_url}{OTA_MANIFEST_ENDPOINT}"),
163        ));
164        vars.push((
165            ENV_OTA_MODULE_URL.to_string(),
166            format!("{dev_url}{OTA_MODULE_ENDPOINT}"),
167        ));
168    }
169    vars
170}
171
172/// Validates, signs, and publishes a `.json` `DynamicNodeSpec`, `.wasm` binary, or Rust widget crate into `store` without restarting the host app.
173///
174/// # Arguments
175///
176/// - `&UpdateStore` - Mounted v1 OTA store.
177/// - `&DevServerConfig` - Active dev server configuration carrying project/channel/route/slot/key metadata.
178/// - `&Path` - Watched `.json`, `.wasm`, `Cargo.toml`, or Rust crate directory path.
179///
180/// # Returns
181///
182/// - `io::Result<PublishReport>` - Atomic publish summary triggering live v1 SSE delivery.
183pub fn push_hot_ota_artifact(
184    store: &UpdateStore,
185    config: &DevServerConfig,
186    artifact_path: &Path,
187) -> io::Result<PublishReport> {
188    let (project, channel, signing_key): (String, String, String) =
189        resolve_dev_ota_identity(config);
190    push_watched_ota_source(
191        store,
192        artifact_path,
193        (&project, &channel),
194        (
195            config.try_get_ota_route().as_deref(),
196            config.try_get_ota_slot().as_deref(),
197        ),
198        config.try_get_package().as_deref(),
199        signing_key.as_bytes(),
200    )
201}
202
203/// Publishes a synthetic signed v1 declarative status release into `store` so dev v1 OTA endpoints are immediately live.
204///
205/// # Arguments
206///
207/// - `&UpdateStore` - Mounted v1 OTA store.
208/// - `&DevServerConfig` - Active dev server configuration.
209/// - `&str` - Status card heading text.
210///
211/// # Returns
212///
213/// - `io::Result<PublishReport>` - Atomic publish summary.
214fn publish_dev_status_v1_release(
215    store: &UpdateStore,
216    config: &DevServerConfig,
217    title: &str,
218) -> io::Result<PublishReport> {
219    let (project, channel, signing_key): (String, String, String) =
220        resolve_dev_ota_identity(config);
221    let card: DynamicNodeSpec = DynamicNodeSpec::column()
222        .child(DynamicNodeSpec::text(title.to_string()))
223        .child(DynamicNodeSpec::text(DEV_OTA_INITIAL_BODY.to_string()));
224    let json_bytes: Vec<u8> = to_string_pretty(&card)
225        .map(String::into_bytes)
226        .map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
227    store.publish_artifact_direct(
228        &project,
229        &channel,
230        config.try_get_ota_route().as_deref(),
231        config.try_get_ota_slot().as_deref(),
232        &json_bytes,
233        signing_key.as_bytes(),
234    )
235}
236
237/// Starts a live HTTP, SSE hot-reload, debounced file-watcher, and real v1 OTA dev server in background threads.
238///
239/// # Arguments
240///
241/// - `DevServerConfig` - Full dev server configuration.
242///
243/// # Returns
244///
245/// - `io::Result<DevServerHandle>` - Running server handle or startup error.
246pub fn start_dev_server(config: DevServerConfig) -> io::Result<DevServerHandle> {
247    start_dev_server_with_hook(config, None)
248}
249
250/// Starts a live hot-reload dev server with an optional pluggable ecosystem rebuild hook.
251///
252/// # Arguments
253///
254/// - `DevServerConfig` - Full dev server configuration.
255/// - `Option<DevRebuildHook>` - Optional rebuild callback for `harmony`/`wearable`/`miniapp`/`quickapp` targets.
256///
257/// # Returns
258///
259/// - `io::Result<DevServerHandle>` - Running server handle or startup error.
260pub fn start_dev_server_with_hook(
261    config: DevServerConfig,
262    rebuild_hook: Option<DevRebuildHook>,
263) -> io::Result<DevServerHandle> {
264    let is_process_target: bool = matches!(
265        config.get_target(),
266        DevTargetArg::Native | DevTargetArg::Tui | DevTargetArg::Cli
267    );
268    if !is_process_target {
269        fs::create_dir_all(config.get_out_dir())?;
270    }
271    let mut initial_pages: usize = 0;
272    let mode_label: String = match config.get_target() {
273        DevTargetArg::Docs => {
274            let docs_opts: DocsBuildOptions = docs_options_for_dev(&config);
275            let report: GeneratedSiteReport =
276                build_docs_site(config.get_src_dir(), config.get_out_dir(), &docs_opts)?;
277            initial_pages = report.get_page_count();
278            MODE_LABEL_DOCS.to_string()
279        }
280        DevTargetArg::Web => {
281            if let Some(hook) = rebuild_hook.as_ref() {
282                let _: String = hook(&config, &[])?;
283            } else {
284                rebuild_web_dev_bundle(&config)?;
285            }
286            MODE_LABEL_WEB.to_string()
287        }
288        DevTargetArg::Native => MODE_LABEL_NATIVE.to_string(),
289        DevTargetArg::Tui => MODE_LABEL_TUI.to_string(),
290        DevTargetArg::Cli => MODE_LABEL_CLI.to_string(),
291        DevTargetArg::Harmony => MODE_LABEL_HARMONY.to_string(),
292        DevTargetArg::Wearable => MODE_LABEL_WEARABLE.to_string(),
293        DevTargetArg::Miniapp => MODE_LABEL_MINIAPP.to_string(),
294        DevTargetArg::Quickapp => MODE_LABEL_QUICKAPP.to_string(),
295    };
296    let (ota_project, ota_channel, _signing_key): (String, String, String) =
297        resolve_dev_ota_identity(&config);
298    let ota_store_dir: PathBuf = resolve_dev_ota_store_dir(&config);
299    let mut ota_store: UpdateStore = UpdateStore::new(ota_store_dir);
300    let _: &mut UpdateStore = ota_store.set_max_artifact_bytes(DEFAULT_MAX_ARTIFACT_BYTES);
301    if config.get_enable_ota() {
302        ota_store.init_layout()?;
303        if let Some(watch_path) = config.try_get_watch_ota_path()
304            && watch_path.exists()
305        {
306            let _: PublishReport = push_hot_ota_artifact(&ota_store, &config, watch_path)?;
307        } else {
308            let _: io::Result<PublishReport> =
309                publish_dev_status_v1_release(&ota_store, &config, OTA_INITIAL_TITLE);
310        }
311    }
312    let initial_ota: OtaBundleState = build_dev_ota_state(1, OTA_INITIAL_TITLE, Vec::new());
313    let hub: Arc<HmrHub> = Arc::new(HmrHub::new(initial_ota));
314    let bind_addr: String = format!("{}:{}", config.get_host(), config.get_port());
315    let listener: TcpListener = TcpListener::bind(&bind_addr)?;
316    let address: SocketAddr = listener.local_addr()?;
317    listener.set_nonblocking(true)?;
318    let serve_ctx: HttpServeContext = HttpServeContext {
319        out_dir: config.get_out_dir().clone(),
320        base_url: config.get_base_url().clone(),
321        enable_ota: config.get_enable_ota(),
322        coop_coep: config.get_coop_coep(),
323        spa_fallback: config.get_spa_fallback(),
324        ota_store: ota_store.clone(),
325        hub: Arc::clone(&hub),
326    };
327    let http_thread: JoinHandle<()> = thread::spawn(move || {
328        run_http_accept_loop(listener, serve_ctx);
329    });
330    let watch_hub: Arc<HmrHub> = Arc::clone(&hub);
331    let watch_cfg: DevServerConfig = config.clone();
332    let watch_store: UpdateStore = ota_store.clone();
333    let dev_url: String = format!("http://{address}");
334    let watch_thread: JoinHandle<()> = thread::spawn(move || {
335        run_watch_rebuild_loop(watch_cfg, dev_url, watch_store, watch_hub, rebuild_hook);
336    });
337    Ok(DevServerHandle {
338        address,
339        out_dir: config.get_out_dir().clone(),
340        mode: mode_label,
341        page_count: initial_pages,
342        ota_store,
343        ota_project,
344        ota_channel,
345        hub,
346        http_thread: Some(http_thread),
347        watch_thread: Some(watch_thread),
348    })
349}
350
351/// Starts the dev server and either exits immediately (`once=true`) or serves continuously until interrupted.
352///
353/// # Arguments
354///
355/// - `DevServerConfig` - Dev server configuration.
356///
357/// # Returns
358///
359/// - `io::Result<DevServerReport>` - Server startup summary report or I/O error.
360pub fn run_dev_blocking(config: DevServerConfig) -> io::Result<DevServerReport> {
361    run_dev_blocking_with_hook(config, None)
362}
363
364/// Starts the dev server with an optional ecosystem rebuild hook and serves continuously unless `once=true`.
365///
366/// # Arguments
367///
368/// - `DevServerConfig` - Dev server configuration.
369/// - `Option<DevRebuildHook>` - Optional pluggable ecosystem rebuild callback.
370///
371/// # Returns
372///
373/// - `io::Result<DevServerReport>` - Server startup summary report or I/O error.
374pub fn run_dev_blocking_with_hook(
375    config: DevServerConfig,
376    rebuild_hook: Option<DevRebuildHook>,
377) -> io::Result<DevServerReport> {
378    let once: bool = config.get_once();
379    let mut handle: DevServerHandle = start_dev_server_with_hook(config, rebuild_hook)?;
380    let report: DevServerReport = handle.report();
381    if once {
382        handle.shutdown();
383        return Ok(report);
384    }
385    eprintln!(
386        "[euv-dev] mode={} url={} hmr={} ota_v1={} health={}",
387        report.get_mode(),
388        report.get_url(),
389        report.get_hmr_url(),
390        report.get_v1_manifest_url(),
391        report.get_health_url()
392    );
393    for lan_url in report.get_lan_urls().iter() {
394        eprintln!("[euv-dev] lan={lan_url}");
395    }
396    while handle.hub.is_running() {
397        thread::sleep(Duration::from_millis(250));
398    }
399    handle.shutdown();
400    Ok(report)
401}
402
403/// Constructs `DocsBuildOptions` wired for live dev hot reload from a `DevServerConfig`.
404///
405/// # Arguments
406///
407/// - `&DevServerConfig` - Active dev server configuration.
408///
409/// # Returns
410///
411/// - `DocsBuildOptions` - Populated docs build options with dev HMR endpoint.
412fn docs_options_for_dev(config: &DevServerConfig) -> DocsBuildOptions {
413    let mut opts: DocsBuildOptions = DocsBuildOptions::default();
414    opts.set_title(config.try_get_title().clone())
415        .set_base_url(config.get_base_url().clone())
416        .set_hmr_endpoint(Some(HMR_ENDPOINT.to_string()))
417        .set_assets_root(Some(config.get_src_dir().clone()))
418        .set_clean_urls(true);
419    opts
420}
421
422/// Runs the non-blocking HTTP accept loop dispatching static files, SSE `/__euv_hmr`, and OTA endpoints.
423///
424/// # Arguments
425///
426/// - `TcpListener` - Bound non-blocking TCP listener.
427/// - `HttpServeContext` - Output directory, base prefix, OTA gate, and shared HMR hub.
428fn run_http_accept_loop(listener: TcpListener, ctx: HttpServeContext) {
429    while ctx.get_hub().is_running() {
430        match listener.accept() {
431            Ok((stream, _)) => {
432                if !ctx.get_hub().is_running() {
433                    break;
434                }
435                let conn_ctx: HttpServeContext = ctx.clone();
436                drop(thread::spawn(move || {
437                    serve_http_connection(stream, &conn_ctx);
438                }));
439            }
440            Err(err) if err.kind() == ErrorKind::WouldBlock => {
441                thread::sleep(Duration::from_millis(20));
442            }
443            Err(_) => {
444                thread::sleep(Duration::from_millis(50));
445            }
446        }
447    }
448}
449
450/// Runs the debounced recursive file watcher loop rebuilding docs, web bundles, ecosystem bundles, v1 OTA artifacts, or native binaries via build-before-swap.
451///
452/// # Arguments
453///
454/// - `DevServerConfig` - Active dev server configuration.
455/// - `String` - Base HTTP URL of the active dev server forwarded to native child processes.
456/// - `UpdateStore` - Mounted v1 OTA update store.
457/// - `Arc<HmrHub>` - Shared HMR and OTA hub.
458/// - `Option<DevRebuildHook>` - Optional pluggable ecosystem rebuild callback.
459fn run_watch_rebuild_loop(
460    config: DevServerConfig,
461    dev_url: String,
462    ota_store: UpdateStore,
463    hub: Arc<HmrHub>,
464    rebuild_hook: Option<DevRebuildHook>,
465) {
466    let allowed_exts: &[&str] = match config.get_target() {
467        DevTargetArg::Docs => &WATCH_EXTS_DOCS,
468        _ => &WATCH_EXTS_CODE,
469    };
470    let is_process_target: bool = matches!(
471        config.get_target(),
472        DevTargetArg::Native | DevTargetArg::Tui | DevTargetArg::Cli
473    );
474    let exclude_out: Option<&Path> = if is_process_target {
475        None
476    } else {
477        Some(config.get_out_dir().as_path())
478    };
479    let mut prev_snap: WatchSnapshot =
480        WatchSnapshot::scan_excluding(config.get_src_dir(), allowed_exts, exclude_out)
481            .unwrap_or_default();
482    let mut prev_ota_stamp: String = config
483        .try_get_watch_ota_path()
484        .as_deref()
485        .map(compute_ota_artifact_stamp)
486        .unwrap_or_default();
487    let mut child_guard: ChildProcessGuard = ChildProcessGuard::default();
488    let mut swap_ctrl: BuildBeforeSwapController = BuildBeforeSwapController::default();
489    if is_process_target
490        && !config.get_once()
491        && let Ok(initial_child) = spawn_native_app_child(&config, &dev_url)
492    {
493        child_guard.replace(initial_child);
494        swap_ctrl.mark_initial_launched();
495    }
496    let mut debouncer: DebouncedWatcher = DebouncedWatcher::new(config.get_debounce_ms());
497    let base_poll_ms: u64 = config.get_poll_ms().clamp(25, 5000);
498    let settle_poll_ms: u64 = base_poll_ms.min(30);
499    while hub.is_running() {
500        let sleep_ms: u64 = if debouncer.has_pending() {
501            settle_poll_ms
502        } else {
503            base_poll_ms
504        };
505        thread::sleep(Duration::from_millis(sleep_ms));
506        if !hub.is_running() {
507            break;
508        }
509        if config.get_enable_ota()
510            && let Some(watch_ota_path) = config.try_get_watch_ota_path()
511            && watch_ota_path.exists()
512        {
513            let next_ota_stamp: String = compute_ota_artifact_stamp(watch_ota_path);
514            if next_ota_stamp != prev_ota_stamp {
515                prev_ota_stamp = next_ota_stamp;
516                let changed_ota: Vec<String> = vec![watch_ota_path.display().to_string()];
517                match push_hot_ota_artifact(&ota_store, &config, watch_ota_path) {
518                    Ok(pub_report) => {
519                        let next_ver: u64 = hub.revision() + 1;
520                        let ota_title: String = format!(
521                            "Hot OTA v{} (seq {})",
522                            next_ver,
523                            pub_report.get_to_release()
524                        );
525                        hub.set_ota_state(build_dev_ota_state(
526                            next_ver,
527                            &ota_title,
528                            changed_ota.clone(),
529                        ));
530                        let _: u64 = hub.publish(
531                            HmrEventKind::OtaUpdate,
532                            format!("{MSG_HOT_OTA_PUSHED} (seq={})", pub_report.get_to_release()),
533                            changed_ota,
534                        );
535                    }
536                    Err(err) => {
537                        let _: u64 =
538                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_ota);
539                    }
540                }
541                if config.get_hot_ota() {
542                    continue;
543                }
544            }
545        }
546        let now: Instant = Instant::now();
547        if let Ok(next_snap) =
548            WatchSnapshot::scan_excluding(config.get_src_dir(), allowed_exts, exclude_out)
549        {
550            let changes: FileChangeSet = prev_snap.diff(&next_snap);
551            if !changes.is_empty() {
552                prev_snap = next_snap;
553                debouncer.record_changes(changes, now);
554            }
555        }
556        let Some(flushed) = debouncer.flush_ready(now) else {
557            continue;
558        };
559        let changed_files: Vec<String> = flushed.all_paths();
560        match config.get_target() {
561            DevTargetArg::Docs => {
562                let docs_opts: DocsBuildOptions = docs_options_for_dev(&config);
563                match build_docs_site(config.get_src_dir(), config.get_out_dir(), &docs_opts) {
564                    Ok(report) => {
565                        let next_ver: u64 = hub.revision() + 1;
566                        if config.get_enable_ota() {
567                            let ota_title: String = format!(
568                                "Docs Hot Update v{next_ver} ({} pages)",
569                                report.get_page_count()
570                            );
571                            let _: io::Result<PublishReport> =
572                                publish_dev_status_v1_release(&ota_store, &config, &ota_title);
573                            hub.set_ota_state(build_dev_ota_state(
574                                next_ver,
575                                &ota_title,
576                                changed_files.clone(),
577                            ));
578                        }
579                        let _: u64 = hub.publish(
580                            HmrEventKind::Reload,
581                            format!("{MSG_DOCS_REBUILT} ({} pages)", report.get_page_count()),
582                            changed_files,
583                        );
584                    }
585                    Err(err) => {
586                        let _: u64 =
587                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
588                    }
589                }
590            }
591            DevTargetArg::Web => {
592                let rebuild_result: io::Result<String> = match rebuild_hook.as_ref() {
593                    Some(hook) => hook(&config, &changed_files),
594                    None => {
595                        rebuild_web_dev_bundle(&config).map(|_: ()| MSG_WEB_REBUILT.to_string())
596                    }
597                };
598                match rebuild_result {
599                    Ok(summary) => {
600                        let next_ver: u64 = hub.revision() + 1;
601                        if config.get_enable_ota() {
602                            let ota_title: String = format!("Web WASM Hot Update v{next_ver}");
603                            let _: io::Result<PublishReport> =
604                                publish_dev_status_v1_release(&ota_store, &config, &ota_title);
605                            hub.set_ota_state(build_dev_ota_state(
606                                next_ver,
607                                &ota_title,
608                                changed_files.clone(),
609                            ));
610                        }
611                        let _: u64 = hub.publish(HmrEventKind::Reload, summary, changed_files);
612                    }
613                    Err(err) => {
614                        let _: u64 =
615                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
616                    }
617                }
618            }
619            DevTargetArg::Native | DevTargetArg::Tui | DevTargetArg::Cli => {
620                if config.get_hot_ota()
621                    && let Some(watch_ota_path) = config.try_get_watch_ota_path()
622                    && watch_ota_path.exists()
623                {
624                    match push_hot_ota_artifact(&ota_store, &config, watch_ota_path) {
625                        Ok(pub_report) => {
626                            let next_ver: u64 = hub.revision() + 1;
627                            let ota_title: String = format!(
628                                "Hot OTA v{} (seq {})",
629                                next_ver,
630                                pub_report.get_to_release()
631                            );
632                            hub.set_ota_state(build_dev_ota_state(
633                                next_ver,
634                                &ota_title,
635                                changed_files.clone(),
636                            ));
637                            let _: u64 = hub.publish(
638                                HmrEventKind::OtaUpdate,
639                                format!(
640                                    "{MSG_HOT_OTA_PUSHED} (seq={})",
641                                    pub_report.get_to_release()
642                                ),
643                                changed_files,
644                            );
645                        }
646                        Err(err) => {
647                            let _: u64 = hub.publish(
648                                HmrEventKind::BuildError,
649                                err.to_string(),
650                                changed_files,
651                            );
652                        }
653                    }
654                    continue;
655                }
656                let outcome: SwapOutcome = swap_ctrl.apply_rebuild(
657                    || build_native_binary_first(&config),
658                    || {},
659                    || {
660                        child_guard.terminate();
661                        let next_child: Child = spawn_native_app_child(&config, &dev_url)?;
662                        child_guard.replace(next_child);
663                        Ok(())
664                    },
665                );
666                match outcome {
667                    SwapOutcome::LaunchedInitial | SwapOutcome::Swapped => {
668                        let next_ver: u64 = hub.revision() + 1;
669                        if config.get_enable_ota() {
670                            let ota_title: String = format!("Native OTA Hot Update v{next_ver}");
671                            let _: io::Result<PublishReport> =
672                                publish_dev_status_v1_release(&ota_store, &config, &ota_title);
673                            hub.set_ota_state(build_dev_ota_state(
674                                next_ver,
675                                &ota_title,
676                                changed_files.clone(),
677                            ));
678                        }
679                        let _: u64 = hub.publish(
680                            HmrEventKind::OtaUpdate,
681                            MSG_NATIVE_RESTARTED.to_string(),
682                            changed_files,
683                        );
684                    }
685                    SwapOutcome::KeptRunningOnError(err_msg) => {
686                        eprintln!("[euv-dev] {MSG_NATIVE_BUILD_FAILED_KEPT}: {err_msg}");
687                        let _: u64 = hub.publish(
688                            HmrEventKind::BuildError,
689                            format!("{MSG_NATIVE_BUILD_FAILED_KEPT}: {err_msg}"),
690                            changed_files,
691                        );
692                    }
693                }
694            }
695            DevTargetArg::Harmony
696            | DevTargetArg::Wearable
697            | DevTargetArg::Miniapp
698            | DevTargetArg::Quickapp => {
699                let rebuild_result: io::Result<String> = match rebuild_hook.as_ref() {
700                    Some(hook) => hook(&config, &changed_files),
701                    None => rebuild_ecosystem_dev_target(&config),
702                };
703                match rebuild_result {
704                    Ok(summary) => {
705                        let next_ver: u64 = hub.revision() + 1;
706                        if config.get_enable_ota() {
707                            let ota_title: String =
708                                format!("{:?} OTA Hot Update v{next_ver}", config.get_target());
709                            let _: io::Result<PublishReport> =
710                                publish_dev_status_v1_release(&ota_store, &config, &ota_title);
711                            hub.set_ota_state(build_dev_ota_state(
712                                next_ver,
713                                &ota_title,
714                                changed_files.clone(),
715                            ));
716                        }
717                        let _: u64 = hub.publish(HmrEventKind::OtaUpdate, summary, changed_files);
718                    }
719                    Err(err) => {
720                        let _: u64 =
721                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
722                    }
723                }
724            }
725        }
726    }
727    child_guard.terminate();
728}
729
730/// Computes a fast deterministic fingerprint for a watched OTA file or widget crate directory.
731///
732/// # Arguments
733///
734/// - `&Path` - Watched `.json`, `.wasm`, or crate directory path.
735///
736/// # Returns
737///
738/// - `String` - SHA-256 hex digest representing the watched artifact state.
739fn compute_ota_artifact_stamp(watch_path: &Path) -> String {
740    if watch_path.is_file() {
741        return fs::read(watch_path)
742            .map(|bytes: Vec<u8>| sha256_hex(&bytes))
743            .unwrap_or_default();
744    }
745    let snap: WatchSnapshot = WatchSnapshot::scan(watch_path, &WATCH_EXTS_CODE).unwrap_or_default();
746    let mut acc: String = String::new();
747    for (entry_path, stamp) in snap.get_entries().iter() {
748        acc.push_str(&format!(
749            "{}:{}:{}\n",
750            entry_path.display(),
751            stamp.get_modified_nanos(),
752            stamp.get_size_bytes()
753        ));
754    }
755    sha256_hex(acc.as_bytes())
756}
757
758/// Resolves the crate directory for `package` under `src_dir` so `wasm-pack` compiles the right workspace member.
759///
760/// # Arguments
761///
762/// - `&Path` - Project or workspace root directory.
763/// - `Option<&str>` - Optional `--package` name.
764///
765/// # Returns
766///
767/// - `PathBuf` - Directory containing the target crate's `Cargo.toml`.
768#[must_use]
769pub fn resolve_web_package_dir(src_dir: &Path, package: Option<&str>) -> PathBuf {
770    let Some(pkg_name) = package
771        .map(str::trim)
772        .filter(|name: &&str| !name.is_empty())
773    else {
774        return src_dir.to_path_buf();
775    };
776    let direct: PathBuf = src_dir.join(pkg_name);
777    if direct.join(CARGO_TOML_NAME).is_file() {
778        return direct;
779    }
780    if let Some(short_name) = pkg_name.strip_prefix(PKG_EUV_PREFIX) {
781        let short_dir: PathBuf = src_dir.join(short_name);
782        if short_dir.join(CARGO_TOML_NAME).is_file() {
783            return short_dir;
784        }
785    }
786    let expected_name_line: String = format!("name = \"{pkg_name}\"");
787    if let Ok(entries) = fs::read_dir(src_dir) {
788        for entry_res in entries.flatten() {
789            let candidate: PathBuf = entry_res.path();
790            let manifest: PathBuf = candidate.join(CARGO_TOML_NAME);
791            if candidate.is_dir()
792                && manifest.is_file()
793                && let Ok(contents) = fs::read_to_string(&manifest)
794                && contents.contains(&expected_name_line)
795            {
796                return candidate;
797            }
798        }
799    }
800    src_dir.to_path_buf()
801}
802
803/// Rebuilds the WebAssembly bundle into `config.out_dir` (honoring `--package`) and injects the dev SSE hot-reload + error-overlay script.
804///
805/// # Arguments
806///
807/// - `&DevServerConfig` - Active web dev configuration.
808///
809/// # Returns
810///
811/// - `io::Result<()>` - Build result.
812fn rebuild_web_dev_bundle(config: &DevServerConfig) -> io::Result<()> {
813    let out_dir: &Path = config.get_out_dir();
814    let crate_dir: PathBuf =
815        resolve_web_package_dir(config.get_src_dir(), config.try_get_package().as_deref());
816    let abs_out_dir: PathBuf = if out_dir.is_absolute() {
817        out_dir.to_path_buf()
818    } else {
819        let cwd: PathBuf = env::current_dir()?;
820        cwd.join(out_dir)
821    };
822    let mut wp_args: Vec<String> = vec![
823        ARG_BUILD.to_string(),
824        ARG_TARGET.to_string(),
825        ARG_TARGET_WEB.to_string(),
826        ARG_OUT_DIR.to_string(),
827        abs_out_dir.display().to_string(),
828    ];
829    if config.get_release() {
830        wp_args.push(ARG_RELEASE.to_string());
831    }
832    let output: Output = Command::new(BIN_WASM_PACK)
833        .args(&wp_args)
834        .current_dir(&crate_dir)
835        .output()?;
836    if !output.status.success() {
837        let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
838        return Err(Error::other(format!("{ERR_STEP_FAILED}: {stderr}")));
839    }
840    if abs_out_dir.exists() {
841        let index_path: PathBuf = package_zero_js_web_bundle(&abs_out_dir, WEB_BUNDLE_TITLE)?;
842        let html: String = fs::read_to_string(&index_path)?;
843        let with_hmr: String = inject_dev_hmr_into_html(&html, HMR_ENDPOINT);
844        fs::write(&index_path, with_hmr)?;
845    }
846    Ok(())
847}
848
849/// Maps `DevTargetArg` to the exact `TargetArg` preserved when launching native, TUI, or CLI apps.
850///
851/// # Arguments
852///
853/// - `DevTargetArg` - Active dev pipeline target.
854///
855/// # Returns
856///
857/// - `TargetArg` - Concrete run target (`Native`, `Tui`, or `Cli`).
858#[must_use]
859pub const fn run_target_for_dev(target: DevTargetArg) -> TargetArg {
860    match target {
861        DevTargetArg::Tui => TargetArg::Tui,
862        DevTargetArg::Cli => TargetArg::Cli,
863        DevTargetArg::Web => TargetArg::Web,
864        DevTargetArg::Harmony => TargetArg::Harmony,
865        DevTargetArg::Wearable => TargetArg::Wearable,
866        DevTargetArg::Miniapp => TargetArg::Wechat,
867        DevTargetArg::Quickapp => TargetArg::Quickapp,
868        DevTargetArg::Native | DevTargetArg::Docs => TargetArg::Native,
869    }
870}
871
872/// Compiles the native/TUI/CLI binary via `cargo build` BEFORE terminating the active running process.
873///
874/// # Arguments
875///
876/// - `&DevServerConfig` - Active dev configuration.
877///
878/// # Returns
879///
880/// - `io::Result<()>` - `Ok(())` when compilation succeeds; error carrying compiler stderr otherwise.
881fn build_native_binary_first(config: &DevServerConfig) -> io::Result<()> {
882    let mut args: Vec<String> = vec![ARG_BUILD.to_string()];
883    if let Some(pkg) = config.try_get_package() {
884        args.push(ARG_PACKAGE.to_string());
885        args.push(pkg.clone());
886    }
887    if config.get_release() {
888        args.push(ARG_RELEASE.to_string());
889    }
890    let output: Output = Command::new(BIN_CARGO)
891        .args(&args)
892        .current_dir(config.get_src_dir())
893        .output()?;
894    if output.status.success() {
895        Ok(())
896    } else {
897        let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
898        Err(Error::other(stderr))
899    }
900}
901
902/// Spawns a fresh native/TUI/CLI `cargo run` child process preserving exact target flags, TTY stdio, and v1 OTA env vars.
903///
904/// # Arguments
905///
906/// - `&DevServerConfig` - Active dev configuration.
907/// - `&str` - Base HTTP URL of the active dev server.
908///
909/// # Returns
910///
911/// - `io::Result<Child>` - Spawned child process handle or error.
912fn spawn_native_app_child(config: &DevServerConfig, dev_url: &str) -> io::Result<Child> {
913    let run_target: TargetArg = run_target_for_dev(config.get_target());
914    let step: BuildStep = resolve_run_step(
915        run_target,
916        config.get_render(),
917        config.get_release(),
918        config.try_get_package().as_deref(),
919    );
920    let mut cmd: Command = Command::new(step.get_program());
921    let is_terminal_target: bool =
922        matches!(config.get_target(), DevTargetArg::Tui | DevTargetArg::Cli);
923    let _: &mut Command = cmd
924        .args(step.get_args())
925        .current_dir(config.get_src_dir())
926        .stdout(Stdio::inherit())
927        .stderr(Stdio::inherit());
928    if is_terminal_target {
929        let _: &mut Command = cmd.stdin(Stdio::inherit());
930    } else {
931        let _: &mut Command = cmd.stdin(Stdio::null());
932    }
933    for (env_key, env_val) in build_child_dev_env(config, dev_url).into_iter() {
934        let _: &mut Command = cmd.env(env_key, env_val);
935    }
936    cmd.spawn()
937}
938
939/// Executes the real resolved build plan for `harmony`, `wearable`, `miniapp`, or `quickapp` dev targets.
940///
941/// # Arguments
942///
943/// - `&DevServerConfig` - Active ecosystem dev configuration.
944///
945/// # Returns
946///
947/// - `io::Result<String>` - Human-readable rebuild summary or build error.
948fn rebuild_ecosystem_dev_target(config: &DevServerConfig) -> io::Result<String> {
949    let target_arg: TargetArg = run_target_for_dev(config.get_target());
950    let plans: Vec<BuildPlan> =
951        resolve_build_plans(target_arg, config.get_render(), config.get_release());
952    for plan in plans.iter() {
953        for step in plan.get_steps().iter() {
954            let output: Output = Command::new(step.get_program())
955                .args(step.get_args())
956                .current_dir(config.get_src_dir())
957                .output()?;
958            if !output.status.success() {
959                let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
960                return Err(Error::other(format!(
961                    "{ERR_STEP_FAILED} ({}): {stderr}",
962                    plan.get_target().get_name()
963                )));
964            }
965        }
966    }
967    Ok(format!(
968        "{MSG_ECOSYSTEM_REBUILT} ({:?})",
969        config.get_target()
970    ))
971}
972
973/// Handles a single incoming HTTP/1.1 connection for static files, SPA fallback, SSE `/__euv_hmr`, real v1 OTA endpoints, and legacy OTA shims.
974///
975/// # Arguments
976///
977/// - `TcpStream` - Connected client socket.
978/// - `&HttpServeContext` - Output directory, base prefix, OTA store, COOP/COEP, SPA fallback, and shared HMR hub.
979fn serve_http_connection(mut stream: TcpStream, ctx: &HttpServeContext) {
980    drop(stream.set_nonblocking(false));
981    drop(stream.set_read_timeout(Some(Duration::from_secs(3))));
982    let (req_line, headers): (String, BTreeMap<String, String>) = {
983        let mut reader: BufReader<&TcpStream> = BufReader::new(&stream);
984        let mut line: String = String::new();
985        if reader.read_line(&mut line).is_err() || line.is_empty() {
986            return;
987        }
988        let mut hdr_map: BTreeMap<String, String> = BTreeMap::new();
989        let mut header_count: usize = 0;
990        while header_count < 64 {
991            let mut hdr: String = String::new();
992            match reader.read_line(&mut hdr) {
993                Ok(0) => break,
994                Ok(_) if hdr == "\r\n" || hdr == "\n" => break,
995                Ok(_) => {
996                    if let Some((name, value)) = hdr.split_once(':') {
997                        let _: Option<String> = hdr_map
998                            .insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
999                    }
1000                    header_count += 1;
1001                }
1002                Err(_) => break,
1003            }
1004        }
1005        (line, hdr_map)
1006    };
1007    let mut parts: SplitWhitespace<'_> = req_line.split_whitespace();
1008    let method: &str = parts.next().unwrap_or("");
1009    let raw_target: &str = parts.next().unwrap_or("/");
1010    let (path_only, query_only): (&str, &str) = match raw_target.split_once('?') {
1011        Some((path_part, query_part)) => (path_part, query_part),
1012        None => (raw_target, ""),
1013    };
1014    let hub: &Arc<HmrHub> = ctx.get_hub();
1015    if path_only == HMR_ENDPOINT {
1016        if method.eq_ignore_ascii_case(HTTP_METHOD_OPTIONS) {
1017            drop(stream.write_all(HTTP_204_OPTIONS_RESP.as_bytes()));
1018            drop(stream.flush());
1019            return;
1020        }
1021        serve_sse_stream(stream, hub);
1022        return;
1023    }
1024    if ctx.get_enable_ota()
1025        && let Some((project, channel)) = parse_v1_events_path(path_only)
1026    {
1027        if method.eq_ignore_ascii_case(HTTP_METHOD_OPTIONS) {
1028            drop(stream.write_all(HTTP_204_OPTIONS_RESP.as_bytes()));
1029            drop(stream.flush());
1030            return;
1031        }
1032        let last_event_id: Option<u64> = headers
1033            .get(HTTP_HDR_LAST_EVENT_ID)
1034            .cloned()
1035            .or_else(|| extract_query_param(query_only, QUERY_KEY_DEV_LAST_EVENT_ID))
1036            .and_then(|raw: String| raw.trim().parse::<u64>().ok());
1037        serve_v1_ota_sse_stream(
1038            stream,
1039            ctx.get_ota_store(),
1040            &project,
1041            &channel,
1042            last_event_id,
1043            hub,
1044        );
1045        return;
1046    }
1047    if ctx.get_enable_ota() {
1048        let if_none_match: Option<&str> = headers.get(HTTP_HDR_IF_NONE_MATCH).map(String::as_str);
1049        let range_hdr: Option<&str> = headers.get(HTTP_HDR_RANGE).map(String::as_str);
1050        if let Some(ota_resp) = handle_embedded_v1_ota_request(
1051            ctx.get_ota_store(),
1052            method,
1053            raw_target,
1054            if_none_match,
1055            range_hdr,
1056        ) {
1057            let head_only: bool = method.eq_ignore_ascii_case(HTTP_METHOD_HEAD);
1058            write_embedded_ota_response(&mut stream, &ota_resp, head_only);
1059            return;
1060        }
1061    }
1062    if method.eq_ignore_ascii_case(HTTP_METHOD_OPTIONS) {
1063        drop(stream.write_all(HTTP_204_OPTIONS_RESP.as_bytes()));
1064        drop(stream.flush());
1065        return;
1066    }
1067    let head_only: bool = method.eq_ignore_ascii_case(HTTP_METHOD_HEAD);
1068    if path_only == OTA_MANIFEST_ENDPOINT {
1069        if ctx.get_enable_ota()
1070            && let Some(ota) = hub.ota_snapshot()
1071            && let Ok(json) = to_string_pretty(ota.get_manifest())
1072        {
1073            write_http_response(
1074                &mut stream,
1075                MIME_JSON,
1076                json.as_bytes(),
1077                head_only,
1078                ctx.get_coop_coep(),
1079            );
1080            return;
1081        }
1082        drop(stream.write_all(HTTP_404_RESP.as_bytes()));
1083        return;
1084    }
1085    if path_only == OTA_MODULE_ENDPOINT {
1086        if ctx.get_enable_ota()
1087            && let Some(ota) = hub.ota_snapshot()
1088        {
1089            write_http_response(
1090                &mut stream,
1091                MIME_WASM,
1092                ota.get_wasm_bytes().as_slice(),
1093                head_only,
1094                ctx.get_coop_coep(),
1095            );
1096            return;
1097        }
1098        drop(stream.write_all(HTTP_404_RESP.as_bytes()));
1099        return;
1100    }
1101    if path_only == DEV_STATUS_ENDPOINT {
1102        let payload: String = match hub.current_event() {
1103            Some(ui_event) => {
1104                to_string_pretty(&ui_event).unwrap_or_else(|_| EMPTY_JSON_OBJECT.to_string())
1105            }
1106            None => format!("{{\"revision\":{}}}", hub.revision()),
1107        };
1108        write_http_response(
1109            &mut stream,
1110            MIME_JSON,
1111            payload.as_bytes(),
1112            head_only,
1113            ctx.get_coop_coep(),
1114        );
1115        return;
1116    }
1117    let decoded_path: String = percent_decode_path(path_only);
1118    let stripped_path: &str = strip_base_prefix(&decoded_path, ctx.get_base_url());
1119    if let Some(file_path) =
1120        resolve_static_file_with_spa(ctx.get_out_dir(), stripped_path, ctx.get_spa_fallback())
1121        && let Ok(bytes) = fs::read(&file_path)
1122    {
1123        let mime: &str = mime_type_for_path(&file_path);
1124        write_http_response(&mut stream, mime, &bytes, head_only, ctx.get_coop_coep());
1125        return;
1126    }
1127    drop(stream.write_all(HTTP_404_RESP.as_bytes()));
1128}
1129
1130/// Streams real v1 OTA `release.activated` SSE frames with `Last-Event-ID` replay from `ota_store`.
1131///
1132/// # Arguments
1133///
1134/// - `TcpStream` - Long-lived SSE client socket.
1135/// - `&UpdateStore` - Backing atomic update store.
1136/// - `&str` - Logical project identifier.
1137/// - `&str` - Release channel name.
1138/// - `Option<u64>` - Optional `Last-Event-ID` cursor for replay.
1139/// - `&Arc<HmrHub>` - Shared hub coordinating server shutdown.
1140fn serve_v1_ota_sse_stream(
1141    mut stream: TcpStream,
1142    ota_store: &UpdateStore,
1143    project: &str,
1144    channel: &str,
1145    last_event_id: Option<u64>,
1146    hub: &Arc<HmrHub>,
1147) {
1148    if stream.write_all(HTTP_V1_SSE_HEADERS.as_bytes()).is_err() || stream.flush().is_err() {
1149        return;
1150    }
1151    let mut last_sent_seq: u64 = match last_event_id {
1152        Some(cursor) => {
1153            let replay: Vec<StoredReleaseEvent> = ota_store
1154                .read_events_after(project, channel, cursor)
1155                .unwrap_or_default();
1156            let mut highest: u64 = cursor;
1157            for rec in replay.into_iter() {
1158                if let Ok(json) = to_string(rec.get_event()) {
1159                    let frame: String = format!(
1160                        "id: {}\nevent: {SSE_EVENT_RELEASE_ACTIVATED}\ndata: {json}\n\n",
1161                        rec.get_event_id()
1162                    );
1163                    if stream.write_all(frame.as_bytes()).is_err() || stream.flush().is_err() {
1164                        return;
1165                    }
1166                    if rec.get_event_id() > highest {
1167                        highest = rec.get_event_id();
1168                    }
1169                }
1170            }
1171            highest
1172        }
1173        None => ota_store
1174            .read_channel_pointer(project, channel)
1175            .ok()
1176            .flatten()
1177            .map(|ptr: ChannelPointer| ptr.get_active_release_seq())
1178            .unwrap_or(0),
1179    };
1180    let mut idle_ticks: u32 = 0;
1181    while hub.is_running() {
1182        thread::sleep(Duration::from_millis(50));
1183        if let Ok(events) = ota_store.read_events_after(project, channel, last_sent_seq)
1184            && !events.is_empty()
1185        {
1186            idle_ticks = 0;
1187            for rec in events.into_iter() {
1188                if let Ok(json) = to_string(rec.get_event()) {
1189                    let frame: String = format!(
1190                        "id: {}\nevent: {SSE_EVENT_RELEASE_ACTIVATED}\ndata: {json}\n\n",
1191                        rec.get_event_id()
1192                    );
1193                    if stream.write_all(frame.as_bytes()).is_err() || stream.flush().is_err() {
1194                        return;
1195                    }
1196                    if rec.get_event_id() > last_sent_seq {
1197                        last_sent_seq = rec.get_event_id();
1198                    }
1199                }
1200            }
1201        } else {
1202            idle_ticks += 1;
1203            if idle_ticks >= 100 {
1204                idle_ticks = 0;
1205                if stream.write_all(SSE_PING_LINE.as_bytes()).is_err() || stream.flush().is_err() {
1206                    return;
1207                }
1208            }
1209        }
1210    }
1211}
1212
1213/// Extracts a single named parameter from a raw HTTP query string.
1214///
1215/// # Arguments
1216///
1217/// - `&str` - Query string without leading `?`.
1218/// - `&str` - Parameter key name.
1219///
1220/// # Returns
1221///
1222/// - `Option<String>` - Parameter value if found.
1223fn extract_query_param(query: &str, key: &str) -> Option<String> {
1224    for pair in query.split('&') {
1225        if let Some((param_key, param_val)) = pair.split_once('=')
1226            && param_key == key
1227        {
1228            return Some(param_val.to_string());
1229        }
1230    }
1231    None
1232}
1233
1234/// Serializes an `EmbeddedOtaResponse` onto a raw HTTP/1.1 `TcpStream` with CORS headers.
1235///
1236/// # Arguments
1237///
1238/// - `&mut TcpStream` - Client socket.
1239/// - `&EmbeddedOtaResponse` - Protocol-level v1 OTA response.
1240/// - `bool` - When `true`, suppresses body bytes (`HEAD` or `304`/`204`).
1241fn write_embedded_ota_response(
1242    stream: &mut TcpStream,
1243    resp: &EmbeddedOtaResponse,
1244    head_only: bool,
1245) {
1246    let status_code: u16 = resp.get_status_code();
1247    let omit_body: bool = head_only || status_code == 204 || status_code == 304;
1248    let body_len: usize = if status_code == 204 || status_code == 304 {
1249        0
1250    } else {
1251        resp.get_body().len()
1252    };
1253    let mut header_buf: String = format!(
1254        "HTTP/1.1 {status_code} {}\r\nContent-Type: {}\r\n{HTTP_EMBEDDED_CORS_BLOCK}",
1255        resp.get_status_text(),
1256        resp.get_content_type()
1257    );
1258    for (name, value) in resp.get_headers().iter() {
1259        header_buf.push_str(&format!("{name}: {value}\r\n"));
1260    }
1261    header_buf.push_str(&format!("Content-Length: {body_len}{HTTP_CONN_CLOSE_SEP}"));
1262    drop(stream.write_all(header_buf.as_bytes()));
1263    if !omit_body && !resp.get_body().is_empty() {
1264        drop(stream.write_all(resp.get_body()));
1265    }
1266    drop(stream.flush());
1267}
1268
1269/// Streams live Server-Sent Events (`event: reload` / `ota` / `error`) whenever `hub` increments revision.
1270///
1271/// # Arguments
1272///
1273/// - `TcpStream` - Long-lived client TCP stream.
1274/// - `&Arc<HmrHub>` - Shared HMR hub.
1275fn serve_sse_stream(mut stream: TcpStream, hub: &Arc<HmrHub>) {
1276    if stream.write_all(HTTP_SSE_HEADERS.as_bytes()).is_err() || stream.flush().is_err() {
1277        return;
1278    }
1279    let mut last_sent_rev: u64 = hub.revision();
1280    let mut idle_ticks: u32 = 0;
1281    while hub.is_running() {
1282        thread::sleep(Duration::from_millis(50));
1283        let cur_rev: u64 = hub.revision();
1284        if cur_rev != last_sent_rev {
1285            last_sent_rev = cur_rev;
1286            idle_ticks = 0;
1287            if let Some(ui_event) = hub.current_event() {
1288                let ev_name: &str = match ui_event.get_kind() {
1289                    HmrEventKind::Reload => HMR_EVENT_RELOAD,
1290                    HmrEventKind::OtaUpdate => HMR_EVENT_OTA,
1291                    HmrEventKind::BuildError => HMR_EVENT_ERROR,
1292                };
1293                let data: String = to_string_pretty(&ui_event)
1294                    .unwrap_or_else(|_| format!("{{\"revision\":{cur_rev}}}"))
1295                    .replace('\n', " ");
1296                let frame: String = format!("event: {ev_name}\ndata: {data}\n\n");
1297                if stream.write_all(frame.as_bytes()).is_err() || stream.flush().is_err() {
1298                    return;
1299                }
1300            }
1301        } else {
1302            idle_ticks += 1;
1303            if idle_ticks >= 100 {
1304                idle_ticks = 0;
1305                if stream.write_all(SSE_PING_LINE.as_bytes()).is_err() || stream.flush().is_err() {
1306                    return;
1307                }
1308            }
1309        }
1310    }
1311}
1312
1313/// Writes an HTTP/1.1 200 response with CORS, no-cache, and optional COOP/COEP headers, omitting the body on `HEAD` requests.
1314///
1315/// # Arguments
1316///
1317/// - `&mut TcpStream` - Client socket.
1318/// - `&str` - Content-Type header value.
1319/// - `&[u8]` - Response payload bytes.
1320/// - `bool` - When `true`, writes headers only (`HEAD`).
1321/// - `bool` - When `true`, emits `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` headers.
1322fn write_http_response(
1323    stream: &mut TcpStream,
1324    mime: &str,
1325    body: &[u8],
1326    head_only: bool,
1327    coop_coep: bool,
1328) {
1329    let isolation_hdrs: &str = if coop_coep {
1330        HTTP_COOP_COEP_HEADERS
1331    } else {
1332        ""
1333    };
1334    let header: String = format!(
1335        "{HTTP_200_PREFIX}{mime}{HTTP_CORS_HEADERS}{}{isolation_hdrs}{HTTP_CONN_CLOSE_SEP}",
1336        body.len()
1337    );
1338    drop(stream.write_all(header.as_bytes()));
1339    if !head_only {
1340        drop(stream.write_all(body));
1341    }
1342    drop(stream.flush());
1343}
1344
1345/// Strips a configured `base_url` prefix from an incoming request path when present.
1346///
1347/// # Arguments
1348///
1349/// - `&'a str` - Percent-decoded HTTP request path.
1350/// - `&str` - Configured base URL prefix (for example `""` or `"/docs"`).
1351///
1352/// # Returns
1353///
1354/// - `&'a str` - Relative path rooted at the output directory.
1355fn strip_base_prefix<'a>(path: &'a str, base_url: &str) -> &'a str {
1356    let normalized: &str = base_url.trim_matches('/');
1357    if normalized.is_empty() {
1358        return path;
1359    }
1360    let trimmed: &str = path.trim_start_matches('/');
1361    if let Some(rest) = trimmed.strip_prefix(normalized)
1362        && (rest.is_empty() || rest.starts_with('/'))
1363    {
1364        return rest;
1365    }
1366    path
1367}
1368
1369/// Decodes `%XX` percent-encoded byte sequences in a URL path into UTF-8 text.
1370///
1371/// # Arguments
1372///
1373/// - `&str` - Raw URL path component.
1374///
1375/// # Returns
1376///
1377/// - `String` - Decoded UTF-8 URL path.
1378fn percent_decode_path(input: &str) -> String {
1379    if !input.contains('%') {
1380        return input.to_string();
1381    }
1382    let bytes: &[u8] = input.as_bytes();
1383    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
1384    let mut item_index: usize = 0;
1385    while item_index < bytes.len() {
1386        if bytes[item_index] == ASCII_PERCENT
1387            && item_index + 2 < bytes.len()
1388            && let (Some(hi), Some(lo)) = (
1389                hex_nibble(bytes[item_index + 1]),
1390                hex_nibble(bytes[item_index + 2]),
1391            )
1392        {
1393            out.push((hi << 4) | lo);
1394            item_index += 3;
1395            continue;
1396        }
1397        out.push(bytes[item_index]);
1398        item_index += 1;
1399    }
1400    String::from_utf8(out).unwrap_or_else(|_| input.to_string())
1401}
1402
1403/// Converts a single ASCII hexadecimal byte into its 4-bit value.
1404///
1405/// # Arguments
1406///
1407/// - `u8` - Candidate ASCII hex byte.
1408///
1409/// # Returns
1410///
1411/// - `Option<u8>` - Numeric nibble (`0..=15`) when valid.
1412fn hex_nibble(byte: u8) -> Option<u8> {
1413    match byte {
1414        ASCII_DIGIT_ZERO..=ASCII_DIGIT_NINE => Some(byte - ASCII_DIGIT_ZERO),
1415        ASCII_LOWER_A..=ASCII_LOWER_F => Some(byte - ASCII_LOWER_A + 10),
1416        ASCII_UPPER_A..=ASCII_UPPER_F => Some(byte - ASCII_UPPER_A + 10),
1417        _ => None,
1418    }
1419}
1420
1421/// Resolves an HTTP request path safely within `out_dir` supporting clean URLs, `index.html`, and optional SPA route fallback.
1422///
1423/// # Arguments
1424///
1425/// - `&Path` - Served output directory root.
1426/// - `&str` - Sanitized URL path component.
1427/// - `bool` - When `true`, falls back to `out_dir/index.html` for non-asset client-side routes.
1428///
1429/// # Returns
1430///
1431/// - `Option<PathBuf>` - Existing file path inside `out_dir`, if found.
1432#[must_use]
1433pub fn resolve_static_file_with_spa(
1434    out_dir: &Path,
1435    url_path: &str,
1436    spa_fallback: bool,
1437) -> Option<PathBuf> {
1438    let trimmed: &str = url_path.trim_matches('/');
1439    let mut safe_rel: PathBuf = PathBuf::new();
1440    let mut last_seg: &str = "";
1441    for seg in trimmed.split('/') {
1442        if seg.is_empty() || seg == "." || seg == ".." {
1443            continue;
1444        }
1445        last_seg = seg;
1446        safe_rel.push(seg);
1447    }
1448    if safe_rel.as_os_str().is_empty() {
1449        let root_idx: PathBuf = out_dir.join(INDEX_HTML_NAME);
1450        return root_idx.is_file().then_some(root_idx);
1451    }
1452    let direct: PathBuf = out_dir.join(&safe_rel);
1453    if direct.is_file() {
1454        return Some(direct);
1455    }
1456    let clean_idx: PathBuf = direct.join(INDEX_HTML_NAME);
1457    if clean_idx.is_file() {
1458        return Some(clean_idx);
1459    }
1460    let html_file: PathBuf = out_dir.join(format!("{}.html", safe_rel.display()));
1461    if html_file.is_file() {
1462        return Some(html_file);
1463    }
1464    if spa_fallback && !last_seg.contains('.') {
1465        let root_idx: PathBuf = out_dir.join(INDEX_HTML_NAME);
1466        if root_idx.is_file() {
1467            return Some(root_idx);
1468        }
1469    }
1470    None
1471}
1472
1473/// Determines the HTTP `Content-Type` header for a static file path by extension.
1474///
1475/// # Arguments
1476///
1477/// - `&Path` - File path.
1478///
1479/// # Returns
1480///
1481/// - `&'static str` - Appropriate MIME type string.
1482#[must_use]
1483pub fn mime_type_for_path(path: &Path) -> &'static str {
1484    let Some(ext) = path.extension().and_then(|ext_os: &OsStr| ext_os.to_str()) else {
1485        return MIME_OCTET;
1486    };
1487    if ext.eq_ignore_ascii_case(EXT_HTML) {
1488        MIME_HTML
1489    } else if ext.eq_ignore_ascii_case(EXT_JSON) || ext.eq_ignore_ascii_case(EXT_MAP) {
1490        MIME_JSON
1491    } else if ext.eq_ignore_ascii_case(EXT_XML) {
1492        MIME_XML
1493    } else if ext.eq_ignore_ascii_case(EXT_CSS) {
1494        MIME_CSS
1495    } else if ext.eq_ignore_ascii_case(EXT_JS) || ext.eq_ignore_ascii_case(EXT_MJS) {
1496        MIME_JS
1497    } else if ext.eq_ignore_ascii_case(EXT_WASM) {
1498        MIME_WASM
1499    } else if ext.eq_ignore_ascii_case(EXT_EUVZ) || ext.eq_ignore_ascii_case(EXT_BR) {
1500        MIME_OCTET
1501    } else if ext.eq_ignore_ascii_case(EXT_SVG) {
1502        MIME_SVG
1503    } else if ext.eq_ignore_ascii_case(EXT_PNG) {
1504        MIME_PNG
1505    } else if ext.eq_ignore_ascii_case(EXT_JPG) || ext.eq_ignore_ascii_case(EXT_JPEG) {
1506        MIME_JPEG
1507    } else if ext.eq_ignore_ascii_case(EXT_WEBP) {
1508        MIME_WEBP
1509    } else if ext.eq_ignore_ascii_case(EXT_GIF) {
1510        MIME_GIF
1511    } else if ext.eq_ignore_ascii_case(EXT_AVIF) {
1512        MIME_AVIF
1513    } else if ext.eq_ignore_ascii_case(EXT_ICO) {
1514        MIME_ICO
1515    } else if ext.eq_ignore_ascii_case(EXT_WOFF2) {
1516        MIME_WOFF2
1517    } else if ext.eq_ignore_ascii_case(EXT_WOFF) {
1518        MIME_WOFF
1519    } else if ext.eq_ignore_ascii_case(EXT_TTF) {
1520        MIME_TTF
1521    } else if ext.eq_ignore_ascii_case(EXT_TXT) {
1522        MIME_TEXT
1523    } else {
1524        MIME_OCTET
1525    }
1526}
1527
1528/// Recursively populates `entries` with modification stamps for all watched files under `dir`.
1529///
1530/// # Arguments
1531///
1532/// - `&Path` - Current directory to scan.
1533/// - `&[&str]` - Allowed lowercase file extensions.
1534/// - `Option<&Path>` - Optional canonical output directory excluded from watching.
1535/// - `Option<&Path>` - Canonical path of `dir` when `exclude_dir` lies within `dir`.
1536/// - `bool` - Whether non-symlink child directories must be tested against `exclude_dir`.
1537/// - `&mut BTreeMap<PathBuf, FileStamp>` - Accumulator map.
1538///
1539/// # Returns
1540///
1541/// - `io::Result<()>` - Scan result.
1542pub(crate) fn scan_dir_stamps(
1543    dir: &Path,
1544    allowed_exts: &[&str],
1545    exclude_dir: Option<&Path>,
1546    canon_dir: Option<&Path>,
1547    check_real_exclude: bool,
1548    entries: &mut BTreeMap<PathBuf, FileStamp>,
1549) -> io::Result<()> {
1550    for entry_res in fs::read_dir(dir)? {
1551        let entry: DirEntry = entry_res?;
1552        let path: PathBuf = entry.path();
1553        if let Ok(ft) = entry.file_type() {
1554            if ft.is_dir() {
1555                let file_name: OsString = entry.file_name();
1556                let name: Cow<'_, str> = file_name.to_string_lossy();
1557                if should_skip_watch_dir(&name) {
1558                    continue;
1559                }
1560                if check_real_exclude && let Some(excluded) = exclude_dir {
1561                    if let Some(cur_canon) = canon_dir {
1562                        let child_canon: PathBuf = cur_canon.join(&file_name);
1563                        if child_canon == excluded || child_canon.starts_with(excluded) {
1564                            continue;
1565                        }
1566                        let recurse_check: bool = excluded.starts_with(&child_canon);
1567                        let next_canon: Option<&Path> =
1568                            recurse_check.then_some(child_canon.as_path());
1569                        scan_dir_stamps(
1570                            &path,
1571                            allowed_exts,
1572                            exclude_dir,
1573                            next_canon,
1574                            recurse_check,
1575                            entries,
1576                        )?;
1577                        continue;
1578                    }
1579                    let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
1580                    if canon == excluded || canon.starts_with(excluded) {
1581                        continue;
1582                    }
1583                }
1584                scan_dir_stamps(
1585                    &path,
1586                    allowed_exts,
1587                    exclude_dir,
1588                    None,
1589                    check_real_exclude,
1590                    entries,
1591                )?;
1592                continue;
1593            }
1594            if ft.is_file() {
1595                if has_allowed_extension(&path, allowed_exts)
1596                    && let Ok(meta) = entry.metadata()
1597                {
1598                    let _: Option<FileStamp> = entries.insert(path, stamp_from_metadata(&meta));
1599                }
1600                continue;
1601            }
1602        }
1603        let Ok(meta) = fs::metadata(&path) else {
1604            continue;
1605        };
1606        if meta.is_dir() {
1607            let file_name: OsString = entry.file_name();
1608            let name: Cow<'_, str> = file_name.to_string_lossy();
1609            if should_skip_watch_dir(&name) {
1610                continue;
1611            }
1612            if let Some(excluded) = exclude_dir {
1613                let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
1614                if canon == excluded || canon.starts_with(excluded) {
1615                    continue;
1616                }
1617                let recurse_check: bool = excluded.starts_with(&canon);
1618                let next_canon: Option<&Path> = recurse_check.then_some(canon.as_path());
1619                scan_dir_stamps(
1620                    &path,
1621                    allowed_exts,
1622                    exclude_dir,
1623                    next_canon,
1624                    recurse_check,
1625                    entries,
1626                )?;
1627                continue;
1628            }
1629            scan_dir_stamps(&path, allowed_exts, None, None, false, entries)?;
1630        } else if meta.is_file() && has_allowed_extension(&path, allowed_exts) {
1631            let _: Option<FileStamp> = entries.insert(path, stamp_from_metadata(&meta));
1632        }
1633    }
1634    Ok(())
1635}
1636
1637/// Returns `true` when directory `name` should be excluded from file watching.
1638///
1639/// # Arguments
1640///
1641/// - `&str` - Directory name.
1642///
1643/// # Returns
1644///
1645/// - `bool` - Whether the watcher skips this directory.
1646fn should_skip_watch_dir(name: &str) -> bool {
1647    name.starts_with('.')
1648        || WATCH_IGNORED_DIRS
1649            .iter()
1650            .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
1651}
1652
1653/// Returns `true` when `path` has an extension listed in `allowed_exts`.
1654///
1655/// # Arguments
1656///
1657/// - `&Path` - Candidate file path.
1658/// - `&[&str]` - Allowed lowercase extensions.
1659///
1660/// # Returns
1661///
1662/// - `bool` - Whether the file should be watched.
1663fn has_allowed_extension(path: &Path, allowed_exts: &[&str]) -> bool {
1664    path.extension()
1665        .and_then(|ext_os: &OsStr| ext_os.to_str())
1666        .is_some_and(|ext: &str| {
1667            allowed_exts
1668                .iter()
1669                .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
1670        })
1671}
1672
1673/// Extracts a deterministic `FileStamp` from filesystem `Metadata`.
1674///
1675/// # Arguments
1676///
1677/// - `&Metadata` - File metadata.
1678///
1679/// # Returns
1680///
1681/// - `FileStamp` - Modification timestamp and byte size pair.
1682fn stamp_from_metadata(meta: &Metadata) -> FileStamp {
1683    let nanos: u128 = meta
1684        .modified()
1685        .ok()
1686        .and_then(|modified_time: SystemTime| modified_time.duration_since(UNIX_EPOCH).ok())
1687        .map(|elapsed: Duration| elapsed.as_nanos())
1688        .unwrap_or(0);
1689    FileStamp::new(nanos, meta.len())
1690}