euv-cli 0.50.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
use super::*;

/// Normalizes a Web asset URL base prefix to match `scripts/build/build-web.sh` semantics.
///
/// # Arguments
///
/// - `&str` - Raw `--base` prefix (e.g. `""`, `"."`, `"./"`, `"/"`, `"/euv"`, `"sub/path"`).
///
/// # Returns
///
/// - `String` - Normalized prefix ending with `/` (default `"./"`).
#[must_use]
pub fn normalize_web_asset_base(raw: &str) -> String {
    let trimmed: &str = raw.trim();
    if trimmed.is_empty() || trimmed == "." || trimmed == "./" {
        return WEB_DEFAULT_ASSET_BASE.to_string();
    }
    if trimmed == "/" {
        return "/".to_string();
    }
    let without_trailing: &str = trimmed.trim_end_matches('/');
    if without_trailing.is_empty() {
        return "/".to_string();
    }
    if without_trailing.starts_with('/') || without_trailing.starts_with("./") {
        format!("{without_trailing}/")
    } else {
        format!("./{without_trailing}/")
    }
}

/// Composes `RUSTFLAGS` for `wasm32-unknown-unknown` preserving bulk-memory, `getrandom_backend="wasm_js"`, and `simd128`.
///
/// # Arguments
///
/// - `Option<&str>` - Existing `RUSTFLAGS` environment value, if any.
///
/// # Returns
///
/// - `String` - Complete `RUSTFLAGS` string safe against `.cargo/config.toml` override drops.
#[must_use]
pub fn build_web_rustflags(existing: Option<&str>) -> String {
    let mut parts: Vec<String> = Vec::new();
    let base: &str = existing.map(str::trim).unwrap_or("");
    if !base.is_empty() {
        parts.push(base.to_string());
    }
    if !base.contains(WEB_RUSTFLAG_BULK_MEMORY_TOKEN) {
        parts.push(WEB_RUSTFLAG_BULK_MEMORY.to_string());
    }
    if !base.contains(WEB_RUSTFLAG_GETRANDOM_TOKEN) {
        parts.push(WEB_RUSTFLAG_GETRANDOM.to_string());
    }
    if !base.contains(WEB_RUSTFLAG_SIMD128_TOKEN) {
        parts.push(WEB_RUSTFLAG_SIMD128.to_string());
    }
    parts.join(" ")
}

/// Strips ES module exports and rewrites `import.meta.url` WASM resolution inside `wasm-bindgen` glue JS.
///
/// # Arguments
///
/// - `&str` - Raw generated `wasm-bindgen` web-target JS glue text.
/// - `&str` - Exact `<lib>_bg.wasm` filename.
/// - `&str` - Normalized asset base prefix (e.g. `"./"` or `"/euv/"`).
///
/// # Returns
///
/// - `String` - Clean inline JavaScript loader ready to embed inside `<script type="module">`.
#[must_use]
pub fn transform_web_bindgen_glue(raw_js: &str, wasm_file: &str, asset_base: &str) -> String {
    let normalized_base: String = normalize_web_asset_base(asset_base);
    let wasm_href: String = format!("{normalized_base}{wasm_file}");
    let single_url_expr: String = format!("new URL('{wasm_file}', import.meta.url)");
    let double_url_expr: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
    let replacement: String = format!("'{wasm_href}'");
    let rewritten: String = raw_js
        .replace(&single_url_expr, &replacement)
        .replace(&double_url_expr, &replacement);
    let cleaned_lines: Vec<String> = rewritten
        .lines()
        .filter(|line: &&str| {
            let trimmed: &str = line.trim_start();
            !trimmed.starts_with(WEB_EXPORT_BRACE) && !trimmed.starts_with(WEB_EXPORT_DEFAULT)
        })
        .map(|line: &str| {
            line.strip_prefix(WEB_EXPORT_PREFIX)
                .unwrap_or(line)
                .to_string()
        })
        .collect();
    cleaned_lines.join("\n")
}

