microsoft-webui-cli 0.0.18

CLI tool for building WebUI applications
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

use anyhow::{Context, Result};
use clap::Args;
use expand_tilde::expand_tilde;
use std::collections::HashSet;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};

use super::common::*;
use crate::utils::error::CliError;
use crate::utils::output;

#[derive(Args)]
pub struct BuildArgs {
    #[command(flatten)]
    pub app_args: AppArgs,

    /// Output destination. Either a folder (e.g. `./dist`) or a `.bin` file path
    /// (e.g. `./dist/app1.bin`). When a `.bin` file path is given, the protocol
    /// is written with that filename and CSS files are emitted next to it.
    #[arg(long)]
    pub out: PathBuf,

    /// Comma-separated root component tags to emit as static CDN-loadable assets
    #[arg(long, value_delimiter = ',', value_name = "TAGS")]
    pub emit_component_assets: Vec<String>,

    /// Design token theme to validate against: a JSON file path or npm package name.
    /// Missing unresolved CSS tokens fail the build.
    #[arg(long)]
    pub theme: Option<String>,
}

/// Resolve the `--out` argument into `(output_directory, protocol_filename)`.
///
/// If `out` ends with a `.bin` extension, it is treated as a full file path:
/// the parent becomes the output directory (or `.` if none) and the file name
/// becomes the protocol filename. Otherwise `out` is treated as a directory and
/// the default `protocol.bin` filename is used.
///
/// The filename is kept as an `OsString` so non-UTF8 paths round-trip unchanged.
fn resolve_out(out: &Path) -> (PathBuf, OsString) {
    if out.extension().and_then(|e| e.to_str()) == Some("bin") {
        let name = out
            .file_name()
            .map(OsString::from)
            .unwrap_or_else(|| OsString::from("protocol.bin"));
        let dir = match out.parent() {
            Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
            _ => PathBuf::from("."),
        };
        (dir, name)
    } else {
        (out.to_path_buf(), OsString::from("protocol.bin"))
    }
}

fn validate_output_file_names(
    protocol_name: &std::ffi::OsStr,
    result: &webui::BuildResult,
) -> Result<()> {
    let mut names =
        HashSet::with_capacity(1 + result.css_files.len() + result.component_asset_files.len());
    names.insert(protocol_name.to_os_string());
    for (name, _) in &result.css_files {
        let name = OsString::from(name);
        if !names.insert(name.clone()) {
            anyhow::bail!(
                "output filename collision for '{}'. Adjust --asset-file-name-template to include [ext] or another unique asset-type segment.",
                name.to_string_lossy()
            );
        }
    }
    for file in &result.component_asset_files {
        let name = OsString::from(&file.name);
        if !names.insert(name.clone()) {
            anyhow::bail!(
                "output filename collision for '{}'. Adjust --asset-file-name-template to include [ext] or another unique asset-type segment.",
                name.to_string_lossy()
            );
        }
    }
    Ok(())
}

pub fn execute(args: &BuildArgs) -> Result<()> {
    run(args).inspect_err(|err| {
        output::error(err);
        if let Some(cli_err) = err.chain().find_map(|c| c.downcast_ref::<CliError>()) {
            output::hint(cli_err.hint());
        }
        eprintln!();
    })
}

