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