/// Renders the self-contained zero-JS `index.html` / `404.html` document with preload hint, tap-highlight resets, and streaming splash loader.
///
/// # Arguments
///
/// - `&str` - Page title text.
/// - `&str` - Normalized asset base URL prefix (`"./"` default).
/// - `&str` - Exact `<lib>_bg.wasm` filename.
/// - `&str` - Raw `wasm-bindgen` web-target JS glue text.
/// - `&str` - Self-contained PNG `data:image/png;base64,...` icon URI.
///
/// # Returns
///
/// - `String` - Complete HTML document string.
#[must_use]
pub fn render_zero_js_web_html(
    title: &str,
    asset_base: &str,
    wasm_file: &str,
    raw_js_glue: &str,
    logo_data_uri: &str,
) -> String {
    let normalized_base: String = normalize_web_asset_base(asset_base);
    let wasm_href: String = format!("{normalized_base}{wasm_file}");
    let cleaned_glue: String = transform_web_bindgen_glue(raw_js_glue, wasm_file, &normalized_base);
    let safe_title: String = escape_web_html(title);
    let mut html: String = String::with_capacity(
        cleaned_glue.len() + safe_title.len() * 2 + logo_data_uri.len() * 3 + 4_096,
    );
    html.push_str(WEB_SHELL_HEAD_OPEN);
    html.push_str(WEB_SHELL_PRELOAD_OPEN);
    html.push_str(&wasm_href);
    html.push_str(WEB_SHELL_PRELOAD_CLOSE);
    html.push_str(WEB_SHELL_FAVICON_OPEN);
    html.push_str(logo_data_uri);
    html.push_str(WEB_SHELL_APPLE_ICON_MID);
    html.push_str(logo_data_uri);
    html.push_str(WEB_SHELL_TITLE_OPEN);
    html.push_str(&safe_title);
    html.push_str(WEB_SHELL_STYLE_AND_LOADER);
    html.push_str(logo_data_uri);
    html.push_str(WEB_SHELL_LOGO_END);
    html.push_str(&safe_title);
    html.push_str(WEB_SHELL_SCRIPT_OPEN);
    html.push_str(&cleaned_glue);
    html.push_str(WEB_SHELL_BOOT_OPEN);
    html.push_str(&wasm_href);
    html.push_str(WEB_SHELL_BOOT_BODY);
    html
}

/// Packages a `wasm-bindgen` output directory into a verified zero-JS bundle (`index.html`, `404.html`, `.nojekyll`, icons, `euv-release.json`).
///
/// # Arguments
///
/// - `&Path` - Output directory containing `<lib>_bg.wasm` and `<lib>.js`.
/// - `&str` - HTML page title.
/// - `&str` - Asset URL base prefix (`"./"` default).
/// - `&str` - Numeric semantic version string written to `euv-release.json`.
/// - `Option<&Path>` - Optional custom PNG icon path override.
/// - `bool` - When `true`, enforces all release invariants (0 `.js`, 0 AI-schema leaks, preload/404/SHA-256 verification).
///
/// # Returns
///
/// - `io::Result<ReleaseAssetManifest>` - Written (and optionally verified) `euv-release.json` manifest.
pub fn package_web_bundle_directory(
    out_dir: &Path,
    title: &str,
    asset_base: &str,
    version: &str,
    custom_icon: Option<&Path>,
    verify_release: bool,
) -> io::Result<ReleaseAssetManifest> {
    let dir_meta: Metadata = fs::symlink_metadata(out_dir)?;
    if dir_meta.file_type().is_symlink() || !dir_meta.is_dir() {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_WEB_SYMLINK_OUT}: {}", out_dir.display()),
        ));
    }
    let normalized_base: String = normalize_web_asset_base(asset_base);
    let mut wasm_name: Option<String> = None;
    let mut loader_path: Option<PathBuf> = None;
    let mut removable: Vec<PathBuf> = Vec::new();
    for entry_res in fs::read_dir(out_dir)? {
        let entry: DirEntry = entry_res?;
        let path: PathBuf = entry.path();
        if !path.is_file() {
            continue;
        }
        let name: String = entry.file_name().to_string_lossy().into_owned();
        if name.ends_with(WEB_EXT_WASM) {
            if name.ends_with(WEB_BG_WASM_SUFFIX) || wasm_name.is_none() {
                wasm_name = Some(name);
            }
        } else if name.ends_with(WEB_EXT_JS) {
            if loader_path.is_none() {
                loader_path = Some(path.clone());
            }
            removable.push(path);
        } else if name.ends_with(WEB_EXT_DTS) || name == WEB_PACKAGE_JSON || name == WEB_GITIGNORE {
            removable.push(path);
        }
    }
    let wasm_file: String =
        wasm_name.ok_or_else(|| Error::new(ErrorKind::NotFound, ERR_WEB_DIR_WASM_MISSING))?;
    let raw_js: String = match loader_path {
        Some(js_path) => fs::read_to_string(&js_path)?,
        None => WEB_FALLBACK_WBG_INIT.to_string(),
    };
    let _: Vec<PathBuf> = write_web_icons(out_dir, custom_icon)?;
    let logo_data_uri: String = resolve_icon_data_uri(custom_icon)?;
    let html: String =
        render_zero_js_web_html(title, &normalized_base, &wasm_file, &raw_js, &logo_data_uri);
    fs::write(out_dir.join(WEB_INDEX_HTML), html.as_bytes())?;
    fs::write(out_dir.join(WEB_NOT_FOUND_HTML), html.as_bytes())?;
    fs::write(out_dir.join(WEB_NOJEKYLL_NAME), [])?;
    for path in removable.into_iter() {
        let _: io::Result<()> = fs::remove_file(path);
    }
    let manifest: ReleaseAssetManifest = write_release_manifest(out_dir, version)?;
    if verify_release {
        verify_zero_js_web_bundle(out_dir, &normalized_base, &wasm_file, version)?;
    }
    Ok(manifest)
}

