microsoft-webui-discovery 0.0.26

External component discovery for WebUI framework
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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! npm package resolution for external component discovery.
//!
//! Resolves npm packages from `node_modules/` using Node.js-style upward
//! traversal. Reads `package.json` exports for template and styles, and
//! parses the Custom Elements Manifest for component tag names.

use anyhow::{bail, Context, Result};
use std::fs;
use std::path::{Component, Path, PathBuf};

use super::cache::{CacheKey, DiscoveryCache};
use super::{DiscoveredComponent, DiscoveryPlugin};

/// Validated npm package context presented to a discovery plugin.
#[derive(Debug, Clone, Copy)]
pub struct PackageContext<'a> {
    /// npm package name.
    pub name: &'a str,
    /// Canonical package root.
    pub root: &'a Path,
    /// Parsed `package.json`.
    pub manifest: &'a serde_json::Value,
    /// Whether package metadata exposes authored browser code.
    pub is_client_owned: bool,
}

pub(crate) struct ComponentDeclaration {
    pub(crate) tag_name: String,
    pub(crate) name: Option<String>,
    pub(crate) module_path: Option<PathBuf>,
}

pub(crate) struct WebUIAssets {
    pub(crate) template_path: PathBuf,
    pub(crate) styles_path: Option<PathBuf>,
    pub(crate) manifest_path: PathBuf,
}

/// Maximum file size for package.json and custom elements manifests (10 MB).
const MAX_MANIFEST_SIZE: u64 = 10 * 1024 * 1024;

/// Conditional export keys in priority order for fallback resolution.
const EXPORT_PRIORITY: &[&str] = &["default", "import", "require"];

/// Package fields that conventionally point to a browser/module entry.
const SCRIPT_ENTRY_FIELDS: &[&str] = &["main", "module", "browser"];

/// WebUI asset exports that do not imply authored browser code.
const WEBUI_ASSET_EXPORTS: &[&str] = &[
    "./template-webui.html",
    "./styles.css",
    "./component-asset.js",
];

/// Find `node_modules/` by walking up from `start` directory.
fn find_node_modules(start: &Path) -> Result<PathBuf> {
    let mut current = Some(start);
    while let Some(dir) = current {
        let candidate = dir.join("node_modules");
        if candidate.is_dir() {
            return Ok(candidate);
        }
        current = dir.parent();
    }
    bail!(
        "Could not find node_modules/ directory \
         (searched upward from {})",
        start.display()
    );
}

/// Find `node_modules/` by walking up from `primary`, falling back to a
/// walk up from `fallback` when the primary search comes up empty.
///
/// The fallback rescues callers whose primary search root lives outside
/// any project tree. For example, `webui-press` builds each docs page in a
/// synthesized scratch directory under the system temp folder, which has no
/// `node_modules` ancestor; the project's `node_modules` is instead reached
/// from the process working directory the command was invoked in. The error
/// from the primary search is preserved when both roots fail.
fn find_node_modules_with_fallback(primary: &Path, fallback: &Path) -> Result<PathBuf> {
    find_node_modules(primary).or_else(|primary_err| {
        if fallback == primary {
            return Err(primary_err);
        }
        find_node_modules(fallback).map_err(|_| primary_err)
    })
}

/// Check if a package name is a bare scope (e.g., `@reactive-ui` without a sub-package).
fn is_bare_scope(name: &str) -> bool {
    name.starts_with('@') && !name.contains('/')
}

/// Validate that a relative path from package.json does not escape the package directory.
///
/// Rejects absolute paths, root-relative paths, and any `..` components
/// to prevent path traversal attacks.
fn validate_relative_path(rel_path: &str, field_name: &str) -> Result<()> {
    let path = Path::new(rel_path);
    if path.is_absolute() || rel_path.starts_with('/') || rel_path.starts_with('\\') {
        bail!("Absolute path not allowed in {}: {}", field_name, rel_path);
    }
    if path.components().any(|c| matches!(c, Component::ParentDir)) {
        bail!(
            "Parent directory traversal (..) not allowed in {}: {}",
            field_name,
            rel_path
        );
    }
    Ok(())
}

/// Read a file with a size limit to prevent denial-of-service via oversized manifests.
fn read_to_string_limited(path: &Path, max_size: u64) -> Result<String> {
    let metadata =
        fs::metadata(path).with_context(|| format!("Failed to stat {}", path.display()))?;
    if metadata.len() > max_size {
        bail!(
            "File too large ({} bytes, max {}): {}",
            metadata.len(),
            max_size,
            path.display()
        );
    }
    fs::read_to_string(path).with_context(|| format!("Failed to read {}", path.display()))
}