fn run(args: &BuildArgs) -> Result<()> {
    let app_input = expand_tilde(&args.app_args.app)
        .with_context(|| format!("Failed to expand app path: {}", args.app_args.app.display()))?
        .into_owned();
    let out = expand_tilde(&args.out)
        .with_context(|| format!("Failed to expand output path: {}", args.out.display()))?
        .into_owned();

    let app = app_input
        .canonicalize()
        .map_err(|_| CliError::AppFolderNotFound {
            path: args.app_args.app.display().to_string(),
        })?;

    let entry_path = app.join(&args.app_args.entry);
    if !entry_path.is_file() {
        return Err(CliError::EntryReadFailed {
            path: entry_path.display().to_string(),
        }
        .into());
    }

    let (out_dir, protocol_name) = resolve_out(&out);
    let protocol_path = out_dir.join(&protocol_name);

    output::header("WebUI Build");
    output::field("App", &app.display());
    output::field("Entry", &args.app_args.entry);
    output::field("Output", &protocol_path.display());
    output::field("CSS", &args.app_args.css);
    if let Some(ref plugin_name) = args.app_args.plugin {
        output::field("Plugin", plugin_name);
    }
    if !args.app_args.components.is_empty() {
        output::field("Components", &args.app_args.components.join(", "));
    }
    if !args.emit_component_assets.is_empty() {
        output::field("Component assets", &args.emit_component_assets.join(", "));
    }
    if let Some(ref theme) = args.theme {
        output::field("Theme", theme);
    }
    eprintln!();

    let mut build_options = args.app_args.to_build_options(&app);
    build_options.component_asset_roots = args.emit_component_assets.clone();
    build_options.theme = args
        .theme
        .as_deref()
        .map(|theme| load_theme(theme, &app))
        .transpose()?;
    let result = webui::build(build_options).with_context(|| "Build failed")?;
    validate_output_file_names(&protocol_name, &result)?;

    fs::create_dir_all(&out_dir)
        .with_context(|| format!("Failed to create {}", out_dir.display()))?;
    fs::write(&protocol_path, &result.protocol_bytes)
        .with_context(|| format!("Failed to write {}", protocol_path.display()))?;
    for (name, content) in &result.css_files {
        fs::write(out_dir.join(name), content)
            .with_context(|| format!("Failed to write {name} to {}", out_dir.display()))?;
    }
    for file in &result.component_asset_files {
        fs::write(out_dir.join(&file.name), &file.content).with_context(|| {
            format!(
                "Failed to write component asset {} to {}",
                file.name,
                out_dir.display()
            )
        })?;
    }
    let stats = result.stats;

    output::success(&format!(
        "Registered {} component{}",
        console::style(stats.component_count).bold(),
        if stats.component_count == 1 { "" } else { "s" }
    ));

    output::success(&format!(
        "Parsed {} ({} fragment{})",
        console::style(&args.app_args.entry).bold(),
        console::style(stats.fragment_count).bold(),
        if stats.fragment_count == 1 { "" } else { "s" }
    ));

    if stats.token_count > 0 {
        output::success(&format!(
            "Discovered {} CSS token{}",
            console::style(stats.token_count).bold(),
            if stats.token_count == 1 { "" } else { "s" }
        ));
    }

    if !result.component_asset_files.is_empty() {
        output::success(&format!(
            "Emitted {} component asset{}",
            console::style(result.component_asset_files.len()).bold(),
            if result.component_asset_files.len() == 1 {
                ""
            } else {
                "s"
            }
        ));
    }

    let files_written = 1 + stats.css_file_count + result.component_asset_files.len();
    output::success(&format!(
        "Wrote {}",
        console::style(Path::new(&protocol_name).display()).bold()
    ));

    for advisory in &result.warnings {
        output::warning_diagnostic(advisory);
    }

    output::finish(&format!(
        "Build complete ({} file{} written) {}",
        console::style(files_written).bold(),
        if files_written == 1 { "" } else { "s" },
        console::style(format!("in {:.0?}", stats.duration)).dim(),
    ));

    Ok(())
}

