microsoft-webui-discovery 0.0.29

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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! FAST manifest naming and converted template/style layouts.

use super::DiscoveryPlugin;
use crate::npm::{
    bare_module_package_name, package_component_declarations, package_export_path,
    package_export_path_from_metadata, package_has_authored_script, package_metadata,
    read_optional_file, read_required_file, resolve_bare_module_specifier,
    resolve_self_module_specifier, validate_package_asset_path, ComponentDeclaration,
    PackageContext,
};
use crate::{has_sibling_script, DiscoveredComponent};
use anyhow::{bail, Context, Result};
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use walkdir::WalkDir;

// Initial estimate for module, template, and style dependencies.
const FAST_CACHE_FILES_PER_COMPONENT: usize = 16;

/// Discovery for FAST generated component layouts.
#[derive(Debug, Default, Clone, Copy)]
pub struct FastDiscoveryPlugin;

impl FastDiscoveryPlugin {
    /// Create FAST discovery.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl DiscoveryPlugin for FastDiscoveryPlugin {
    fn cache_namespace(&self) -> &'static str {
        "fast"
    }

    fn requires_package_metadata(&self) -> bool {
        true
    }

    fn discover_local(&self, root: &Path) -> Result<Vec<DiscoveredComponent>> {
        discover_local_templates(root, fast_local_tag)
    }

    fn supports_package(&self, package: PackageContext<'_>) -> Result<bool> {
        if package_metadata(package)?.get("customElements").is_some() {
            return Ok(true);
        }
        crate::catalog::has_templates_matching(&crate::catalog::root(package)?, ordinary_html)
    }

    fn package_cache_files(&self, package: PackageContext<'_>) -> Result<Vec<PathBuf>> {
        let declarations = declarations(package)?;
        let names: HashSet<_> = declarations
            .iter()
            .map(|item| item.tag_name.as_str())
            .collect();
        let mut files =
            crate::catalog::cache_files_matching(&crate::catalog::root(package)?, |path| {
                fallback_html(path, &names)
            })?;
        if package_metadata(package)?.get("customElements").is_some() {
            files.push(crate::npm::custom_elements_manifest_path(package)?);
        }
        if declarations.is_empty() {
            return Ok(files);
        }
        let assets = exported_assets(package, declarations.len())?;
        let capacity = if assets.template.is_some() {
            4
        } else {
            1 + declarations.len() * FAST_CACHE_FILES_PER_COMPONENT
        };
        files.reserve(capacity);
        let uses_package_template = assets.template.is_some();
        for declaration in declarations {
            let module = resolve_declaration_module(package, &declaration, !uses_package_template)?;
            files.extend(module.resolution_dependencies.iter().cloned());
            if let Some(package_json) = &module.package_json {
                files.push(package_json.clone());
            }
            let module_path =
                package_path(&module.root, &module.relative_path).with_context(|| {
                    format!(
                        "FAST component <{}> in package '{}' has an invalid CEM module path",
                        declaration.tag_name, package.name
                    )
                })?;
            validate_module_asset(&module, &module_path, "FAST component module")?;
            files.push(module_path);
            if uses_package_template {
                continue;
            }
            let chosen_styles = assets.styles.as_ref().or(module.exported_styles.as_ref());
            if let Some(template) = &module.exported_template {
                if let Some(styles) = chosen_styles {
                    files.push(styles.clone());
                } else {
                    for styles in fast_style_candidates(template) {
                        validate_module_asset(&module, &styles, "FAST component styles")?;
                        files.push(styles);
                    }
                }
                files.push(template.clone());
                continue;
            }
            let declaration_name = declaration.name.as_deref().unwrap_or(&declaration.tag_name);
            for candidate in
                fast_template_candidates(&module.root, &module.relative_path, declaration_name)
            {
                validate_module_asset(&module, &candidate, "FAST component template")?;
                files.push(candidate.clone());
                if chosen_styles.is_none() {
                    for styles in fast_style_candidates(&candidate) {
                        validate_module_asset(&module, &styles, "FAST component styles")?;
                        files.push(styles);
                    }
                }
            }
            if assets.styles.is_none() {
                files.extend(module.exported_styles);
            }
        }
        if let Some(template) = assets.template {
            if let Some(styles) = assets.styles {
                files.push(styles);
            } else {
                for styles in fast_style_candidates(&template) {
                    validate_package_asset_path(package.root, &styles, "FAST component styles")?;
                    files.push(styles);
                }
            }
            files.push(template);
        } else {
            files.extend(assets.styles);
        }
        Ok(files)
    }

    fn discover_package(&self, package: PackageContext<'_>) -> Result<Vec<DiscoveredComponent>> {
        let declarations = declarations(package)?;
        let mut components = {
            let names: HashSet<_> = declarations
                .iter()
                .map(|item| item.tag_name.as_str())
                .collect();
            crate::catalog::discover_matching(
                package.name,
                &crate::catalog::root(package)?,
                |path| fallback_html(path, &names),
            )?
        };
        if declarations.is_empty() {
            if components.is_empty() {
                bail!(
                    "No components found in package '{}'. Declare FAST components through \
                     customElements or provide <component-name>.html files.",
                    package.name
                );
            }
            return Ok(components);
        }

        let assets = exported_assets(package, declarations.len())?;
        components.reserve(declarations.len());
        let source_is_client_owned = package_has_authored_script(package_metadata(package)?);
        let mut seen_templates = HashSet::with_capacity(declarations.len());
        for declaration in declarations {
            let uses_package_template = assets.template.is_some();
            let module = resolve_declaration_module(package, &declaration, !uses_package_template)?;
            let template_path = if let Some(path) = &assets.template {
                path.clone()
            } else {
                inferred_template(package, &declaration, &module)?
            };
            if !seen_templates.insert(template_path.clone()) {
                bail!(
                    "FAST template {} maps to multiple component declarations",
                    template_path.display()
                );
            }
            let html_content = read_required_file(&template_path, "FAST component template")?;
            let module_styles = if uses_package_template {
                None
            } else {
                module.exported_styles.as_ref()
            };
            let css_content = match (&assets.styles, module_styles) {
                (Some(path), _) | (None, Some(path)) => {
                    Some(read_required_file(path, "FAST component styles")?)
                }
                (None, None) => {
                    let styles = resolve_fast_styles(&template_path);
                    if let Some(path) = &styles {
                        if uses_package_template {
                            validate_package_asset_path(
                                package.root,
                                path,
                                "FAST component styles",
                            )?;
                        } else {
                            validate_module_asset(&module, path, "FAST component styles")?;
                        }
                    }
                    read_optional_file(styles.as_deref(), "FAST component styles")?
                }
            };
            components.push(DiscoveredComponent {
                tag_name: declaration.tag_name,
                html_content,
                css_content,
                is_client_owned: source_is_client_owned || module.is_client_owned,
                source: package.name.to_string(),
            });
        }
        Ok(components)
    }
}

