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