/// Standalone build function for testing without CLI args.
#[cfg(test)]
pub fn build(app: &std::path::Path, out: &std::path::Path, entry: &str) -> Result<()> {
    run(&BuildArgs {
        app_args: AppArgs {
            app: app.to_path_buf(),
            entry: entry.to_string(),
            css: CssStrategy::Link,
            dom: DomStrategy::Shadow,
            plugin: None,
            components: Vec::new(),
            asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
            css_public_base: None,
            legal_comments: LegalComments::Inline,
        },
        out: out.to_path_buf(),
        emit_component_assets: Vec::new(),
        theme: None,
    })
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::Path;
    use tempfile::TempDir;
    use webui_protocol::web_ui_fragment::Fragment;
    use webui_protocol::WebUIProtocol;

    fn create_app_dir(files: &[(&str, &str)]) -> TempDir {
        let dir = TempDir::new().unwrap();
        for (name, content) in files {
            let path = dir.path().join(name);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(&path, content).unwrap();
        }
        dir
    }

    #[test]
    fn test_build_simple_html() {
        let app_dir = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let out_dir = TempDir::new().unwrap();

        build(app_dir.path(), out_dir.path(), "index.html").unwrap();

        let protocol_path = out_dir.path().join("protocol.bin");
        assert!(protocol_path.exists());

        let bytes = fs::read(&protocol_path).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();
        assert!(protocol.fragments.contains_key("index.html"));
    }

    #[test]
    fn test_build_with_directives() {
        let html = r#"<h1>Hello</h1>
<for each="item in items">
    <p>{{item.name}}</p>
</for>
<if condition="show">
    <p>Visible</p>
</if>"#;
        let app_dir = create_app_dir(&[("index.html", html)]);
        let out_dir = TempDir::new().unwrap();

        build(app_dir.path(), out_dir.path(), "index.html").unwrap();

        let bytes = fs::read(out_dir.path().join("protocol.bin")).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();

        let index = &protocol.fragments["index.html"].fragments;
        assert!(index
            .iter()
            .any(|f| matches!(f.fragment.as_ref(), Some(Fragment::ForLoop(_)))));
        assert!(index
            .iter()
            .any(|f| matches!(f.fragment.as_ref(), Some(Fragment::IfCond(_)))));
    }

    #[test]
    fn test_build_with_component_css() {
        let app_dir = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            ("my-card.html", "<div><slot></slot></div>"),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let out_dir = TempDir::new().unwrap();

        build(app_dir.path(), out_dir.path(), "index.html").unwrap();

        assert!(out_dir.path().join("protocol.bin").exists());
        let css_path = out_dir.path().join("my-card.css");
        assert!(css_path.exists());
        let css = fs::read_to_string(&css_path).unwrap();
        assert!(css.contains("color: red"));
    }

    #[test]
    fn test_build_with_inline_css_skips_css_files() {
        let app_dir = create_app_dir(&[
            ("index.html", "<my-card>Hello</my-card>"),
            ("my-card.html", "<div><slot></slot></div>"),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let out_dir = TempDir::new().unwrap();

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Style,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: Vec::new(),
            theme: None,
        })
        .unwrap();

        assert!(out_dir.path().join("protocol.bin").exists());
        // Inline mode should NOT write external CSS files
        assert!(!out_dir.path().join("my-card.css").exists());
    }

    #[test]
    fn test_build_emits_static_component_assets() {
        let app_dir = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", r#"<div w-ref="{slot}"></div>"#),
            (
                "mail-thread.html",
                r#"<if condition="hasMessages"><mail-message title="{{title}}"></mail-message></if>"#,
            ),
            ("mail-message.html", "<p>{{title}}</p>"),
        ]);
        let out_dir = TempDir::new().unwrap();

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: Some(Plugin::WebUI),
                components: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: vec!["mail-thread".to_string()],
            theme: None,
        })
        .unwrap();

        let asset_path = out_dir.path().join("mail-thread.webui.js");
        assert!(asset_path.exists());

        let bytes = fs::read(out_dir.path().join("protocol.bin")).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();
        let index_fragments = &protocol.fragments["index.html"].fragments;
        assert!(
            !index_fragments.iter().any(|fragment| matches!(
                fragment.fragment.as_ref(),
                Some(Fragment::Component(component)) if component.fragment_id == "mail-thread"
            )),
            "mail-thread must not be reachable from the SSR entry fragment"
        );

        let asset = fs::read_to_string(asset_path).unwrap();
        assert!(asset.contains(r#""type":"webui-component-asset""#));
        assert!(asset.contains(r#""version":1"#));
        assert!(!asset.contains(r#""plugin""#));
        assert!(!asset.contains(r#""inventory""#));
        assert!(asset.contains(r#""components":["mail-message","mail-thread"]"#));
        assert!(asset.contains(r#""templates":{"mail-message":"#));
        assert!(asset.contains(r#""mail-thread":"#));
        assert!(asset.contains(r#""templateFunctions":{"mail-thread":"#));
        assert!(asset.contains("export default asset;"));
    }

    #[test]
    fn test_build_rejects_duplicate_component_assets_before_writing() {
        let app_dir = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            ("mail-thread.html", "<p>Mail</p>"),
        ]);
        let out_dir = TempDir::new().unwrap();

        let result = run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: Some(Plugin::WebUI),
                components: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: vec!["mail-thread".to_string(), "mail-thread".to_string()],
            theme: None,
        });

        assert!(result.is_err());
        assert!(!out_dir.path().join("protocol.bin").exists());
    }

    #[test]
    fn test_build_emits_fast_component_assets() {
        let app_dir = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            ("fast-card.html", "<p>{{title}}</p>"),
        ]);
        let out_dir = TempDir::new().unwrap();

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: Some(Plugin::FastV3),
                components: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: vec!["fast-card".to_string()],
            theme: None,
        })
        .unwrap();

        let asset_path = out_dir.path().join("fast-card.webui.js");
        assert!(asset_path.exists());
        let asset = fs::read_to_string(asset_path).unwrap();
        assert!(asset.contains(r#""type":"webui-component-asset""#));
        assert!(asset.contains(r#""version":1"#));
        assert!(!asset.contains(r#""plugin""#));
        assert!(!asset.contains(r#""templateFunctionModule""#));
        assert!(!asset.contains(r#""templateFunctions""#));
        assert!(asset.contains("<f-template"));
    }

    #[test]
    fn test_build_emits_hashed_component_asset_filename() {
        let app_dir = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            ("mail-thread.html", "<p>{{title}}</p>"),
        ]);
        let out_dir = TempDir::new().unwrap();

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: Some(Plugin::WebUI),
                components: Vec::new(),
                asset_file_name_template: "[name]-[hash].[ext]".to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: vec!["mail-thread".to_string()],
            theme: None,
        })
        .unwrap();

        let asset_names: Vec<String> = fs::read_dir(out_dir.path())
            .unwrap()
            .filter_map(|entry| {
                let entry = entry.unwrap();
                let name = entry.file_name();
                let name = name.to_string_lossy();
                if name.ends_with(".webui.js") {
                    Some(name.into_owned())
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(asset_names.len(), 1);
        assert!(asset_names[0].starts_with("mail-thread-"));
        assert!(asset_names[0].ends_with(".webui.js"));
        assert_ne!(asset_names[0], "mail-thread-.webui.js");
    }

    #[test]
    fn test_build_missing_index_html() {
        let app_dir = create_app_dir(&[("other.html", "<h1>Not index</h1>")]);
        let out_dir = TempDir::new().unwrap();

        let result = build(app_dir.path(), out_dir.path(), "index.html");
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(err.contains("Failed to read"));
    }

    #[test]
    fn test_build_missing_app_folder() {
        let out_dir = TempDir::new().unwrap();
        let result = build(Path::new("/nonexistent/path"), out_dir.path(), "index.html");
        assert!(result.is_err());
    }

    #[test]
    fn test_build_creates_output_dir() {
        let app_dir = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let out_dir = TempDir::new().unwrap();
        let nested_out = out_dir.path().join("nested").join("output");

        build(app_dir.path(), &nested_out, "index.html").unwrap();

        assert!(nested_out.join("protocol.bin").exists());
    }

    #[test]
    fn test_build_protocol_is_valid_protobuf() {
        let app_dir = create_app_dir(&[("index.html", "<h1>{{title}}</h1>")]);
        let out_dir = TempDir::new().unwrap();

        build(app_dir.path(), out_dir.path(), "index.html").unwrap();

        let bytes = fs::read(out_dir.path().join("protocol.bin")).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();
        assert!(protocol.fragments.contains_key("index.html"));
    }

    #[test]
    fn test_build_hello_world_example() {
        let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let app_dir = manifest_dir.join("../../examples/app/hello-world/src");
        let out_dir = TempDir::new().unwrap();

        build(&app_dir, out_dir.path(), "index.html").unwrap();

        let bytes = fs::read(out_dir.path().join("protocol.bin")).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();
        let index = &protocol.fragments["index.html"].fragments;

        assert!(index
            .iter()
            .any(|f| matches!(f.fragment.as_ref(), Some(Fragment::ForLoop(fl)) if fl.collection == "people")));
        assert!(index
            .iter()
            .any(|f| matches!(f.fragment.as_ref(), Some(Fragment::IfCond(_)))));
        assert!(index.iter().any(
            |f| matches!(f.fragment.as_ref(), Some(Fragment::Signal(s)) if s.value == "raw_description" && s.raw)
        ));
    }

    #[test]
    fn test_build_custom_entry_file() {
        let app_dir = create_app_dir(&[("page.html", "<h1>Custom Entry</h1>")]);
        let out_dir = TempDir::new().unwrap();

        build(app_dir.path(), out_dir.path(), "page.html").unwrap();

        let bytes = fs::read(out_dir.path().join("protocol.bin")).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();
        assert!(protocol.fragments.contains_key("page.html"));
        assert!(!protocol.fragments.contains_key("index.html"));
    }

    #[test]
    fn test_build_with_components_local_path() {
        // App directory with an entry that uses an external component
        let app_dir = create_app_dir(&[("index.html", "<ext-card>Hello</ext-card>")]);

        // External component directory (separate from app)
        let ext_dir = TempDir::new().unwrap();
        fs::write(
            ext_dir.path().join("ext-card.html"),
            "<div class=\"card\"><slot></slot></div>",
        )
        .unwrap();
        fs::write(
            ext_dir.path().join("ext-card.css"),
            ".card { border: 1px solid #ccc; }",
        )
        .unwrap();

        let out_dir = TempDir::new().unwrap();
        let ext_path = ext_dir.path().to_string_lossy().to_string();

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: vec![ext_path],
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: Vec::new(),
            theme: None,
        })
        .unwrap();

        // protocol.bin should exist
        assert!(out_dir.path().join("protocol.bin").exists());
        // External component CSS should be emitted
        let css_path = out_dir.path().join("ext-card.css");
        assert!(css_path.exists());
        let css = fs::read_to_string(&css_path).unwrap();
        assert!(css.contains("border"));
    }

    #[test]
    fn test_build_with_components_npm_package() {
        // Create a mock project with node_modules alongside app dir
        let project_dir = TempDir::new().unwrap();
        let nm = project_dir.path().join("node_modules");
        let pkg_dir = nm.join("test-widget");
        fs::create_dir_all(&pkg_dir).unwrap();

        // Create the npm package files
        fs::write(
            pkg_dir.join("template-webui.html"),
            "<button><slot></slot></button>",
        )
        .unwrap();
        fs::write(pkg_dir.join("styles.css"), ".btn { padding: 4px; }").unwrap();

        let manifest = serde_json::json!({
            "schemaVersion": "1.0.0",
            "modules": [{
                "kind": "javascript-module",
                "declarations": [{
                    "kind": "class",
                    "tagName": "test-widget"
                }]
            }]
        });
        fs::write(
            pkg_dir.join("custom-elements.json"),
            serde_json::to_string(&manifest).unwrap(),
        )
        .unwrap();

        let pkg_json = serde_json::json!({
            "name": "test-widget",
            "version": "1.0.0",
            "customElements": "./custom-elements.json",
            "exports": {
                "./template-webui.html": "./template-webui.html",
                "./styles.css": "./styles.css"
            }
        });
        fs::write(
            pkg_dir.join("package.json"),
            serde_json::to_string(&pkg_json).unwrap(),
        )
        .unwrap();

        // Create app directory under project_dir (node_modules found via upward walk)
        let app_dir = project_dir.path().join("src");
        fs::create_dir_all(&app_dir).unwrap();
        fs::write(
            app_dir.join("index.html"),
            "<test-widget>Click me</test-widget>",
        )
        .unwrap();

        let out_dir = TempDir::new().unwrap();

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir,
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: vec!["test-widget".to_string()],
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: Vec::new(),
            theme: None,
        })
        .unwrap();

        assert!(out_dir.path().join("protocol.bin").exists());
        let css_path = out_dir.path().join("test-widget.css");
        assert!(css_path.exists());
        let css = fs::read_to_string(&css_path).unwrap();
        assert!(css.contains("padding"));
    }

    #[test]
    fn test_build_with_components_npm_scoped() {
        // Create a mock scoped npm package
        let project_dir = TempDir::new().unwrap();
        let nm = project_dir.path().join("node_modules");
        let scope_dir = nm.join("@myui");
        fs::create_dir_all(&scope_dir).unwrap();

        // Create two sub-packages under the scope
        for (sub, tag, html) in &[
            ("btn", "myui-btn", "<button><slot></slot></button>"),
            ("txt", "myui-txt", "<span><slot></slot></span>"),
        ] {
            let pkg_dir = scope_dir.join(sub);
            fs::create_dir_all(&pkg_dir).unwrap();

            fs::write(pkg_dir.join("template-webui.html"), html).unwrap();

            let manifest = serde_json::json!({
                "schemaVersion": "1.0.0",
                "modules": [{
                    "kind": "javascript-module",
                    "declarations": [{ "kind": "class", "tagName": tag }]
                }]
            });
            fs::write(
                pkg_dir.join("custom-elements.json"),
                serde_json::to_string(&manifest).unwrap(),
            )
            .unwrap();

            let pkg_json = serde_json::json!({
                "name": format!("@myui/{sub}"),
                "version": "1.0.0",
                "customElements": "./custom-elements.json",
                "exports": {
                    "./template-webui.html": "./template-webui.html"
                }
            });
            fs::write(
                pkg_dir.join("package.json"),
                serde_json::to_string(&pkg_json).unwrap(),
            )
            .unwrap();
        }

        // App under project_dir
        let app_dir = project_dir.path().join("src");
        fs::create_dir_all(&app_dir).unwrap();
        fs::write(
            app_dir.join("index.html"),
            "<myui-btn>Go</myui-btn><myui-txt>Hi</myui-txt>",
        )
        .unwrap();

        let out_dir = TempDir::new().unwrap();

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir,
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: vec!["@myui".to_string()],
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: Vec::new(),
            theme: None,
        })
        .unwrap();

        assert!(out_dir.path().join("protocol.bin").exists());
    }

    #[test]
    fn test_build_protocol_includes_tokens_from_components() {
        let app_dir = create_app_dir(&[
            ("index.html", "<my-btn></my-btn>"),
            ("my-btn.html", "<button><slot></slot></button>"),
            (
                "my-btn.css",
                ".btn { color: var(--text-color); padding: var(--spacing-m); }",
            ),
        ]);
        let out_dir = TempDir::new().unwrap();

        build(app_dir.path(), out_dir.path(), "index.html").unwrap();

        let bytes = fs::read(out_dir.path().join("protocol.bin")).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();

        assert_eq!(protocol.tokens, vec!["spacing-m", "text-color"]);
    }

    #[test]
    fn test_build_theme_missing_token_fails() {
        let app_dir = create_app_dir(&[
            ("index.html", "<my-btn></my-btn>"),
            ("my-btn.html", "<button><slot></slot></button>"),
            (
                "my-btn.css",
                ":host { --token-a: red; --foo-bar: var(--token-a, var(--token-b, var(--token-c))); }",
            ),
            ("theme.json", r#"{"themes":{"light":{"token-b":"green"}}}"#),
        ]);
        let out_dir = TempDir::new().unwrap();
        let result = run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: out_dir.path().to_path_buf(),
            emit_component_assets: Vec::new(),
            theme: Some(
                app_dir
                    .path()
                    .join("theme.json")
                    .to_string_lossy()
                    .to_string(),
            ),
        });

        let err = result.expect_err("missing theme token must fail");
        let message = format!("{err:#}");
        assert!(message.contains("missing-theme-token"), "msg: {message}");
        assert!(message.contains("--token-c"), "msg: {message}");
        assert!(!out_dir.path().join("protocol.bin").exists());
    }

    #[test]
    fn test_build_custom_protocol_name() {
        let app_dir = create_app_dir(&[
            ("index.html", "<my-card>Hi</my-card>"),
            ("my-card.html", "<div><slot></slot></div>"),
            ("my-card.css", ".card { color: red; }"),
        ]);
        let out_dir = TempDir::new().unwrap();
        let custom_path = out_dir.path().join("app1.bin");

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: custom_path.clone(),
            emit_component_assets: Vec::new(),
            theme: None,
        })
        .unwrap();

        // Protocol is written under the requested filename, not protocol.bin.
        assert!(custom_path.exists());
        assert!(!out_dir.path().join("protocol.bin").exists());

        // The bytes are a valid protocol.
        let bytes = fs::read(&custom_path).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();
        assert!(protocol.fragments.contains_key("index.html"));

        // CSS files are emitted next to the renamed protocol.
        assert!(out_dir.path().join("my-card.css").exists());
    }

    #[test]
    fn test_build_custom_protocol_name_creates_parent_dir() {
        let app_dir = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let out_dir = TempDir::new().unwrap();
        let nested = out_dir.path().join("nested").join("app2.bin");

        run(&BuildArgs {
            app_args: AppArgs {
                app: app_dir.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            out: nested.clone(),
            emit_component_assets: Vec::new(),
            theme: None,
        })
        .unwrap();

        assert!(nested.exists());
        assert!(!nested.parent().unwrap().join("protocol.bin").exists());
    }

    #[test]
    fn test_resolve_out_directory() {
        let (dir, name) = resolve_out(Path::new("./dist"));
        assert_eq!(dir, PathBuf::from("./dist"));
        assert_eq!(name, "protocol.bin");
    }

    #[test]
    fn test_resolve_out_bin_file_with_parent() {
        let (dir, name) = resolve_out(Path::new("./dist/app1.bin"));
        assert_eq!(dir, PathBuf::from("./dist"));
        assert_eq!(name, "app1.bin");
    }

    #[test]
    fn test_resolve_out_bin_file_no_parent() {
        let (dir, name) = resolve_out(Path::new("app1.bin"));
        assert_eq!(dir, PathBuf::from("."));
        assert_eq!(name, "app1.bin");
    }

    #[test]
    fn test_build_protocol_excludes_entry_defined_tokens() {
        let html = r#"<style>
            :root { --text-color: #333; --spacing-m: 12px; }
            body { color: var(--text-color); }
        </style>
        <my-btn></my-btn>"#;
        let app_dir = create_app_dir(&[
            ("index.html", html),
            ("my-btn.html", "<button><slot></slot></button>"),
            (
                "my-btn.css",
                ".btn { color: var(--text-color); margin: var(--spacing-m); }",
            ),
        ]);
        let out_dir = TempDir::new().unwrap();

        build(app_dir.path(), out_dir.path(), "index.html").unwrap();

        let bytes = fs::read(out_dir.path().join("protocol.bin")).unwrap();
        let protocol = WebUIProtocol::from_protobuf(&bytes).unwrap();

        // Both tokens are defined in entry :root — should not be in protocol
        assert!(
            protocol.tokens.is_empty(),
            "Entry-defined tokens should be excluded: {:?}",
            protocol.tokens
        );
    }
}