fn declarations(package: PackageContext<'_>) -> Result<Vec<ComponentDeclaration>> {
    if package_metadata(package)?.get("customElements").is_some() {
        package_component_declarations(package)
    } else {
        Ok(Vec::new())
    }
}

fn ordinary_html(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| {
            !name.ends_with(".template.html") && !name.ends_with(".template-webui.html")
        })
}

fn fallback_html(path: &Path, names: &HashSet<&str>) -> bool {
    ordinary_html(path)
        && crate::catalog::template_tag(path).is_some_and(|name| !names.contains(name))
}

struct ExportedAssets {
    template: Option<PathBuf>,
    styles: Option<PathBuf>,
}

fn exported_assets(package: PackageContext<'_>, declarations: usize) -> Result<ExportedAssets> {
    let template = package_export_path(package, "./template-webui.html")?;
    if template.as_ref().is_some_and(|path| {
        !path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.ends_with(".template-webui.html"))
    }) {
        bail!(
            "Package '{}' must export a .template-webui.html file for FAST discovery.",
            package.name
        );
    }
    if template.is_some() && declarations != 1 {
        bail!(
            "Package '{}' exports one './template-webui.html' but declares {declarations} components. \
             Use one component declaration or per-module .template-webui.html files.",
            package.name
        );
    }
    let styles = if declarations == 1 {
        package_export_path(package, "./styles.css")?
    } else {
        None
    };
    Ok(ExportedAssets { template, styles })
}