/// Resolve an npm package or scope to discovered components.
pub fn resolve(
    name: &str,
    search_dir: &Path,
    plugin: &dyn DiscoveryPlugin,
    cache: &mut DiscoveryCache,
) -> Result<Vec<DiscoveredComponent>> {
    // Walk up from the build's app directory first, then fall back to the
    // process working directory. The fallback covers callers whose app
    // directory lives outside the project (e.g. a system-temp scratch dir),
    // where the project's `node_modules` is only reachable from the cwd the
    // command was invoked in.
    let fallback = std::env::current_dir().unwrap_or_else(|_| search_dir.to_path_buf());
    let node_modules = find_node_modules_with_fallback(search_dir, &fallback)?;

    if is_bare_scope(name) {
        resolve_scoped(name, &node_modules, plugin, cache)
    } else {
        resolve_single(name, &node_modules, plugin, cache)
    }
}

/// Enumerate all sub-packages under a scoped directory (e.g., `@reactive-ui/*`).
fn resolve_scoped(
    scope: &str,
    node_modules: &Path,
    plugin: &dyn DiscoveryPlugin,
    cache: &mut DiscoveryCache,
) -> Result<Vec<DiscoveredComponent>> {
    let scope_dir = node_modules.join(scope);
    if !scope_dir.is_dir() {
        bail!(
            "Scoped package directory not found: {}",
            scope_dir.display()
        );
    }

    let mut all = Vec::new();
    for entry in fs::read_dir(&scope_dir)
        .with_context(|| format!("Failed to read scope directory: {}", scope_dir.display()))?
    {
        let entry = entry?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let sub_name = format!("{}/{}", scope, entry.file_name().to_string_lossy());
        // Sub-packages without WebUI exports are expected — skip silently.
        if let Ok(components) = resolve_single(&sub_name, node_modules, plugin, cache) {
            all.extend(components);
        }
    }

    Ok(all)
}

/// Resolve a single npm package to discovered components.
fn resolve_single(
    name: &str,
    node_modules: &Path,
    plugin: &dyn DiscoveryPlugin,
    cache: &mut DiscoveryCache,
) -> Result<Vec<DiscoveredComponent>> {
    let pkg_dir = node_modules.join(name);

    // Resolve symlinks (pnpm, npm workspaces, yarn)
    let pkg_dir = fs::canonicalize(&pkg_dir).with_context(|| {
        format!(
            "Package not found or broken symlink: {} (looked in {})",
            name,
            node_modules.display()
        )
    })?;

    if !pkg_dir.is_dir() {
        bail!("Package path is not a directory: {}", pkg_dir.display());
    }

    let pkg_json_path = pkg_dir.join("package.json");
    if !pkg_json_path.exists() {
        bail!("No package.json found at {}", pkg_json_path.display());
    }

    // Read and parse package.json
    let pkg_json_content = read_to_string_limited(&pkg_json_path, MAX_MANIFEST_SIZE)?;
    let pkg_json: serde_json::Value = serde_json::from_str(&pkg_json_content)
        .with_context(|| format!("Failed to parse {}", pkg_json_path.display()))?;

    let is_client_owned = package_has_authored_script(&pkg_json);
    let package = PackageContext {
        name,
        root: &pkg_dir,
        manifest: &pkg_json,
        is_client_owned,
    };
    let cache_files = plugin.package_cache_files(package)?;
    let fingerprint = DiscoveryCache::fingerprint(&pkg_json_path, &cache_files)?;
    let cache_key = CacheKey {
        namespace: plugin.cache_namespace(),
        source: name,
        package_json: &pkg_json_path,
        fingerprint,
    };
    if let Some(cached) = cache.get(&cache_key)? {
        return Ok(cached);
    }
    let components = plugin.discover_package(package)?;

    // Do not persist a mixed snapshot if package files changed during discovery.
    if DiscoveryCache::fingerprint(&pkg_json_path, &cache_files)? == fingerprint {
        cache.put(&cache_key, &components)?;
    }

    Ok(components)
}

