skif-js-syntax 0.3.0

oxc-based JS/TS module facts and static config extraction for skif; never executes code.
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
//! The components a declaration file generated by `unplugin-vue-components` registers, and how Vue resolves a tag
//! name to one (ADR 0084).

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(|first| first.to_uppercase().chain(chars).collect())
        .unwrap_or_default()
}

/// 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"]
        );
    }
}