fn inferred_template(
    package: PackageContext<'_>,
    declaration: &ComponentDeclaration,
    module: &ResolvedCemModule,
) -> Result<PathBuf> {
    if let Some(template) = &module.exported_template {
        return Ok(template.clone());
    }
    let name = declaration.name.as_deref().unwrap_or(&declaration.tag_name);
    let template =
        resolve_fast_template(&module.root, &module.relative_path, name).with_context(|| {
            format!(
                "Failed to locate FAST template for <{}> in package '{}'",
                declaration.tag_name, package.name
            )
        })?;
    validate_module_asset(module, &template, "FAST component template")?;
    Ok(template)
}

fn validate_module_asset(module: &ResolvedCemModule, path: &Path, kind: &str) -> Result<()> {
    validate_package_asset_path(&module.root, path, kind)
        .with_context(|| format!("{kind} resolved outside package: {}", path.display()))?;
    Ok(())
}

struct ResolvedCemModule {
    root: PathBuf,
    relative_path: PathBuf,
    package_json: Option<PathBuf>,
    resolution_dependencies: Vec<PathBuf>,
    exported_template: Option<PathBuf>,
    exported_styles: Option<PathBuf>,
    is_client_owned: bool,
}

fn resolve_declaration_module(
    package: PackageContext<'_>,
    declaration: &ComponentDeclaration,
    resolve_assets: bool,
) -> Result<ResolvedCemModule> {
    resolve_declaration_module_inner(package, declaration, resolve_assets).with_context(|| {
        format!(
            "Failed to resolve FAST component <{}> declared by package '{}'",
            declaration.tag_name, package.name
        )
    })
}

fn resolve_declaration_module_inner(
    package: PackageContext<'_>,
    declaration: &ComponentDeclaration,
    resolve_assets: bool,
) -> Result<ResolvedCemModule> {
    let specifier = declaration.module_specifier.as_deref().with_context(|| {
        format!(
            "FAST component <{}> in package '{}' has no CEM module path",
            declaration.tag_name, package.name
        )
    })?;
    let relative_path = Path::new(specifier);
    let name = declaration.name.as_deref().unwrap_or(&declaration.tag_name);
    let explicitly_relative = specifier.starts_with("./") || specifier.starts_with("../");
    let local_module = package_path(package.root, relative_path);
    let local_candidates = fast_template_candidates(package.root, relative_path, name);
    let has_local_module = local_module.as_ref().is_some_and(|path| path.is_file());
    let has_local_template = local_candidates.iter().any(|path| path.is_file());
    if explicitly_relative
        || (!specifier.starts_with('@') && (has_local_module || has_local_template))
    {
        return Ok(ResolvedCemModule {
            root: package.root.to_path_buf(),
            relative_path: relative_path.to_path_buf(),
            package_json: None,
            resolution_dependencies: Vec::new(),
            exported_template: None,
            exported_styles: None,
            is_client_owned: false,
        });
    }
    let bare_package = bare_module_package_name(specifier)?;
    let manifest = package_metadata(package)?;
    let self_name = manifest.get("name").and_then(serde_json::Value::as_str);
    if let Some(self_name) = self_name {
        if bare_package == Some(self_name) {
            return Ok(ResolvedCemModule {
                root: package.root.to_path_buf(),
                relative_path: resolve_self_module_specifier(
                    self_name,
                    package.root,
                    specifier,
                    manifest,
                )?,
                package_json: None,
                resolution_dependencies: Vec::new(),
                exported_template: None,
                exported_styles: None,
                is_client_owned: false,
            });
        }
    }
    let can_resolve_bare = specifier.starts_with('@')
        || match bare_package {
            Some(name) => package_has_dependency(manifest, name),
            None => false,
        };
    if can_resolve_bare {
        let resolved = resolve_bare_module_specifier(specifier, package.root)?.with_context(|| {
            format!(
                "Package '{}' declares bare CEM module '{specifier}', but its package could not be resolved",
                package.name
            )
        })?;
        let mut resolution_dependencies = resolved.resolution_dependencies;
        if !specifier.starts_with('@') {
            resolution_dependencies.extend(local_module);
            resolution_dependencies.extend(local_candidates);
        }
        let exported_template = if resolve_assets {
            package_export_path_from_metadata(
                &resolved.name,
                &resolved.root,
                &resolved.ordered_manifest,
                "./template-webui.html",
            )?
        } else {
            None
        };
        if exported_template.as_ref().is_some_and(|path| {
            !path
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| name.ends_with(".template-webui.html"))
        }) {
            bail!(
                "Package '{}' must export a .template-webui.html file for FAST discovery.",
                resolved.name
            );
        }
        let exported_styles = if resolve_assets {
            package_export_path_from_metadata(
                &resolved.name,
                &resolved.root,
                &resolved.ordered_manifest,
                "./styles.css",
            )?
        } else {
            None
        };
        let is_client_owned = package_has_authored_script(&resolved.manifest)
            || module_path_is_script(&resolved.relative_path);
        return Ok(ResolvedCemModule {
            root: resolved.root,
            relative_path: resolved.relative_path,
            package_json: Some(resolved.package_json),
            resolution_dependencies,
            exported_template,
            exported_styles,
            is_client_owned,
        });
    }
    Ok(ResolvedCemModule {
        root: package.root.to_path_buf(),
        relative_path: relative_path.to_path_buf(),
        package_json: None,
        resolution_dependencies: Vec::new(),
        exported_template: None,
        exported_styles: None,
        is_client_owned: false,
    })
}

