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