euv-cli 0.41.1

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, and new across Web, Android, iOS, iPadOS, macOS, Windows, and Linux.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
use super::*;

/// Builds a complete static documentation site from all `.md` files beneath `src_dir` into `out_dir`.
///
/// # Arguments
///
/// - `&Path` - Project or Markdown source root directory.
/// - `&Path` - Destination output directory.
/// - `&DocsBuildOptions` - Site title, base URL, clean URL, asset copy, and optional dev HMR configuration.
///
/// # Returns
///
/// - `io::Result<GeneratedSiteReport>` - Summary report of generated pages or I/O error.
pub fn build_docs_site(
    src_dir: &Path,
    out_dir: &Path,
    options: &DocsBuildOptions,
) -> io::Result<GeneratedSiteReport> {
    build_docs_bundle(src_dir, out_dir, options)
}

/// Compiles a fresh signed Dynamic WASM OTA hot-update bundle for version `version`.
///
/// # Arguments
///
/// - `u64` - Monotonic OTA bundle version number.
/// - `&str` - Human-readable title embedded into the executable `.wasm` module.
/// - `Vec<String>` - Source file paths triggering this hot update.
///
/// # Returns
///
/// - `OtaBundleState` - Signed manifest and executable `.wasm` bytes.
#[must_use]
pub fn build_dev_ota_state(
    version: u64,
    title: &str,
    changed_files: Vec<String>,
) -> OtaBundleState {
    let accent_hex: u32 = if version.is_multiple_of(2) {
        0x2563EB
    } else {
        0x059669
    };
    let wasm_bytes: Vec<u8> = build_partial_widget_wasm(title, version, accent_hex);
    let checksum: u64 = compute_wasm_checksum(&wasm_bytes);
    let signature: String = compute_wasm_signature(&wasm_bytes, version, OTA_DEV_SIGNING_KEY);
    let manifest: OtaManifest = OtaManifest::new(
        version,
        OTA_SLOT_DEV.to_string(),
        OTA_MODULE_ENDPOINT.to_string(),
        checksum,
        signature,
        wasm_bytes.len(),
        changed_files,
    );
    OtaBundleState::new(manifest, wasm_bytes)
}

/// Injects the dev-only SSE hot-reload script right before `</body>` in an HTML document.
///
/// # Arguments
///
/// - `&str` - Original HTML source string.
/// - `&str` - SSE HMR endpoint URL path.
///
/// # Returns
///
/// - `String` - HTML document containing the live-reload client snippet.
#[must_use]
pub fn inject_dev_hmr_into_html(html: &str, hmr_endpoint: &str) -> String {
    if html.contains(hmr_endpoint) {
        return html.to_string();
    }
    let snippet: String = format!("{DEV_HMR_SCRIPT_PREFIX}{hmr_endpoint}{DEV_HMR_SCRIPT_SUFFIX}");
    if let Some(pos) = html.rfind(HTML_BODY_CLOSE_TAG) {
        let mut out: String = String::with_capacity(html.len() + snippet.len());
        out.push_str(&html[..pos]);
        out.push_str(&snippet);
        out.push_str(&html[pos..]);
        out
    } else {
        format!("{html}{snippet}")
    }
}