fn package_has_dependency(manifest: &serde_json::Value, name: &str) -> bool {
    ["dependencies", "peerDependencies", "optionalDependencies"]
        .into_iter()
        .any(|field| {
            manifest
                .get(field)
                .and_then(serde_json::Value::as_object)
                .is_some_and(|dependencies| dependencies.contains_key(name))
        })
}

fn module_path_is_script(path: &Path) -> bool {
    path.extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| matches!(extension, "js" | "mjs" | "cjs" | "ts"))
}

fn discover_local_templates(
    root: &Path,
    tag_name_for_path: fn(&Path) -> Option<&str>,
) -> Result<Vec<DiscoveredComponent>> {
    let source = root.display().to_string();
    let mut components = Vec::new();
    for entry in WalkDir::new(root).sort_by_file_name() {
        let entry = entry.with_context(|| format!("Failed to scan {}", root.display()))?;
        let path = entry.path();
        if !path.is_file()
            || !path
                .extension()
                .is_some_and(|extension| extension == "html")
        {
            continue;
        }
        let Some(tag_name) = tag_name_for_path(path) else {
            continue;
        };
        let html_content = read_required_file(path, "component template")?;
        let css_content =
            read_optional_file(resolve_local_styles(path).as_deref(), "component styles")?;
        components.push(DiscoveredComponent {
            tag_name: tag_name.to_string(),
            html_content,
            css_content,
            is_client_owned: has_sibling_script(path)?,
            source: source.clone(),
        });
    }
    Ok(components)
}

fn fast_local_tag(path: &Path) -> Option<&str> {
    let file_name = path.file_name()?.to_str()?;
    if file_name.ends_with(".template.html") {
        return None;
    }
    file_name
        .strip_suffix(".template-webui.html")
        .or_else(|| crate::catalog::template_tag(path))
}

fn resolve_local_styles(template_path: &Path) -> Option<PathBuf> {
    let standard = template_path.with_extension("css");
    if standard.is_file() {
        return Some(standard);
    }
    resolve_fast_styles(template_path)
}

