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::AppContext;
  7use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
  8use lsp::{CodeActionKind, LanguageServerBinary};
  9use node_runtime::NodeRuntime;
 10use project::project_settings::ProjectSettings;
 11use serde_json::{json, Value};
 12use settings::Settings;
 13use smol::{fs, io::BufReader, stream::StreamExt};
 14use std::{
 15    any::Any,
 16    ffi::OsString,
 17    path::{Path, PathBuf},
 18    sync::Arc,
 19};
 20use util::{
 21    fs::remove_matching,
 22    github::{build_tarball_url, GitHubLspBinaryVersion},
 23    maybe, ResultExt,
 24};
 25
 26fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 27    vec![server_path.into(), "--stdio".into()]
 28}
 29
 30fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 31    vec![server_path.into(), "--stdio".into()]
 32}
 33
 34pub struct TypeScriptLspAdapter {
 35    node: Arc<dyn NodeRuntime>,
 36}
 37
 38impl TypeScriptLspAdapter {
 39    const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
 40    const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
 41
 42    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
 43        TypeScriptLspAdapter { node }
 44    }
 45}
 46
 47struct TypeScriptVersions {
 48    typescript_version: String,
 49    server_version: String,
 50}
 51
 52#[async_trait(?Send)]
 53impl LspAdapter for TypeScriptLspAdapter {
 54    fn name(&self) -> LanguageServerName {
 55        LanguageServerName("typescript-language-server".into())
 56    }
 57
 58    async fn fetch_latest_server_version(
 59        &self,
 60        _: &dyn LspAdapterDelegate,
 61    ) -> Result<Box<dyn 'static + Send + Any>> {
 62        Ok(Box::new(TypeScriptVersions {
 63            typescript_version: self.node.npm_package_latest_version("typescript").await?,
 64            server_version: self
 65                .node
 66                .npm_package_latest_version("typescript-language-server")
 67                .await?,
 68        }) as Box<_>)
 69    }
 70
 71    async fn fetch_server_binary(
 72        &self,
 73        latest_version: Box<dyn 'static + Send + Any>,
 74        container_dir: PathBuf,
 75        _: &dyn LspAdapterDelegate,
 76    ) -> Result<LanguageServerBinary> {
 77        let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
 78        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
 79        let package_name = "typescript";
 80
 81        let should_install_language_server = self
 82            .node
 83            .should_install_npm_package(
 84                package_name,
 85                &server_path,
 86                &container_dir,
 87                latest_version.typescript_version.as_str(),
 88            )
 89            .await;
 90
 91        if should_install_language_server {
 92            self.node
 93                .npm_install_packages(
 94                    &container_dir,
 95                    &[
 96                        (package_name, latest_version.typescript_version.as_str()),
 97                        (
 98                            "typescript-language-server",
 99                            latest_version.server_version.as_str(),
100                        ),
101                    ],
102                )
103                .await?;
104        }
105
106        Ok(LanguageServerBinary {
107            path: self.node.binary_path().await?,
108            env: None,
109            arguments: typescript_server_binary_arguments(&server_path),
110        })
111    }
112
113    async fn cached_server_binary(
114        &self,
115        container_dir: PathBuf,
116        _: &dyn LspAdapterDelegate,
117    ) -> Option<LanguageServerBinary> {
118        get_cached_ts_server_binary(container_dir, &*self.node).await
119    }
120
121    async fn installation_test_binary(
122        &self,
123        container_dir: PathBuf,
124    ) -> Option<LanguageServerBinary> {
125        get_cached_ts_server_binary(container_dir, &*self.node).await
126    }
127
128    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
129        Some(vec![
130            CodeActionKind::QUICKFIX,
131            CodeActionKind::REFACTOR,
132            CodeActionKind::REFACTOR_EXTRACT,
133            CodeActionKind::SOURCE,
134        ])
135    }
136
137    async fn label_for_completion(
138        &self,
139        item: &lsp::CompletionItem,
140        language: &Arc<language::Language>,
141    ) -> Option<language::CodeLabel> {
142        use lsp::CompletionItemKind as Kind;
143        let len = item.label.len();
144        let grammar = language.grammar()?;
145        let highlight_id = match item.kind? {
146            Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
147            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
148            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
149            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
150            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
151            Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
152            _ => None,
153        }?;
154
155        let text = match &item.detail {
156            Some(detail) => format!("{} {}", item.label, detail),
157            None => item.label.clone(),
158        };
159
160        Some(language::CodeLabel {
161            text,
162            runs: vec![(0..len, highlight_id)],
163            filter_range: 0..len,
164        })
165    }
166
167    async fn initialization_options(
168        self: Arc<Self>,
169        _: &Arc<dyn LspAdapterDelegate>,
170    ) -> Result<Option<serde_json::Value>> {
171        Ok(Some(json!({
172            "provideFormatter": true,
173            "tsserver": {
174                "path": "node_modules/typescript/lib",
175            },
176            "preferences": {
177                "includeInlayParameterNameHints": "all",
178                "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
179                "includeInlayFunctionParameterTypeHints": true,
180                "includeInlayVariableTypeHints": true,
181                "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
182                "includeInlayPropertyDeclarationTypeHints": true,
183                "includeInlayFunctionLikeReturnTypeHints": true,
184                "includeInlayEnumMemberValueHints": true,
185            }
186        })))
187    }
188
189    fn language_ids(&self) -> HashMap<String, String> {
190        HashMap::from_iter([
191            ("TypeScript".into(), "typescript".into()),
192            ("JavaScript".into(), "javascript".into()),
193            ("TSX".into(), "typescriptreact".into()),
194        ])
195    }
196}
197
198async fn get_cached_ts_server_binary(
199    container_dir: PathBuf,
200    node: &dyn NodeRuntime,
201) -> Option<LanguageServerBinary> {
202    maybe!(async {
203        let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
204        let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
205        if new_server_path.exists() {
206            Ok(LanguageServerBinary {
207                path: node.binary_path().await?,
208                env: None,
209                arguments: typescript_server_binary_arguments(&new_server_path),
210            })
211        } else if old_server_path.exists() {
212            Ok(LanguageServerBinary {
213                path: node.binary_path().await?,
214                env: None,
215                arguments: typescript_server_binary_arguments(&old_server_path),
216            })
217        } else {
218            Err(anyhow!(
219                "missing executable in directory {:?}",
220                container_dir
221            ))
222        }
223    })
224    .await
225    .log_err()
226}
227
228pub struct EsLintLspAdapter {
229    node: Arc<dyn NodeRuntime>,
230}
231
232impl EsLintLspAdapter {
233    const CURRENT_VERSION: &'static str = "release/2.4.4";
234
235    const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
236    const SERVER_NAME: &'static str = "eslint";
237
238    const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
239        &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
240
241    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
242        EsLintLspAdapter { node }
243    }
244}
245
246#[async_trait(?Send)]
247impl LspAdapter for EsLintLspAdapter {
248    fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
249        let eslint_user_settings = ProjectSettings::get_global(cx)
250            .lsp
251            .get(Self::SERVER_NAME)
252            .and_then(|s| s.settings.clone())
253            .unwrap_or_default();
254
255        let mut code_action_on_save = json!({
256            // We enable this, but without also configuring `code_actions_on_format`
257            // in the Zed configuration, it doesn't have an effect.
258            "enable": true,
259        });
260
261        if let Some(code_action_settings) = eslint_user_settings
262            .get("codeActionOnSave")
263            .and_then(|settings| settings.as_object())
264        {
265            if let Some(enable) = code_action_settings.get("enable") {
266                code_action_on_save["enable"] = enable.clone();
267            }
268            if let Some(mode) = code_action_settings.get("mode") {
269                code_action_on_save["mode"] = mode.clone();
270            }
271            if let Some(rules) = code_action_settings.get("rules") {
272                code_action_on_save["rules"] = rules.clone();
273            }
274        }
275
276        let problems = eslint_user_settings
277            .get("problems")
278            .cloned()
279            .unwrap_or_else(|| json!({}));
280
281        let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
282        let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
283            .iter()
284            .any(|file| workspace_root.join(file).is_file());
285
286        json!({
287            "": {
288                "validate": "on",
289                "rulesCustomizations": [],
290                "run": "onType",
291                "nodePath": node_path,
292                "workingDirectory": {"mode": "auto"},
293                "workspaceFolder": {
294                    "uri": workspace_root,
295                    "name": workspace_root.file_name()
296                        .unwrap_or_else(|| workspace_root.as_os_str()),
297                },
298                "problems": problems,
299                "codeActionOnSave": code_action_on_save,
300                "experimental": {
301                    "useFlatConfig": use_flat_config,
302                },
303            }
304        })
305    }
306
307    fn name(&self) -> LanguageServerName {
308        LanguageServerName(Self::SERVER_NAME.into())
309    }
310
311    async fn fetch_latest_server_version(
312        &self,
313        _delegate: &dyn LspAdapterDelegate,
314    ) -> Result<Box<dyn 'static + Send + Any>> {
315        let url = build_tarball_url("microsoft/vscode-eslint", Self::CURRENT_VERSION)?;
316
317        Ok(Box::new(GitHubLspBinaryVersion {
318            name: Self::CURRENT_VERSION.into(),
319            url,
320        }))
321    }
322
323    async fn fetch_server_binary(
324        &self,
325        version: Box<dyn 'static + Send + Any>,
326        container_dir: PathBuf,
327        delegate: &dyn LspAdapterDelegate,
328    ) -> Result<LanguageServerBinary> {
329        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
330        let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
331        let server_path = destination_path.join(Self::SERVER_PATH);
332
333        if fs::metadata(&server_path).await.is_err() {
334            remove_matching(&container_dir, |entry| entry != destination_path).await;
335
336            let mut response = delegate
337                .http_client()
338                .get(&version.url, Default::default(), true)
339                .await
340                .map_err(|err| anyhow!("error downloading release: {}", err))?;
341            let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
342            let archive = Archive::new(decompressed_bytes);
343            archive.unpack(&destination_path).await?;
344
345            let mut dir = fs::read_dir(&destination_path).await?;
346            let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
347            let repo_root = destination_path.join("vscode-eslint");
348            fs::rename(first.path(), &repo_root).await?;
349
350            self.node
351                .run_npm_subcommand(Some(&repo_root), "install", &[])
352                .await?;
353
354            self.node
355                .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
356                .await?;
357        }
358
359        Ok(LanguageServerBinary {
360            path: self.node.binary_path().await?,
361            env: None,
362            arguments: eslint_server_binary_arguments(&server_path),
363        })
364    }
365
366    async fn cached_server_binary(
367        &self,
368        container_dir: PathBuf,
369        _: &dyn LspAdapterDelegate,
370    ) -> Option<LanguageServerBinary> {
371        get_cached_eslint_server_binary(container_dir, &*self.node).await
372    }
373
374    async fn installation_test_binary(
375        &self,
376        container_dir: PathBuf,
377    ) -> Option<LanguageServerBinary> {
378        get_cached_eslint_server_binary(container_dir, &*self.node).await
379    }
380}
381
382async fn get_cached_eslint_server_binary(
383    container_dir: PathBuf,
384    node: &dyn NodeRuntime,
385) -> Option<LanguageServerBinary> {
386    maybe!(async {
387        // This is unfortunate but we don't know what the version is to build a path directly
388        let mut dir = fs::read_dir(&container_dir).await?;
389        let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
390        if !first.file_type().await?.is_dir() {
391            return Err(anyhow!("First entry is not a directory"));
392        }
393        let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
394
395        Ok(LanguageServerBinary {
396            path: node.binary_path().await?,
397            env: None,
398            arguments: eslint_server_binary_arguments(&server_path),
399        })
400    })
401    .await
402    .log_err()
403}
404
405#[cfg(test)]
406mod tests {
407    use gpui::{Context, TestAppContext};
408    use text::BufferId;
409    use unindent::Unindent;
410
411    #[gpui::test]
412    async fn test_outline(cx: &mut TestAppContext) {
413        let language = crate::language("typescript", tree_sitter_typescript::language_typescript());
414
415        let text = r#"
416            function a() {
417              // local variables are omitted
418              let a1 = 1;
419              // all functions are included
420              async function a2() {}
421            }
422            // top-level variables are included
423            let b: C
424            function getB() {}
425            // exported variables are included
426            export const d = e;
427        "#
428        .unindent();
429
430        let buffer = cx.new_model(|cx| {
431            language::Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
432                .with_language(language, cx)
433        });
434        let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
435        assert_eq!(
436            outline
437                .items
438                .iter()
439                .map(|item| (item.text.as_str(), item.depth))
440                .collect::<Vec<_>>(),
441            &[
442                ("function a()", 0),
443                ("async function a2()", 1),
444                ("let b", 0),
445                ("function getB()", 0),
446                ("const d", 0),
447            ]
448        );
449    }
450}