/// Starts a live HTTP, SSE hot-reload, file-watcher, and Dynamic WASM OTA dev server in background threads.
///
/// # Arguments
///
/// - `DevServerConfig` - Full dev server configuration.
///
/// # Returns
///
/// - `io::Result<DevServerHandle>` - Running server handle or startup error.
pub fn start_dev_server(config: DevServerConfig) -> io::Result<DevServerHandle> {
    if config.get_target() != DevTargetArg::Native {
        fs::create_dir_all(config.get_out_dir())?;
    }
    let mut initial_pages: usize = 0;
    let mode_label: String = match config.get_target() {
        DevTargetArg::Docs => {
            let docs_opts: DocsBuildOptions = docs_options_for_dev(&config);
            let report: GeneratedSiteReport =
                build_docs_site(config.get_src_dir(), config.get_out_dir(), &docs_opts)?;
            initial_pages = report.get_page_count();
            MODE_LABEL_DOCS.to_string()
        }
        DevTargetArg::Web => {
            rebuild_web_dev_bundle(&config)?;
            MODE_LABEL_WEB.to_string()
        }
        DevTargetArg::Native => MODE_LABEL_NATIVE.to_string(),
    };
    let initial_ota: OtaBundleState = build_dev_ota_state(1, OTA_INITIAL_TITLE, Vec::new());
    let hub: Arc<HmrHub> = Arc::new(HmrHub::new(initial_ota));
    let bind_addr: String = format!("{}:{}", config.get_host(), config.get_port());
    let listener: TcpListener = TcpListener::bind(&bind_addr)?;
    let address: SocketAddr = listener.local_addr()?;
    listener.set_nonblocking(true)?;
    let serve_ctx: HttpServeContext = HttpServeContext {
        out_dir: config.get_out_dir().clone(),
        base_url: config.get_base_url().clone(),
        enable_ota: config.get_enable_ota(),
        hub: Arc::clone(&hub),
    };
    let http_thread: JoinHandle<()> = thread::spawn(move || {
        run_http_accept_loop(listener, serve_ctx);
    });
    let watch_hub: Arc<HmrHub> = Arc::clone(&hub);
    let watch_cfg: DevServerConfig = config.clone();
    let dev_url: String = format!("http://{address}");
    let watch_thread: JoinHandle<()> = thread::spawn(move || {
        run_watch_rebuild_loop(watch_cfg, dev_url, watch_hub);
    });
    Ok(DevServerHandle {
        address,
        out_dir: config.get_out_dir().clone(),
        mode: mode_label,
        page_count: initial_pages,
        hub,
        http_thread: Some(http_thread),
        watch_thread: Some(watch_thread),
    })
}

/// Starts the dev server and either exits immediately (`once=true`) or serves continuously until interrupted.
///
/// # Arguments
///
/// - `DevServerConfig` - Dev server configuration.
///
/// # Returns
///
/// - `io::Result<DevServerReport>` - Server startup summary report or I/O error.
pub fn run_dev_blocking(config: DevServerConfig) -> io::Result<DevServerReport> {
    let once: bool = config.get_once();
    let mut handle: DevServerHandle = start_dev_server(config)?;
    let report: DevServerReport = handle.report();
    if once {
        handle.shutdown();
        return Ok(report);
    }
    eprintln!(
        "[euv-dev] mode={} url={} hmr={} ota={}",
        report.get_mode(),
        report.get_url(),
        report.get_hmr_url(),
        report.get_ota_manifest_url()
    );
    while handle.hub.is_running() {
        thread::sleep(Duration::from_millis(250));
    }
    handle.shutdown();
    Ok(report)
}

/// Constructs `DocsBuildOptions` wired for live dev hot reload from a `DevServerConfig`.
///
/// # Arguments
///
/// - `&DevServerConfig` - Active dev server configuration.
///
/// # Returns
///
/// - `DocsBuildOptions` - Populated docs build options with dev HMR endpoint.
fn docs_options_for_dev(config: &DevServerConfig) -> DocsBuildOptions {
    let mut opts: DocsBuildOptions = DocsBuildOptions::default();
    opts.set_title(config.try_get_title().clone())
        .set_base_url(config.get_base_url().clone())
        .set_hmr_endpoint(Some(HMR_ENDPOINT.to_string()))
        .set_assets_root(Some(config.get_src_dir().clone()))
        .set_clean_urls(true);
    opts
}

/// Runs the non-blocking HTTP accept loop dispatching static files, SSE `/__euv_hmr`, and OTA endpoints.
///
/// # Arguments
///
/// - `TcpListener` - Bound non-blocking TCP listener.
/// - `HttpServeContext` - Output directory, base prefix, OTA gate, and shared HMR hub.
fn run_http_accept_loop(listener: TcpListener, ctx: HttpServeContext) {
    while ctx.get_hub().is_running() {
        match listener.accept() {
            Ok((stream, _)) => {
                if !ctx.get_hub().is_running() {
                    break;
                }
                let conn_ctx: HttpServeContext = ctx.clone();
                drop(thread::spawn(move || {
                    serve_http_connection(stream, &conn_ctx);
                }));
            }
            Err(err) if err.kind() == ErrorKind::WouldBlock => {
                thread::sleep(Duration::from_millis(20));
            }
            Err(_) => {
                thread::sleep(Duration::from_millis(50));
            }
        }
    }
}

