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(?Send)]
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 latest_version: Box<dyn 'static + Send + Any>,
75 container_dir: PathBuf,
76 _: &dyn LspAdapterDelegate,
77 ) -> Result<LanguageServerBinary> {
78 let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
79 let server_path = container_dir.join(Self::NEW_SERVER_PATH);
80 let package_name = "typescript";
81
82 let should_install_language_server = self
83 .node
84 .should_install_npm_package(
85 package_name,
86 &server_path,
87 &container_dir,
88 latest_version.typescript_version.as_str(),
89 )
90 .await;
91
92 if should_install_language_server {
93 self.node
94 .npm_install_packages(
95 &container_dir,
96 &[
97 (package_name, latest_version.typescript_version.as_str()),
98 (
99 "typescript-language-server",
100 latest_version.server_version.as_str(),
101 ),
102 ],
103 )
104 .await?;
105 }
106
107 Ok(LanguageServerBinary {
108 path: self.node.binary_path().await?,
109 env: None,
110 arguments: typescript_server_binary_arguments(&server_path),
111 })
112 }
113
114 async fn cached_server_binary(
115 &self,
116 container_dir: PathBuf,
117 _: &dyn LspAdapterDelegate,
118 ) -> Option<LanguageServerBinary> {
119 get_cached_ts_server_binary(container_dir, &*self.node).await
120 }
121
122 async fn installation_test_binary(
123 &self,
124 container_dir: PathBuf,
125 ) -> Option<LanguageServerBinary> {
126 get_cached_ts_server_binary(container_dir, &*self.node).await
127 }
128
129 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
130 Some(vec![
131 CodeActionKind::QUICKFIX,
132 CodeActionKind::REFACTOR,
133 CodeActionKind::REFACTOR_EXTRACT,
134 CodeActionKind::SOURCE,
135 ])
136 }
137
138 async fn label_for_completion(
139 &self,
140 item: &lsp::CompletionItem,
141 language: &Arc<language::Language>,
142 ) -> Option<language::CodeLabel> {
143 use lsp::CompletionItemKind as Kind;
144 let len = item.label.len();
145 let grammar = language.grammar()?;
146 let highlight_id = match item.kind? {
147 Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
148 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
149 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
150 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
151 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
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 fn language_ids(&self) -> HashMap<String, String> {
190 HashMap::from_iter([
191 ("TypeScript".into(), "typescript".into()),
192 ("JavaScript".into(), "javascript".into()),
193 ("TSX".into(), "typescriptreact".into()),
194 ])
195 }
196}
197
198async fn get_cached_ts_server_binary(
199 container_dir: PathBuf,
200 node: &dyn NodeRuntime,
201) -> Option<LanguageServerBinary> {
202 async_maybe!({
203 let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
204 let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
205 if new_server_path.exists() {
206 Ok(LanguageServerBinary {
207 path: node.binary_path().await?,
208 env: None,
209 arguments: typescript_server_binary_arguments(&new_server_path),
210 })
211 } else if old_server_path.exists() {
212 Ok(LanguageServerBinary {
213 path: node.binary_path().await?,
214 env: None,
215 arguments: typescript_server_binary_arguments(&old_server_path),
216 })
217 } else {
218 Err(anyhow!(
219 "missing executable in directory {:?}",
220 container_dir
221 ))
222 }
223 })
224 .await
225 .log_err()
226}
227
228pub struct EsLintLspAdapter {
229 node: Arc<dyn NodeRuntime>,
230}
231
232impl EsLintLspAdapter {
233 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
234 const SERVER_NAME: &'static str = "eslint";
235
236 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
237 EsLintLspAdapter { node }
238 }
239}
240
241#[async_trait(?Send)]
242impl LspAdapter for EsLintLspAdapter {
243 fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
244 let eslint_user_settings = ProjectSettings::get_global(cx)
245 .lsp
246 .get(Self::SERVER_NAME)
247 .and_then(|s| s.settings.clone())
248 .unwrap_or_default();
249
250 let mut code_action_on_save = json!({
251 // We enable this, but without also configuring `code_actions_on_format`
252 // in the Zed configuration, it doesn't have an effect.
253 "enable": true,
254 });
255
256 if let Some(code_action_settings) = eslint_user_settings
257 .get("codeActionOnSave")
258 .and_then(|settings| settings.as_object())
259 {
260 if let Some(enable) = code_action_settings.get("enable") {
261 code_action_on_save["enable"] = enable.clone();
262 }
263 if let Some(mode) = code_action_settings.get("mode") {
264 code_action_on_save["mode"] = mode.clone();
265 }
266 if let Some(rules) = code_action_settings.get("rules") {
267 code_action_on_save["rules"] = rules.clone();
268 }
269 }
270
271 let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
272
273 json!({
274 "": {
275 "validate": "on",
276 "rulesCustomizations": [],
277 "run": "onType",
278 "nodePath": node_path,
279 "workingDirectory": {"mode": "auto"},
280 "workspaceFolder": {
281 "uri": workspace_root,
282 "name": workspace_root.file_name()
283 .unwrap_or_else(|| workspace_root.as_os_str()),
284 },
285 "problems": {},
286 "codeActionOnSave": code_action_on_save,
287 "experimental": {
288 "useFlatConfig": workspace_root.join("eslint.config.js").is_file(),
289 },
290 }
291 })
292 }
293
294 fn name(&self) -> LanguageServerName {
295 LanguageServerName(Self::SERVER_NAME.into())
296 }
297
298 async fn fetch_latest_server_version(
299 &self,
300 delegate: &dyn LspAdapterDelegate,
301 ) -> Result<Box<dyn 'static + Send + Any>> {
302 // We're using this hardcoded release tag, because ESLint's API changed with
303 // >= 2.3 and we haven't upgraded yet.
304 let release = github_release_with_tag(
305 "microsoft/vscode-eslint",
306 "release/2.2.20-Insider",
307 delegate.http_client(),
308 )
309 .await?;
310 Ok(Box::new(GitHubLspBinaryVersion {
311 name: release.tag_name,
312 url: release.tarball_url,
313 }))
314 }
315
316 async fn fetch_server_binary(
317 &self,
318 version: Box<dyn 'static + Send + Any>,
319 container_dir: PathBuf,
320 delegate: &dyn LspAdapterDelegate,
321 ) -> Result<LanguageServerBinary> {
322 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
323 let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
324 let server_path = destination_path.join(Self::SERVER_PATH);
325
326 if fs::metadata(&server_path).await.is_err() {
327 remove_matching(&container_dir, |entry| entry != destination_path).await;
328
329 let mut response = delegate
330 .http_client()
331 .get(&version.url, Default::default(), true)
332 .await
333 .map_err(|err| anyhow!("error downloading release: {}", err))?;
334 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
335 let archive = Archive::new(decompressed_bytes);
336 archive.unpack(&destination_path).await?;
337
338 let mut dir = fs::read_dir(&destination_path).await?;
339 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
340 let repo_root = destination_path.join("vscode-eslint");
341 fs::rename(first.path(), &repo_root).await?;
342
343 self.node
344 .run_npm_subcommand(Some(&repo_root), "install", &[])
345 .await?;
346
347 self.node
348 .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
349 .await?;
350 }
351
352 Ok(LanguageServerBinary {
353 path: self.node.binary_path().await?,
354 env: None,
355 arguments: eslint_server_binary_arguments(&server_path),
356 })
357 }
358
359 async fn cached_server_binary(
360 &self,
361 container_dir: PathBuf,
362 _: &dyn LspAdapterDelegate,
363 ) -> Option<LanguageServerBinary> {
364 get_cached_eslint_server_binary(container_dir, &*self.node).await
365 }
366
367 async fn installation_test_binary(
368 &self,
369 container_dir: PathBuf,
370 ) -> Option<LanguageServerBinary> {
371 get_cached_eslint_server_binary(container_dir, &*self.node).await
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}