/// Verifies every release invariant on a zero-JS WebAssembly bundle directory.
///
/// # Arguments
///
/// - `&Path` - Packaged web distribution directory.
/// - `&str` - Normalized asset URL base prefix.
/// - `&str` - Expected primary `.wasm` filename.
/// - `&str` - Expected numeric semantic version in `euv-release.json`.
///
/// # Returns
///
/// - `io::Result<ReleaseAssetManifest>` - Verified release manifest or error detailing the failed check.
pub fn verify_zero_js_web_bundle(
    out_dir: &Path,
    asset_base: &str,
    wasm_file: &str,
    expected_version: &str,
) -> io::Result<ReleaseAssetManifest> {
    for entry_res in fs::read_dir(out_dir)? {
        let entry: DirEntry = entry_res?;
        let path: PathBuf = entry.path();
        if path.is_file()
            && path
                .file_name()
                .map(|name: &OsStr| name.to_string_lossy().ends_with(WEB_EXT_JS))
                .unwrap_or(false)
        {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("{ERR_WEB_EXTERNAL_JS_REMAIN}: {}", path.display()),
            ));
        }
    }
    let _: AiSchemaScanReport = verify_no_ai_schema_leak(&out_dir.join(wasm_file))?;
    let index_bytes: Vec<u8> = fs::read(out_dir.join(WEB_INDEX_HTML))?;
    let fallback_bytes: Vec<u8> = fs::read(out_dir.join(WEB_NOT_FOUND_HTML))?;
    if index_bytes != fallback_bytes {
        return Err(Error::new(
            ErrorKind::InvalidData,
            ERR_WEB_FALLBACK_MISMATCH,
        ));
    }
    if !out_dir.join(WEB_NOJEKYLL_NAME).is_file() {
        return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_NOJEKYLL_MISSING));
    }
    let html: String = String::from_utf8(index_bytes)
        .map_err(|err: FromUtf8Error| Error::new(ErrorKind::InvalidData, err.to_string()))?;
    let normalized_base: String = normalize_web_asset_base(asset_base);
    let expected_href: String = format!("{normalized_base}{wasm_file}");
    let expected_js_lit: String = format!("'{expected_href}'");
    let expected_preload: String =
        format!("{WEB_SHELL_PRELOAD_OPEN}{expected_href}{WEB_SHELL_PRELOAD_CLOSE}");
    let preload_trimmed: &str = expected_preload.trim_end();
    if !html.contains(&expected_js_lit) || !html.contains(preload_trimmed) {
        return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_PRELOAD_OR_HREF));
    }
    if normalized_base == WEB_DEFAULT_ASSET_BASE {
        let forbidden_single: String = format!("'/{wasm_file}'");
        let forbidden_double: String = format!("\"/{wasm_file}\"");
        if html.contains(&forbidden_single) || html.contains(&forbidden_double) {
            return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_ROOT_ABS_WASM));
        }
    }
    let required: [&str; 5] = [
        WEB_INDEX_HTML,
        WEB_NOT_FOUND_HTML,
        wasm_file,
        WEB_FAVICON_PNG,
        WEB_APPLE_TOUCH_PNG,
    ];
    verify_release_manifest(out_dir, Some(expected_version), &required)
}

