Skip to main content

rust_anything/ts/
mod.rs

1//! The TypeScript/JavaScript language plugin: discovery, parsing and the npm crate table.
2
3pub mod deps;
4pub mod discover;
5pub mod exports;
6pub mod jsdoc;
7pub mod scan;
8pub mod shape;
9pub mod tsconfig;
10
11/// The code of a file as TS: the file itself, or only the `<script>` blocks of a
12/// `.vue`/`.svelte`/`.astro` component. Text outside scripts becomes blank lines so
13/// reported line numbers stay right.
14pub fn script_of(path: &str, text: &str) -> String {
15    let is_sfc = [".vue", ".svelte", ".astro"]
16        .iter()
17        .any(|ext| path.ends_with(ext));
18    if !is_sfc {
19        return text.to_string();
20    }
21    let mut out = String::with_capacity(text.len());
22    let mut rest = text;
23    while let Some(open) = rest.find("<script") {
24        out.extend(rest[..open].chars().filter(|&c| c == '\n'));
25        let after_open = &rest[open..];
26        let Some(tag_end) = after_open.find('>') else {
27            break;
28        };
29        out.extend(after_open[..=tag_end].chars().filter(|&c| c == '\n'));
30        let body = &after_open[tag_end + 1..];
31        let close = body.find("</script>").unwrap_or(body.len());
32        out.push_str(&body[..close]);
33        out.push('\n');
34        rest = &body[close..];
35        rest = rest.strip_prefix("</script>").unwrap_or(rest);
36    }
37    out
38}
39
40#[cfg(test)]
41mod tests {
42    use super::script_of;
43
44    #[test]
45    fn keeps_only_scripts_with_line_numbers() {
46        let sfc = "<template>\n<div/>\n</template>\n<script setup lang=\"ts\">\nimport x from './x'\n</script>\n";
47        let script = script_of("App.vue", sfc);
48        assert_eq!(script.lines().nth(4), Some("import x from './x'"));
49    }
50}