typescript.rs

   1use anyhow::{Context as _, Result};
   2use async_trait::async_trait;
   3use chrono::{DateTime, Local};
   4use collections::HashMap;
   5use futures::future::join_all;
   6use gpui::{App, AppContext, AsyncApp, Task};
   7use http_client::github::{AssetKind, GitHubLspBinaryVersion, build_asset_url};
   8use language::{
   9    ContextLocation, ContextProvider, File, LanguageName, LanguageToolchainStore, LspAdapter,
  10    LspAdapterDelegate, Toolchain,
  11};
  12use lsp::{CodeActionKind, LanguageServerBinary, LanguageServerName};
  13use node_runtime::{NodeRuntime, VersionStrategy};
  14use project::{Fs, lsp_store::language_server_settings};
  15use serde_json::{Value, json};
  16use smol::{fs, lock::RwLock, stream::StreamExt};
  17use std::{
  18    any::Any,
  19    borrow::Cow,
  20    ffi::OsString,
  21    path::{Path, PathBuf},
  22    sync::Arc,
  23};
  24use task::{TaskTemplate, TaskTemplates, VariableName};
  25use util::merge_json_value_into;
  26use util::{ResultExt, fs::remove_matching, maybe};
  27
  28use crate::{PackageJson, PackageJsonData, github_download::download_server_binary};
  29
  30#[derive(Debug)]
  31pub(crate) struct TypeScriptContextProvider {
  32    last_package_json: PackageJsonContents,
  33}
  34
  35const TYPESCRIPT_RUNNER_VARIABLE: VariableName =
  36    VariableName::Custom(Cow::Borrowed("TYPESCRIPT_RUNNER"));
  37
  38const TYPESCRIPT_JEST_TEST_NAME_VARIABLE: VariableName =
  39    VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JEST_TEST_NAME"));
  40
  41const TYPESCRIPT_VITEST_TEST_NAME_VARIABLE: VariableName =
  42    VariableName::Custom(Cow::Borrowed("TYPESCRIPT_VITEST_TEST_NAME"));
  43
  44const TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE: VariableName =
  45    VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JEST_PACKAGE_PATH"));
  46
  47const TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE: VariableName =
  48    VariableName::Custom(Cow::Borrowed("TYPESCRIPT_MOCHA_PACKAGE_PATH"));
  49
  50const TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE: VariableName =
  51    VariableName::Custom(Cow::Borrowed("TYPESCRIPT_VITEST_PACKAGE_PATH"));
  52
  53const TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE: VariableName =
  54    VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JASMINE_PACKAGE_PATH"));
  55
  56#[derive(Clone, Debug, Default)]
  57struct PackageJsonContents(Arc<RwLock<HashMap<PathBuf, PackageJson>>>);
  58
  59impl PackageJsonData {
  60    fn fill_task_templates(&self, task_templates: &mut TaskTemplates) {
  61        if self.jest_package_path.is_some() {
  62            task_templates.0.push(TaskTemplate {
  63                label: "jest file test".to_owned(),
  64                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
  65                args: vec![
  66                    "exec".to_owned(),
  67                    "--".to_owned(),
  68                    "jest".to_owned(),
  69                    "--runInBand".to_owned(),
  70                    VariableName::File.template_value(),
  71                ],
  72                cwd: Some(TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE.template_value()),
  73                ..TaskTemplate::default()
  74            });
  75            task_templates.0.push(TaskTemplate {
  76                label: format!("jest test {}", VariableName::Symbol.template_value()),
  77                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
  78                args: vec![
  79                    "exec".to_owned(),
  80                    "--".to_owned(),
  81                    "jest".to_owned(),
  82                    "--runInBand".to_owned(),
  83                    "--testNamePattern".to_owned(),
  84                    format!(
  85                        "\"{}\"",
  86                        TYPESCRIPT_JEST_TEST_NAME_VARIABLE.template_value()
  87                    ),
  88                    VariableName::File.template_value(),
  89                ],
  90                tags: vec![
  91                    "ts-test".to_owned(),
  92                    "js-test".to_owned(),
  93                    "tsx-test".to_owned(),
  94                ],
  95                cwd: Some(TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE.template_value()),
  96                ..TaskTemplate::default()
  97            });
  98        }
  99
 100        if self.vitest_package_path.is_some() {
 101            task_templates.0.push(TaskTemplate {
 102                label: format!("{} file test", "vitest".to_owned()),
 103                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
 104                args: vec![
 105                    "exec".to_owned(),
 106                    "--".to_owned(),
 107                    "vitest".to_owned(),
 108                    "run".to_owned(),
 109                    "--poolOptions.forks.minForks=0".to_owned(),
 110                    "--poolOptions.forks.maxForks=1".to_owned(),
 111                    VariableName::File.template_value(),
 112                ],
 113                cwd: Some(TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE.template_value()),
 114                ..TaskTemplate::default()
 115            });
 116            task_templates.0.push(TaskTemplate {
 117                label: format!(
 118                    "{} test {}",
 119                    "vitest".to_owned(),
 120                    VariableName::Symbol.template_value(),
 121                ),
 122                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
 123                args: vec![
 124                    "exec".to_owned(),
 125                    "--".to_owned(),
 126                    "vitest".to_owned(),
 127                    "run".to_owned(),
 128                    "--poolOptions.forks.minForks=0".to_owned(),
 129                    "--poolOptions.forks.maxForks=1".to_owned(),
 130                    "--testNamePattern".to_owned(),
 131                    format!(
 132                        "\"{}\"",
 133                        TYPESCRIPT_VITEST_TEST_NAME_VARIABLE.template_value()
 134                    ),
 135                    VariableName::File.template_value(),
 136                ],
 137                tags: vec![
 138                    "ts-test".to_owned(),
 139                    "js-test".to_owned(),
 140                    "tsx-test".to_owned(),
 141                ],
 142                cwd: Some(TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE.template_value()),
 143                ..TaskTemplate::default()
 144            });
 145        }
 146
 147        if self.mocha_package_path.is_some() {
 148            task_templates.0.push(TaskTemplate {
 149                label: format!("{} file test", "mocha".to_owned()),
 150                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
 151                args: vec![
 152                    "exec".to_owned(),
 153                    "--".to_owned(),
 154                    "mocha".to_owned(),
 155                    VariableName::File.template_value(),
 156                ],
 157                cwd: Some(TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE.template_value()),
 158                ..TaskTemplate::default()
 159            });
 160            task_templates.0.push(TaskTemplate {
 161                label: format!(
 162                    "{} test {}",
 163                    "mocha".to_owned(),
 164                    VariableName::Symbol.template_value(),
 165                ),
 166                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
 167                args: vec![
 168                    "exec".to_owned(),
 169                    "--".to_owned(),
 170                    "mocha".to_owned(),
 171                    "--grep".to_owned(),
 172                    format!("\"{}\"", VariableName::Symbol.template_value()),
 173                    VariableName::File.template_value(),
 174                ],
 175                tags: vec![
 176                    "ts-test".to_owned(),
 177                    "js-test".to_owned(),
 178                    "tsx-test".to_owned(),
 179                ],
 180                cwd: Some(TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE.template_value()),
 181                ..TaskTemplate::default()
 182            });
 183        }
 184
 185        if self.jasmine_package_path.is_some() {
 186            task_templates.0.push(TaskTemplate {
 187                label: format!("{} file test", "jasmine".to_owned()),
 188                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
 189                args: vec![
 190                    "exec".to_owned(),
 191                    "--".to_owned(),
 192                    "jasmine".to_owned(),
 193                    VariableName::File.template_value(),
 194                ],
 195                cwd: Some(TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE.template_value()),
 196                ..TaskTemplate::default()
 197            });
 198            task_templates.0.push(TaskTemplate {
 199                label: format!(
 200                    "{} test {}",
 201                    "jasmine".to_owned(),
 202                    VariableName::Symbol.template_value(),
 203                ),
 204                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
 205                args: vec![
 206                    "exec".to_owned(),
 207                    "--".to_owned(),
 208                    "jasmine".to_owned(),
 209                    format!("--filter={}", VariableName::Symbol.template_value()),
 210                    VariableName::File.template_value(),
 211                ],
 212                tags: vec![
 213                    "ts-test".to_owned(),
 214                    "js-test".to_owned(),
 215                    "tsx-test".to_owned(),
 216                ],
 217                cwd: Some(TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE.template_value()),
 218                ..TaskTemplate::default()
 219            });
 220        }
 221
 222        let script_name_counts: HashMap<_, usize> =
 223            self.scripts
 224                .iter()
 225                .fold(HashMap::default(), |mut acc, (_, script)| {
 226                    *acc.entry(script).or_default() += 1;
 227                    acc
 228                });
 229        for (path, script) in &self.scripts {
 230            let label = if script_name_counts.get(script).copied().unwrap_or_default() > 1
 231                && let Some(parent) = path.parent().and_then(|parent| parent.file_name())
 232            {
 233                let parent = parent.to_string_lossy();
 234                format!("{parent}/package.json > {script}")
 235            } else {
 236                format!("package.json > {script}")
 237            };
 238            task_templates.0.push(TaskTemplate {
 239                label,
 240                command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
 241                args: vec!["run".to_owned(), script.to_owned()],
 242                tags: vec!["package-script".into()],
 243                cwd: Some(
 244                    path.parent()
 245                        .unwrap_or(Path::new("/"))
 246                        .to_string_lossy()
 247                        .to_string(),
 248                ),
 249                ..TaskTemplate::default()
 250            });
 251        }
 252    }
 253}
 254
 255impl TypeScriptContextProvider {
 256    pub fn new() -> Self {
 257        Self {
 258            last_package_json: PackageJsonContents::default(),
 259        }
 260    }
 261
 262    fn combined_package_json_data(
 263        &self,
 264        fs: Arc<dyn Fs>,
 265        worktree_root: &Path,
 266        file_relative_path: &Path,
 267        cx: &App,
 268    ) -> Task<anyhow::Result<PackageJsonData>> {
 269        let new_json_data = file_relative_path
 270            .ancestors()
 271            .map(|path| worktree_root.join(path))
 272            .map(|parent_path| {
 273                self.package_json_data(&parent_path, self.last_package_json.clone(), fs.clone(), cx)
 274            })
 275            .collect::<Vec<_>>();
 276
 277        cx.background_spawn(async move {
 278            let mut package_json_data = PackageJsonData::default();
 279            for new_data in join_all(new_json_data).await.into_iter().flatten() {
 280                package_json_data.merge(new_data);
 281            }
 282            Ok(package_json_data)
 283        })
 284    }
 285
 286    fn package_json_data(
 287        &self,
 288        directory_path: &Path,
 289        existing_package_json: PackageJsonContents,
 290        fs: Arc<dyn Fs>,
 291        cx: &App,
 292    ) -> Task<anyhow::Result<PackageJsonData>> {
 293        let package_json_path = directory_path.join("package.json");
 294        let metadata_check_fs = fs.clone();
 295        cx.background_spawn(async move {
 296            let metadata = metadata_check_fs
 297                .metadata(&package_json_path)
 298                .await
 299                .with_context(|| format!("getting metadata for {package_json_path:?}"))?
 300                .with_context(|| format!("missing FS metadata for {package_json_path:?}"))?;
 301            let mtime = DateTime::<Local>::from(metadata.mtime.timestamp_for_user());
 302            let existing_data = {
 303                let contents = existing_package_json.0.read().await;
 304                contents
 305                    .get(&package_json_path)
 306                    .filter(|package_json| package_json.mtime == mtime)
 307                    .map(|package_json| package_json.data.clone())
 308            };
 309            match existing_data {
 310                Some(existing_data) => Ok(existing_data),
 311                None => {
 312                    let package_json_string =
 313                        fs.load(&package_json_path).await.with_context(|| {
 314                            format!("loading package.json from {package_json_path:?}")
 315                        })?;
 316                    let package_json: HashMap<String, serde_json_lenient::Value> =
 317                        serde_json_lenient::from_str(&package_json_string).with_context(|| {
 318                            format!("parsing package.json from {package_json_path:?}")
 319                        })?;
 320                    let new_data =
 321                        PackageJsonData::new(package_json_path.as_path().into(), package_json);
 322                    {
 323                        let mut contents = existing_package_json.0.write().await;
 324                        contents.insert(
 325                            package_json_path,
 326                            PackageJson {
 327                                mtime,
 328                                data: new_data.clone(),
 329                            },
 330                        );
 331                    }
 332                    Ok(new_data)
 333                }
 334            }
 335        })
 336    }
 337}
 338
 339async fn detect_package_manager(
 340    worktree_root: PathBuf,
 341    fs: Arc<dyn Fs>,
 342    package_json_data: Option<PackageJsonData>,
 343) -> &'static str {
 344    if let Some(package_json_data) = package_json_data
 345        && let Some(package_manager) = package_json_data.package_manager
 346    {
 347        return package_manager;
 348    }
 349    if fs.is_file(&worktree_root.join("pnpm-lock.yaml")).await {
 350        return "pnpm";
 351    }
 352    if fs.is_file(&worktree_root.join("yarn.lock")).await {
 353        return "yarn";
 354    }
 355    "npm"
 356}
 357
 358impl ContextProvider for TypeScriptContextProvider {
 359    fn associated_tasks(
 360        &self,
 361        fs: Arc<dyn Fs>,
 362        file: Option<Arc<dyn File>>,
 363        cx: &App,
 364    ) -> Task<Option<TaskTemplates>> {
 365        let Some(file) = project::File::from_dyn(file.as_ref()).cloned() else {
 366            return Task::ready(None);
 367        };
 368        let Some(worktree_root) = file.worktree.read(cx).root_dir() else {
 369            return Task::ready(None);
 370        };
 371        let file_relative_path = file.path().clone();
 372        let package_json_data =
 373            self.combined_package_json_data(fs.clone(), &worktree_root, &file_relative_path, cx);
 374
 375        cx.background_spawn(async move {
 376            let mut task_templates = TaskTemplates(Vec::new());
 377            task_templates.0.push(TaskTemplate {
 378                label: format!(
 379                    "execute selection {}",
 380                    VariableName::SelectedText.template_value()
 381                ),
 382                command: "node".to_owned(),
 383                args: vec![
 384                    "-e".to_owned(),
 385                    format!("\"{}\"", VariableName::SelectedText.template_value()),
 386                ],
 387                ..TaskTemplate::default()
 388            });
 389
 390            match package_json_data.await {
 391                Ok(package_json) => {
 392                    package_json.fill_task_templates(&mut task_templates);
 393                }
 394                Err(e) => {
 395                    log::error!(
 396                        "Failed to read package.json for worktree {file_relative_path:?}: {e:#}"
 397                    );
 398                }
 399            }
 400
 401            Some(task_templates)
 402        })
 403    }
 404
 405    fn build_context(
 406        &self,
 407        current_vars: &task::TaskVariables,
 408        location: ContextLocation<'_>,
 409        _project_env: Option<HashMap<String, String>>,
 410        _toolchains: Arc<dyn LanguageToolchainStore>,
 411        cx: &mut App,
 412    ) -> Task<Result<task::TaskVariables>> {
 413        let mut vars = task::TaskVariables::default();
 414
 415        if let Some(symbol) = current_vars.get(&VariableName::Symbol) {
 416            vars.insert(
 417                TYPESCRIPT_JEST_TEST_NAME_VARIABLE,
 418                replace_test_name_parameters(symbol),
 419            );
 420            vars.insert(
 421                TYPESCRIPT_VITEST_TEST_NAME_VARIABLE,
 422                replace_test_name_parameters(symbol),
 423            );
 424        }
 425        let file_path = location
 426            .file_location
 427            .buffer
 428            .read(cx)
 429            .file()
 430            .map(|file| file.path());
 431
 432        let args = location.worktree_root.zip(location.fs).zip(file_path).map(
 433            |((worktree_root, fs), file_path)| {
 434                (
 435                    self.combined_package_json_data(fs.clone(), &worktree_root, file_path, cx),
 436                    worktree_root,
 437                    fs,
 438                )
 439            },
 440        );
 441        cx.background_spawn(async move {
 442            if let Some((task, worktree_root, fs)) = args {
 443                let package_json_data = task.await.log_err();
 444                vars.insert(
 445                    TYPESCRIPT_RUNNER_VARIABLE,
 446                    detect_package_manager(worktree_root, fs, package_json_data.clone())
 447                        .await
 448                        .to_owned(),
 449                );
 450
 451                if let Some(package_json_data) = package_json_data {
 452                    if let Some(path) = package_json_data.jest_package_path {
 453                        vars.insert(
 454                            TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE,
 455                            path.parent()
 456                                .unwrap_or(Path::new(""))
 457                                .to_string_lossy()
 458                                .to_string(),
 459                        );
 460                    }
 461
 462                    if let Some(path) = package_json_data.mocha_package_path {
 463                        vars.insert(
 464                            TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE,
 465                            path.parent()
 466                                .unwrap_or(Path::new(""))
 467                                .to_string_lossy()
 468                                .to_string(),
 469                        );
 470                    }
 471
 472                    if let Some(path) = package_json_data.vitest_package_path {
 473                        vars.insert(
 474                            TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE,
 475                            path.parent()
 476                                .unwrap_or(Path::new(""))
 477                                .to_string_lossy()
 478                                .to_string(),
 479                        );
 480                    }
 481
 482                    if let Some(path) = package_json_data.jasmine_package_path {
 483                        vars.insert(
 484                            TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE,
 485                            path.parent()
 486                                .unwrap_or(Path::new(""))
 487                                .to_string_lossy()
 488                                .to_string(),
 489                        );
 490                    }
 491                }
 492            }
 493            Ok(vars)
 494        })
 495    }
 496}
 497
 498fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 499    vec![server_path.into(), "--stdio".into()]
 500}
 501
 502fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 503    vec![
 504        "--max-old-space-size=8192".into(),
 505        server_path.into(),
 506        "--stdio".into(),
 507    ]
 508}
 509
 510fn replace_test_name_parameters(test_name: &str) -> String {
 511    let pattern = regex::Regex::new(r"(%|\$)[0-9a-zA-Z]+").unwrap();
 512
 513    regex::escape(&pattern.replace_all(test_name, "(.+?)"))
 514}
 515
 516pub struct TypeScriptLspAdapter {
 517    node: NodeRuntime,
 518}
 519
 520impl TypeScriptLspAdapter {
 521    const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
 522    const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
 523    const SERVER_NAME: LanguageServerName =
 524        LanguageServerName::new_static("typescript-language-server");
 525    const PACKAGE_NAME: &str = "typescript";
 526    pub fn new(node: NodeRuntime) -> Self {
 527        TypeScriptLspAdapter { node }
 528    }
 529    async fn tsdk_path(fs: &dyn Fs, adapter: &Arc<dyn LspAdapterDelegate>) -> Option<&'static str> {
 530        let is_yarn = adapter
 531            .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
 532            .await
 533            .is_ok();
 534
 535        let tsdk_path = if is_yarn {
 536            ".yarn/sdks/typescript/lib"
 537        } else {
 538            "node_modules/typescript/lib"
 539        };
 540
 541        if fs
 542            .is_dir(&adapter.worktree_root_path().join(tsdk_path))
 543            .await
 544        {
 545            Some(tsdk_path)
 546        } else {
 547            None
 548        }
 549    }
 550}
 551
 552struct TypeScriptVersions {
 553    typescript_version: String,
 554    server_version: String,
 555}
 556
 557#[async_trait(?Send)]
 558impl LspAdapter for TypeScriptLspAdapter {
 559    fn name(&self) -> LanguageServerName {
 560        Self::SERVER_NAME
 561    }
 562
 563    async fn fetch_latest_server_version(
 564        &self,
 565        _: &dyn LspAdapterDelegate,
 566    ) -> Result<Box<dyn 'static + Send + Any>> {
 567        Ok(Box::new(TypeScriptVersions {
 568            typescript_version: self.node.npm_package_latest_version("typescript").await?,
 569            server_version: self
 570                .node
 571                .npm_package_latest_version("typescript-language-server")
 572                .await?,
 573        }) as Box<_>)
 574    }
 575
 576    async fn check_if_version_installed(
 577        &self,
 578        version: &(dyn 'static + Send + Any),
 579        container_dir: &PathBuf,
 580        _: &dyn LspAdapterDelegate,
 581    ) -> Option<LanguageServerBinary> {
 582        let version = version.downcast_ref::<TypeScriptVersions>().unwrap();
 583        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
 584
 585        let should_install_language_server = self
 586            .node
 587            .should_install_npm_package(
 588                Self::PACKAGE_NAME,
 589                &server_path,
 590                container_dir,
 591                VersionStrategy::Latest(version.typescript_version.as_str()),
 592            )
 593            .await;
 594
 595        if should_install_language_server {
 596            None
 597        } else {
 598            Some(LanguageServerBinary {
 599                path: self.node.binary_path().await.ok()?,
 600                env: None,
 601                arguments: typescript_server_binary_arguments(&server_path),
 602            })
 603        }
 604    }
 605
 606    async fn fetch_server_binary(
 607        &self,
 608        latest_version: Box<dyn 'static + Send + Any>,
 609        container_dir: PathBuf,
 610        _: &dyn LspAdapterDelegate,
 611    ) -> Result<LanguageServerBinary> {
 612        let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
 613        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
 614
 615        self.node
 616            .npm_install_packages(
 617                &container_dir,
 618                &[
 619                    (
 620                        Self::PACKAGE_NAME,
 621                        latest_version.typescript_version.as_str(),
 622                    ),
 623                    (
 624                        "typescript-language-server",
 625                        latest_version.server_version.as_str(),
 626                    ),
 627                ],
 628            )
 629            .await?;
 630
 631        Ok(LanguageServerBinary {
 632            path: self.node.binary_path().await?,
 633            env: None,
 634            arguments: typescript_server_binary_arguments(&server_path),
 635        })
 636    }
 637
 638    async fn cached_server_binary(
 639        &self,
 640        container_dir: PathBuf,
 641        _: &dyn LspAdapterDelegate,
 642    ) -> Option<LanguageServerBinary> {
 643        get_cached_ts_server_binary(container_dir, &self.node).await
 644    }
 645
 646    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 647        Some(vec![
 648            CodeActionKind::QUICKFIX,
 649            CodeActionKind::REFACTOR,
 650            CodeActionKind::REFACTOR_EXTRACT,
 651            CodeActionKind::SOURCE,
 652        ])
 653    }
 654
 655    async fn label_for_completion(
 656        &self,
 657        item: &lsp::CompletionItem,
 658        language: &Arc<language::Language>,
 659    ) -> Option<language::CodeLabel> {
 660        use lsp::CompletionItemKind as Kind;
 661        let len = item.label.len();
 662        let grammar = language.grammar()?;
 663        let highlight_id = match item.kind? {
 664            Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
 665            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
 666            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
 667            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
 668            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
 669            Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
 670            _ => None,
 671        }?;
 672
 673        let text = if let Some(description) = item
 674            .label_details
 675            .as_ref()
 676            .and_then(|label_details| label_details.description.as_ref())
 677        {
 678            format!("{} {}", item.label, description)
 679        } else if let Some(detail) = &item.detail {
 680            format!("{} {}", item.label, detail)
 681        } else {
 682            item.label.clone()
 683        };
 684        let filter_range = item
 685            .filter_text
 686            .as_deref()
 687            .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
 688            .unwrap_or(0..len);
 689        Some(language::CodeLabel {
 690            text,
 691            runs: vec![(0..len, highlight_id)],
 692            filter_range,
 693        })
 694    }
 695
 696    async fn initialization_options(
 697        self: Arc<Self>,
 698        fs: &dyn Fs,
 699        adapter: &Arc<dyn LspAdapterDelegate>,
 700    ) -> Result<Option<serde_json::Value>> {
 701        let tsdk_path = Self::tsdk_path(fs, adapter).await;
 702        Ok(Some(json!({
 703            "provideFormatter": true,
 704            "hostInfo": "zed",
 705            "tsserver": {
 706                "path": tsdk_path,
 707            },
 708            "preferences": {
 709                "includeInlayParameterNameHints": "all",
 710                "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
 711                "includeInlayFunctionParameterTypeHints": true,
 712                "includeInlayVariableTypeHints": true,
 713                "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
 714                "includeInlayPropertyDeclarationTypeHints": true,
 715                "includeInlayFunctionLikeReturnTypeHints": true,
 716                "includeInlayEnumMemberValueHints": true,
 717            }
 718        })))
 719    }
 720
 721    async fn workspace_configuration(
 722        self: Arc<Self>,
 723        _: &dyn Fs,
 724        delegate: &Arc<dyn LspAdapterDelegate>,
 725        _: Option<Toolchain>,
 726        cx: &mut AsyncApp,
 727    ) -> Result<Value> {
 728        let override_options = cx.update(|cx| {
 729            language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
 730                .and_then(|s| s.settings.clone())
 731        })?;
 732        if let Some(options) = override_options {
 733            return Ok(options);
 734        }
 735        Ok(json!({
 736            "completions": {
 737              "completeFunctionCalls": true
 738            }
 739        }))
 740    }
 741
 742    fn language_ids(&self) -> HashMap<LanguageName, String> {
 743        HashMap::from_iter([
 744            (LanguageName::new("TypeScript"), "typescript".into()),
 745            (LanguageName::new("JavaScript"), "javascript".into()),
 746            (LanguageName::new("TSX"), "typescriptreact".into()),
 747        ])
 748    }
 749}
 750
 751async fn get_cached_ts_server_binary(
 752    container_dir: PathBuf,
 753    node: &NodeRuntime,
 754) -> Option<LanguageServerBinary> {
 755    maybe!(async {
 756        let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
 757        let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
 758        if new_server_path.exists() {
 759            Ok(LanguageServerBinary {
 760                path: node.binary_path().await?,
 761                env: None,
 762                arguments: typescript_server_binary_arguments(&new_server_path),
 763            })
 764        } else if old_server_path.exists() {
 765            Ok(LanguageServerBinary {
 766                path: node.binary_path().await?,
 767                env: None,
 768                arguments: typescript_server_binary_arguments(&old_server_path),
 769            })
 770        } else {
 771            anyhow::bail!("missing executable in directory {container_dir:?}")
 772        }
 773    })
 774    .await
 775    .log_err()
 776}
 777
 778pub struct EsLintLspAdapter {
 779    node: NodeRuntime,
 780}
 781
 782impl EsLintLspAdapter {
 783    const CURRENT_VERSION: &'static str = "2.4.4";
 784    const CURRENT_VERSION_TAG_NAME: &'static str = "release/2.4.4";
 785
 786    #[cfg(not(windows))]
 787    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
 788    #[cfg(windows)]
 789    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
 790
 791    const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
 792    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("eslint");
 793
 794    const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] = &[
 795        "eslint.config.js",
 796        "eslint.config.mjs",
 797        "eslint.config.cjs",
 798        "eslint.config.ts",
 799        "eslint.config.cts",
 800        "eslint.config.mts",
 801    ];
 802
 803    pub fn new(node: NodeRuntime) -> Self {
 804        EsLintLspAdapter { node }
 805    }
 806
 807    fn build_destination_path(container_dir: &Path) -> PathBuf {
 808        container_dir.join(format!("vscode-eslint-{}", Self::CURRENT_VERSION))
 809    }
 810}
 811
 812#[async_trait(?Send)]
 813impl LspAdapter for EsLintLspAdapter {
 814    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 815        Some(vec![
 816            CodeActionKind::QUICKFIX,
 817            CodeActionKind::new("source.fixAll.eslint"),
 818        ])
 819    }
 820
 821    async fn workspace_configuration(
 822        self: Arc<Self>,
 823        _: &dyn Fs,
 824        delegate: &Arc<dyn LspAdapterDelegate>,
 825        _: Option<Toolchain>,
 826        cx: &mut AsyncApp,
 827    ) -> Result<Value> {
 828        let workspace_root = delegate.worktree_root_path();
 829        let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
 830            .iter()
 831            .any(|file| workspace_root.join(file).is_file());
 832
 833        let mut default_workspace_configuration = json!({
 834            "validate": "on",
 835            "rulesCustomizations": [],
 836            "run": "onType",
 837            "nodePath": null,
 838            "workingDirectory": {
 839                "mode": "auto"
 840            },
 841            "workspaceFolder": {
 842                "uri": workspace_root,
 843                "name": workspace_root.file_name()
 844                    .unwrap_or(workspace_root.as_os_str())
 845                    .to_string_lossy(),
 846            },
 847            "problems": {},
 848            "codeActionOnSave": {
 849                // We enable this, but without also configuring code_actions_on_format
 850                // in the Zed configuration, it doesn't have an effect.
 851                "enable": true,
 852            },
 853            "codeAction": {
 854                "disableRuleComment": {
 855                    "enable": true,
 856                    "location": "separateLine",
 857                },
 858                "showDocumentation": {
 859                    "enable": true
 860                }
 861            },
 862            "experimental": {
 863                "useFlatConfig": use_flat_config,
 864            }
 865        });
 866
 867        let override_options = cx.update(|cx| {
 868            language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
 869                .and_then(|s| s.settings.clone())
 870        })?;
 871
 872        if let Some(override_options) = override_options {
 873            merge_json_value_into(override_options, &mut default_workspace_configuration);
 874        }
 875
 876        Ok(json!({
 877            "": default_workspace_configuration
 878        }))
 879    }
 880
 881    fn name(&self) -> LanguageServerName {
 882        Self::SERVER_NAME
 883    }
 884
 885    async fn fetch_latest_server_version(
 886        &self,
 887        _delegate: &dyn LspAdapterDelegate,
 888    ) -> Result<Box<dyn 'static + Send + Any>> {
 889        let url = build_asset_url(
 890            "zed-industries/vscode-eslint",
 891            Self::CURRENT_VERSION_TAG_NAME,
 892            Self::GITHUB_ASSET_KIND,
 893        )?;
 894
 895        Ok(Box::new(GitHubLspBinaryVersion {
 896            name: Self::CURRENT_VERSION.into(),
 897            digest: None,
 898            url,
 899        }))
 900    }
 901
 902    async fn fetch_server_binary(
 903        &self,
 904        version: Box<dyn 'static + Send + Any>,
 905        container_dir: PathBuf,
 906        delegate: &dyn LspAdapterDelegate,
 907    ) -> Result<LanguageServerBinary> {
 908        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
 909        let destination_path = Self::build_destination_path(&container_dir);
 910        let server_path = destination_path.join(Self::SERVER_PATH);
 911
 912        if fs::metadata(&server_path).await.is_err() {
 913            remove_matching(&container_dir, |_| true).await;
 914
 915            download_server_binary(
 916                delegate,
 917                &version.url,
 918                None,
 919                &destination_path,
 920                Self::GITHUB_ASSET_KIND,
 921            )
 922            .await?;
 923
 924            let mut dir = fs::read_dir(&destination_path).await?;
 925            let first = dir.next().await.context("missing first file")??;
 926            let repo_root = destination_path.join("vscode-eslint");
 927            fs::rename(first.path(), &repo_root).await?;
 928
 929            #[cfg(target_os = "windows")]
 930            {
 931                handle_symlink(
 932                    repo_root.join("$shared"),
 933                    repo_root.join("client").join("src").join("shared"),
 934                )
 935                .await?;
 936                handle_symlink(
 937                    repo_root.join("$shared"),
 938                    repo_root.join("server").join("src").join("shared"),
 939                )
 940                .await?;
 941            }
 942
 943            self.node
 944                .run_npm_subcommand(&repo_root, "install", &[])
 945                .await?;
 946
 947            self.node
 948                .run_npm_subcommand(&repo_root, "run-script", &["compile"])
 949                .await?;
 950        }
 951
 952        Ok(LanguageServerBinary {
 953            path: self.node.binary_path().await?,
 954            env: None,
 955            arguments: eslint_server_binary_arguments(&server_path),
 956        })
 957    }
 958
 959    async fn cached_server_binary(
 960        &self,
 961        container_dir: PathBuf,
 962        _: &dyn LspAdapterDelegate,
 963    ) -> Option<LanguageServerBinary> {
 964        let server_path =
 965            Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
 966        Some(LanguageServerBinary {
 967            path: self.node.binary_path().await.ok()?,
 968            env: None,
 969            arguments: eslint_server_binary_arguments(&server_path),
 970        })
 971    }
 972}
 973
 974#[cfg(target_os = "windows")]
 975async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
 976    anyhow::ensure!(
 977        fs::metadata(&src_dir).await.is_ok(),
 978        "Directory {src_dir:?} is not present"
 979    );
 980    if fs::metadata(&dest_dir).await.is_ok() {
 981        fs::remove_file(&dest_dir).await?;
 982    }
 983    fs::create_dir_all(&dest_dir).await?;
 984    let mut entries = fs::read_dir(&src_dir).await?;
 985    while let Some(entry) = entries.try_next().await? {
 986        let entry_path = entry.path();
 987        let entry_name = entry.file_name();
 988        let dest_path = dest_dir.join(&entry_name);
 989        fs::copy(&entry_path, &dest_path).await?;
 990    }
 991    Ok(())
 992}
 993
 994#[cfg(test)]
 995mod tests {
 996    use std::path::Path;
 997
 998    use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
 999    use language::language_settings;
1000    use project::{FakeFs, Project};
1001    use serde_json::json;
1002    use task::TaskTemplates;
1003    use unindent::Unindent;
1004    use util::path;
1005
1006    use crate::typescript::{PackageJsonData, TypeScriptContextProvider};
1007
1008    #[gpui::test]
1009    async fn test_outline(cx: &mut TestAppContext) {
1010        let language = crate::language(
1011            "typescript",
1012            tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
1013        );
1014
1015        let text = r#"
1016            function a() {
1017              // local variables are omitted
1018              let a1 = 1;
1019              // all functions are included
1020              async function a2() {}
1021            }
1022            // top-level variables are included
1023            let b: C
1024            function getB() {}
1025            // exported variables are included
1026            export const d = e;
1027        "#
1028        .unindent();
1029
1030        let buffer = cx.new(|cx| language::Buffer::local(text, cx).with_language(language, cx));
1031        let outline = buffer.read_with(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
1032        assert_eq!(
1033            outline
1034                .items
1035                .iter()
1036                .map(|item| (item.text.as_str(), item.depth))
1037                .collect::<Vec<_>>(),
1038            &[
1039                ("function a()", 0),
1040                ("async function a2()", 1),
1041                ("let b", 0),
1042                ("function getB()", 0),
1043                ("const d", 0),
1044            ]
1045        );
1046    }
1047
1048    #[gpui::test]
1049    async fn test_generator_function_outline(cx: &mut TestAppContext) {
1050        let language = crate::language("javascript", tree_sitter_typescript::LANGUAGE_TSX.into());
1051
1052        let text = r#"
1053            function normalFunction() {
1054                console.log("normal");
1055            }
1056
1057            function* simpleGenerator() {
1058                yield 1;
1059                yield 2;
1060            }
1061
1062            async function* asyncGenerator() {
1063                yield await Promise.resolve(1);
1064            }
1065
1066            function* generatorWithParams(start, end) {
1067                for (let i = start; i <= end; i++) {
1068                    yield i;
1069                }
1070            }
1071
1072            class TestClass {
1073                *methodGenerator() {
1074                    yield "method";
1075                }
1076
1077                async *asyncMethodGenerator() {
1078                    yield "async method";
1079                }
1080            }
1081        "#
1082        .unindent();
1083
1084        let buffer = cx.new(|cx| language::Buffer::local(text, cx).with_language(language, cx));
1085        let outline = buffer.read_with(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
1086        assert_eq!(
1087            outline
1088                .items
1089                .iter()
1090                .map(|item| (item.text.as_str(), item.depth))
1091                .collect::<Vec<_>>(),
1092            &[
1093                ("function normalFunction()", 0),
1094                ("function* simpleGenerator()", 0),
1095                ("async function* asyncGenerator()", 0),
1096                ("function* generatorWithParams( )", 0),
1097                ("class TestClass", 0),
1098                ("*methodGenerator()", 1),
1099                ("async *asyncMethodGenerator()", 1),
1100            ]
1101        );
1102    }
1103
1104    #[gpui::test]
1105    async fn test_package_json_discovery(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1106        cx.update(|cx| {
1107            settings::init(cx);
1108            Project::init_settings(cx);
1109            language_settings::init(cx);
1110        });
1111
1112        let package_json_1 = json!({
1113            "dependencies": {
1114                "mocha": "1.0.0",
1115                "vitest": "1.0.0"
1116            },
1117            "scripts": {
1118                "test": ""
1119            }
1120        })
1121        .to_string();
1122
1123        let package_json_2 = json!({
1124            "devDependencies": {
1125                "vitest": "2.0.0"
1126            },
1127            "scripts": {
1128                "test": ""
1129            }
1130        })
1131        .to_string();
1132
1133        let fs = FakeFs::new(executor);
1134        fs.insert_tree(
1135            path!("/root"),
1136            json!({
1137                "package.json": package_json_1,
1138                "sub": {
1139                    "package.json": package_json_2,
1140                    "file.js": "",
1141                }
1142            }),
1143        )
1144        .await;
1145
1146        let provider = TypeScriptContextProvider::new();
1147        let package_json_data = cx
1148            .update(|cx| {
1149                provider.combined_package_json_data(
1150                    fs.clone(),
1151                    path!("/root").as_ref(),
1152                    "sub/file1.js".as_ref(),
1153                    cx,
1154                )
1155            })
1156            .await
1157            .unwrap();
1158        pretty_assertions::assert_eq!(
1159            package_json_data,
1160            PackageJsonData {
1161                jest_package_path: None,
1162                mocha_package_path: Some(Path::new(path!("/root/package.json")).into()),
1163                vitest_package_path: Some(Path::new(path!("/root/sub/package.json")).into()),
1164                jasmine_package_path: None,
1165                scripts: [
1166                    (
1167                        Path::new(path!("/root/package.json")).into(),
1168                        "test".to_owned()
1169                    ),
1170                    (
1171                        Path::new(path!("/root/sub/package.json")).into(),
1172                        "test".to_owned()
1173                    )
1174                ]
1175                .into_iter()
1176                .collect(),
1177                package_manager: None,
1178            }
1179        );
1180
1181        let mut task_templates = TaskTemplates::default();
1182        package_json_data.fill_task_templates(&mut task_templates);
1183        let task_templates = task_templates
1184            .0
1185            .into_iter()
1186            .map(|template| (template.label, template.cwd))
1187            .collect::<Vec<_>>();
1188        pretty_assertions::assert_eq!(
1189            task_templates,
1190            [
1191                (
1192                    "vitest file test".into(),
1193                    Some("$ZED_CUSTOM_TYPESCRIPT_VITEST_PACKAGE_PATH".into()),
1194                ),
1195                (
1196                    "vitest test $ZED_SYMBOL".into(),
1197                    Some("$ZED_CUSTOM_TYPESCRIPT_VITEST_PACKAGE_PATH".into()),
1198                ),
1199                (
1200                    "mocha file test".into(),
1201                    Some("$ZED_CUSTOM_TYPESCRIPT_MOCHA_PACKAGE_PATH".into()),
1202                ),
1203                (
1204                    "mocha test $ZED_SYMBOL".into(),
1205                    Some("$ZED_CUSTOM_TYPESCRIPT_MOCHA_PACKAGE_PATH".into()),
1206                ),
1207                (
1208                    "root/package.json > test".into(),
1209                    Some(path!("/root").into())
1210                ),
1211                (
1212                    "sub/package.json > test".into(),
1213                    Some(path!("/root/sub").into())
1214                ),
1215            ]
1216        );
1217    }
1218}