/// Resolves dynamic package metadata, `wasm-bindgen` version, and `theme-*` features via `cargo metadata`.
///
/// # Arguments
///
/// - `&Path` - Workspace or crate root directory.
/// - `&str` - Cargo package name to inspect.
///
/// # Returns
///
/// - `io::Result<WebPackageMetadata>` - Resolved metadata for WebAssembly builds.
pub fn resolve_web_package_metadata(
    repo_root: &Path,
    package: &str,
) -> io::Result<WebPackageMetadata> {
    let output: Output = Command::new(WEB_BIN_CARGO)
        .current_dir(repo_root)
        .args([
            WEB_ARG_METADATA,
            WEB_ARG_FORMAT_VERSION,
            "1",
            WEB_ARG_FILTER_PLATFORM,
            WEB_RUST_TARGET,
        ])
        .output()?;
    if !output.status.success() {
        let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
        return Err(Error::other(format!(
            "{ERR_WEB_METADATA_PACKAGE}: {stderr}"
        )));
    }
    let stdout: String = String::from_utf8_lossy(&output.stdout).into_owned();
    let root_val: Value = from_str(&stdout)
        .map_err(|err: serde_json::Error| Error::new(ErrorKind::InvalidData, err.to_string()))?;
    let packages: &Vec<Value> = root_val
        .get(META_KEY_PACKAGES)
        .and_then(Value::as_array)
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_WEB_METADATA_PACKAGE))?;
    let mut pkg_id_to_name_ver: BTreeMap<String, (String, String)> = BTreeMap::new();
    let mut matched_pkg: Option<&Value> = None;
    for pkg in packages.iter() {
        let pkg_id: String = pkg
            .get("id")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let pkg_name: String = pkg
            .get(META_KEY_NAME)
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let pkg_ver: String = pkg
            .get(META_KEY_VERSION)
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        if pkg_name == package {
            matched_pkg = Some(pkg);
        }
        let _: Option<(String, String)> = pkg_id_to_name_ver.insert(pkg_id, (pkg_name, pkg_ver));
    }
    let pkg_val: &Value = matched_pkg.ok_or_else(|| {
        Error::new(
            ErrorKind::NotFound,
            format!("{ERR_WEB_METADATA_PACKAGE}: {package}"),
        )
    })?;
    let pkg_id: &str = pkg_val.get("id").and_then(Value::as_str).unwrap_or("");
    let version: String = pkg_val
        .get(META_KEY_VERSION)
        .and_then(Value::as_str)
        .unwrap_or(WEB_FALLBACK_VERSION)
        .to_string();
    let lib_name: String = resolve_lib_target_name(pkg_val, package);
    let mut theme_features: Vec<String> = Vec::new();
    if let Some(feat_map) = pkg_val.get(META_KEY_FEATURES).and_then(Value::as_object) {
        for key in feat_map.keys() {
            if key.starts_with(WEB_THEME_FEATURE_PREFIX) {
                theme_features.push(key.clone());
            }
        }
    }
    theme_features.sort();
    let target_dir: PathBuf = match env::var_os(ENV_CARGO_TARGET_DIR) {
        Some(val) if !val.is_empty() => PathBuf::from(val),
        _ => root_val
            .get(META_KEY_TARGET_DIR)
            .and_then(Value::as_str)
            .map(PathBuf::from)
            .unwrap_or_else(|| repo_root.join(WEB_TARGET_DIR_NAME)),
    };
    let mut wb_version: Option<String> = None;
    if let Some(nodes) = root_val
        .get(META_KEY_RESOLVE)
        .and_then(|res: &Value| res.get(META_KEY_NODES))
        .and_then(Value::as_array)
    {
        for node in nodes.iter() {
            if node.get("id").and_then(Value::as_str) == Some(pkg_id)
                && let Some(deps) = node.get(META_KEY_DEPENDENCIES).and_then(Value::as_array)
            {
                for dep_id_val in deps.iter() {
                    if let Some(dep_id) = dep_id_val.as_str()
                        && let Some((dep_name, dep_ver)) = pkg_id_to_name_ver.get(dep_id)
                        && dep_name == DEP_NAME_WASM_BINDGEN
                    {
                        wb_version = Some(dep_ver.clone());
                        break;
                    }
                }
            }
        }
    }
    Ok(WebPackageMetadata::new(
        package.to_string(),
        lib_name,
        version,
        target_dir,
        wb_version,
        theme_features,
    ))
}