fn resolve_fast_styles(template_path: &Path) -> Option<PathBuf> {
    fast_style_candidates(template_path)
        .into_iter()
        .find(|candidate| candidate.is_file())
}

fn fast_style_candidates(template_path: &Path) -> Vec<PathBuf> {
    let Some(file_name) = template_path.file_name().and_then(|name| name.to_str()) else {
        return Vec::new();
    };
    let Some(prefix) = file_name.strip_suffix(".template-webui.html") else {
        return Vec::new();
    };
    let Some(parent) = template_path.parent() else {
        return Vec::new();
    };
    let mut candidates = Vec::with_capacity(2);
    for suffix in [".styles.css", ".css"] {
        candidates.push(parent.join(format!("{prefix}{suffix}")));
    }
    candidates
}

fn fast_template_candidates(
    root: &Path,
    module_path: &Path,
    declaration_name: &str,
) -> Vec<PathBuf> {
    let Some(module) = package_path(root, module_path) else {
        return Vec::new();
    };
    let parent = module.parent().unwrap_or(root);
    let module_stem = module.file_stem().and_then(|stem| stem.to_str());
    let declaration_stem = to_kebab_case(declaration_name);
    let mut candidates = Vec::with_capacity(5);
    for stem in module_stem
        .into_iter()
        .chain(std::iter::once(declaration_stem.as_str()))
    {
        push_template_candidate(&mut candidates, parent, stem);
    }

    // Some generated manifests expose a virtual public module path while the
    // package stores the implementation under a compact or base class noun.
    if !module.is_file() {
        let component_root = if parent == root {
            root
        } else {
            parent
                .parent()
                .filter(|candidate| candidate.starts_with(root))
                .unwrap_or(root)
        };
        push_nested_template_candidate(&mut candidates, component_root, declaration_stem.as_str());
        let compact_stem = declaration_stem.replace('-', "");
        push_nested_template_candidate(&mut candidates, component_root, &compact_stem);
        if let Some((_, suffix)) = declaration_stem.rsplit_once('-') {
            push_nested_template_candidate(&mut candidates, component_root, suffix);
        }
    }
    if !candidates.iter().any(|candidate| candidate.is_file()) {
        for directory in parent
            .ancestors()
            .skip(1)
            .take_while(|path| path.starts_with(root))
        {
            for stem in module_stem
                .into_iter()
                .chain(std::iter::once(declaration_stem.as_str()))
            {
                push_template_candidate(&mut candidates, directory, stem);
            }
        }
    }
    candidates
}

fn package_path(root: &Path, relative: &Path) -> Option<PathBuf> {
    if relative.is_absolute()
        || relative.components().any(|component| {
            matches!(
                component,
                Component::Prefix(_) | Component::RootDir | Component::ParentDir
            )
        })
    {
        return None;
    }
    Some(root.join(relative))
}

fn push_template_candidate(candidates: &mut Vec<PathBuf>, parent: &Path, stem: &str) {
    let candidate = parent.join(format!("{stem}.template-webui.html"));
    if !candidates.contains(&candidate) {
        candidates.push(candidate);
    }
}

fn push_nested_template_candidate(candidates: &mut Vec<PathBuf>, root: &Path, stem: &str) {
    push_template_candidate(candidates, &root.join(stem), stem);
}

fn resolve_fast_template(
    root: &Path,
    module_path: &Path,
    declaration_name: &str,
) -> Result<PathBuf> {
    for candidate in fast_template_candidates(root, module_path, declaration_name) {
        if candidate.is_file() {
            return Ok(candidate);
        }
    }
    bail!("no matching <component>.template-webui.html file found; raw .template.html assets are not used")
}

fn to_kebab_case(name: &str) -> String {
    let mut result = String::with_capacity(name.len() + 4);
    for (index, character) in name.chars().enumerate() {
        if character.is_ascii_uppercase() {
            if index != 0 {
                result.push('-');
            }
            result.push(character.to_ascii_lowercase());
        } else {
            result.push(character);
        }
    }
    result
}

#[cfg(test)]
mod tests;