/// Resolve an export path from the `exports` field in `package.json`.
///
/// Handles two common formats:
/// - Direct string: `"./template-webui.html": "./dist/template.html"`
/// - Conditional object: `"./template-webui.html": { "default": "./dist/template.html" }`
fn resolve_export(exports: &serde_json::Value, key: &str) -> Option<String> {
    match exports.get(key)? {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Object(obj) => {
            for key in EXPORT_PRIORITY {
                if let Some(serde_json::Value::String(s)) = obj.get(*key) {
                    return Some(s.clone());
                }
            }
            None
        }
        _ => None,
    }
}

pub(crate) fn resolve_webui_assets(package: PackageContext<'_>) -> Result<WebUIAssets> {
    let package_json = package.root.join("package.json");
    let exports = package
        .manifest
        .get("exports")
        .with_context(|| format!("No 'exports' field in {}", package_json.display()))?;
    let template_rel = resolve_export(exports, "./template-webui.html").with_context(|| {
        format!(
            "No './template-webui.html' export in {}",
            package_json.display()
        )
    })?;
    validate_relative_path(&template_rel, "exports[\"./template-webui.html\"]")?;
    let styles_path = if let Some(relative) = resolve_export(exports, "./styles.css") {
        validate_relative_path(&relative, "exports[\"./styles.css\"]")?;
        Some(package.root.join(relative))
    } else {
        None
    };
    Ok(WebUIAssets {
        template_path: package.root.join(template_rel),
        styles_path,
        manifest_path: custom_elements_manifest_path(package)?,
    })
}

pub(crate) fn package_component_declarations(
    package: PackageContext<'_>,
) -> Result<Vec<ComponentDeclaration>> {
    let path = custom_elements_manifest_path(package)?;
    parse_custom_elements_manifest(&path)
}

pub(crate) fn custom_elements_manifest_path(package: PackageContext<'_>) -> Result<PathBuf> {
    let package_json = package.root.join("package.json");
    let relative = package
        .manifest
        .get("customElements")
        .and_then(serde_json::Value::as_str)
        .with_context(|| format!("No 'customElements' field in {}", package_json.display()))?;
    validate_relative_path(relative, "customElements")?;
    Ok(package.root.join(relative))
}

pub(crate) fn read_required_file(path: &Path, kind: &str) -> Result<String> {
    read_to_string_limited(path, MAX_MANIFEST_SIZE)
        .with_context(|| format!("Failed to read {kind}: {}", path.display()))
}

pub(crate) fn read_optional_file(path: Option<&Path>, kind: &str) -> Result<Option<String>> {
    match path {
        Some(path) if path.is_file() => read_required_file(path, kind).map(Some),
        _ => Ok(None),
    }
}

fn package_has_authored_script(pkg_json: &serde_json::Value) -> bool {
    for field in SCRIPT_ENTRY_FIELDS {
        match pkg_json.get(*field) {
            Some(serde_json::Value::String(path)) if is_script_path(path) => return true,
            Some(serde_json::Value::Object(map)) if map.values().any(export_value_has_script) => {
                return true;
            }
            _ => {}
        }
    }

    let Some(exports) = pkg_json.get("exports") else {
        return false;
    };
    match exports {
        serde_json::Value::String(path) => is_script_path(path),
        serde_json::Value::Array(values) => values.iter().any(export_value_has_script),
        serde_json::Value::Object(map) => {
            if let Some(root) = map.get(".") {
                return export_value_has_script(root);
            }
            map.iter()
                .any(|(key, value)| !is_webui_asset_export(key) && export_value_has_script(value))
        }
        _ => false,
    }
}

fn export_value_has_script(value: &serde_json::Value) -> bool {
    match value {
        serde_json::Value::String(path) => is_script_path(path),
        serde_json::Value::Array(values) => values.iter().any(export_value_has_script),
        serde_json::Value::Object(map) => map.values().any(export_value_has_script),
        _ => false,
    }
}

fn is_webui_asset_export(key: &str) -> bool {
    WEBUI_ASSET_EXPORTS.contains(&key)
}

fn is_script_path(path: &str) -> bool {
    let path = path.split_once('?').map_or(path, |(prefix, _)| prefix);
    path.ends_with(".js")
        || path.ends_with(".mjs")
        || path.ends_with(".cjs")
        || path.ends_with(".ts")
}