/// Builds a complete zero-JS WebAssembly bundle or `--raw-wasm` artifact in pure Rust.
///
/// # Arguments
///
/// - `&WebBuildConfig` - Web build configuration.
///
/// # Returns
///
/// - `io::Result<WebBuildReport>` - Structured build report with artifact sizes and timing.
pub fn build_web_bundle(config: &WebBuildConfig) -> io::Result<WebBuildReport> {
    let started: SystemTime = SystemTime::now();
    let repo_root: &Path = config.get_repo_root().as_path();
    let out_dir: PathBuf = resolve_output_path(repo_root, config.get_out_dir());
    if let Ok(meta) = fs::symlink_metadata(&out_dir)
        && meta.file_type().is_symlink()
    {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_WEB_SYMLINK_OUT}: {}", out_dir.display()),
        ));
    }
    if out_dir.exists() {
        fs::remove_dir_all(&out_dir)?;
    }
    fs::create_dir_all(&out_dir)?;
    let metadata: WebPackageMetadata =
        resolve_web_package_metadata(repo_root, config.get_package())?;
    let version: String = match config.try_get_version() {
        Some(explicit) if !explicit.trim().is_empty() => explicit.trim().to_string(),
        _ => metadata.get_version().clone(),
    };
    let lib_name: &str = metadata.get_lib_name().as_str();
    let base_url: String = normalize_web_asset_base(config.get_base_url());
    let rustflags: String = build_web_rustflags(env::var(ENV_RUSTFLAGS).ok().as_deref());
    let mut cargo_args: Vec<String> = vec![
        WEB_ARG_BUILD.to_string(),
        WEB_ARG_TARGET.to_string(),
        WEB_RUST_TARGET.to_string(),
        WEB_ARG_LIB.to_string(),
        WEB_ARG_PACKAGE.to_string(),
        config.get_package().clone(),
    ];
    if config.get_release() {
        cargo_args.push(WEB_ARG_RELEASE.to_string());
    }
    if config.get_no_default_features() {
        cargo_args.push(WEB_ARG_NO_DEFAULT_FEATURES.to_string());
    }
    if !config.get_features().is_empty() {
        cargo_args.push(WEB_ARG_FEATURES.to_string());
        cargo_args.push(config.get_features().join(","));
    }
    let mut cargo_cmd: Command = Command::new(WEB_BIN_CARGO);
    let _: &mut Command = cargo_cmd
        .current_dir(repo_root)
        .args(&cargo_args)
        .env(ENV_RUSTFLAGS, &rustflags);
    if config.get_release() {
        let _: &mut Command = cargo_cmd.env(ENV_CARGO_RELEASE_PANIC, PANIC_ABORT_VALUE);
    }
    run_streaming_command(&mut cargo_cmd)?;
    let profile_dir: &str = if config.get_release() {
        WEB_PROFILE_RELEASE
    } else {
        WEB_PROFILE_DEBUG
    };
    let compiled_wasm: PathBuf = metadata
        .get_target_dir()
        .join(WEB_RUST_TARGET)
        .join(profile_dir)
        .join(format!("{lib_name}{WEB_EXT_WASM}"));
    if !compiled_wasm.is_file() {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!(
                "{ERR_WEB_COMPILED_WASM_MISSING}: {}",
                compiled_wasm.display()
            ),
        ));
    }
    let custom_icon: Option<&Path> = config.try_get_icon_path().as_deref();
    if config.get_raw_wasm() {
        let wasm_file: String = format!("{lib_name}{WEB_EXT_WASM}");
        let dest_wasm: PathBuf = out_dir.join(&wasm_file);
        let wasm_bytes: u64 = fs::copy(&compiled_wasm, &dest_wasm)?;
        if config.get_release() && config.get_verify() {
            let _: AiSchemaScanReport = verify_no_ai_schema_leak(&dest_wasm)?;
        }
        let icon_paths: Vec<PathBuf> = write_web_raw_icons(&out_dir, custom_icon)?;
        let plans: Vec<BuildPlan> =
            resolve_build_plans(TargetArg::Web, RenderArg::Auto, config.get_release());
        let plan_json: String = to_string_pretty(&plans)
            .map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
        fs::write(out_dir.join(WEB_BUILD_PLAN_JSON), plan_json.as_bytes())?;
        let archive_written: Option<PathBuf> = maybe_archive_web_dir(repo_root, &out_dir, config)?;
        let elapsed_ms: u64 = elapsed_millis(started);
        return Ok(WebBuildReport {
            package: config.get_package().clone(),
            version,
            out_dir,
            base_url,
            wasm_file,
            wasm_bytes,
            wasm_opt_applied: false,
            raw_wasm: true,
            file_count: icon_paths.len() + 2,
            elapsed_ms,
            manifest_path: None,
            archive_path: archive_written,
        });
    }
    verify_wasm_bindgen_cli_version(metadata.try_get_wasm_bindgen_version().as_deref())?;
    let mut wb_cmd: Command = Command::new(WEB_BIN_WASM_BINDGEN);
    let _: &mut Command = wb_cmd.current_dir(repo_root).args([
        WEB_ARG_TARGET,
        WEB_TARGET_MODE,
        WEB_ARG_NO_TS,
        WEB_ARG_OUT_DIR,
        &out_dir.to_string_lossy(),
        WEB_ARG_OUT_NAME,
        lib_name,
        &compiled_wasm.to_string_lossy(),
    ]);
    run_streaming_command(&mut wb_cmd)?;
    let wasm_file: String = format!("{lib_name}{WEB_BG_WASM_SUFFIX}");
    let bg_wasm_path: PathBuf = out_dir.join(&wasm_file);
    let env_skip_opt: bool = env::var(ENV_SKIP_WASM_OPT)
        .map(|val: String| val.trim() == "1")
        .unwrap_or(false);
    let wasm_opt_applied: bool =
        if config.get_release() && !config.get_skip_wasm_opt() && !env_skip_opt {
            run_optional_wasm_opt(
                &bg_wasm_path,
                &out_dir.join(format!("{lib_name}{WEB_OPT_WASM_SUFFIX}")),
            )
        } else {
            false
        };
    let manifest: ReleaseAssetManifest = package_web_bundle_directory(
        &out_dir,
        config.get_title(),
        &base_url,
        &version,
        custom_icon,
        config.get_verify() && config.get_release(),
    )?;
    let wasm_bytes: u64 = fs::metadata(&bg_wasm_path)?.len();
    let archive_written: Option<PathBuf> = maybe_archive_web_dir(repo_root, &out_dir, config)?;
    let elapsed_ms: u64 = elapsed_millis(started);
    Ok(WebBuildReport {
        package: config.get_package().clone(),
        version,
        out_dir: out_dir.clone(),
        base_url,
        wasm_file,
        wasm_bytes,
        wasm_opt_applied,
        raw_wasm: false,
        file_count: manifest.get_files().len(),
        elapsed_ms,
        manifest_path: Some(out_dir.join(RELEASE_MANIFEST_NAME)),
        archive_path: archive_written,
    })
}