/// Runs the recursive file watcher loop rebuilding docs, web bundles, or native binaries on file changes.
///
/// # Arguments
///
/// - `DevServerConfig` - Active dev server configuration.
/// - `String` - Base HTTP URL of the active dev server forwarded to native child processes.
/// - `Arc<HmrHub>` - Shared HMR and OTA hub.
fn run_watch_rebuild_loop(config: DevServerConfig, dev_url: String, hub: Arc<HmrHub>) {
    let allowed_exts: &[&str] = match config.get_target() {
        DevTargetArg::Docs => &WATCH_EXTS_DOCS,
        DevTargetArg::Web | DevTargetArg::Native => &WATCH_EXTS_CODE,
    };
    let exclude_out: Option<&Path> = if config.get_target() == DevTargetArg::Native {
        None
    } else {
        Some(config.get_out_dir().as_path())
    };
    let mut prev_snap: WatchSnapshot =
        WatchSnapshot::scan_excluding(config.get_src_dir(), allowed_exts, exclude_out)
            .unwrap_or_default();
    let mut native_child: Option<Child> =
        if config.get_target() == DevTargetArg::Native && !config.get_once() {
            spawn_native_app_child(&config, &dev_url).ok()
        } else {
            None
        };
    let poll_dur: Duration = Duration::from_millis(config.get_poll_ms().clamp(50, 5000));
    while hub.is_running() {
        thread::sleep(poll_dur);
        if !hub.is_running() {
            break;
        }
        let Ok(next_snap) =
            WatchSnapshot::scan_excluding(config.get_src_dir(), allowed_exts, exclude_out)
        else {
            continue;
        };
        let changes: FileChangeSet = prev_snap.diff(&next_snap);
        if changes.is_empty() {
            continue;
        }
        prev_snap = next_snap;
        let changed_files: Vec<String> = changes.all_paths();
        match config.get_target() {
            DevTargetArg::Docs => {
                let docs_opts: DocsBuildOptions = docs_options_for_dev(&config);
                match build_docs_site(config.get_src_dir(), config.get_out_dir(), &docs_opts) {
                    Ok(report) => {
                        let next_ver: u64 = hub.revision() + 1;
                        if config.get_enable_ota() {
                            let ota_title: String = format!(
                                "Docs Hot Update v{next_ver} ({} pages)",
                                report.get_page_count()
                            );
                            hub.set_ota_state(build_dev_ota_state(
                                next_ver,
                                &ota_title,
                                changed_files.clone(),
                            ));
                        }
                        let _: u64 = hub.publish(
                            HmrEventKind::Reload,
                            format!("{MSG_DOCS_REBUILT} ({} pages)", report.get_page_count()),
                            changed_files,
                        );
                    }
                    Err(err) => {
                        let _: u64 =
                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
                    }
                }
            }
            DevTargetArg::Web => match rebuild_web_dev_bundle(&config) {
                Ok(()) => {
                    let next_ver: u64 = hub.revision() + 1;
                    if config.get_enable_ota() {
                        let ota_title: String = format!("Web WASM Hot Update v{next_ver}");
                        hub.set_ota_state(build_dev_ota_state(
                            next_ver,
                            &ota_title,
                            changed_files.clone(),
                        ));
                    }
                    let _: u64 = hub.publish(
                        HmrEventKind::Reload,
                        MSG_WEB_REBUILT.to_string(),
                        changed_files,
                    );
                }
                Err(err) => {
                    let _: u64 =
                        hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
                }
            },
            DevTargetArg::Native => {
                if let Some(mut old_child) = native_child.take() {
                    drop(old_child.kill());
                    drop(old_child.wait());
                }
                match spawn_native_app_child(&config, &dev_url) {
                    Ok(child) => {
                        native_child = Some(child);
                        let next_ver: u64 = hub.revision() + 1;
                        if config.get_enable_ota() {
                            let ota_title: String = format!("Native OTA Hot Update v{next_ver}");
                            hub.set_ota_state(build_dev_ota_state(
                                next_ver,
                                &ota_title,
                                changed_files.clone(),
                            ));
                        }
                        let _: u64 = hub.publish(
                            HmrEventKind::OtaUpdate,
                            MSG_NATIVE_RESTARTED.to_string(),
                            changed_files,
                        );
                    }
                    Err(err) => {
                        let _: u64 =
                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
                    }
                }
            }
        }
    }
    if let Some(mut child) = native_child.take() {
        drop(child.kill());
        drop(child.wait());
    }
}

