ctb_formats_javascript/
typescript.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from dlint: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Derived from Deno's dlint (https://github.com/denoland/deno_lint).
22// For parts derived from dlint:
23// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
24
25// See additional licensing details at end of file.
26
27//! TypeScript tools. While I usually try never to remove features, I can't
28//! promise that in this case. I'll probably find some way to keep it working,
29//! though.
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace crate prelude"
35)]
36pub(crate) use ctb_utilities::*;
37
38use anyhow::{Result, bail};
39use deno_ast::{ModuleSpecifier, SourceRange, SourceTextInfo};
40use deno_lint::diagnostic::{
41    LintDiagnostic, LintDiagnosticDetails, LintDiagnosticRange, LintDocsUrl,
42};
43use once_cell::sync::OnceCell;
44use std::path::{Path, PathBuf};
45
46use crate::project_files_resolver::{
47    resolve_file_paths_in_dir, resolve_project_files,
48};
49use crate::tsconfig::find_tsconfig;
50
51static EXTRACTED_COMPILER_DIR: OnceCell<tempfile::TempDir> = OnceCell::new();
52
53#[derive(serde::Deserialize, Default, Clone)]
54#[serde(default)]
55struct TsConfigJson {
56    include: Vec<String>,
57    exclude: Vec<String>,
58}
59
60/// Resolves file paths specified in a tsconfig.json file.
61pub fn resolve_tsconfig_files(
62    tsconfig_path: &std::path::Path,
63) -> Result<Vec<std::path::PathBuf>> {
64    let content = std::fs::read_to_string(tsconfig_path)?;
65    let clean_json = ctb_formats_json::jsonc::strip_jsonc_comments(&content);
66    let config: TsConfigJson =
67        serde_json::from_str(&clean_json).with_context(|| {
68            format!(
69                "Failed to parse tsconfig.json at {}",
70                tsconfig_path.display()
71            )
72        })?;
73
74    // Reason for fallback: if tsconfig_path has no parent directory component, empty Path serves as relative base.
75    let base_dir = tsconfig_path.parent().unwrap_or(std::path::Path::new(""));
76    resolve_project_files(base_dir, &config.include, &config.exclude)
77}
78
79pub fn get_bootstrapped_compiler() -> Result<Vec<u8>> {
80    if let Some(bytes) = ctb_storage::get_asset("TypeScript-built.tar") {
81        return Ok(bytes);
82    }
83
84    if environment::is_cargo_target_binary() || environment::is_in_test() {
85        if let Ok(bytes) = std::fs::read("vendor/TypeScript-built.tar") {
86            return Ok(bytes);
87        }
88        let mut current = std::env::current_dir()?;
89        loop {
90            let path = current.join("vendor/TypeScript-built.tar");
91            if path.is_file() {
92                return std::fs::read(path).map_err(Into::into);
93            }
94            if !current.pop() {
95                break;
96            }
97        }
98    }
99
100    bail!(
101        "Failed to get bootstrapped compiler (TypeScript-built.tar not found in asset bundle)"
102    )
103}
104
105pub fn get_compiler_dir() -> Result<&'static Path> {
106    let temp_dir =
107        EXTRACTED_COMPILER_DIR.get_or_try_init::<_, anyhow::Error>(|| {
108            let tarball_bytes = get_bootstrapped_compiler()?;
109
110            let temp = tempfile::Builder::new().prefix("ctb-tsc-").tempdir()?;
111
112            let mut archive = tar::Archive::new(&tarball_bytes[..]);
113            archive.unpack(temp.path())?;
114
115            // Copy standard library files from the "tsc" subdirectory to the root temp directory
116            // because sys.js expects them in the parent of the "compiler" folder.
117            let tsc_dir = temp.path().join("tsc");
118            if tsc_dir.exists() {
119                for entry in std::fs::read_dir(&tsc_dir)? {
120                    let entry = entry?;
121                    let path = entry.path();
122                    if path.is_file() {
123                        let name_str =
124                            entry.file_name().to_string_lossy().into_owned();
125                        if name_str.starts_with("lib.")
126                            && name_str.ends_with(".d.ts")
127                        {
128                            let dest = temp.path().join(&name_str);
129                            std::fs::copy(&path, &dest)?;
130                        }
131                    }
132                }
133            }
134
135            Ok(temp)
136        })?;
137    Ok(temp_dir.path())
138}
139
140pub struct TscRunResult {
141    pub output: String,
142    pub exit_code: i32,
143}
144
145pub fn run_tsc(args: &[String]) -> Result<TscRunResult> {
146    let temp_dir = get_compiler_dir()?;
147    let tsc_js_path = temp_dir.join("tsc/tsc.js");
148    let loader_root = temp_dir.join("tsc");
149
150    ctb_formats_javascript_boa_host::start_capturing_stdout();
151
152    let res = ctb_formats_javascript_boa_host::run_js_module_allow_success_exit(
153        &tsc_js_path,
154        &loader_root,
155        args,
156    );
157
158    // Reason for fallback: if stdout capture lock fails or is empty, empty lines vector is returned.
159    let captured_lines =
160        ctb_formats_javascript_boa_host::stop_capturing_stdout()
161            .unwrap_or_default();
162
163    let output = captured_lines.join("");
164
165    let exit_code = match res {
166        Ok(()) => 0,
167        Err(error) => {
168            if let Some(code) =
169                ctb_formats_javascript_boa_host::process_exit_code_from_error(
170                    &error,
171                )
172            {
173                code
174            } else {
175                return Err(error);
176            }
177        }
178    };
179
180    Ok(TscRunResult { output, exit_code })
181}
182
183pub fn ts_check_files(
184    paths: &[PathBuf],
185    add_types: &[String],
186) -> Result<Vec<LintDiagnostic>> {
187    if paths.is_empty() {
188        return Ok(Vec::new());
189    }
190
191    // Canonicalize target files for accurate diagnostic matching
192    let target_canonical_paths: std::collections::HashSet<PathBuf> = paths
193        .iter()
194        // Reason for fallback: if canonicalize fails (e.g. non-existent path), original PathBuf is retained.
195        .map(|p| std::fs::canonicalize(p).unwrap_or_else(|_| p.clone()))
196        .collect();
197
198    // Determine the search start directory for tsconfig.json
199    let start_dir = if let Some(first_path) = paths.first() {
200        if first_path.is_dir() {
201            first_path.clone()
202        } else {
203            first_path.parent().map_or_else(
204                // Reason for fallback: if first_path has no parent and current_dir query fails, empty PathBuf serves as relative base.
205                || std::env::current_dir().unwrap_or_default(),
206                Path::to_path_buf,
207            )
208        }
209    } else {
210        bail!("No paths provided for TypeScript checking.");
211    };
212
213    let tsconfig_json = find_tsconfig(&start_dir);
214    let mut tsc_args = Vec::new();
215    let mut temp_tsconfig_path = None;
216
217    let temp_dir = get_compiler_dir()?;
218
219    if add_types.is_empty() {
220        if let Some(ref config_path) = tsconfig_json {
221            tsc_args.push("-p".to_string());
222            tsc_args.push(config_path.to_string_lossy().into_owned());
223            tsc_args.push("--noEmit".to_string());
224        } else {
225            tsc_args.push("--noEmit".to_string());
226            tsc_args.push("--allowJs".to_string());
227            tsc_args.push("--checkJs".to_string());
228            tsc_args.push("--lib".to_string());
229            tsc_args.push("esnext,dom,dom.iterable".to_string());
230            // tsc_args.push("--ignoreConfig".to_string());
231
232            for p in paths {
233                tsc_args.push(p.to_string_lossy().into_owned());
234            }
235        }
236    } else {
237        let mut paths_map = serde_json::Map::new();
238        for t in add_types {
239            let type_path = temp_dir
240                .join("types")
241                .join(t)
242                .to_string_lossy()
243                .into_owned();
244            paths_map.insert(t.clone(), serde_json::json!([type_path]));
245        }
246
247        if let Some(ref config_path) = tsconfig_json {
248            let temp_config = temp_dir.join("tsconfig.tmp.json");
249            let content = serde_json::json!({
250                "extends": config_path.to_string_lossy().into_owned(),
251                "compilerOptions": {
252                    "paths": paths_map
253                }
254            });
255            std::fs::write(
256                &temp_config,
257                serde_json::to_string_pretty(&content)?,
258            )?;
259            temp_tsconfig_path = Some(temp_config.clone());
260
261            tsc_args.push("-p".to_string());
262            tsc_args.push(temp_config.to_string_lossy().into_owned());
263            tsc_args.push("--noEmit".to_string());
264        } else {
265            let temp_config = temp_dir.join("tsconfig.tmp.json");
266            let content = serde_json::json!({
267                "compilerOptions": {
268                    "allowJs": true,
269                    "checkJs": true,
270                    "noEmit": true,
271                    "lib": ["dom", "dom.iterable", "esnext"],
272                    "paths": paths_map
273                },
274                "files": paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>()
275            });
276            std::fs::write(
277                &temp_config,
278                serde_json::to_string_pretty(&content)?,
279            )?;
280            temp_tsconfig_path = Some(temp_config.clone());
281
282            tsc_args.push("-p".to_string());
283            tsc_args.push(temp_config.to_string_lossy().into_owned());
284        }
285    }
286
287    let tsc_result = run_tsc(&tsc_args);
288
289    if let Some(path) = temp_tsconfig_path {
290        let _ = std::fs::remove_file(path);
291    }
292
293    let tsc_result = tsc_result?;
294    info_fmt!("DEBUG: tsc output:\n{}", tsc_result.output);
295
296    let error_re =
297        regex::Regex::new(r"^(.*?)\((\d+),(\d+)\): error TS(\d+): (.*)$")?;
298    let mut diagnostics = Vec::new();
299
300    for line in tsc_result.output.lines() {
301        if let Some(captures) = error_re.captures(line) {
302            // Reason for fallback: Regex capture group 1 match fallback to empty string if absent.
303            let file_path_str = captures.get(1).map_or("", |m| m.as_str());
304            // Reason for fallback: Regex capture group 2 match fallback to 0 if absent or unparseable.
305            let line_num: usize = captures
306                .get(2)
307                .map_or(0, |m| m.as_str().parse().unwrap_or(0));
308            // Reason for fallback: Regex capture group 3 match fallback to 0 if absent or unparseable.
309            let col_num: usize = captures
310                .get(3)
311                .map_or(0, |m| m.as_str().parse().unwrap_or(0));
312            // Reason for fallback: Regex capture group 4 match fallback to empty string if absent.
313            let code_str = captures.get(4).map_or("", |m| m.as_str());
314            // Reason for fallback: Regex capture group 5 match fallback to empty String if absent.
315            let message = captures
316                .get(5)
317                .map_or_else(String::new, |m| m.as_str().to_string());
318
319            let file_path = PathBuf::from(file_path_str);
320            let mut suffix_components = Vec::new();
321            for comp in file_path.components() {
322                match comp {
323                    std::path::Component::ParentDir
324                    | std::path::Component::CurDir => {}
325                    std::path::Component::Normal(name) => {
326                        suffix_components.push(name);
327                    }
328                    _ => {}
329                }
330            }
331            let suffix_path = suffix_components.iter().collect::<PathBuf>();
332            let matched_target_path = target_canonical_paths
333                .iter()
334                .find(|target_path| target_path.ends_with(&suffix_path));
335
336            if let Some(file_path_canonical) = matched_target_path {
337                if let Ok(source_code) =
338                    std::fs::read_to_string(file_path_canonical)
339                {
340                    let text_info = SourceTextInfo::from_string(source_code);
341                    let line_index = line_num.saturating_sub(1);
342                    let column_index = col_num.saturating_sub(1);
343
344                    let pos = text_info.loc_to_source_pos(
345                        deno_ast::LineAndColumnIndex {
346                            line_index,
347                            column_index,
348                        },
349                    );
350
351                    let next_pos = deno_ast::SourcePos::unsafely_from_byte_pos(
352                        deno_ast::swc::common::BytePos(
353                            pos.as_byte_pos().0.saturating_add(1),
354                        ),
355                    );
356                    let range = SourceRange::new(pos, next_pos);
357
358                    let specifier = ModuleSpecifier::from_file_path(file_path_canonical)
359                        .map_err(|()| anyhow::anyhow!("Failed to convert path to specifier: {file_path_canonical:?}"))?;
360
361                    diagnostics.push(LintDiagnostic {
362                        specifier,
363                        range: Some(LintDiagnosticRange {
364                            text_info,
365                            range,
366                            description: None,
367                        }),
368                        details: LintDiagnosticDetails {
369                            message,
370                            code: format!("TS{code_str}"),
371                            hint: None,
372                            fixes: Vec::new(),
373                            custom_docs_url: LintDocsUrl::None,
374                            info: Vec::new(),
375                        },
376                    });
377                }
378            }
379        }
380    }
381
382    if tsc_result.exit_code != 0 && diagnostics.is_empty() {
383        bail!(
384            "TypeScript compiler exited with code {} without parseable diagnostics. Output:\n{}",
385            tsc_result.exit_code,
386            tsc_result.output
387        );
388    }
389
390    Ok(diagnostics)
391}
392
393pub fn ts_check_directory(
394    dir: &Path,
395    config: Option<crate::deno_config::Config>,
396    add_types: &[String],
397) -> Result<Vec<LintDiagnostic>> {
398    let files = if let Some(cfg) = &config {
399        resolve_file_paths_in_dir(dir, &cfg.files)?
400    } else if let Some(tsconfig_path) = find_tsconfig(dir) {
401        resolve_tsconfig_files(&tsconfig_path)?
402    } else {
403        let deno_json_path = dir.join("deno.json");
404        let parsed_config = if deno_json_path.exists() {
405            let bytes = std::fs::read(&deno_json_path)?;
406            Some(crate::deno_config::parse_config(&bytes)?)
407        } else {
408            None
409        };
410
411        if let Some(cfg) = &parsed_config {
412            resolve_file_paths_in_dir(dir, &cfg.files)?
413        } else {
414            let mut js_files = Vec::new();
415            for entry in walkdir::WalkDir::new(dir)
416                .into_iter()
417                .filter_map(std::result::Result::ok)
418                .filter(|e| e.file_type().is_file())
419            {
420                let path = entry.path();
421                if path.extension().and_then(|s| s.to_str()) == Some("js") {
422                    js_files.push(path.to_path_buf());
423                }
424            }
425            js_files
426        }
427    };
428
429    ts_check_files(&files, add_types)
430}
431
432#[cfg(test)]
433#[allow(
434    clippy::panic,
435    clippy::expect_used,
436    clippy::unwrap_used,
437    clippy::unwrap_in_result,
438    clippy::panic_in_result_fn,
439    clippy::indexing_slicing,
440    clippy::arithmetic_side_effects,
441    reason = "Standard repository test boilerplate"
442)]
443mod tests {
444    use super::*;
445
446    #[crate::ctb_test]
447    fn test_ts_check_file() {
448        let fixture_bytes = crate::get_js_data("fixtures/bogus-docblock.js")
449            .expect("Could not load embedded fixture bogus-docblock.js");
450        let fixture_code = std::str::from_utf8(&fixture_bytes).unwrap();
451
452        let temp_dir = tempfile::tempdir().unwrap();
453        let file_path = temp_dir.path().join("bogus-docblock.js");
454        std::fs::write(&file_path, fixture_code).unwrap();
455
456        // Write a basic tsconfig.json to enable strict JS checking without @ts-check comment
457        let tsconfig_content = r#"{
458            "compilerOptions": {
459                "allowJs": true,
460                "checkJs": true,
461                "noEmit": true,
462                "strict": true,
463                "lib": ["dom", "dom.iterable", "esnext"]
464            }
465        }"#;
466        std::fs::write(temp_dir.path().join("tsconfig.json"), tsconfig_content)
467            .unwrap();
468
469        let diagnostics = ts_check_files(&[file_path.clone()], &[]).unwrap();
470
471        assert!(
472            !diagnostics.is_empty(),
473            "Type checker did not report any diagnostics for bogus-docblock.js!"
474        );
475
476        let has_number_error = diagnostics.iter().any(|d| {
477            d.details.message.contains("Number")
478                || d.details.message.contains("number")
479        });
480        assert!(
481            has_number_error,
482            "Type checker did not flag the spurious 'Number' returns annotation!"
483        );
484    }
485}
486
487/*
488Code from dlint is used under the following license:
489======
490
491MIT License
492
493Copyright (c) 2018-2024 the Deno authors
494
495Permission is hereby granted, free of charge, to any person obtaining a copy
496of this software and associated documentation files (the "Software"), to deal
497in the Software without restriction, including without limitation the rights
498to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
499copies of the Software, and to permit persons to whom the Software is
500furnished to do so, subject to the following conditions:
501
502The above copyright notice and this permission notice shall be included in all
503copies or substantial portions of the Software.
504
505THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
506IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
507FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
508AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
509LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
510OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
511SOFTWARE.
512*/