/// Builds `default` plus every `theme-*` feature variant with deterministic SHA-256 source fingerprint caching.
///
/// # Arguments
///
/// - `&WebBuildConfig` - Base Web build configuration specifying package, root, and output directory.
///
/// # Returns
///
/// - `io::Result<ThemeVariantBuildReport>` - Summary of freshly built vs cached theme variants.
pub fn build_web_theme_variants(config: &WebBuildConfig) -> io::Result<ThemeVariantBuildReport> {
    let started: SystemTime = SystemTime::now();
    let repo_root: &Path = config.get_repo_root().as_path();
    let out_dir: PathBuf = resolve_output_path(repo_root, config.get_out_dir());
    let metadata: WebPackageMetadata =
        resolve_web_package_metadata(repo_root, config.get_package())?;
    let version: String = match config.try_get_version() {
        Some(explicit) if !explicit.trim().is_empty() => explicit.trim().to_string(),
        _ => metadata.get_version().clone(),
    };
    let fingerprint: String = compute_workspace_source_fingerprint(repo_root)?;
    let cache_dir: PathBuf = out_dir.join(WEB_THEME_CACHE_SUBDIR);
    let themes_dir: PathBuf = out_dir.join(WEB_THEMES_SUBDIR);
    fs::create_dir_all(&cache_dir)?;
    fs::create_dir_all(&themes_dir)?;
    let mut variants: Vec<String> = vec![WEB_THEME_DEFAULT_NAME.to_string()];
    for feature in metadata.get_theme_features().iter() {
        variants.push(feature.clone());
    }
    let expected_wasm: String = format!("{}{WEB_BG_WASM_SUFFIX}", metadata.get_lib_name());
    let mut built_variants: Vec<String> = Vec::new();
    let mut cached_variants: Vec<String> = Vec::new();
    for variant in variants.into_iter() {
        let variant_dir: PathBuf = themes_dir.join(&variant);
        let stamp_path: PathBuf = cache_dir.join(format!("{variant}.{WEB_THEME_STAMP_EXT}"));
        let cached_stamp: String = fs::read_to_string(&stamp_path)
            .map(|text: String| text.trim().to_string())
            .unwrap_or_default();
        let has_index: bool = variant_dir
            .join(WEB_INDEX_HTML)
            .metadata()
            .map(|meta: Metadata| meta.len() > 0)
            .unwrap_or(false);
        let has_wasm: bool = variant_dir
            .join(&expected_wasm)
            .metadata()
            .map(|meta: Metadata| meta.len() > 0)
            .unwrap_or(false);
        if cached_stamp == fingerprint && has_index && has_wasm {
            cached_variants.push(variant);
            continue;
        }
        let mut variant_cfg: WebBuildConfig = config.clone();
        let variant_features: Vec<String> = if variant == WEB_THEME_DEFAULT_NAME {
            Vec::new()
        } else {
            vec![variant.clone()]
        };
        variant_cfg
            .set_out_dir(variant_dir)
            .set_no_default_features(true)
            .set_features(variant_features)
            .set_archive_path(None)
            .set_theme_variants(false);
        let _: WebBuildReport = build_web_bundle(&variant_cfg)?;
        fs::write(&stamp_path, format!("{fingerprint}\n").as_bytes())?;
        built_variants.push(variant);
    }
    Ok(ThemeVariantBuildReport::new(
        out_dir,
        version,
        built_variants,
        cached_variants,
        elapsed_millis(started),
    ))
}

