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