// Parse `modules[].{path,declarations[].{name,tagName}}` from a Custom Elements
// Manifest.
fn parse_custom_elements_manifest(path: &Path) -> Result<Vec<ComponentDeclaration>> {
    let content = read_to_string_limited(path, MAX_MANIFEST_SIZE)
        .with_context(|| format!("Custom elements manifest: {}", path.display()))?;
    let manifest: serde_json::Value = serde_json::from_str(&content).with_context(|| {
        format!(
            "Failed to parse custom elements manifest: {}",
            path.display()
        )
    })?;

    let mut seen = std::collections::HashSet::new();
    let mut declarations = Vec::new();

    if let Some(modules) = manifest.get("modules").and_then(|v| v.as_array()) {
        for module in modules {
            let module_path = module.get("path").and_then(|value| value.as_str());
            if let Some(path) = module_path {
                validate_relative_path(path, "customElements modules[].path")?;
            }
            if let Some(module_declarations) = module.get("declarations").and_then(|v| v.as_array())
            {
                for declaration in module_declarations {
                    let Some(tag_name) =
                        declaration.get("tagName").and_then(|value| value.as_str())
                    else {
                        continue;
                    };
                    if seen.insert(tag_name) {
                        declarations.push(ComponentDeclaration {
                            tag_name: tag_name.to_string(),
                            name: declaration
                                .get("name")
                                .and_then(|value| value.as_str())
                                .map(str::to_string),
                            module_path: module_path.map(PathBuf::from),
                        });
                    }
                }
            }
        }
    }

    Ok(declarations)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::WebUIDiscoveryPlugin;
    use std::fs;
    use tempfile::TempDir;

    fn create_npm_package(dir: &Path, name: &str, tag_name: &str, html: &str, css: Option<&str>) {
        let pkg_dir = dir.join(name);
        fs::create_dir_all(&pkg_dir).unwrap();

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

        // Create styles (optional)
        if let Some(css_content) = css {
            fs::write(pkg_dir.join("styles.css"), css_content).unwrap();
        }

        // Create custom elements manifest
        let manifest = serde_json::json!({
            "schemaVersion": "1.0.0",
            "modules": [{
                "kind": "javascript-module",
                "path": "src/index.js",
                "declarations": [{
                    "kind": "class",
                    "name": "MyComponent",
                    "tagName": tag_name
                }]
            }]
        });
        fs::write(
            pkg_dir.join("custom-elements.json"),
            serde_json::to_string_pretty(&manifest).unwrap(),
        )
        .unwrap();

        // Create package.json with exports
        let mut exports = serde_json::json!({
            "./template-webui.html": "./template-webui.html",
        });
        if css.is_some() {
            exports["./styles.css"] = serde_json::json!("./styles.css");
        }
        let pkg_json = serde_json::json!({
            "name": name,
            "version": "1.0.0",
            "customElements": "./custom-elements.json",
            "exports": exports
        });
        fs::write(
            pkg_dir.join("package.json"),
            serde_json::to_string_pretty(&pkg_json).unwrap(),
        )
        .unwrap();
    }

    #[test]
    fn test_find_node_modules_in_cwd() {
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        fs::create_dir(&nm).unwrap();

        let result = find_node_modules(tmp.path());
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap().canonicalize().unwrap(),
            nm.canonicalize().unwrap()
        );
    }

    #[test]
    fn test_find_node_modules_walks_up() {
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        fs::create_dir(&nm).unwrap();
        let sub = tmp.path().join("packages").join("my-app");
        fs::create_dir_all(&sub).unwrap();

        let result = find_node_modules(&sub);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap().canonicalize().unwrap(),
            nm.canonicalize().unwrap()
        );
    }

    #[test]
    fn test_find_node_modules_not_found() {
        let tmp = TempDir::new().unwrap();
        let result = find_node_modules(tmp.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_find_node_modules_fallback_used_when_primary_empty() {
        let primary = TempDir::new().unwrap();
        let project = TempDir::new().unwrap();
        let nm = project.path().join("node_modules");
        fs::create_dir_all(&nm).unwrap();

        let found = find_node_modules_with_fallback(primary.path(), project.path()).unwrap();
        assert_eq!(found, nm);
    }

    #[test]
    fn test_find_node_modules_fallback_prefers_primary() {
        let primary = TempDir::new().unwrap();
        let nm_primary = primary.path().join("node_modules");
        fs::create_dir_all(&nm_primary).unwrap();
        let project = TempDir::new().unwrap();
        fs::create_dir_all(project.path().join("node_modules")).unwrap();

        let found = find_node_modules_with_fallback(primary.path(), project.path()).unwrap();
        assert_eq!(found, nm_primary);
    }

    #[test]
    fn test_find_node_modules_fallback_errors_when_neither_has_it() {
        let primary = TempDir::new().unwrap();
        let fallback = TempDir::new().unwrap();
        assert!(find_node_modules_with_fallback(primary.path(), fallback.path()).is_err());
    }

    #[test]
    fn test_is_bare_scope() {
        assert!(is_bare_scope("@reactive-ui"));
        assert!(is_bare_scope("@scope"));
        assert!(!is_bare_scope("@scope/button"));
        assert!(!is_bare_scope("my-widget"));
    }

    #[test]
    fn test_resolve_single_package() {
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        fs::create_dir(&nm).unwrap();

        create_npm_package(
            &nm,
            "my-widget",
            "my-widget",
            "<div><slot></slot></div>",
            Some(".widget { color: blue; }"),
        );

        let mut cache = DiscoveryCache::open().unwrap();
        let result = resolve(
            "my-widget",
            tmp.path(),
            &WebUIDiscoveryPlugin::new(),
            &mut cache,
        );
        assert!(result.is_ok());

        let components = result.unwrap();
        assert_eq!(components.len(), 1);
        assert_eq!(components[0].tag_name, "my-widget");
        assert_eq!(components[0].html_content, "<div><slot></slot></div>");
        assert_eq!(
            components[0].css_content.as_deref(),
            Some(".widget { color: blue; }")
        );
        assert!(!components[0].is_client_owned);
    }

    #[test]
    fn test_package_script_ownership_uses_manifest_entrypoints() {
        let static_pkg = serde_json::json!({
            "exports": {
                "./template-webui.html": "./template-webui.html",
                "./styles.css": "./styles.css"
            }
        });
        let interactive_pkg = serde_json::json!({
            "exports": {
                ".": { "import": "./dist/index.js" },
                "./template-webui.html": "./template-webui.html"
            }
        });
        let module_pkg = serde_json::json!({
            "module": "./dist/index.mjs",
            "exports": {
                "./template-webui.html": "./template-webui.html"
            }
        });

        assert!(!package_has_authored_script(&static_pkg));
        assert!(package_has_authored_script(&interactive_pkg));
        assert!(package_has_authored_script(&module_pkg));
    }

    #[test]
    fn test_resolve_scoped_package() {
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        let scope_dir = nm.join("@mylib");
        fs::create_dir_all(&scope_dir).unwrap();

        create_npm_package(
            &scope_dir,
            "button",
            "mylib-button",
            "<button><slot></slot></button>",
            Some(".btn { padding: 8px; }"),
        );
        create_npm_package(
            &scope_dir,
            "text",
            "mylib-text",
            "<span><slot></slot></span>",
            None,
        );

        let mut cache = DiscoveryCache::open().unwrap();
        let result = resolve(
            "@mylib",
            tmp.path(),
            &WebUIDiscoveryPlugin::new(),
            &mut cache,
        );
        assert!(result.is_ok());

        let components = result.unwrap();
        assert_eq!(components.len(), 2);

        let names: Vec<&str> = components.iter().map(|c| c.tag_name.as_str()).collect();
        assert!(names.contains(&"mylib-button"));
        assert!(names.contains(&"mylib-text"));
    }

    #[test]
    fn test_resolve_missing_package() {
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        fs::create_dir(&nm).unwrap();

        let mut cache = DiscoveryCache::open().unwrap();
        let result = resolve(
            "nonexistent",
            tmp.path(),
            &WebUIDiscoveryPlugin::new(),
            &mut cache,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_export_direct_string() {
        let exports = serde_json::json!({
            "./template-webui.html": "./dist/template.html"
        });
        let result = resolve_export(&exports, "./template-webui.html");
        assert_eq!(result, Some("./dist/template.html".to_string()));
    }

    #[test]
    fn test_resolve_export_conditional_default() {
        let exports = serde_json::json!({
            "./template-webui.html": {
                "import": "./dist/template.mjs",
                "default": "./dist/template.html"
            }
        });
        let result = resolve_export(&exports, "./template-webui.html");
        assert_eq!(result, Some("./dist/template.html".to_string()));
    }

    #[test]
    fn test_resolve_export_conditional_fallback() {
        let exports = serde_json::json!({
            "./template-webui.html": {
                "import": "./dist/template.mjs"
            }
        });
        let result = resolve_export(&exports, "./template-webui.html");
        assert_eq!(result, Some("./dist/template.mjs".to_string()));
    }

    #[test]
    fn test_resolve_export_missing() {
        let exports = serde_json::json!({
            "./other.html": "./dist/other.html"
        });
        let result = resolve_export(&exports, "./template-webui.html");
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_custom_elements_manifest() {
        let tmp = TempDir::new().unwrap();
        let manifest = serde_json::json!({
            "schemaVersion": "1.0.0",
            "modules": [
                {
                    "kind": "javascript-module",
                    "path": "src/button.js",
                    "declarations": [
                        {
                            "kind": "class",
                            "name": "MyButton",
                            "tagName": "my-button"
                        }
                    ]
                },
                {
                    "kind": "javascript-module",
                    "path": "src/text.js",
                    "declarations": [
                        {
                            "kind": "class",
                            "name": "MyText",
                            "tagName": "my-text"
                        },
                        {
                            "kind": "variable",
                            "name": "VERSION"
                        }
                    ]
                }
            ]
        });

        let cem_path = tmp.path().join("custom-elements.json");
        fs::write(&cem_path, serde_json::to_string_pretty(&manifest).unwrap()).unwrap();

        let result = parse_custom_elements_manifest(&cem_path);
        assert!(result.is_ok());

        let declarations = result.unwrap();
        assert_eq!(declarations.len(), 2);
        assert_eq!(declarations[0].tag_name, "my-button");
        assert_eq!(declarations[1].tag_name, "my-text");
    }

    #[test]
    fn test_parse_custom_elements_manifest_empty() {
        let tmp = TempDir::new().unwrap();
        let manifest = serde_json::json!({
            "schemaVersion": "1.0.0",
            "modules": []
        });

        let cem_path = tmp.path().join("custom-elements.json");
        fs::write(&cem_path, serde_json::to_string_pretty(&manifest).unwrap()).unwrap();

        let result = parse_custom_elements_manifest(&cem_path);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_parse_custom_elements_manifest_deduplicates() {
        let tmp = TempDir::new().unwrap();
        let manifest = serde_json::json!({
            "schemaVersion": "1.0.0",
            "modules": [
                {
                    "kind": "javascript-module",
                    "path": "src/button.js",
                    "declarations": [{ "kind": "class", "name": "MyButton", "tagName": "my-button" }]
                },
                {
                    "kind": "javascript-module",
                    "path": "src/other-button.js",
                    "declarations": [{ "kind": "class", "name": "OtherButton", "tagName": "my-button" }]
                }
            ]
        });

        let cem_path = tmp.path().join("custom-elements.json");
        fs::write(&cem_path, serde_json::to_string(&manifest).unwrap()).unwrap();

        let declarations = parse_custom_elements_manifest(&cem_path).unwrap();
        assert_eq!(declarations.len(), 1);
        assert_eq!(declarations[0].tag_name, "my-button");
    }

    #[test]
    fn test_cached_result_is_reused() {
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        fs::create_dir(&nm).unwrap();

        create_npm_package(&nm, "cached-pkg", "cached-comp", "<div>cached</div>", None);

        let mut cache = DiscoveryCache::open().unwrap();

        // First resolve: populates cache
        let first = resolve(
            "cached-pkg",
            tmp.path(),
            &WebUIDiscoveryPlugin::new(),
            &mut cache,
        )
        .unwrap();
        assert_eq!(first.len(), 1);
        assert_eq!(first[0].tag_name, "cached-comp");

        // Second resolve: should hit cache
        let second = resolve(
            "cached-pkg",
            tmp.path(),
            &WebUIDiscoveryPlugin::new(),
            &mut cache,
        )
        .unwrap();
        assert_eq!(second.len(), 1);
        assert_eq!(second[0].tag_name, "cached-comp");
    }

    #[test]
    fn test_validate_relative_path_rejects_absolute() {
        let result = validate_relative_path("/etc/passwd", "exports");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Absolute path"));
    }

    #[test]
    fn test_validate_relative_path_rejects_parent_traversal() {
        let result = validate_relative_path("../../etc/passwd", "exports");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains(".."));
    }

    #[test]
    fn test_validate_relative_path_rejects_hidden_traversal() {
        let result = validate_relative_path("foo/../../../etc/passwd", "exports");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_relative_path_accepts_valid() {
        assert!(validate_relative_path("./dist/template.html", "exports").is_ok());
        assert!(validate_relative_path("template-webui.html", "exports").is_ok());
        assert!(validate_relative_path("dist/nested/file.css", "exports").is_ok());
    }

    #[test]
    fn test_resolve_symlinked_package() {
        // Simulates pnpm-style layout where node_modules/@scope/pkg is a symlink
        // to node_modules/.pnpm/@scope+pkg@version/node_modules/@scope/pkg.
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        fs::create_dir(&nm).unwrap();

        // Create the real package inside .pnpm store
        let pnpm_store = nm
            .join(".pnpm")
            .join("my-widget@1.0.0")
            .join("node_modules");
        fs::create_dir_all(&pnpm_store).unwrap();
        create_npm_package(
            &pnpm_store,
            "my-widget",
            "my-widget",
            "<div>symlinked</div>",
            Some(".w { color: red; }"),
        );

        // Create a symlink: node_modules/my-widget -> .pnpm store location
        let link_path = nm.join("my-widget");
        let target_path = pnpm_store.join("my-widget");

        #[cfg(unix)]
        std::os::unix::fs::symlink(&target_path, &link_path).unwrap();
        #[cfg(windows)]
        std::os::windows::fs::symlink_dir(&target_path, &link_path).unwrap();

        let mut cache = DiscoveryCache::open().unwrap();
        let result = resolve(
            "my-widget",
            tmp.path(),
            &WebUIDiscoveryPlugin::new(),
            &mut cache,
        );
        assert!(
            result.is_ok(),
            "symlinked package should resolve: {result:?}"
        );

        let components = result.unwrap();
        assert_eq!(components.len(), 1);
        assert_eq!(components[0].tag_name, "my-widget");
        assert_eq!(components[0].html_content, "<div>symlinked</div>");
    }

    #[test]
    fn test_resolve_scoped_symlinked_package() {
        // Simulates pnpm layout for scoped packages:
        // node_modules/@scope/pkg -> .pnpm/@scope+pkg@ver/node_modules/@scope/pkg
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        let scope_dir = nm.join("@mai-ui");
        fs::create_dir_all(&scope_dir).unwrap();

        // Real package inside .pnpm store
        let pnpm_store = nm
            .join(".pnpm")
            .join("@mai-ui+button@1.8.3")
            .join("node_modules")
            .join("@mai-ui");
        fs::create_dir_all(&pnpm_store).unwrap();
        create_npm_package(
            &pnpm_store,
            "button",
            "mai-button",
            "<button><slot></slot></button>",
            None,
        );

        // Symlink: node_modules/@mai-ui/button -> .pnpm store
        let link_path = scope_dir.join("button");
        let target_path = pnpm_store.join("button");

        #[cfg(unix)]
        std::os::unix::fs::symlink(&target_path, &link_path).unwrap();
        #[cfg(windows)]
        std::os::windows::fs::symlink_dir(&target_path, &link_path).unwrap();

        let mut cache = DiscoveryCache::open().unwrap();
        let result = resolve(
            "@mai-ui",
            tmp.path(),
            &WebUIDiscoveryPlugin::new(),
            &mut cache,
        );
        assert!(
            result.is_ok(),
            "scoped symlinked package should resolve: {result:?}"
        );

        let components = result.unwrap();
        assert_eq!(components.len(), 1);
        assert_eq!(components[0].tag_name, "mai-button");
    }

    #[test]
    fn test_resolve_rejects_path_traversal_in_exports() {
        let tmp = TempDir::new().unwrap();
        let nm = tmp.path().join("node_modules");
        let pkg_dir = nm.join("evil-pkg");
        fs::create_dir_all(&pkg_dir).unwrap();

        // Malicious package.json with path traversal in exports
        let pkg_json = serde_json::json!({
            "name": "evil-pkg",
            "version": "1.0.0",
            "customElements": "./custom-elements.json",
            "exports": {
                "./template-webui.html": "../../../etc/passwd"
            }
        });
        fs::write(
            pkg_dir.join("package.json"),
            serde_json::to_string(&pkg_json).unwrap(),
        )
        .unwrap();

        let mut cache = DiscoveryCache::open().unwrap();
        let result = resolve(
            "evil-pkg",
            tmp.path(),
            &WebUIDiscoveryPlugin::new(),
            &mut cache,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains(".."));
    }
}