/// Computes a deterministic SHA-256 fingerprint across workspace manifests and Rust source trees.
///
/// # Arguments
///
/// - `&Path` - Workspace root directory.
///
/// # Returns
///
/// - `io::Result<String>` - Lowercase hexadecimal SHA-256 fingerprint.
pub fn compute_workspace_source_fingerprint(repo_root: &Path) -> io::Result<String> {
    let mut files: Vec<PathBuf> = Vec::new();
    for root_file in [WEB_CARGO_TOML, WEB_CARGO_LOCK] {
        let candidate: PathBuf = repo_root.join(root_file);
        if candidate.is_file() {
            files.push(candidate);
        }
    }
    collect_files_if_dir(&repo_root.join(WEB_SRC_DIR_NAME), &mut files)?;
    for crate_name in WEB_FINGERPRINT_CRATES.iter() {
        let crate_dir: PathBuf = repo_root.join(crate_name);
        let manifest: PathBuf = crate_dir.join(WEB_CARGO_TOML);
        if manifest.is_file() {
            files.push(manifest);
        }
        collect_files_if_dir(&crate_dir.join(WEB_SRC_DIR_NAME), &mut files)?;
    }
    files.sort();
    let mut combined: Vec<u8> = Vec::new();
    for path in files.into_iter() {
        if let Ok(rel) = path.strip_prefix(repo_root) {
            combined.extend_from_slice(rel.to_string_lossy().as_bytes());
            combined.push(0u8);
        }
        let content: Vec<u8> = fs::read(&path)?;
        combined.extend_from_slice(sha256_hex(&content).as_bytes());
        combined.push(b'\n');
    }
    Ok(sha256_hex(&combined))
}

/// Recursively appends regular files under `dir` to `out` when `dir` exists.
///
/// # Arguments
///
/// - `&Path` - Directory to scan.
/// - `&mut Vec<PathBuf>` - Output file list.
///
/// # Returns
///
/// - `io::Result<()>` - Traversal result.
fn collect_files_if_dir(dir: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
    if !dir.is_dir() {
        return Ok(());
    }
    for entry_res in fs::read_dir(dir)? {
        let entry: DirEntry = entry_res?;
        let path: PathBuf = entry.path();
        if path.is_dir() {
            collect_files_if_dir(&path, out)?;
        } else if path.is_file() {
            out.push(path);
        }
    }
    Ok(())
}

/// Extracts the compiled library target name in snake_case from a `cargo metadata` package object.
///
/// # Arguments
///
/// - `&Value` - Package JSON node from `cargo metadata`.
/// - `&str` - Fallback package name.
///
/// # Returns
///
/// - `String` - Snake-case library artifact stem (e.g. `euv_example`).
fn resolve_lib_target_name(pkg_val: &Value, fallback_pkg: &str) -> String {
    if let Some(targets) = pkg_val.get(META_KEY_TARGETS).and_then(Value::as_array) {
        for target in targets.iter() {
            let is_lib: bool = target
                .get(META_KEY_KIND)
                .and_then(Value::as_array)
                .map(|kinds: &Vec<Value>| {
                    kinds.iter().any(|kind_val: &Value| {
                        let kind_str: &str = kind_val.as_str().unwrap_or("");
                        kind_str == META_KIND_CDYLIB
                            || kind_str == "lib"
                            || kind_str == META_KIND_RLIB
                    })
                })
                .unwrap_or(false);
            if is_lib && let Some(name) = target.get(META_KEY_NAME).and_then(Value::as_str) {
                return name.replace('-', "_");
            }
        }
    }
    fallback_pkg.replace('-', "_")
}

/// Checks that the installed `wasm-bindgen` CLI version matches `expected` when resolved from `Cargo.lock`.
///
/// # Arguments
///
/// - `Option<&str>` - Expected `wasm-bindgen` semver resolved from `Cargo.lock`.
///
/// # Returns
///
/// - `io::Result<()>` - Ok when matching or not pinned; error with install guidance on mismatch.
fn verify_wasm_bindgen_cli_version(expected: Option<&str>) -> io::Result<()> {
    let output: Output = Command::new(WEB_BIN_WASM_BINDGEN)
        .arg(WEB_ARG_VERSION)
        .output()
        .map_err(|err: Error| {
            Error::new(
                ErrorKind::NotFound,
                format!("{ERR_WEB_WASM_BINDGEN_MISMATCH}: {err}"),
            )
        })?;
    if !output.status.success() {
        return Err(Error::other(ERR_WEB_WASM_BINDGEN_MISMATCH));
    }
    let stdout: String = String::from_utf8_lossy(&output.stdout).into_owned();
    let actual: &str = stdout.split_whitespace().nth(1).unwrap_or("").trim();
    if let Some(req_ver) = expected
        && actual != req_ver
    {
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!(
                "{ERR_WEB_WASM_BINDGEN_MISMATCH}: installed {actual}, Cargo.lock requires {req_ver} (run: cargo install --locked wasm-bindgen-cli --version {req_ver})"
            ),
        ));
    }
    Ok(())
}