/// Rebuilds the WebAssembly bundle into `config.out_dir` and injects the dev SSE hot-reload script.
///
/// # Arguments
///
/// - `&DevServerConfig` - Active web dev configuration.
///
/// # Returns
///
/// - `io::Result<()>` - Build result.
fn rebuild_web_dev_bundle(config: &DevServerConfig) -> io::Result<()> {
    let out_dir: &Path = config.get_out_dir();
    let mut wp_args: Vec<String> = vec![
        ARG_BUILD.to_string(),
        ARG_TARGET.to_string(),
        ARG_TARGET_WEB.to_string(),
        ARG_OUT_DIR.to_string(),
        out_dir.display().to_string(),
    ];
    if config.get_release() {
        wp_args.push(ARG_RELEASE.to_string());
    }
    let output: Output = Command::new(BIN_WASM_PACK)
        .args(&wp_args)
        .current_dir(config.get_src_dir())
        .output()?;
    if !output.status.success() {
        let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
        return Err(Error::other(format!("{ERR_STEP_FAILED}: {stderr}")));
    }
    if out_dir.exists() {
        let index_path: PathBuf = package_zero_js_web_bundle(out_dir, WEB_BUNDLE_TITLE)?;
        let html: String = fs::read_to_string(&index_path)?;
        let with_hmr: String = inject_dev_hmr_into_html(&html, HMR_ENDPOINT);
        fs::write(&index_path, with_hmr)?;
    }
    Ok(())
}

/// Spawns a fresh native `cargo run` child process with live HMR/OTA endpoint env vars.
///
/// # Arguments
///
/// - `&DevServerConfig` - Active native dev configuration.
/// - `&str` - Base HTTP URL of the active dev server.
///
/// # Returns
///
/// - `io::Result<Child>` - Spawned child process handle or error.
fn spawn_native_app_child(config: &DevServerConfig, dev_url: &str) -> io::Result<Child> {
    let step: BuildStep = resolve_run_step(
        TargetArg::Native,
        config.get_render(),
        config.get_release(),
        config.try_get_package().as_deref(),
    );
    let mut cmd: Command = Command::new(step.get_program());
    let _: &mut Command = cmd
        .args(step.get_args())
        .current_dir(config.get_src_dir())
        .stdin(Stdio::null())
        .env(ENV_DEV_URL, dev_url)
        .env(ENV_HMR_URL, format!("{dev_url}{HMR_ENDPOINT}"));
    if config.get_enable_ota() {
        let _: &mut Command = cmd
            .env(
                ENV_OTA_MANIFEST_URL,
                format!("{dev_url}{OTA_MANIFEST_ENDPOINT}"),
            )
            .env(
                ENV_OTA_MODULE_URL,
                format!("{dev_url}{OTA_MODULE_ENDPOINT}"),
            );
    }
    cmd.spawn()
}

