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 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 async fn workspace_configuration(
190 self: Arc<Self>,
191 _: &Arc<dyn LspAdapterDelegate>,
192 _cx: &mut AsyncAppContext,
193 ) -> Result<Value> {
194 Ok(json!({
195 "completions": {
196 "completeFunctionCalls": true
197 }
198 }))
199 }
200
201 fn language_ids(&self) -> HashMap<String, String> {
202 HashMap::from_iter([
203 ("TypeScript".into(), "typescript".into()),
204 ("JavaScript".into(), "javascript".into()),
205 ("TSX".into(), "typescriptreact".into()),
206 ])
207 }
208}
209
210async fn get_cached_ts_server_binary(
211 container_dir: PathBuf,
212 node: &dyn NodeRuntime,
213) -> Option<LanguageServerBinary> {
214 maybe!(async {
215 let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
216 let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
217 if new_server_path.exists() {
218 Ok(LanguageServerBinary {
219 path: node.binary_path().await?,
220 env: None,
221 arguments: typescript_server_binary_arguments(&new_server_path),
222 })
223 } else if old_server_path.exists() {
224 Ok(LanguageServerBinary {
225 path: node.binary_path().await?,
226 env: None,
227 arguments: typescript_server_binary_arguments(&old_server_path),
228 })
229 } else {
230 Err(anyhow!(
231 "missing executable in directory {:?}",
232 container_dir
233 ))
234 }
235 })
236 .await
237 .log_err()
238}
239
240pub struct EsLintLspAdapter {
241 node: Arc<dyn NodeRuntime>,
242}
243
244impl EsLintLspAdapter {
245 const CURRENT_VERSION: &'static str = "release/2.4.4";
246
247 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
248 const SERVER_NAME: &'static str = "eslint";
249
250 const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
251 &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
252
253 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
254 EsLintLspAdapter { node }
255 }
256}
257
258#[async_trait(?Send)]
259impl LspAdapter for EsLintLspAdapter {
260 async fn workspace_configuration(
261 self: Arc<Self>,
262 delegate: &Arc<dyn LspAdapterDelegate>,
263 cx: &mut AsyncAppContext,
264 ) -> Result<Value> {
265 let workspace_root = delegate.worktree_root_path();
266
267 let eslint_user_settings = cx.update(|cx| {
268 ProjectSettings::get_global(cx)
269 .lsp
270 .get(Self::SERVER_NAME)
271 .and_then(|s| s.settings.clone())
272 .unwrap_or_default()
273 })?;
274
275 let mut code_action_on_save = json!({
276 // We enable this, but without also configuring `code_actions_on_format`
277 // in the Zed configuration, it doesn't have an effect.
278 "enable": true,
279 });
280
281 if let Some(code_action_settings) = eslint_user_settings
282 .get("codeActionOnSave")
283 .and_then(|settings| settings.as_object())
284 {
285 if let Some(enable) = code_action_settings.get("enable") {
286 code_action_on_save["enable"] = enable.clone();
287 }
288 if let Some(mode) = code_action_settings.get("mode") {
289 code_action_on_save["mode"] = mode.clone();
290 }
291 if let Some(rules) = code_action_settings.get("rules") {
292 code_action_on_save["rules"] = rules.clone();
293 }
294 }
295
296 let problems = eslint_user_settings
297 .get("problems")
298 .cloned()
299 .unwrap_or_else(|| json!({}));
300
301 let rules_customizations = eslint_user_settings
302 .get("rulesCustomizations")
303 .cloned()
304 .unwrap_or_else(|| json!([]));
305
306 let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
307 let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
308 .iter()
309 .any(|file| workspace_root.join(file).is_file());
310
311 Ok(json!({
312 "": {
313 "validate": "on",
314 "rulesCustomizations": rules_customizations,
315 "run": "onType",
316 "nodePath": node_path,
317 "workingDirectory": {"mode": "auto"},
318 "workspaceFolder": {
319 "uri": workspace_root,
320 "name": workspace_root.file_name()
321 .unwrap_or_else(|| workspace_root.as_os_str()),
322 },
323 "problems": problems,
324 "codeActionOnSave": code_action_on_save,
325 "experimental": {
326 "useFlatConfig": use_flat_config,
327 },
328 }
329 }))
330 }
331
332 fn name(&self) -> LanguageServerName {
333 LanguageServerName(Self::SERVER_NAME.into())
334 }
335
336 async fn fetch_latest_server_version(
337 &self,
338 _delegate: &dyn LspAdapterDelegate,
339 ) -> Result<Box<dyn 'static + Send + Any>> {
340 let url = build_tarball_url("microsoft/vscode-eslint", Self::CURRENT_VERSION)?;
341
342 Ok(Box::new(GitHubLspBinaryVersion {
343 name: Self::CURRENT_VERSION.into(),
344 url,
345 }))
346 }
347
348 async fn fetch_server_binary(
349 &self,
350 version: Box<dyn 'static + Send + Any>,
351 container_dir: PathBuf,
352 delegate: &dyn LspAdapterDelegate,
353 ) -> Result<LanguageServerBinary> {
354 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
355 let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
356 let server_path = destination_path.join(Self::SERVER_PATH);
357
358 if fs::metadata(&server_path).await.is_err() {
359 remove_matching(&container_dir, |entry| entry != destination_path).await;
360
361 let mut response = delegate
362 .http_client()
363 .get(&version.url, Default::default(), true)
364 .await
365 .map_err(|err| anyhow!("error downloading release: {}", err))?;
366 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
367 let archive = Archive::new(decompressed_bytes);
368 archive.unpack(&destination_path).await?;
369
370 let mut dir = fs::read_dir(&destination_path).await?;
371 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
372 let repo_root = destination_path.join("vscode-eslint");
373 fs::rename(first.path(), &repo_root).await?;
374
375 self.node
376 .run_npm_subcommand(Some(&repo_root), "install", &[])
377 .await?;
378
379 self.node
380 .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
381 .await?;
382 }
383
384 Ok(LanguageServerBinary {
385 path: self.node.binary_path().await?,
386 env: None,
387 arguments: eslint_server_binary_arguments(&server_path),
388 })
389 }
390
391 async fn cached_server_binary(
392 &self,
393 container_dir: PathBuf,
394 _: &dyn LspAdapterDelegate,
395 ) -> Option<LanguageServerBinary> {
396 get_cached_eslint_server_binary(container_dir, &*self.node).await
397 }
398
399 async fn installation_test_binary(
400 &self,
401 container_dir: PathBuf,
402 ) -> Option<LanguageServerBinary> {
403 get_cached_eslint_server_binary(container_dir, &*self.node).await
404 }
405}
406
407async fn get_cached_eslint_server_binary(
408 container_dir: PathBuf,
409 node: &dyn NodeRuntime,
410) -> Option<LanguageServerBinary> {
411 maybe!(async {
412 // This is unfortunate but we don't know what the version is to build a path directly
413 let mut dir = fs::read_dir(&container_dir).await?;
414 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
415 if !first.file_type().await?.is_dir() {
416 return Err(anyhow!("First entry is not a directory"));
417 }
418 let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
419
420 Ok(LanguageServerBinary {
421 path: node.binary_path().await?,
422 env: None,
423 arguments: eslint_server_binary_arguments(&server_path),
424 })
425 })
426 .await
427 .log_err()
428}
429
430#[cfg(test)]
431mod tests {
432 use gpui::{Context, TestAppContext};
433 use unindent::Unindent;
434
435 #[gpui::test]
436 async fn test_outline(cx: &mut TestAppContext) {
437 let language = crate::language("typescript", tree_sitter_typescript::language_typescript());
438
439 let text = r#"
440 function a() {
441 // local variables are omitted
442 let a1 = 1;
443 // all functions are included
444 async function a2() {}
445 }
446 // top-level variables are included
447 let b: C
448 function getB() {}
449 // exported variables are included
450 export const d = e;
451 "#
452 .unindent();
453
454 let buffer =
455 cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
456 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
457 assert_eq!(
458 outline
459 .items
460 .iter()
461 .map(|item| (item.text.as_str(), item.depth))
462 .collect::<Vec<_>>(),
463 &[
464 ("function a()", 0),
465 ("async function a2()", 1),
466 ("let b", 0),
467 ("function getB()", 0),
468 ("const d", 0),
469 ]
470 );
471 }
472}