1use anyhow::{anyhow, Context as _, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_tar::Archive;
4use async_trait::async_trait;
5use collections::HashMap;
6use gpui::AsyncAppContext;
7use http_client::github::{build_asset_url, AssetKind, GitHubLspBinaryVersion};
8use language::{LanguageToolchainStore, LspAdapter, LspAdapterDelegate};
9use lsp::{CodeActionKind, LanguageServerBinary, LanguageServerName};
10use node_runtime::NodeRuntime;
11use project::lsp_store::language_server_settings;
12use project::ContextProviderWithTasks;
13use serde_json::{json, Value};
14use smol::{fs, io::BufReader, stream::StreamExt};
15use std::{
16 any::Any,
17 ffi::OsString,
18 path::{Path, PathBuf},
19 sync::Arc,
20};
21use task::{TaskTemplate, TaskTemplates, VariableName};
22use util::{fs::remove_matching, maybe, ResultExt};
23
24pub(super) fn typescript_task_context() -> ContextProviderWithTasks {
25 ContextProviderWithTasks::new(TaskTemplates(vec![
26 TaskTemplate {
27 label: "jest file test".to_owned(),
28 command: "npx jest".to_owned(),
29 args: vec![VariableName::File.template_value()],
30 ..TaskTemplate::default()
31 },
32 TaskTemplate {
33 label: "jest test $ZED_SYMBOL".to_owned(),
34 command: "npx jest".to_owned(),
35 args: vec![
36 "--testNamePattern".into(),
37 format!("\"{}\"", VariableName::Symbol.template_value()),
38 VariableName::File.template_value(),
39 ],
40 tags: vec!["ts-test".into(), "js-test".into(), "tsx-test".into()],
41 ..TaskTemplate::default()
42 },
43 TaskTemplate {
44 label: "execute selection $ZED_SELECTED_TEXT".to_owned(),
45 command: "node".to_owned(),
46 args: vec![
47 "-e".into(),
48 format!("\"{}\"", VariableName::SelectedText.template_value()),
49 ],
50 ..TaskTemplate::default()
51 },
52 ]))
53}
54
55fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
56 vec![server_path.into(), "--stdio".into()]
57}
58
59fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
60 vec![
61 "--max-old-space-size=8192".into(),
62 server_path.into(),
63 "--stdio".into(),
64 ]
65}
66
67pub struct TypeScriptLspAdapter {
68 node: NodeRuntime,
69}
70
71impl TypeScriptLspAdapter {
72 const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
73 const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
74 const SERVER_NAME: LanguageServerName =
75 LanguageServerName::new_static("typescript-language-server");
76 const PACKAGE_NAME: &str = "typescript";
77 pub fn new(node: NodeRuntime) -> Self {
78 TypeScriptLspAdapter { node }
79 }
80 async fn tsdk_path(adapter: &Arc<dyn LspAdapterDelegate>) -> &'static str {
81 let is_yarn = adapter
82 .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
83 .await
84 .is_ok();
85
86 if is_yarn {
87 ".yarn/sdks/typescript/lib"
88 } else {
89 "node_modules/typescript/lib"
90 }
91 }
92}
93
94struct TypeScriptVersions {
95 typescript_version: String,
96 server_version: String,
97}
98
99#[async_trait(?Send)]
100impl LspAdapter for TypeScriptLspAdapter {
101 fn name(&self) -> LanguageServerName {
102 Self::SERVER_NAME.clone()
103 }
104
105 async fn fetch_latest_server_version(
106 &self,
107 _: &dyn LspAdapterDelegate,
108 ) -> Result<Box<dyn 'static + Send + Any>> {
109 Ok(Box::new(TypeScriptVersions {
110 typescript_version: self.node.npm_package_latest_version("typescript").await?,
111 server_version: self
112 .node
113 .npm_package_latest_version("typescript-language-server")
114 .await?,
115 }) as Box<_>)
116 }
117
118 async fn check_if_version_installed(
119 &self,
120 version: &(dyn 'static + Send + Any),
121 container_dir: &PathBuf,
122 _: &dyn LspAdapterDelegate,
123 ) -> Option<LanguageServerBinary> {
124 let version = version.downcast_ref::<TypeScriptVersions>().unwrap();
125 let server_path = container_dir.join(Self::NEW_SERVER_PATH);
126
127 let should_install_language_server = self
128 .node
129 .should_install_npm_package(
130 Self::PACKAGE_NAME,
131 &server_path,
132 &container_dir,
133 version.typescript_version.as_str(),
134 )
135 .await;
136
137 if should_install_language_server {
138 None
139 } else {
140 Some(LanguageServerBinary {
141 path: self.node.binary_path().await.ok()?,
142 env: None,
143 arguments: typescript_server_binary_arguments(&server_path),
144 })
145 }
146 }
147
148 async fn fetch_server_binary(
149 &self,
150 latest_version: Box<dyn 'static + Send + Any>,
151 container_dir: PathBuf,
152 _: &dyn LspAdapterDelegate,
153 ) -> Result<LanguageServerBinary> {
154 let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
155 let server_path = container_dir.join(Self::NEW_SERVER_PATH);
156
157 self.node
158 .npm_install_packages(
159 &container_dir,
160 &[
161 (
162 Self::PACKAGE_NAME,
163 latest_version.typescript_version.as_str(),
164 ),
165 (
166 "typescript-language-server",
167 latest_version.server_version.as_str(),
168 ),
169 ],
170 )
171 .await?;
172
173 Ok(LanguageServerBinary {
174 path: self.node.binary_path().await?,
175 env: None,
176 arguments: typescript_server_binary_arguments(&server_path),
177 })
178 }
179
180 async fn cached_server_binary(
181 &self,
182 container_dir: PathBuf,
183 _: &dyn LspAdapterDelegate,
184 ) -> Option<LanguageServerBinary> {
185 get_cached_ts_server_binary(container_dir, &self.node).await
186 }
187
188 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
189 Some(vec![
190 CodeActionKind::QUICKFIX,
191 CodeActionKind::REFACTOR,
192 CodeActionKind::REFACTOR_EXTRACT,
193 CodeActionKind::SOURCE,
194 ])
195 }
196
197 async fn label_for_completion(
198 &self,
199 item: &lsp::CompletionItem,
200 language: &Arc<language::Language>,
201 ) -> Option<language::CodeLabel> {
202 use lsp::CompletionItemKind as Kind;
203 let len = item.label.len();
204 let grammar = language.grammar()?;
205 let highlight_id = match item.kind? {
206 Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
207 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
208 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
209 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
210 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
211 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
212 _ => None,
213 }?;
214
215 let one_line = |s: &str| s.replace(" ", "").replace('\n', " ");
216
217 let text = if let Some(description) = item
218 .label_details
219 .as_ref()
220 .and_then(|label_details| label_details.description.as_ref())
221 {
222 format!("{} {}", item.label, one_line(description))
223 } else if let Some(detail) = &item.detail {
224 format!("{} {}", item.label, one_line(detail))
225 } else {
226 item.label.clone()
227 };
228
229 Some(language::CodeLabel {
230 text,
231 runs: vec![(0..len, highlight_id)],
232 filter_range: 0..len,
233 })
234 }
235
236 async fn initialization_options(
237 self: Arc<Self>,
238 adapter: &Arc<dyn LspAdapterDelegate>,
239 ) -> Result<Option<serde_json::Value>> {
240 let tsdk_path = Self::tsdk_path(adapter).await;
241 Ok(Some(json!({
242 "provideFormatter": true,
243 "hostInfo": "zed",
244 "tsserver": {
245 "path": tsdk_path,
246 },
247 "preferences": {
248 "includeInlayParameterNameHints": "all",
249 "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
250 "includeInlayFunctionParameterTypeHints": true,
251 "includeInlayVariableTypeHints": true,
252 "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
253 "includeInlayPropertyDeclarationTypeHints": true,
254 "includeInlayFunctionLikeReturnTypeHints": true,
255 "includeInlayEnumMemberValueHints": true,
256 }
257 })))
258 }
259
260 async fn workspace_configuration(
261 self: Arc<Self>,
262 delegate: &Arc<dyn LspAdapterDelegate>,
263 _: Arc<dyn LanguageToolchainStore>,
264 cx: &mut AsyncAppContext,
265 ) -> Result<Value> {
266 let override_options = cx.update(|cx| {
267 language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
268 .and_then(|s| s.settings.clone())
269 })?;
270 if let Some(options) = override_options {
271 return Ok(options);
272 }
273 Ok(json!({
274 "completions": {
275 "completeFunctionCalls": true
276 }
277 }))
278 }
279
280 fn language_ids(&self) -> HashMap<String, String> {
281 HashMap::from_iter([
282 ("TypeScript".into(), "typescript".into()),
283 ("JavaScript".into(), "javascript".into()),
284 ("TSX".into(), "typescriptreact".into()),
285 ])
286 }
287}
288
289async fn get_cached_ts_server_binary(
290 container_dir: PathBuf,
291 node: &NodeRuntime,
292) -> Option<LanguageServerBinary> {
293 maybe!(async {
294 let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
295 let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
296 if new_server_path.exists() {
297 Ok(LanguageServerBinary {
298 path: node.binary_path().await?,
299 env: None,
300 arguments: typescript_server_binary_arguments(&new_server_path),
301 })
302 } else if old_server_path.exists() {
303 Ok(LanguageServerBinary {
304 path: node.binary_path().await?,
305 env: None,
306 arguments: typescript_server_binary_arguments(&old_server_path),
307 })
308 } else {
309 Err(anyhow!(
310 "missing executable in directory {:?}",
311 container_dir
312 ))
313 }
314 })
315 .await
316 .log_err()
317}
318
319pub struct EsLintLspAdapter {
320 node: NodeRuntime,
321}
322
323impl EsLintLspAdapter {
324 const CURRENT_VERSION: &'static str = "2.4.4";
325 const CURRENT_VERSION_TAG_NAME: &'static str = "release/2.4.4";
326
327 #[cfg(not(windows))]
328 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
329 #[cfg(windows)]
330 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
331
332 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
333 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("eslint");
334
335 const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
336 &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
337
338 pub fn new(node: NodeRuntime) -> Self {
339 EsLintLspAdapter { node }
340 }
341
342 fn build_destination_path(container_dir: &Path) -> PathBuf {
343 container_dir.join(format!("vscode-eslint-{}", Self::CURRENT_VERSION))
344 }
345}
346
347#[async_trait(?Send)]
348impl LspAdapter for EsLintLspAdapter {
349 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
350 Some(vec![
351 CodeActionKind::QUICKFIX,
352 CodeActionKind::new("source.fixAll.eslint"),
353 ])
354 }
355
356 async fn workspace_configuration(
357 self: Arc<Self>,
358 delegate: &Arc<dyn LspAdapterDelegate>,
359 _: Arc<dyn LanguageToolchainStore>,
360 cx: &mut AsyncAppContext,
361 ) -> Result<Value> {
362 let workspace_root = delegate.worktree_root_path();
363
364 let eslint_user_settings = cx.update(|cx| {
365 language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
366 .and_then(|s| s.settings.clone())
367 .unwrap_or_default()
368 })?;
369
370 let mut code_action_on_save = json!({
371 // We enable this, but without also configuring `code_actions_on_format`
372 // in the Zed configuration, it doesn't have an effect.
373 "enable": true,
374 });
375
376 if let Some(code_action_settings) = eslint_user_settings
377 .get("codeActionOnSave")
378 .and_then(|settings| settings.as_object())
379 {
380 if let Some(enable) = code_action_settings.get("enable") {
381 code_action_on_save["enable"] = enable.clone();
382 }
383 if let Some(mode) = code_action_settings.get("mode") {
384 code_action_on_save["mode"] = mode.clone();
385 }
386 if let Some(rules) = code_action_settings.get("rules") {
387 code_action_on_save["rules"] = rules.clone();
388 }
389 }
390
391 let problems = eslint_user_settings
392 .get("problems")
393 .cloned()
394 .unwrap_or_else(|| json!({}));
395
396 let rules_customizations = eslint_user_settings
397 .get("rulesCustomizations")
398 .cloned()
399 .unwrap_or_else(|| json!([]));
400
401 let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
402 let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
403 .iter()
404 .any(|file| workspace_root.join(file).is_file());
405
406 Ok(json!({
407 "": {
408 "validate": "on",
409 "rulesCustomizations": rules_customizations,
410 "run": "onType",
411 "nodePath": node_path,
412 "workingDirectory": {"mode": "auto"},
413 "workspaceFolder": {
414 "uri": workspace_root,
415 "name": workspace_root.file_name()
416 .unwrap_or(workspace_root.as_os_str()),
417 },
418 "problems": problems,
419 "codeActionOnSave": code_action_on_save,
420 "codeAction": {
421 "disableRuleComment": {
422 "enable": true,
423 "location": "separateLine",
424 },
425 "showDocumentation": {
426 "enable": true
427 }
428 },
429 "experimental": {
430 "useFlatConfig": use_flat_config,
431 },
432 }
433 }))
434 }
435
436 fn name(&self) -> LanguageServerName {
437 Self::SERVER_NAME.clone()
438 }
439
440 async fn fetch_latest_server_version(
441 &self,
442 _delegate: &dyn LspAdapterDelegate,
443 ) -> Result<Box<dyn 'static + Send + Any>> {
444 let url = build_asset_url(
445 "zed-industries/vscode-eslint",
446 Self::CURRENT_VERSION_TAG_NAME,
447 Self::GITHUB_ASSET_KIND,
448 )?;
449
450 Ok(Box::new(GitHubLspBinaryVersion {
451 name: Self::CURRENT_VERSION.into(),
452 url,
453 }))
454 }
455
456 async fn fetch_server_binary(
457 &self,
458 version: Box<dyn 'static + Send + Any>,
459 container_dir: PathBuf,
460 delegate: &dyn LspAdapterDelegate,
461 ) -> Result<LanguageServerBinary> {
462 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
463 let destination_path = Self::build_destination_path(&container_dir);
464 let server_path = destination_path.join(Self::SERVER_PATH);
465
466 if fs::metadata(&server_path).await.is_err() {
467 remove_matching(&container_dir, |entry| entry != destination_path).await;
468
469 let mut response = delegate
470 .http_client()
471 .get(&version.url, Default::default(), true)
472 .await
473 .map_err(|err| anyhow!("error downloading release: {}", err))?;
474 match Self::GITHUB_ASSET_KIND {
475 AssetKind::TarGz => {
476 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
477 let archive = Archive::new(decompressed_bytes);
478 archive.unpack(&destination_path).await.with_context(|| {
479 format!("extracting {} to {:?}", version.url, destination_path)
480 })?;
481 }
482 AssetKind::Gz => {
483 let mut decompressed_bytes =
484 GzipDecoder::new(BufReader::new(response.body_mut()));
485 let mut file =
486 fs::File::create(&destination_path).await.with_context(|| {
487 format!(
488 "creating a file {:?} for a download from {}",
489 destination_path, version.url,
490 )
491 })?;
492 futures::io::copy(&mut decompressed_bytes, &mut file)
493 .await
494 .with_context(|| {
495 format!("extracting {} to {:?}", version.url, destination_path)
496 })?;
497 }
498 AssetKind::Zip => {
499 node_runtime::extract_zip(
500 &destination_path,
501 BufReader::new(response.body_mut()),
502 )
503 .await
504 .with_context(|| {
505 format!("unzipping {} to {:?}", version.url, destination_path)
506 })?;
507 }
508 }
509
510 let mut dir = fs::read_dir(&destination_path).await?;
511 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
512 let repo_root = destination_path.join("vscode-eslint");
513 fs::rename(first.path(), &repo_root).await?;
514
515 #[cfg(target_os = "windows")]
516 {
517 handle_symlink(
518 repo_root.join("$shared"),
519 repo_root.join("client").join("src").join("shared"),
520 )
521 .await?;
522 handle_symlink(
523 repo_root.join("$shared"),
524 repo_root.join("server").join("src").join("shared"),
525 )
526 .await?;
527 }
528
529 self.node
530 .run_npm_subcommand(&repo_root, "install", &[])
531 .await?;
532
533 self.node
534 .run_npm_subcommand(&repo_root, "run-script", &["compile"])
535 .await?;
536 }
537
538 Ok(LanguageServerBinary {
539 path: self.node.binary_path().await?,
540 env: None,
541 arguments: eslint_server_binary_arguments(&server_path),
542 })
543 }
544
545 async fn cached_server_binary(
546 &self,
547 container_dir: PathBuf,
548 _: &dyn LspAdapterDelegate,
549 ) -> Option<LanguageServerBinary> {
550 let server_path =
551 Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
552 Some(LanguageServerBinary {
553 path: self.node.binary_path().await.ok()?,
554 env: None,
555 arguments: eslint_server_binary_arguments(&server_path),
556 })
557 }
558}
559
560#[cfg(target_os = "windows")]
561async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
562 if fs::metadata(&src_dir).await.is_err() {
563 return Err(anyhow!("Directory {} not present.", src_dir.display()));
564 }
565 if fs::metadata(&dest_dir).await.is_ok() {
566 fs::remove_file(&dest_dir).await?;
567 }
568 fs::create_dir_all(&dest_dir).await?;
569 let mut entries = fs::read_dir(&src_dir).await?;
570 while let Some(entry) = entries.try_next().await? {
571 let entry_path = entry.path();
572 let entry_name = entry.file_name();
573 let dest_path = dest_dir.join(&entry_name);
574 fs::copy(&entry_path, &dest_path).await?;
575 }
576 Ok(())
577}
578
579#[cfg(test)]
580mod tests {
581 use gpui::{Context, TestAppContext};
582 use unindent::Unindent;
583
584 #[gpui::test]
585 async fn test_outline(cx: &mut TestAppContext) {
586 let language = crate::language(
587 "typescript",
588 tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
589 );
590
591 let text = r#"
592 function a() {
593 // local variables are omitted
594 let a1 = 1;
595 // all functions are included
596 async function a2() {}
597 }
598 // top-level variables are included
599 let b: C
600 function getB() {}
601 // exported variables are included
602 export const d = e;
603 "#
604 .unindent();
605
606 let buffer =
607 cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
608 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
609 assert_eq!(
610 outline
611 .items
612 .iter()
613 .map(|item| (item.text.as_str(), item.depth))
614 .collect::<Vec<_>>(),
615 &[
616 ("function a()", 0),
617 ("async function a2()", 1),
618 ("let b", 0),
619 ("function getB()", 0),
620 ("const d", 0),
621 ]
622 );
623 }
624}