/// Handles a single incoming HTTP/1.1 connection for static files, SSE `/__euv_hmr`, or Dynamic WASM OTA.
///
/// # Arguments
///
/// - `TcpStream` - Connected client socket.
/// - `&HttpServeContext` - Output directory, base prefix, OTA gate, and shared HMR hub.
fn serve_http_connection(mut stream: TcpStream, ctx: &HttpServeContext) {
    drop(stream.set_nonblocking(false));
    drop(stream.set_read_timeout(Some(Duration::from_secs(3))));
    let req_line: String = {
        let mut reader: BufReader<&TcpStream> = BufReader::new(&stream);
        let mut line: String = String::new();
        if reader.read_line(&mut line).is_err() || line.is_empty() {
            return;
        }
        let mut header_count: usize = 0;
        while header_count < 64 {
            let mut hdr: String = String::new();
            match reader.read_line(&mut hdr) {
                Ok(0) => break,
                Ok(_) if hdr == "\r\n" || hdr == "\n" => break,
                Ok(_) => header_count += 1,
                Err(_) => break,
            }
        }
        line
    };
    let mut parts: SplitWhitespace<'_> = req_line.split_whitespace();
    let method: &str = parts.next().unwrap_or("");
    let raw_target: &str = parts.next().unwrap_or("/");
    if method.eq_ignore_ascii_case(HTTP_METHOD_OPTIONS) {
        drop(stream.write_all(HTTP_204_OPTIONS_RESP.as_bytes()));
        drop(stream.flush());
        return;
    }
    let head_only: bool = method.eq_ignore_ascii_case(HTTP_METHOD_HEAD);
    let path_only: &str = raw_target.split('?').next().unwrap_or("/");
    let hub: &Arc<HmrHub> = ctx.get_hub();
    if path_only == HMR_ENDPOINT {
        serve_sse_stream(stream, hub);
        return;
    }
    if path_only == OTA_MANIFEST_ENDPOINT {
        if ctx.get_enable_ota()
            && let Some(ota) = hub.ota_snapshot()
            && let Ok(json) = to_string_pretty(ota.get_manifest())
        {
            write_http_response(&mut stream, MIME_JSON, json.as_bytes(), head_only);
            return;
        }
        drop(stream.write_all(HTTP_404_RESP.as_bytes()));
        return;
    }
    if path_only == OTA_MODULE_ENDPOINT {
        if ctx.get_enable_ota()
            && let Some(ota) = hub.ota_snapshot()
        {
            write_http_response(
                &mut stream,
                MIME_WASM,
                ota.get_wasm_bytes().as_slice(),
                head_only,
            );
            return;
        }
        drop(stream.write_all(HTTP_404_RESP.as_bytes()));
        return;
    }
    if path_only == DEV_STATUS_ENDPOINT {
        let payload: String = match hub.current_event() {
            Some(ev) => to_string_pretty(&ev).unwrap_or_else(|_| EMPTY_JSON_OBJECT.to_string()),
            None => format!("{{\"revision\":{}}}", hub.revision()),
        };
        write_http_response(&mut stream, MIME_JSON, payload.as_bytes(), head_only);
        return;
    }
    let decoded_path: String = percent_decode_path(path_only);
    let stripped_path: &str = strip_base_prefix(&decoded_path, ctx.get_base_url());
    if let Some(file_path) = resolve_static_file(ctx.get_out_dir(), stripped_path)
        && let Ok(bytes) = fs::read(&file_path)
    {
        let mime: &str = mime_type_for_path(&file_path);
        write_http_response(&mut stream, mime, &bytes, head_only);
        return;
    }
    drop(stream.write_all(HTTP_404_RESP.as_bytes()));
}

/// Streams live Server-Sent Events (`event: reload` / `ota` / `error`) whenever `hub` increments revision.
///
/// # Arguments
///
/// - `TcpStream` - Long-lived client TCP stream.
/// - `&Arc<HmrHub>` - Shared HMR hub.
fn serve_sse_stream(mut stream: TcpStream, hub: &Arc<HmrHub>) {
    if stream.write_all(HTTP_SSE_HEADERS.as_bytes()).is_err() || stream.flush().is_err() {
        return;
    }
    let mut last_sent_rev: u64 = hub.revision();
    let mut idle_ticks: u32 = 0;
    while hub.is_running() {
        thread::sleep(Duration::from_millis(50));
        let cur_rev: u64 = hub.revision();
        if cur_rev != last_sent_rev {
            last_sent_rev = cur_rev;
            idle_ticks = 0;
            if let Some(ev) = hub.current_event() {
                let ev_name: &str = match ev.get_kind() {
                    HmrEventKind::Reload => HMR_EVENT_RELOAD,
                    HmrEventKind::OtaUpdate => HMR_EVENT_OTA,
                    HmrEventKind::BuildError => HMR_EVENT_ERROR,
                };
                let data: String = to_string_pretty(&ev)
                    .unwrap_or_else(|_| format!("{{\"revision\":{cur_rev}}}"))
                    .replace('\n', " ");
                let frame: String = format!("event: {ev_name}\ndata: {data}\n\n");
                if stream.write_all(frame.as_bytes()).is_err() || stream.flush().is_err() {
                    return;
                }
            }
        } else {
            idle_ticks += 1;
            if idle_ticks >= 100 {
                idle_ticks = 0;
                if stream.write_all(SSE_PING_LINE.as_bytes()).is_err() || stream.flush().is_err() {
                    return;
                }
            }
        }
    }
}

