Skip to main content

fallow_extract/
html.rs

1//! HTML file parsing for script, stylesheet, and Angular template references.
2//!
3//! Extracts `<script src="...">` and `<link rel="stylesheet" href="...">` references
4//! from HTML files, creating graph edges so that referenced JS/CSS assets (and their
5//! transitive imports) are reachable from the HTML entry point.
6//!
7//! Also scans for Angular template syntax (`{{ }}`, `[prop]`, `(event)`, `@if`, etc.)
8//! and stores referenced identifiers as `MemberAccess` entries with a sentinel object,
9//! enabling the analysis phase to credit component class members used in external templates.
10
11use std::path::Path;
12use std::sync::LazyLock;
13
14use oxc_span::Span;
15
16use crate::asset_url::normalize_asset_url;
17use crate::sfc_template::angular::{self, ANGULAR_TPL_SENTINEL};
18use crate::{ImportInfo, ImportedName, MemberAccess, ModuleInfo};
19use fallow_types::discover::FileId;
20
21/// Regex to match HTML comments (`<!-- ... -->`) for stripping before extraction.
22static HTML_COMMENT_RE: LazyLock<regex::Regex> =
23    LazyLock::new(|| regex::Regex::new(r"(?s)<!--.*?-->").expect("valid regex"));
24
25/// Regex to extract `src` attribute from `<script>` tags.
26/// Matches both `<script src="...">` and `<script type="module" src="...">`.
27/// Uses `(?s)` so `.` matches newlines (multi-line attributes).
28static SCRIPT_SRC_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
29    regex::Regex::new(r#"(?si)<script\b(?:[^>"']|"[^"]*"|'[^']*')*?\bsrc\s*=\s*["']([^"']+)["']"#)
30        .expect("valid regex")
31});
32
33/// Regex to extract `href` attribute from `<link>` tags with `rel="stylesheet"` or
34/// `rel="modulepreload"`.
35/// Handles attributes in any order (rel before or after href).
36static LINK_HREF_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
37    regex::Regex::new(
38        r#"(?si)<link\b(?:[^>"']|"[^"]*"|'[^']*')*?\brel\s*=\s*["'](stylesheet|modulepreload)["'](?:[^>"']|"[^"]*"|'[^']*')*?\bhref\s*=\s*["']([^"']+)["']"#,
39    )
40    .expect("valid regex")
41});
42
43/// Regex for the reverse attribute order: href before rel.
44static LINK_HREF_REVERSE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
45    regex::Regex::new(
46        r#"(?si)<link\b(?:[^>"']|"[^"]*"|'[^']*')*?\bhref\s*=\s*["']([^"']+)["'](?:[^>"']|"[^"]*"|'[^']*')*?\brel\s*=\s*["'](stylesheet|modulepreload)["']"#,
47    )
48    .expect("valid regex")
49});
50
51/// Check if a path is an HTML file.
52// Keep in sync with fallow_core::analyze::predicates::is_html_file (crate boundary prevents sharing)
53pub(crate) fn is_html_file(path: &Path) -> bool {
54    path.extension()
55        .and_then(|e| e.to_str())
56        .is_some_and(|ext| ext == "html")
57}
58
59/// Returns true if an HTML asset reference is a remote URL that should be skipped.
60pub(crate) fn is_remote_url(src: &str) -> bool {
61    src.starts_with("http://")
62        || src.starts_with("https://")
63        || src.starts_with("//")
64        || src.starts_with("data:")
65}
66
67/// Extract local (non-remote) asset references from HTML-like markup.
68///
69/// Returns the raw `src`/`href` strings (trimmed, remote URLs filtered). Shared
70/// between the HTML file parser and the JS/TS visitor's tagged template
71/// literal override so `` html`<script src="...">` `` in Hono/lit-html/htm
72/// layouts emits the same asset edges as a real `.html` file.
73pub(crate) fn collect_asset_refs(source: &str) -> Vec<String> {
74    let stripped = HTML_COMMENT_RE.replace_all(source, "");
75    let mut refs: Vec<String> = Vec::new();
76
77    for cap in SCRIPT_SRC_RE.captures_iter(&stripped) {
78        if let Some(m) = cap.get(1) {
79            let src = m.as_str().trim();
80            if !src.is_empty() && !is_remote_url(src) {
81                refs.push(src.to_string());
82            }
83        }
84    }
85
86    for cap in LINK_HREF_RE.captures_iter(&stripped) {
87        if let Some(m) = cap.get(2) {
88            let href = m.as_str().trim();
89            if !href.is_empty() && !is_remote_url(href) {
90                refs.push(href.to_string());
91            }
92        }
93    }
94    for cap in LINK_HREF_REVERSE_RE.captures_iter(&stripped) {
95        if let Some(m) = cap.get(1) {
96            let href = m.as_str().trim();
97            if !href.is_empty() && !is_remote_url(href) {
98                refs.push(href.to_string());
99            }
100        }
101    }
102
103    refs
104}
105
106/// Parse an HTML file, extracting script and stylesheet references as imports.
107#[cfg(test)]
108pub(crate) fn parse_html_to_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
109    parse_html_to_module_with_complexity(file_id, source, content_hash, false)
110}
111
112/// Parse an HTML file and optionally compute Angular template complexity.
113pub(crate) fn parse_html_to_module_with_complexity(
114    file_id: FileId,
115    source: &str,
116    content_hash: u64,
117    need_complexity: bool,
118) -> ModuleInfo {
119    let suppressions = crate::suppress::parse_suppressions_from_source(source);
120
121    // Bare filenames (e.g., `src="app.js"`) are normalized to `./app.js` so
122    // the resolver doesn't misclassify them as npm packages.
123    let mut imports: Vec<ImportInfo> = collect_asset_refs(source)
124        .into_iter()
125        .map(|raw| ImportInfo {
126            source: normalize_asset_url(&raw),
127            imported_name: ImportedName::SideEffect,
128            local_name: String::new(),
129            is_type_only: false,
130            from_style: false,
131            span: Span::default(),
132            source_span: Span::default(),
133        })
134        .collect();
135
136    // Deduplicate: the same asset may be referenced by both <script src> and
137    // <link rel="modulepreload" href> for the same path.
138    imports.sort_unstable_by(|a, b| a.source.cmp(&b.source));
139    imports.dedup_by(|a, b| a.source == b.source);
140
141    // Scan for Angular template syntax ({{ }}, [prop], (event), @if, etc.).
142    //
143    // Bare identifier refs (e.g. `title`, `dataService`, pipe names) are stored
144    // as `MemberAccess` entries with a sentinel object name so the analysis
145    // phase can credit them as members of the component class.
146    //
147    // Static member-access chains (`dataService.getTotal`) where `dataService`
148    // is an unresolved identifier are stored as regular (non-sentinel)
149    // `MemberAccess` entries. The analysis phase resolves these through the
150    // importing component's typed instance bindings (from
151    // `ClassHeritageInfo.instance_bindings`) to credit the target class's
152    // member as used.
153    let template_refs = angular::collect_angular_template_refs(source);
154    let mut member_accesses: Vec<MemberAccess> = template_refs
155        .identifiers
156        .into_iter()
157        .map(|name| MemberAccess {
158            object: ANGULAR_TPL_SENTINEL.to_string(),
159            member: name,
160        })
161        .collect();
162    member_accesses.extend(template_refs.member_accesses);
163
164    let complexity = if need_complexity {
165        crate::template_complexity::compute_angular_template_complexity(source)
166            .into_iter()
167            .collect()
168    } else {
169        Vec::new()
170    };
171
172    ModuleInfo {
173        file_id,
174        exports: Vec::new(),
175        imports,
176        re_exports: Vec::new(),
177        dynamic_imports: Vec::new(),
178        dynamic_import_patterns: Vec::new(),
179        require_calls: Vec::new(),
180        member_accesses,
181        whole_object_uses: Vec::new(),
182        has_cjs_exports: false,
183        content_hash,
184        suppressions,
185        unused_import_bindings: Vec::new(),
186        type_referenced_import_bindings: Vec::new(),
187        value_referenced_import_bindings: Vec::new(),
188        line_offsets: fallow_types::extract::compute_line_offsets(source),
189        complexity,
190        flag_uses: Vec::new(),
191        class_heritage: vec![],
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    // ── is_html_file ─────────────────────────────────────────────
200
201    #[test]
202    fn is_html_file_html() {
203        assert!(is_html_file(Path::new("index.html")));
204    }
205
206    #[test]
207    fn is_html_file_nested() {
208        assert!(is_html_file(Path::new("pages/about.html")));
209    }
210
211    #[test]
212    fn is_html_file_rejects_htm() {
213        assert!(!is_html_file(Path::new("index.htm")));
214    }
215
216    #[test]
217    fn is_html_file_rejects_js() {
218        assert!(!is_html_file(Path::new("app.js")));
219    }
220
221    #[test]
222    fn is_html_file_rejects_ts() {
223        assert!(!is_html_file(Path::new("app.ts")));
224    }
225
226    #[test]
227    fn is_html_file_rejects_vue() {
228        assert!(!is_html_file(Path::new("App.vue")));
229    }
230
231    // ── is_remote_url ────────────────────────────────────────────
232
233    #[test]
234    fn remote_url_http() {
235        assert!(is_remote_url("http://example.com/script.js"));
236    }
237
238    #[test]
239    fn remote_url_https() {
240        assert!(is_remote_url("https://cdn.example.com/style.css"));
241    }
242
243    #[test]
244    fn remote_url_protocol_relative() {
245        assert!(is_remote_url("//cdn.example.com/lib.js"));
246    }
247
248    #[test]
249    fn remote_url_data() {
250        assert!(is_remote_url("data:text/javascript;base64,abc"));
251    }
252
253    #[test]
254    fn local_relative_not_remote() {
255        assert!(!is_remote_url("./src/entry.js"));
256    }
257
258    #[test]
259    fn local_root_relative_not_remote() {
260        assert!(!is_remote_url("/src/entry.js"));
261    }
262
263    // ── parse_html_to_module: script src extraction ──────────────
264
265    #[test]
266    fn extracts_module_script_src() {
267        let info = parse_html_to_module(
268            FileId(0),
269            r#"<script type="module" src="./src/entry.js"></script>"#,
270            0,
271        );
272        assert_eq!(info.imports.len(), 1);
273        assert_eq!(info.imports[0].source, "./src/entry.js");
274    }
275
276    #[test]
277    fn extracts_plain_script_src() {
278        let info = parse_html_to_module(
279            FileId(0),
280            r#"<script src="./src/polyfills.js"></script>"#,
281            0,
282        );
283        assert_eq!(info.imports.len(), 1);
284        assert_eq!(info.imports[0].source, "./src/polyfills.js");
285    }
286
287    #[test]
288    fn extracts_multiple_scripts() {
289        let info = parse_html_to_module(
290            FileId(0),
291            r#"
292            <script type="module" src="./src/entry.js"></script>
293            <script src="./src/polyfills.js"></script>
294            "#,
295            0,
296        );
297        assert_eq!(info.imports.len(), 2);
298    }
299
300    #[test]
301    fn skips_inline_script() {
302        let info = parse_html_to_module(FileId(0), r#"<script>console.log("hello");</script>"#, 0);
303        assert!(info.imports.is_empty());
304    }
305
306    #[test]
307    fn skips_remote_script() {
308        let info = parse_html_to_module(
309            FileId(0),
310            r#"<script src="https://cdn.example.com/lib.js"></script>"#,
311            0,
312        );
313        assert!(info.imports.is_empty());
314    }
315
316    #[test]
317    fn skips_protocol_relative_script() {
318        let info = parse_html_to_module(
319            FileId(0),
320            r#"<script src="//cdn.example.com/lib.js"></script>"#,
321            0,
322        );
323        assert!(info.imports.is_empty());
324    }
325
326    // ── parse_html_to_module: link href extraction ───────────────
327
328    #[test]
329    fn extracts_stylesheet_link() {
330        let info = parse_html_to_module(
331            FileId(0),
332            r#"<link rel="stylesheet" href="./src/global.css" />"#,
333            0,
334        );
335        assert_eq!(info.imports.len(), 1);
336        assert_eq!(info.imports[0].source, "./src/global.css");
337    }
338
339    #[test]
340    fn extracts_modulepreload_link() {
341        let info = parse_html_to_module(
342            FileId(0),
343            r#"<link rel="modulepreload" href="./src/vendor.js" />"#,
344            0,
345        );
346        assert_eq!(info.imports.len(), 1);
347        assert_eq!(info.imports[0].source, "./src/vendor.js");
348    }
349
350    #[test]
351    fn extracts_link_with_reversed_attrs() {
352        let info = parse_html_to_module(
353            FileId(0),
354            r#"<link href="./src/global.css" rel="stylesheet" />"#,
355            0,
356        );
357        assert_eq!(info.imports.len(), 1);
358        assert_eq!(info.imports[0].source, "./src/global.css");
359    }
360
361    // ── Bare asset references normalized to relative paths ──────
362    // Regression tests for the same class of bug as #99 (Angular templateUrl).
363    // Browsers resolve `src="app.js"` and `href="styles.css"` relative to the
364    // HTML file, so emitting these as bare specifiers would misclassify them
365    // as unlisted npm packages.
366
367    #[test]
368    fn bare_script_src_normalized_to_relative() {
369        let info = parse_html_to_module(FileId(0), r#"<script src="app.js"></script>"#, 0);
370        assert_eq!(info.imports.len(), 1);
371        assert_eq!(info.imports[0].source, "./app.js");
372    }
373
374    #[test]
375    fn bare_module_script_src_normalized_to_relative() {
376        let info = parse_html_to_module(
377            FileId(0),
378            r#"<script type="module" src="main.ts"></script>"#,
379            0,
380        );
381        assert_eq!(info.imports.len(), 1);
382        assert_eq!(info.imports[0].source, "./main.ts");
383    }
384
385    #[test]
386    fn bare_stylesheet_link_href_normalized_to_relative() {
387        let info = parse_html_to_module(
388            FileId(0),
389            r#"<link rel="stylesheet" href="styles.css" />"#,
390            0,
391        );
392        assert_eq!(info.imports.len(), 1);
393        assert_eq!(info.imports[0].source, "./styles.css");
394    }
395
396    #[test]
397    fn bare_link_href_reversed_attrs_normalized_to_relative() {
398        let info = parse_html_to_module(
399            FileId(0),
400            r#"<link href="styles.css" rel="stylesheet" />"#,
401            0,
402        );
403        assert_eq!(info.imports.len(), 1);
404        assert_eq!(info.imports[0].source, "./styles.css");
405    }
406
407    #[test]
408    fn bare_modulepreload_link_href_normalized_to_relative() {
409        let info = parse_html_to_module(
410            FileId(0),
411            r#"<link rel="modulepreload" href="vendor.js" />"#,
412            0,
413        );
414        assert_eq!(info.imports.len(), 1);
415        assert_eq!(info.imports[0].source, "./vendor.js");
416    }
417
418    #[test]
419    fn bare_asset_with_subdir_normalized_to_relative() {
420        let info = parse_html_to_module(FileId(0), r#"<script src="assets/app.js"></script>"#, 0);
421        assert_eq!(info.imports.len(), 1);
422        assert_eq!(info.imports[0].source, "./assets/app.js");
423    }
424
425    #[test]
426    fn root_absolute_script_src_unchanged() {
427        // `/src/main.ts` is a web convention (Vite root-relative) and must
428        // stay absolute so the resolver's HTML special case applies.
429        let info = parse_html_to_module(FileId(0), r#"<script src="/src/main.ts"></script>"#, 0);
430        assert_eq!(info.imports.len(), 1);
431        assert_eq!(info.imports[0].source, "/src/main.ts");
432    }
433
434    #[test]
435    fn parent_relative_script_src_unchanged() {
436        let info = parse_html_to_module(
437            FileId(0),
438            r#"<script src="../shared/vendor.js"></script>"#,
439            0,
440        );
441        assert_eq!(info.imports.len(), 1);
442        assert_eq!(info.imports[0].source, "../shared/vendor.js");
443    }
444
445    #[test]
446    fn skips_preload_link() {
447        let info = parse_html_to_module(
448            FileId(0),
449            r#"<link rel="preload" href="./src/font.woff2" as="font" />"#,
450            0,
451        );
452        assert!(info.imports.is_empty());
453    }
454
455    #[test]
456    fn skips_icon_link() {
457        let info =
458            parse_html_to_module(FileId(0), r#"<link rel="icon" href="./favicon.ico" />"#, 0);
459        assert!(info.imports.is_empty());
460    }
461
462    #[test]
463    fn skips_remote_stylesheet() {
464        let info = parse_html_to_module(
465            FileId(0),
466            r#"<link rel="stylesheet" href="https://fonts.googleapis.com/css" />"#,
467            0,
468        );
469        assert!(info.imports.is_empty());
470    }
471
472    // ── HTML comment stripping ───────────────────────────────────
473
474    #[test]
475    fn skips_commented_out_script() {
476        let info = parse_html_to_module(
477            FileId(0),
478            r#"<!-- <script src="./old.js"></script> -->
479            <script src="./new.js"></script>"#,
480            0,
481        );
482        assert_eq!(info.imports.len(), 1);
483        assert_eq!(info.imports[0].source, "./new.js");
484    }
485
486    #[test]
487    fn skips_commented_out_link() {
488        let info = parse_html_to_module(
489            FileId(0),
490            r#"<!-- <link rel="stylesheet" href="./old.css" /> -->
491            <link rel="stylesheet" href="./new.css" />"#,
492            0,
493        );
494        assert_eq!(info.imports.len(), 1);
495        assert_eq!(info.imports[0].source, "./new.css");
496    }
497
498    // ── Multi-line attributes ────────────────────────────────────
499
500    #[test]
501    fn handles_multiline_script_tag() {
502        let info = parse_html_to_module(
503            FileId(0),
504            "<script\n  type=\"module\"\n  src=\"./src/entry.js\"\n></script>",
505            0,
506        );
507        assert_eq!(info.imports.len(), 1);
508        assert_eq!(info.imports[0].source, "./src/entry.js");
509    }
510
511    #[test]
512    fn handles_multiline_link_tag() {
513        let info = parse_html_to_module(
514            FileId(0),
515            "<link\n  rel=\"stylesheet\"\n  href=\"./src/global.css\"\n/>",
516            0,
517        );
518        assert_eq!(info.imports.len(), 1);
519        assert_eq!(info.imports[0].source, "./src/global.css");
520    }
521
522    // ── Full HTML document ───────────────────────────────────────
523
524    #[test]
525    fn full_vite_html() {
526        let info = parse_html_to_module(
527            FileId(0),
528            r#"<!doctype html>
529<html>
530  <head>
531    <link rel="stylesheet" href="./src/global.css" />
532    <link rel="icon" href="/favicon.ico" />
533  </head>
534  <body>
535    <div id="app"></div>
536    <script type="module" src="./src/entry.js"></script>
537  </body>
538</html>"#,
539            0,
540        );
541        assert_eq!(info.imports.len(), 2);
542        let sources: Vec<&str> = info.imports.iter().map(|i| i.source.as_str()).collect();
543        assert!(sources.contains(&"./src/global.css"));
544        assert!(sources.contains(&"./src/entry.js"));
545    }
546
547    // ── Edge cases ───────────────────────────────────────────────
548
549    #[test]
550    fn empty_html() {
551        let info = parse_html_to_module(FileId(0), "", 0);
552        assert!(info.imports.is_empty());
553    }
554
555    #[test]
556    fn html_with_no_assets() {
557        let info = parse_html_to_module(
558            FileId(0),
559            r"<!doctype html><html><body><h1>Hello</h1></body></html>",
560            0,
561        );
562        assert!(info.imports.is_empty());
563    }
564
565    #[test]
566    fn single_quoted_attributes() {
567        let info = parse_html_to_module(FileId(0), r"<script src='./src/entry.js'></script>", 0);
568        assert_eq!(info.imports.len(), 1);
569        assert_eq!(info.imports[0].source, "./src/entry.js");
570    }
571
572    #[test]
573    fn all_imports_are_side_effect() {
574        let info = parse_html_to_module(
575            FileId(0),
576            r#"<script src="./entry.js"></script>
577            <link rel="stylesheet" href="./style.css" />"#,
578            0,
579        );
580        for imp in &info.imports {
581            assert!(matches!(imp.imported_name, ImportedName::SideEffect));
582            assert!(imp.local_name.is_empty());
583            assert!(!imp.is_type_only);
584        }
585    }
586
587    #[test]
588    fn suppression_comments_extracted() {
589        let info = parse_html_to_module(
590            FileId(0),
591            "<!-- fallow-ignore-file -->\n<script src=\"./entry.js\"></script>",
592            0,
593        );
594        // HTML comments use <!-- --> not //, so suppression parsing
595        // from source text won't find standard JS-style comments.
596        // This is expected — HTML suppression is not supported.
597        assert_eq!(info.imports.len(), 1);
598    }
599
600    // ── Angular template scanning ──────────────────────────────
601
602    #[test]
603    fn angular_template_extracts_member_refs() {
604        let info = parse_html_to_module(
605            FileId(0),
606            "<h1>{{ title() }}</h1>\n\
607             <p [class.highlighted]=\"isHighlighted\">{{ greeting() }}</p>\n\
608             <button (click)=\"onButtonClick()\">Toggle</button>",
609            0,
610        );
611        let names: rustc_hash::FxHashSet<&str> = info
612            .member_accesses
613            .iter()
614            .filter(|a| a.object == ANGULAR_TPL_SENTINEL)
615            .map(|a| a.member.as_str())
616            .collect();
617        assert!(names.contains("title"), "should contain 'title'");
618        assert!(
619            names.contains("isHighlighted"),
620            "should contain 'isHighlighted'"
621        );
622        assert!(names.contains("greeting"), "should contain 'greeting'");
623        assert!(
624            names.contains("onButtonClick"),
625            "should contain 'onButtonClick'"
626        );
627    }
628
629    #[test]
630    fn plain_html_no_angular_refs() {
631        let info = parse_html_to_module(
632            FileId(0),
633            "<!doctype html><html><body><h1>Hello</h1></body></html>",
634            0,
635        );
636        assert!(info.member_accesses.is_empty());
637    }
638}