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 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 });
245
246 if let Some(code_action_settings) = eslint_user_settings
247 .get("codeActionOnSave")
248 .and_then(|settings| settings.as_object())
249 {
250 if let Some(enable) = code_action_settings.get("enable") {
251 code_action_on_save["enable"] = enable.clone();
252 }
253 if let Some(mode) = code_action_settings.get("mode") {
254 code_action_on_save["mode"] = mode.clone();
255 }
256 if let Some(rules) = code_action_settings.get("rules") {
257 code_action_on_save["rules"] = rules.clone();
258 }
259 }
260
261 json!({
262 "": {
263 "validate": "on",
264 "rulesCustomizations": [],
265 "run": "onType",
266 "nodePath": null,
267 "workingDirectory": {"mode": "auto"},
268 "workspaceFolder": {
269 "uri": workspace_root,
270 "name": workspace_root.file_name()
271 .unwrap_or_else(|| workspace_root.as_os_str()),
272 },
273 "problems": {},
274 "codeActionOnSave": code_action_on_save,
275 "experimental": {
276 "useFlatConfig": workspace_root.join("eslint.config.js").is_file(),
277 },
278 }
279 })
280 }
281
282 fn name(&self) -> LanguageServerName {
283 LanguageServerName(Self::SERVER_NAME.into())
284 }
285
286 fn short_name(&self) -> &'static str {
287 "eslint"
288 }
289
290 async fn fetch_latest_server_version(
291 &self,
292 delegate: &dyn LspAdapterDelegate,
293 ) -> Result<Box<dyn 'static + Send + Any>> {
294 // We're using this hardcoded release tag, because ESLint's API changed with
295 // >= 2.3 and we haven't upgraded yet.
296 let release = github_release_with_tag(
297 "microsoft/vscode-eslint",
298 "release/2.2.20-Insider",
299 delegate.http_client(),
300 )
301 .await?;
302 Ok(Box::new(GitHubLspBinaryVersion {
303 name: release.tag_name,
304 url: release.tarball_url,
305 }))
306 }
307
308 async fn fetch_server_binary(
309 &self,
310 version: Box<dyn 'static + Send + Any>,
311 container_dir: PathBuf,
312 delegate: &dyn LspAdapterDelegate,
313 ) -> Result<LanguageServerBinary> {
314 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
315 let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
316 let server_path = destination_path.join(Self::SERVER_PATH);
317
318 if fs::metadata(&server_path).await.is_err() {
319 remove_matching(&container_dir, |entry| entry != destination_path).await;
320
321 let mut response = delegate
322 .http_client()
323 .get(&version.url, Default::default(), true)
324 .await
325 .map_err(|err| anyhow!("error downloading release: {}", err))?;
326 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
327 let archive = Archive::new(decompressed_bytes);
328 archive.unpack(&destination_path).await?;
329
330 let mut dir = fs::read_dir(&destination_path).await?;
331 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
332 let repo_root = destination_path.join("vscode-eslint");
333 fs::rename(first.path(), &repo_root).await?;
334
335 self.node
336 .run_npm_subcommand(Some(&repo_root), "install", &[])
337 .await?;
338
339 self.node
340 .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
341 .await?;
342 }
343
344 Ok(LanguageServerBinary {
345 path: self.node.binary_path().await?,
346 env: None,
347 arguments: eslint_server_binary_arguments(&server_path),
348 })
349 }
350
351 async fn cached_server_binary(
352 &self,
353 container_dir: PathBuf,
354 _: &dyn LspAdapterDelegate,
355 ) -> Option<LanguageServerBinary> {
356 get_cached_eslint_server_binary(container_dir, &*self.node).await
357 }
358
359 async fn installation_test_binary(
360 &self,
361 container_dir: PathBuf,
362 ) -> Option<LanguageServerBinary> {
363 get_cached_eslint_server_binary(container_dir, &*self.node).await
364 }
365
366 async fn label_for_completion(
367 &self,
368 _item: &lsp::CompletionItem,
369 _language: &Arc<language::Language>,
370 ) -> Option<language::CodeLabel> {
371 None
372 }
373
374 fn initialization_options(&self) -> Option<serde_json::Value> {
375 None
376 }
377}
378
379async fn get_cached_eslint_server_binary(
380 container_dir: PathBuf,
381 node: &dyn NodeRuntime,
382) -> Option<LanguageServerBinary> {
383 async_maybe!({
384 // This is unfortunate but we don't know what the version is to build a path directly
385 let mut dir = fs::read_dir(&container_dir).await?;
386 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
387 if !first.file_type().await?.is_dir() {
388 return Err(anyhow!("First entry is not a directory"));
389 }
390 let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
391
392 Ok(LanguageServerBinary {
393 path: node.binary_path().await?,
394 env: None,
395 arguments: eslint_server_binary_arguments(&server_path),
396 })
397 })
398 .await
399 .log_err()
400}
401
402#[cfg(test)]
403mod tests {
404 use gpui::{Context, TestAppContext};
405 use text::BufferId;
406 use unindent::Unindent;
407
408 #[gpui::test]
409 async fn test_outline(cx: &mut TestAppContext) {
410 let language = crate::language(
411 "typescript",
412 tree_sitter_typescript::language_typescript(),
413 None,
414 )
415 .await;
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}