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 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 let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
258
259 json!({
260 "": {
261 "validate": "on",
262 "rulesCustomizations": [],
263 "run": "onType",
264 "nodePath": node_path,
265 "workingDirectory": {"mode": "auto"},
266 "workspaceFolder": {
267 "uri": workspace_root,
268 "name": workspace_root.file_name()
269 .unwrap_or_else(|| workspace_root.as_os_str()),
270 },
271 "problems": {},
272 "codeActionOnSave": code_action_on_save,
273 "experimental": {
274 "useFlatConfig": workspace_root.join("eslint.config.js").is_file(),
275 },
276 }
277 })
278 }
279
280 fn name(&self) -> LanguageServerName {
281 LanguageServerName(Self::SERVER_NAME.into())
282 }
283
284 async fn fetch_latest_server_version(
285 &self,
286 delegate: &dyn LspAdapterDelegate,
287 ) -> Result<Box<dyn 'static + Send + Any>> {
288 // At the time of writing the latest vscode-eslint release was released in 2020 and requires
289 // special custom LSP protocol extensions be handled to fully initialize. Download the latest
290 // prerelease instead to sidestep this issue
291 let release = latest_github_release(
292 "microsoft/vscode-eslint",
293 false,
294 true,
295 delegate.http_client(),
296 )
297 .await?;
298 Ok(Box::new(GitHubLspBinaryVersion {
299 name: release.tag_name,
300 url: release.tarball_url,
301 }))
302 }
303
304 async fn fetch_server_binary(
305 &self,
306 version: Box<dyn 'static + Send + Any>,
307 container_dir: PathBuf,
308 delegate: &dyn LspAdapterDelegate,
309 ) -> Result<LanguageServerBinary> {
310 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
311 let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
312 let server_path = destination_path.join(Self::SERVER_PATH);
313
314 if fs::metadata(&server_path).await.is_err() {
315 remove_matching(&container_dir, |entry| entry != destination_path).await;
316
317 let mut response = delegate
318 .http_client()
319 .get(&version.url, Default::default(), true)
320 .await
321 .map_err(|err| anyhow!("error downloading release: {}", err))?;
322 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
323 let archive = Archive::new(decompressed_bytes);
324 archive.unpack(&destination_path).await?;
325
326 let mut dir = fs::read_dir(&destination_path).await?;
327 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
328 let repo_root = destination_path.join("vscode-eslint");
329 fs::rename(first.path(), &repo_root).await?;
330
331 self.node
332 .run_npm_subcommand(Some(&repo_root), "install", &[])
333 .await?;
334
335 self.node
336 .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
337 .await?;
338 }
339
340 Ok(LanguageServerBinary {
341 path: self.node.binary_path().await?,
342 env: None,
343 arguments: eslint_server_binary_arguments(&server_path),
344 })
345 }
346
347 async fn cached_server_binary(
348 &self,
349 container_dir: PathBuf,
350 _: &dyn LspAdapterDelegate,
351 ) -> Option<LanguageServerBinary> {
352 get_cached_eslint_server_binary(container_dir, &*self.node).await
353 }
354
355 async fn installation_test_binary(
356 &self,
357 container_dir: PathBuf,
358 ) -> Option<LanguageServerBinary> {
359 get_cached_eslint_server_binary(container_dir, &*self.node).await
360 }
361
362 async fn label_for_completion(
363 &self,
364 _item: &lsp::CompletionItem,
365 _language: &Arc<language::Language>,
366 ) -> Option<language::CodeLabel> {
367 None
368 }
369
370 fn initialization_options(&self) -> Option<serde_json::Value> {
371 None
372 }
373}
374
375async fn get_cached_eslint_server_binary(
376 container_dir: PathBuf,
377 node: &dyn NodeRuntime,
378) -> Option<LanguageServerBinary> {
379 async_maybe!({
380 // This is unfortunate but we don't know what the version is to build a path directly
381 let mut dir = fs::read_dir(&container_dir).await?;
382 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
383 if !first.file_type().await?.is_dir() {
384 return Err(anyhow!("First entry is not a directory"));
385 }
386 let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
387
388 Ok(LanguageServerBinary {
389 path: node.binary_path().await?,
390 env: None,
391 arguments: eslint_server_binary_arguments(&server_path),
392 })
393 })
394 .await
395 .log_err()
396}
397
398#[cfg(test)]
399mod tests {
400 use gpui::{Context, TestAppContext};
401 use text::BufferId;
402 use unindent::Unindent;
403
404 #[gpui::test]
405 async fn test_outline(cx: &mut TestAppContext) {
406 let language = crate::language("typescript", tree_sitter_typescript::language_typescript());
407
408 let text = r#"
409 function a() {
410 // local variables are omitted
411 let a1 = 1;
412 // all functions are included
413 async function a2() {}
414 }
415 // top-level variables are included
416 let b: C
417 function getB() {}
418 // exported variables are included
419 export const d = e;
420 "#
421 .unindent();
422
423 let buffer = cx.new_model(|cx| {
424 language::Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
425 .with_language(language, cx)
426 });
427 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
428 assert_eq!(
429 outline
430 .items
431 .iter()
432 .map(|item| (item.text.as_str(), item.depth))
433 .collect::<Vec<_>>(),
434 &[
435 ("function a()", 0),
436 ("async function a2()", 1),
437 ("let b", 0),
438 ("function getB()", 0),
439 ("const d", 0),
440 ]
441 );
442 }
443}