//! The components a declaration file generated by `unplugin-vue-components` registers, and how Vue resolves a tag
//! name to one (ADR 0020).
use oxc_allocator::Allocator;
use oxc_ast::ast::{
Argument, BindingPattern, CallExpression, Expression, Program, TSImportType, TSPropertySignature,
VariableDeclarator,
};
use oxc_ast_visit::{Visit, walk};
use oxc_parser::Parser;
use oxc_span::SourceType;
/// A component registered globally by a generated declaration file:
/// `AppButton: typeof import('./src/components/AppButton.vue')['default']`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegisteredComponent {
/// The name the component is registered by; templates use it as written or in kebab-case.
pub name: String,
/// The module specifier as written, relative to the declaration file.
pub specifier: String,
}
/// The components `source`, the text of a `components.d.ts` that `unplugin-vue-components` generated, registers from
/// files of the project, in source order: each property of `GlobalComponents` and each global `const` whose type is
/// `typeof import('./…')[…]`, as knip reads them. A `Lazy` variant of a registered name (`LazyAppIcon` beside
/// `AppIcon`) is the same component and is left out; a `LazyImage` registered on its own is a component of its own.
/// Components of packages (`typeof import('vant')['Button']`) are left out too: the declaration file keeps importing
/// them.
#[must_use]
pub fn registered_components(source: &str) -> Vec<RegisteredComponent> {
let allocator = Allocator::default();
let parsed = Parser::new(&allocator, source, SourceType::d_ts()).parse();
let mut registrations = Registrations::default();
registrations.visit_program(&parsed.program);
let found = registrations.found;
let is_variant = |component: &RegisteredComponent| {
component.name.strip_prefix("Lazy").is_some_and(|base| {
found
.iter()
.any(|other| other.name == base && other.specifier == component.specifier)
})
};
found
.iter()
.filter(|component| !is_variant(component))
.cloned()
.collect()
}
/// Vue's `camelize`: each `-` before a word character is dropped and the character upper-cased (`my-button` as
/// `myButton`).
#[must_use]
pub fn camelize(name: &str) -> String {
let mut camel = String::with_capacity(name.len());
let mut chars = name.chars().peekable();
while let Some(c) = chars.next() {
match chars.peek() {
Some(&next) if c == '-' && (next.is_ascii_alphanumeric() || next == '_') => {
camel.push(next.to_ascii_uppercase());
chars.next();
}
_ => camel.push(c),
}
}
camel
}
/// Vue's `capitalize`: the first character upper-cased (`myButton` as `MyButton`).
#[must_use]
pub fn capitalize(name: &str) -> String {
let mut chars = name.chars();
chars
.next()
.map_or_default(|first| first.to_uppercase().chain(chars).collect())
}
/// The names Vue looks a tag up by, in its order and without repeats: as written, camelized, and camelized and
/// capitalised (`my-button`, `myButton`, `MyButton`). The compiler resolves a tag to a binding of the script this way,
/// and the runtime (`resolveAsset`) to a registered component.
#[must_use]
pub fn resolved_names(tag: &str) -> Vec<String> {
let camel = camelize(tag);
let pascal = capitalize(&camel);
let mut names = vec![tag.to_owned()];
for name in [camel, pascal] {
if !names.contains(&name) {
names.push(name);
}
}
names
}
/// Whether `tag` is an element of HTML, SVG or `MathML`, or the `component` and `slot` of Vue's compiler, as written:
/// Vue never resolves such a tag to a registered component. The match is case-sensitive, as Vue's: `<Button>` is a
/// component.
#[must_use]
pub fn is_native_tag(tag: &str) -> bool {
NATIVE_TAGS.contains(&tag)
}
/// The registered component the tag `tag` names, by [`resolved_names`], or by the name after a `Lazy` prefix
/// (`LazyAppButton`, `lazy-app-button`) as knip also matches it; `None` for a native tag ([`is_native_tag`]).
#[must_use]
pub fn registered_name(tag: &str, is_registered: impl Fn(&str) -> bool) -> Option<String> {
if is_native_tag(tag) {
return None;
}
let names = resolved_names(tag);
names.iter().find(|name| is_registered(name)).cloned().or_else(|| {
names
.iter()
.filter_map(|name| name.strip_prefix("Lazy"))
.find(|base| is_registered(base))
.map(str::to_owned)
})
}
/// The names of the `resolveComponent('AppButton')` calls of `program` (also `_resolveComponent` and a member
/// `Vue.resolveComponent`) whose argument is a string: a render function resolves the registered component by it.
pub(crate) fn resolved_components(program: &Program<'_>) -> Vec<String> {
let mut calls = ResolveCalls::default();
calls.visit_program(program);
calls.names
}
#[derive(Default)]
struct ResolveCalls {
names: Vec<String>,
}
impl<'a> Visit<'a> for ResolveCalls {
fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
let callee = match &it.callee {
Expression::Identifier(id) => Some(id.name.as_str()),
Expression::StaticMemberExpression(member) => Some(member.property.name.as_str()),
_ => None,
};
if callee.is_some_and(|callee| matches!(callee, "resolveComponent" | "_resolveComponent")) {
let name = match it.arguments.first() {
Some(Argument::StringLiteral(literal)) => Some(crate::js_string(literal.value)),
Some(Argument::TemplateLiteral(literal)) if literal.expressions.is_empty() => literal
.quasis
.first()
.and_then(|quasi| quasi.value.cooked)
.map(crate::js_string),
_ => None,
};
if let Some(name) = name.filter(|name| !name.is_empty()) {
self.names.push(name);
}
}
walk::walk_call_expression(self, it);
}
}
/// HTML, SVG and `MathML` elements as Vue's `isHTMLTag`, `isSVGTag` and `isMathMLTag` list them, and the `component`
/// and `slot` its compiler handles itself.
const NATIVE_TAGS: &[&str] = &[
// HTML
"html",
"body",
"base",
"head",
"link",
"meta",
"style",
"title",
"address",
"article",
"aside",
"footer",
"header",
"hgroup",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"nav",
"section",
"div",
"dd",
"dl",
"dt",
"figcaption",
"figure",
"picture",
"hr",
"img",
"li",
"main",
"ol",
"p",
"pre",
"ul",
"a",
"b",
"abbr",
"bdi",
"bdo",
"br",
"cite",
"code",
"data",
"dfn",
"em",
"i",
"kbd",
"mark",
"q",
"rp",
"rt",
"ruby",
"s",
"samp",
"small",
"span",
"strong",
"sub",
"sup",
"time",
"u",
"var",
"wbr",
"area",
"audio",
"map",
"track",
"video",
"embed",
"object",
"param",
"source",
"canvas",
"script",
"noscript",
"del",
"ins",
"caption",
"col",
"colgroup",
"table",
"thead",
"tbody",
"td",
"th",
"tr",
"button",
"datalist",
"fieldset",
"form",
"input",
"label",
"legend",
"meter",
"optgroup",
"option",
"output",
"progress",
"select",
"textarea",
"details",
"dialog",
"menu",
"summary",
"template",
"blockquote",
"iframe",
"tfoot",
"search",
"slot",
"component",
// SVG
"svg",
"animate",
"animateMotion",
"animateTransform",
"circle",
"clipPath",
"color-profile",
"defs",
"desc",
"discard",
"ellipse",
"feBlend",
"feColorMatrix",
"feComponentTransfer",
"feComposite",
"feConvolveMatrix",
"feDiffuseLighting",
"feDisplacementMap",
"feDistantLight",
"feDropShadow",
"feFlood",
"feFuncA",
"feFuncB",
"feFuncG",
"feFuncR",
"feGaussianBlur",
"feImage",
"feMerge",
"feMergeNode",
"feMorphology",
"feOffset",
"fePointLight",
"feSpecularLighting",
"feSpotLight",
"feTile",
"feTurbulence",
"filter",
"foreignObject",
"g",
"hatch",
"hatchpath",
"image",
"line",
"linearGradient",
"marker",
"mask",
"mesh",
"meshgradient",
"meshpatch",
"meshrow",
"metadata",
"mpath",
"path",
"pattern",
"polygon",
"polyline",
"radialGradient",
"rect",
"set",
"solidcolor",
"stop",
"switch",
"symbol",
"text",
"textPath",
"tspan",
"unknown",
"use",
"view",
// MathML
"annotation",
"annotation-xml",
"maction",
"maligngroup",
"malignmark",
"math",
"menclose",
"merror",
"mfenced",
"mfrac",
"mfraction",
"mglyph",
"mi",
"mlabeledtr",
"mlongdiv",
"mmultiscripts",
"mn",
"mo",
"mover",
"mpadded",
"mphantom",
"mprescripts",
"mroot",
"mrow",
"ms",
"mscarries",
"mscarry",
"msgroup",
"msline",
"mspace",
"msqrt",
"msrow",
"mstack",
"mstyle",
"msub",
"msubsup",
"msup",
"mtable",
"mtd",
"mtext",
"mtr",
"munder",
"munderover",
"none",
"semantics",
];
#[derive(Default)]
struct Registrations {
/// The name of the property or constant whose type is being read.
current: Option<String>,
found: Vec<RegisteredComponent>,
}
impl Registrations {
fn within(&mut self, name: Option<String>, body: impl FnOnce(&mut Self)) {
self.current = name;
body(self);
self.current = None;
}
}
/// A relative specifier that does not go through `node_modules`.
fn is_local(specifier: &str) -> bool {
specifier.starts_with('.') && !specifier.split('/').any(|segment| segment == "node_modules")
}
impl<'a> Visit<'a> for Registrations {
fn visit_ts_property_signature(&mut self, it: &TSPropertySignature<'a>) {
let name = it.key.static_name().map(|key| crate::js_string(key.as_js_str()));
self.within(name, |this| walk::walk_ts_property_signature(this, it));
}
fn visit_variable_declarator(&mut self, it: &VariableDeclarator<'a>) {
let name = match &it.id {
BindingPattern::BindingIdentifier(id) => Some(id.name.as_str().to_owned()),
_ => None,
};
self.within(name, |this| walk::walk_variable_declarator(this, it));
}
fn visit_ts_import_type(&mut self, it: &TSImportType<'a>) {
// The first `import()` type of a registration names its module.
if let Some(name) = self.current.take() {
let specifier = crate::js_string(it.source.value);
if is_local(&specifier) {
self.found.push(RegisteredComponent { name, specifier });
}
}
walk::walk_ts_import_type(self, it);
}
}
#[cfg(test)]
mod tests {
use oxc_allocator::Allocator;
use oxc_parser::Parser;
use oxc_span::SourceType;
use super::{
RegisteredComponent, camelize, is_native_tag, registered_components, registered_name, resolved_components,
resolved_names,
};
fn component(name: &str, specifier: &str) -> RegisteredComponent {
RegisteredComponent {
name: name.to_owned(),
specifier: specifier.to_owned(),
}
}
#[test]
fn reads_the_local_components_of_the_interface_and_the_globals() {
let source = "/* eslint-disable */\n// Generated by unplugin-vue-components\nexport {}\ndeclare module 'vue' {\n export interface GlobalComponents {\n AppButton: typeof import('./src/components/AppButton.vue')['default']\n 'AppCard': typeof import('./src/components/AppCard.vue')['default']\n VanButton: typeof import('vant/es')['Button']\n Hidden: typeof import('./node_modules/x/Hidden.vue')['default']\n }\n}\ndeclare global {\n const AppIcon: typeof import('./src/components/AppIcon.vue')['default']\n const LazyAppIcon: typeof import('./src/components/AppIcon.vue')['default']\n}\n";
let found = registered_components(source);
let expected = [
("AppButton", "./src/components/AppButton.vue"),
("AppCard", "./src/components/AppCard.vue"),
("AppIcon", "./src/components/AppIcon.vue"),
]
.map(|(name, specifier)| RegisteredComponent {
name: name.to_owned(),
specifier: specifier.to_owned(),
});
assert_eq!(found, expected);
}
#[test]
fn a_lazy_name_is_left_out_only_as_the_variant_of_a_registered_one() {
let source = "// Generated by unplugin-vue-components\ndeclare global {\n const AppIcon: typeof import('./src/AppIcon.vue')['default']\n const LazyAppIcon: typeof import('./src/AppIcon.vue')['default']\n const LazyImage: typeof import('./src/LazyImage.vue')['default']\n}\n";
assert_eq!(
registered_components(source),
[
component("AppIcon", "./src/AppIcon.vue"),
component("LazyImage", "./src/LazyImage.vue"),
]
);
}
#[test]
fn tags_resolve_as_vue_resolves_them() {
assert_eq!(camelize("u-i-button"), "uIButton");
assert_eq!(camelize("my-button-2"), "myButton2");
assert_eq!(resolved_names("my-button"), ["my-button", "myButton", "MyButton"]);
assert_eq!(resolved_names("myButton"), ["myButton", "MyButton"]);
assert_eq!(resolved_names("AppButton"), ["AppButton"]);
let registered = ["MyButton", "UIButton", "AppIcon", "Button"];
let lookup = |tag: &str| registered_name(tag, |name| registered.contains(&name));
for (tag, name) in [
("myButton", "MyButton"),
("my-button", "MyButton"),
("MyButton", "MyButton"),
("u-i-button", "UIButton"),
("UIButton", "UIButton"),
("lazy-app-icon", "AppIcon"),
("LazyAppIcon", "AppIcon"),
("Button", "Button"),
] {
assert_eq!(lookup(tag).as_deref(), Some(name), "{tag}");
}
// `ui-button` is `UiButton` to Vue, and native tags are never components.
for tag in ["ui-button", "button", "template", "script", "style", "div", "svg"] {
assert_eq!(lookup(tag), None, "{tag}");
}
assert!(is_native_tag("clipPath"));
assert!(!is_native_tag("Div"));
}
#[test]
fn resolve_component_calls_name_components() {
let source = "import { resolveComponent, h } from 'vue';\nexport default { render() { return [h(resolveComponent('AppButton')), Vue.resolveComponent(`app-card`), _resolveComponent(\"AppIcon\"), resolveComponent(name)]; } };\n";
let allocator = Allocator::default();
let parsed = Parser::new(&allocator, source, SourceType::mjs()).parse();
assert_eq!(
resolved_components(&parsed.program),
["AppButton", "app-card", "AppIcon"]
);
}
}