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