typescript.rs

  1use anyhow::{anyhow, Result};
  2use async_compression::futures::bufread::GzipDecoder;
  3use async_tar::Archive;
  4use async_trait::async_trait;
  5use collections::HashMap;
  6use gpui::AsyncAppContext;
  7use http_client::github::{build_asset_url, AssetKind, GitHubLspBinaryVersion};
  8use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
  9use lsp::{CodeActionKind, LanguageServerBinary};
 10use node_runtime::NodeRuntime;
 11use project::lsp_store::language_server_settings;
 12use project::ContextProviderWithTasks;
 13use serde_json::{json, Value};
 14use smol::{fs, io::BufReader, stream::StreamExt};
 15use std::{
 16    any::Any,
 17    ffi::OsString,
 18    path::{Path, PathBuf},
 19    sync::Arc,
 20};
 21use task::{TaskTemplate, TaskTemplates, VariableName};
 22use util::{fs::remove_matching, maybe, ResultExt};
 23
 24pub(super) fn typescript_task_context() -> ContextProviderWithTasks {
 25    ContextProviderWithTasks::new(TaskTemplates(vec![
 26        TaskTemplate {
 27            label: "jest file test".to_owned(),
 28            command: "npx jest".to_owned(),
 29            args: vec![VariableName::File.template_value()],
 30            ..TaskTemplate::default()
 31        },
 32        TaskTemplate {
 33            label: "jest test $ZED_SYMBOL".to_owned(),
 34            command: "npx jest".to_owned(),
 35            args: vec![
 36                "--testNamePattern".into(),
 37                format!("\"{}\"", VariableName::Symbol.template_value()),
 38                VariableName::File.template_value(),
 39            ],
 40            tags: vec!["ts-test".into(), "js-test".into(), "tsx-test".into()],
 41            ..TaskTemplate::default()
 42        },
 43        TaskTemplate {
 44            label: "execute selection $ZED_SELECTED_TEXT".to_owned(),
 45            command: "node".to_owned(),
 46            args: vec![
 47                "-e".into(),
 48                format!("\"{}\"", VariableName::SelectedText.template_value()),
 49            ],
 50            ..TaskTemplate::default()
 51        },
 52    ]))
 53}
 54
 55fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 56    vec![server_path.into(), "--stdio".into()]
 57}
 58
 59fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 60    vec![
 61        "--max-old-space-size=8192".into(),
 62        server_path.into(),
 63        "--stdio".into(),
 64    ]
 65}
 66
 67pub struct TypeScriptLspAdapter {
 68    node: NodeRuntime,
 69}
 70
 71impl TypeScriptLspAdapter {
 72    const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
 73    const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
 74    const SERVER_NAME: LanguageServerName =
 75        LanguageServerName::new_static("typescript-language-server");
 76    pub fn new(node: NodeRuntime) -> Self {
 77        TypeScriptLspAdapter { node }
 78    }
 79    async fn tsdk_path(adapter: &Arc<dyn LspAdapterDelegate>) -> &'static str {
 80        let is_yarn = adapter
 81            .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
 82            .await
 83            .is_ok();
 84
 85        if is_yarn {
 86            ".yarn/sdks/typescript/lib"
 87        } else {
 88            "node_modules/typescript/lib"
 89        }
 90    }
 91}
 92
 93struct TypeScriptVersions {
 94    typescript_version: String,
 95    server_version: String,
 96}
 97
 98#[async_trait(?Send)]
 99impl LspAdapter for TypeScriptLspAdapter {
100    fn name(&self) -> LanguageServerName {
101        Self::SERVER_NAME.clone()
102    }
103
104    async fn fetch_latest_server_version(
105        &self,
106        _: &dyn LspAdapterDelegate,
107    ) -> Result<Box<dyn 'static + Send + Any>> {
108        Ok(Box::new(TypeScriptVersions {
109            typescript_version: self.node.npm_package_latest_version("typescript").await?,
110            server_version: self
111                .node
112                .npm_package_latest_version("typescript-language-server")
113                .await?,
114        }) as Box<_>)
115    }
116
117    async fn fetch_server_binary(
118        &self,
119        latest_version: Box<dyn 'static + Send + Any>,
120        container_dir: PathBuf,
121        _: &dyn LspAdapterDelegate,
122    ) -> Result<LanguageServerBinary> {
123        let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
124        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
125        let package_name = "typescript";
126
127        let should_install_language_server = self
128            .node
129            .should_install_npm_package(
130                package_name,
131                &server_path,
132                &container_dir,
133                latest_version.typescript_version.as_str(),
134            )
135            .await;
136
137        if should_install_language_server {
138            self.node
139                .npm_install_packages(
140                    &container_dir,
141                    &[
142                        (package_name, latest_version.typescript_version.as_str()),
143                        (
144                            "typescript-language-server",
145                            latest_version.server_version.as_str(),
146                        ),
147                    ],
148                )
149                .await?;
150        }
151
152        Ok(LanguageServerBinary {
153            path: self.node.binary_path().await?,
154            env: None,
155            arguments: typescript_server_binary_arguments(&server_path),
156        })
157    }
158
159    async fn cached_server_binary(
160        &self,
161        container_dir: PathBuf,
162        _: &dyn LspAdapterDelegate,
163    ) -> Option<LanguageServerBinary> {
164        get_cached_ts_server_binary(container_dir, &self.node).await
165    }
166
167    async fn installation_test_binary(
168        &self,
169        container_dir: PathBuf,
170    ) -> Option<LanguageServerBinary> {
171        get_cached_ts_server_binary(container_dir, &self.node).await
172    }
173
174    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
175        Some(vec![
176            CodeActionKind::QUICKFIX,
177            CodeActionKind::REFACTOR,
178            CodeActionKind::REFACTOR_EXTRACT,
179            CodeActionKind::SOURCE,
180        ])
181    }
182
183    async fn label_for_completion(
184        &self,
185        item: &lsp::CompletionItem,
186        language: &Arc<language::Language>,
187    ) -> Option<language::CodeLabel> {
188        use lsp::CompletionItemKind as Kind;
189        let len = item.label.len();
190        let grammar = language.grammar()?;
191        let highlight_id = match item.kind? {
192            Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
193            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
194            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
195            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
196            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
197            Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
198            _ => None,
199        }?;
200
201        let text = match &item.detail {
202            Some(detail) => format!("{} {}", item.label, detail),
203            None => item.label.clone(),
204        };
205
206        Some(language::CodeLabel {
207            text,
208            runs: vec![(0..len, highlight_id)],
209            filter_range: 0..len,
210        })
211    }
212
213    async fn initialization_options(
214        self: Arc<Self>,
215        adapter: &Arc<dyn LspAdapterDelegate>,
216    ) -> Result<Option<serde_json::Value>> {
217        let tsdk_path = Self::tsdk_path(adapter).await;
218        Ok(Some(json!({
219            "provideFormatter": true,
220            "hostInfo": "zed",
221            "tsserver": {
222                "path": tsdk_path,
223            },
224            "preferences": {
225                "includeInlayParameterNameHints": "all",
226                "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
227                "includeInlayFunctionParameterTypeHints": true,
228                "includeInlayVariableTypeHints": true,
229                "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
230                "includeInlayPropertyDeclarationTypeHints": true,
231                "includeInlayFunctionLikeReturnTypeHints": true,
232                "includeInlayEnumMemberValueHints": true,
233            }
234        })))
235    }
236
237    async fn workspace_configuration(
238        self: Arc<Self>,
239        delegate: &Arc<dyn LspAdapterDelegate>,
240        cx: &mut AsyncAppContext,
241    ) -> Result<Value> {
242        let override_options = cx.update(|cx| {
243            language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
244                .and_then(|s| s.settings.clone())
245        })?;
246        if let Some(options) = override_options {
247            return Ok(options);
248        }
249        Ok(json!({
250            "completions": {
251              "completeFunctionCalls": true
252            }
253        }))
254    }
255
256    fn language_ids(&self) -> HashMap<String, String> {
257        HashMap::from_iter([
258            ("TypeScript".into(), "typescript".into()),
259            ("JavaScript".into(), "javascript".into()),
260            ("TSX".into(), "typescriptreact".into()),
261        ])
262    }
263}
264
265async fn get_cached_ts_server_binary(
266    container_dir: PathBuf,
267    node: &NodeRuntime,
268) -> Option<LanguageServerBinary> {
269    maybe!(async {
270        let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
271        let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
272        if new_server_path.exists() {
273            Ok(LanguageServerBinary {
274                path: node.binary_path().await?,
275                env: None,
276                arguments: typescript_server_binary_arguments(&new_server_path),
277            })
278        } else if old_server_path.exists() {
279            Ok(LanguageServerBinary {
280                path: node.binary_path().await?,
281                env: None,
282                arguments: typescript_server_binary_arguments(&old_server_path),
283            })
284        } else {
285            Err(anyhow!(
286                "missing executable in directory {:?}",
287                container_dir
288            ))
289        }
290    })
291    .await
292    .log_err()
293}
294
295pub struct EsLintLspAdapter {
296    node: NodeRuntime,
297}
298
299impl EsLintLspAdapter {
300    const CURRENT_VERSION: &'static str = "2.4.4";
301    const CURRENT_VERSION_TAG_NAME: &'static str = "release/2.4.4";
302
303    #[cfg(not(windows))]
304    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
305    #[cfg(windows)]
306    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
307
308    const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
309    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("eslint");
310
311    const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
312        &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
313
314    pub fn new(node: NodeRuntime) -> Self {
315        EsLintLspAdapter { node }
316    }
317
318    fn build_destination_path(container_dir: &Path) -> PathBuf {
319        container_dir.join(format!("vscode-eslint-{}", Self::CURRENT_VERSION))
320    }
321}
322
323#[async_trait(?Send)]
324impl LspAdapter for EsLintLspAdapter {
325    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
326        Some(vec![
327            CodeActionKind::QUICKFIX,
328            CodeActionKind::new("source.fixAll.eslint"),
329        ])
330    }
331
332    async fn workspace_configuration(
333        self: Arc<Self>,
334        delegate: &Arc<dyn LspAdapterDelegate>,
335        cx: &mut AsyncAppContext,
336    ) -> Result<Value> {
337        let workspace_root = delegate.worktree_root_path();
338
339        let eslint_user_settings = cx.update(|cx| {
340            language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
341                .and_then(|s| s.settings.clone())
342                .unwrap_or_default()
343        })?;
344
345        let mut code_action_on_save = json!({
346            // We enable this, but without also configuring `code_actions_on_format`
347            // in the Zed configuration, it doesn't have an effect.
348            "enable": true,
349        });
350
351        if let Some(code_action_settings) = eslint_user_settings
352            .get("codeActionOnSave")
353            .and_then(|settings| settings.as_object())
354        {
355            if let Some(enable) = code_action_settings.get("enable") {
356                code_action_on_save["enable"] = enable.clone();
357            }
358            if let Some(mode) = code_action_settings.get("mode") {
359                code_action_on_save["mode"] = mode.clone();
360            }
361            if let Some(rules) = code_action_settings.get("rules") {
362                code_action_on_save["rules"] = rules.clone();
363            }
364        }
365
366        let problems = eslint_user_settings
367            .get("problems")
368            .cloned()
369            .unwrap_or_else(|| json!({}));
370
371        let rules_customizations = eslint_user_settings
372            .get("rulesCustomizations")
373            .cloned()
374            .unwrap_or_else(|| json!([]));
375
376        let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
377        let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
378            .iter()
379            .any(|file| workspace_root.join(file).is_file());
380
381        Ok(json!({
382            "": {
383                "validate": "on",
384                "rulesCustomizations": rules_customizations,
385                "run": "onType",
386                "nodePath": node_path,
387                "workingDirectory": {"mode": "auto"},
388                "workspaceFolder": {
389                    "uri": workspace_root,
390                    "name": workspace_root.file_name()
391                        .unwrap_or(workspace_root.as_os_str()),
392                },
393                "problems": problems,
394                "codeActionOnSave": code_action_on_save,
395                "codeAction": {
396                    "disableRuleComment": {
397                        "enable": true,
398                        "location": "separateLine",
399                    },
400                    "showDocumentation": {
401                        "enable": true
402                    }
403                },
404                "experimental": {
405                    "useFlatConfig": use_flat_config,
406                },
407            }
408        }))
409    }
410
411    fn name(&self) -> LanguageServerName {
412        Self::SERVER_NAME.clone()
413    }
414
415    async fn fetch_latest_server_version(
416        &self,
417        _delegate: &dyn LspAdapterDelegate,
418    ) -> Result<Box<dyn 'static + Send + Any>> {
419        let url = build_asset_url(
420            "microsoft/vscode-eslint",
421            Self::CURRENT_VERSION_TAG_NAME,
422            Self::GITHUB_ASSET_KIND,
423        )?;
424
425        Ok(Box::new(GitHubLspBinaryVersion {
426            name: Self::CURRENT_VERSION.into(),
427            url,
428        }))
429    }
430
431    async fn fetch_server_binary(
432        &self,
433        version: Box<dyn 'static + Send + Any>,
434        container_dir: PathBuf,
435        delegate: &dyn LspAdapterDelegate,
436    ) -> Result<LanguageServerBinary> {
437        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
438        let destination_path = Self::build_destination_path(&container_dir);
439        let server_path = destination_path.join(Self::SERVER_PATH);
440
441        if fs::metadata(&server_path).await.is_err() {
442            remove_matching(&container_dir, |entry| entry != destination_path).await;
443
444            let mut response = delegate
445                .http_client()
446                .get(&version.url, Default::default(), true)
447                .await
448                .map_err(|err| anyhow!("error downloading release: {}", err))?;
449            match Self::GITHUB_ASSET_KIND {
450                AssetKind::TarGz => {
451                    let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
452                    let archive = Archive::new(decompressed_bytes);
453                    archive.unpack(&destination_path).await?;
454                }
455                AssetKind::Zip => {
456                    node_runtime::extract_zip(
457                        &destination_path,
458                        BufReader::new(response.body_mut()),
459                    )
460                    .await?;
461                }
462            }
463
464            let mut dir = fs::read_dir(&destination_path).await?;
465            let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
466            let repo_root = destination_path.join("vscode-eslint");
467            fs::rename(first.path(), &repo_root).await?;
468
469            #[cfg(target_os = "windows")]
470            {
471                handle_symlink(
472                    repo_root.join("$shared"),
473                    repo_root.join("client").join("src").join("shared"),
474                )
475                .await?;
476                handle_symlink(
477                    repo_root.join("$shared"),
478                    repo_root.join("server").join("src").join("shared"),
479                )
480                .await?;
481            }
482
483            self.node
484                .run_npm_subcommand(&repo_root, "install", &[])
485                .await?;
486
487            self.node
488                .run_npm_subcommand(&repo_root, "run-script", &["compile"])
489                .await?;
490        }
491
492        Ok(LanguageServerBinary {
493            path: self.node.binary_path().await?,
494            env: None,
495            arguments: eslint_server_binary_arguments(&server_path),
496        })
497    }
498
499    async fn cached_server_binary(
500        &self,
501        container_dir: PathBuf,
502        _: &dyn LspAdapterDelegate,
503    ) -> Option<LanguageServerBinary> {
504        let server_path =
505            Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
506        Some(LanguageServerBinary {
507            path: self.node.binary_path().await.ok()?,
508            env: None,
509            arguments: eslint_server_binary_arguments(&server_path),
510        })
511    }
512
513    async fn installation_test_binary(
514        &self,
515        container_dir: PathBuf,
516    ) -> Option<LanguageServerBinary> {
517        let server_path =
518            Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
519        Some(LanguageServerBinary {
520            path: self.node.binary_path().await.ok()?,
521            env: None,
522            arguments: eslint_server_binary_arguments(&server_path),
523        })
524    }
525}
526
527#[cfg(target_os = "windows")]
528async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
529    if fs::metadata(&src_dir).await.is_err() {
530        return Err(anyhow!("Directory {} not present.", src_dir.display()));
531    }
532    if fs::metadata(&dest_dir).await.is_ok() {
533        fs::remove_file(&dest_dir).await?;
534    }
535    fs::create_dir_all(&dest_dir).await?;
536    let mut entries = fs::read_dir(&src_dir).await?;
537    while let Some(entry) = entries.try_next().await? {
538        let entry_path = entry.path();
539        let entry_name = entry.file_name();
540        let dest_path = dest_dir.join(&entry_name);
541        fs::copy(&entry_path, &dest_path).await?;
542    }
543    Ok(())
544}
545
546#[cfg(test)]
547mod tests {
548    use gpui::{Context, TestAppContext};
549    use unindent::Unindent;
550
551    #[gpui::test]
552    async fn test_outline(cx: &mut TestAppContext) {
553        let language = crate::language(
554            "typescript",
555            tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
556        );
557
558        let text = r#"
559            function a() {
560              // local variables are omitted
561              let a1 = 1;
562              // all functions are included
563              async function a2() {}
564            }
565            // top-level variables are included
566            let b: C
567            function getB() {}
568            // exported variables are included
569            export const d = e;
570        "#
571        .unindent();
572
573        let buffer =
574            cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
575        let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
576        assert_eq!(
577            outline
578                .items
579                .iter()
580                .map(|item| (item.text.as_str(), item.depth))
581                .collect::<Vec<_>>(),
582            &[
583                ("function a()", 0),
584                ("async function a2()", 1),
585                ("let b", 0),
586                ("function getB()", 0),
587                ("const d", 0),
588            ]
589        );
590    }
591}