/// Runs optional binaryen `wasm-opt -Oz` optimization in place, returning `false` cleanly on missing tool or failure.
///
/// # Arguments
///
/// - `&Path` - Input `.wasm` binary to optimize.
/// - `&Path` - Temporary output `.wasm` path swapped atomically on success.
///
/// # Returns
///
/// - `bool` - `true` if `wasm-opt` succeeded and replaced the `.wasm` binary.
fn run_optional_wasm_opt(wasm_path: &Path, opt_tmp_path: &Path) -> bool {
    let probe: io::Result<Output> = Command::new(WEB_BIN_WASM_OPT).arg(WEB_ARG_VERSION).output();
    if !probe
        .map(|out: Output| out.status.success())
        .unwrap_or(false)
    {
        return false;
    }
    let status: io::Result<ExitStatus> = Command::new(WEB_BIN_WASM_OPT)
        .args(WEB_WASM_OPT_FLAGS)
        .arg(wasm_path)
        .arg("-o")
        .arg(opt_tmp_path)
        .status();
    if status
        .map(|code: ExitStatus| code.success())
        .unwrap_or(false)
        && fs::rename(opt_tmp_path, wasm_path).is_ok()
    {
        true
    } else {
        let _: io::Result<()> = fs::remove_file(opt_tmp_path);
        false
    }
}

/// Archives `out_dir` when `config.try_get_archive_path()` is set.
///
/// # Arguments
///
/// - `&Path` - Repository root used to resolve relative archive paths.
/// - `&Path` - Directory to archive.
/// - `&WebBuildConfig` - Active build config.
///
/// # Returns
///
/// - `io::Result<Option<PathBuf>>` - Written archive path when requested.
fn maybe_archive_web_dir(
    repo_root: &Path,
    out_dir: &Path,
    config: &WebBuildConfig,
) -> io::Result<Option<PathBuf>> {
    if let Some(archive_rel) = config.try_get_archive_path() {
        let dest: PathBuf = resolve_output_path(repo_root, archive_rel);
        let _: u64 = archive_directory_auto(out_dir, &dest, None)?;
        Ok(Some(dest))
    } else {
        Ok(None)
    }
}

/// Resolves a potentially relative output path against `repo_root`.
///
/// # Arguments
///
/// - `&Path` - Base repository root directory.
/// - `&Path` - Candidate output path.
///
/// # Returns
///
/// - `PathBuf` - Resolved filesystem path.
fn resolve_output_path(repo_root: &Path, candidate: &Path) -> PathBuf {
    if candidate.is_absolute() {
        candidate.to_path_buf()
    } else {
        repo_root.join(candidate)
    }
}

/// Executes a configured external command with streaming inherited stdout/stderr.
///
/// # Arguments
///
/// - `&mut Command` - Command to execute.
///
/// # Returns
///
/// - `io::Result<()>` - Error if spawn fails or exit status is non-zero.
fn run_streaming_command(cmd: &mut Command) -> io::Result<()> {
    let status: ExitStatus = cmd
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()?;
    if status.success() {
        Ok(())
    } else {
        Err(Error::other(format!("{ERR_WEB_CMD_FAILED}: {status}")))
    }
}

/// Computes elapsed wall-clock milliseconds since `started`.
///
/// # Arguments
///
/// - `SystemTime` - Start timestamp.
///
/// # Returns
///
/// - `u64` - Elapsed milliseconds.
fn elapsed_millis(started: SystemTime) -> u64 {
    started
        .elapsed()
        .map(|dur: Duration| dur.as_millis() as u64)
        .unwrap_or(0)
}

/// Escapes HTML special characters in user-provided text.
///
/// # Arguments
///
/// - `&str` - Raw UTF-8 text.
///
/// # Returns
///
/// - `String` - Escaped HTML-safe string.
fn escape_web_html(input: &str) -> String {
    let mut out: String = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '&' => out.push_str(WEB_HTML_AMP),
            '<' => out.push_str(WEB_HTML_LT),
            '>' => out.push_str(WEB_HTML_GT),
            '"' => out.push_str(WEB_HTML_QUOT),
            _ => out.push(ch),
        }
    }
    out
}