/// Writes an HTTP/1.1 200 response with CORS and no-cache headers, omitting the body on `HEAD` requests.
///
/// # Arguments
///
/// - `&mut TcpStream` - Client socket.
/// - `&str` - Content-Type header value.
/// - `&[u8]` - Response payload bytes.
/// - `bool` - When `true`, writes headers only (`HEAD`).
fn write_http_response(stream: &mut TcpStream, mime: &str, body: &[u8], head_only: bool) {
    let header: String = format!(
        "{HTTP_200_PREFIX}{mime}{HTTP_CORS_HEADERS}{}{HTTP_CONN_CLOSE_SEP}",
        body.len()
    );
    drop(stream.write_all(header.as_bytes()));
    if !head_only {
        drop(stream.write_all(body));
    }
    drop(stream.flush());
}

/// Strips a configured `base_url` prefix from an incoming request path when present.
///
/// # Arguments
///
/// - `&'a str` - Percent-decoded HTTP request path.
/// - `&str` - Configured base URL prefix (for example `""` or `"/docs"`).
///
/// # Returns
///
/// - `&'a str` - Relative path rooted at the output directory.
fn strip_base_prefix<'a>(path: &'a str, base_url: &str) -> &'a str {
    let normalized: &str = base_url.trim_matches('/');
    if normalized.is_empty() {
        return path;
    }
    let trimmed: &str = path.trim_start_matches('/');
    if let Some(rest) = trimmed.strip_prefix(normalized)
        && (rest.is_empty() || rest.starts_with('/'))
    {
        return rest;
    }
    path
}

/// Decodes `%XX` percent-encoded byte sequences in a URL path into UTF-8 text.
///
/// # Arguments
///
/// - `&str` - Raw URL path component.
///
/// # Returns
///
/// - `String` - Decoded UTF-8 URL path.
fn percent_decode_path(input: &str) -> String {
    let bytes: &[u8] = input.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i: usize = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
        {
            out.push((hi << 4) | lo);
            i += 3;
            continue;
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8(out).unwrap_or_else(|_| input.to_string())
}

/// Converts a single ASCII hexadecimal byte into its 4-bit value.
///
/// # Arguments
///
/// - `u8` - Candidate ASCII hex byte.
///
/// # Returns
///
/// - `Option<u8>` - Numeric nibble (`0..=15`) when valid.
fn hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// Resolves an HTTP request path safely within `out_dir` supporting clean URLs and `index.html` fallbacks.
///
/// # Arguments
///
/// - `&Path` - Served output directory root.
/// - `&str` - Sanitized URL path component.
///
/// # Returns
///
/// - `Option<PathBuf>` - Existing file path inside `out_dir`, if found.
fn resolve_static_file(out_dir: &Path, url_path: &str) -> Option<PathBuf> {
    let trimmed: &str = url_path.trim_matches('/');
    let mut safe_rel: PathBuf = PathBuf::new();
    for seg in trimmed.split('/') {
        if seg.is_empty() || seg == "." || seg == ".." {
            continue;
        }
        safe_rel.push(seg);
    }
    if safe_rel.as_os_str().is_empty() {
        let root_idx: PathBuf = out_dir.join(INDEX_HTML_NAME);
        return root_idx.is_file().then_some(root_idx);
    }
    let direct: PathBuf = out_dir.join(&safe_rel);
    if direct.is_file() {
        return Some(direct);
    }
    let clean_idx: PathBuf = direct.join(INDEX_HTML_NAME);
    if clean_idx.is_file() {
        return Some(clean_idx);
    }
    let html_file: PathBuf = out_dir.join(format!("{}.html", safe_rel.display()));
    if html_file.is_file() {
        return Some(html_file);
    }
    None
}

/// Determines the HTTP `Content-Type` header for a static file path by extension.
///
/// # Arguments
///
/// - `&Path` - File path.
///
/// # Returns
///
/// - `&'static str` - Appropriate MIME type string.
#[must_use]
pub fn mime_type_for_path(path: &Path) -> &'static str {
    let ext: String = path
        .extension()
        .and_then(|s: &OsStr| s.to_str())
        .map(str::to_ascii_lowercase)
        .unwrap_or_default();
    match ext.as_str() {
        EXT_HTML => MIME_HTML,
        EXT_JSON => MIME_JSON,
        EXT_XML => MIME_XML,
        EXT_CSS => MIME_CSS,
        EXT_WASM => MIME_WASM,
        EXT_SVG => MIME_SVG,
        EXT_PNG => MIME_PNG,
        EXT_JPG | EXT_JPEG => MIME_JPEG,
        EXT_WEBP => MIME_WEBP,
        _ => MIME_OCTET,
    }
}

/// Recursively populates `entries` with modification stamps for all watched files under `dir`.
///
/// # Arguments
///
/// - `&Path` - Current directory to scan.
/// - `&[&str]` - Allowed lowercase file extensions.
/// - `Option<&Path>` - Optional canonical output directory excluded from watching.
/// - `&mut BTreeMap<PathBuf, FileStamp>` - Accumulator map.
///
/// # Returns
///
/// - `io::Result<()>` - Scan result.
pub(crate) fn scan_dir_stamps(
    dir: &Path,
    allowed_exts: &[&str],
    exclude_dir: Option<&Path>,
    entries: &mut BTreeMap<PathBuf, FileStamp>,
) -> io::Result<()> {
    for entry_res in fs::read_dir(dir)? {
        let entry: DirEntry = entry_res?;
        let path: PathBuf = entry.path();
        if path.is_dir() {
            let name: String = entry.file_name().to_string_lossy().into_owned();
            if should_skip_watch_dir(&name) {
                continue;
            }
            if let Some(excluded) = exclude_dir {
                let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
                if canon == excluded || canon.starts_with(excluded) {
                    continue;
                }
            }
            scan_dir_stamps(&path, allowed_exts, exclude_dir, entries)?;
        } else if path.is_file()
            && has_allowed_extension(&path, allowed_exts)
            && let Ok(meta) = fs::metadata(&path)
        {
            entries.insert(path, stamp_from_metadata(&meta));
        }
    }
    Ok(())
}

/// Returns `true` when directory `name` should be excluded from file watching.
///
/// # Arguments
///
/// - `&str` - Directory name.
///
/// # Returns
///
/// - `bool` - Whether the watcher skips this directory.
fn should_skip_watch_dir(name: &str) -> bool {
    name.starts_with('.')
        || WATCH_IGNORED_DIRS
            .iter()
            .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
}

/// Returns `true` when `path` has an extension listed in `allowed_exts`.
///
/// # Arguments
///
/// - `&Path` - Candidate file path.
/// - `&[&str]` - Allowed lowercase extensions.
///
/// # Returns
///
/// - `bool` - Whether the file should be watched.
fn has_allowed_extension(path: &Path, allowed_exts: &[&str]) -> bool {
    path.extension()
        .and_then(|s: &OsStr| s.to_str())
        .is_some_and(|ext: &str| {
            allowed_exts
                .iter()
                .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
        })
}

/// Extracts a deterministic `FileStamp` from filesystem `Metadata`.
///
/// # Arguments
///
/// - `&Metadata` - File metadata.
///
/// # Returns
///
/// - `FileStamp` - Modification timestamp and byte size pair.
fn stamp_from_metadata(meta: &Metadata) -> FileStamp {
    let nanos: u128 = meta
        .modified()
        .ok()
        .and_then(|t: SystemTime| t.duration_since(UNIX_EPOCH).ok())
        .map(|d: Duration| d.as_nanos())
        .unwrap_or(0);
    FileStamp::new(nanos, meta.len())
}