1use anyhow::{Context as _, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_tar::Archive;
4use async_trait::async_trait;
5use chrono::{DateTime, Local};
6use collections::HashMap;
7use futures::future::join_all;
8use gpui::{App, AppContext, AsyncApp, Task};
9use http_client::github::{AssetKind, GitHubLspBinaryVersion, build_asset_url};
10use language::{
11 ContextLocation, ContextProvider, File, LanguageToolchainStore, LspAdapter, LspAdapterDelegate,
12};
13use lsp::{CodeActionKind, LanguageServerBinary, LanguageServerName};
14use node_runtime::NodeRuntime;
15use project::{Fs, lsp_store::language_server_settings};
16use serde_json::{Value, json};
17use smol::{fs, io::BufReader, lock::RwLock, stream::StreamExt};
18use std::{
19 any::Any,
20 borrow::Cow,
21 ffi::OsString,
22 path::{Path, PathBuf},
23 sync::Arc,
24};
25use task::{TaskTemplate, TaskTemplates, VariableName};
26use util::archive::extract_zip;
27use util::merge_json_value_into;
28use util::{ResultExt, fs::remove_matching, maybe};
29
30use crate::{PackageJson, PackageJsonData};
31
32#[derive(Debug)]
33pub(crate) struct TypeScriptContextProvider {
34 last_package_json: PackageJsonContents,
35}
36
37const TYPESCRIPT_RUNNER_VARIABLE: VariableName =
38 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_RUNNER"));
39
40const TYPESCRIPT_JEST_TEST_NAME_VARIABLE: VariableName =
41 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JEST_TEST_NAME"));
42
43const TYPESCRIPT_VITEST_TEST_NAME_VARIABLE: VariableName =
44 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_VITEST_TEST_NAME"));
45
46const TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE: VariableName =
47 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JEST_PACKAGE_PATH"));
48
49const TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE: VariableName =
50 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_MOCHA_PACKAGE_PATH"));
51
52const TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE: VariableName =
53 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_VITEST_PACKAGE_PATH"));
54
55const TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE: VariableName =
56 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JASMINE_PACKAGE_PATH"));
57
58#[derive(Clone, Debug, Default)]
59struct PackageJsonContents(Arc<RwLock<HashMap<PathBuf, PackageJson>>>);
60
61impl PackageJsonData {
62 fn fill_task_templates(&self, task_templates: &mut TaskTemplates) {
63 if self.jest_package_path.is_some() {
64 task_templates.0.push(TaskTemplate {
65 label: "jest file test".to_owned(),
66 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
67 args: vec![
68 "exec".to_owned(),
69 "--".to_owned(),
70 "jest".to_owned(),
71 "--runInBand".to_owned(),
72 VariableName::File.template_value(),
73 ],
74 cwd: Some(TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE.template_value()),
75 ..TaskTemplate::default()
76 });
77 task_templates.0.push(TaskTemplate {
78 label: format!("jest test {}", VariableName::Symbol.template_value()),
79 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
80 args: vec![
81 "exec".to_owned(),
82 "--".to_owned(),
83 "jest".to_owned(),
84 "--runInBand".to_owned(),
85 "--testNamePattern".to_owned(),
86 format!(
87 "\"{}\"",
88 TYPESCRIPT_JEST_TEST_NAME_VARIABLE.template_value()
89 ),
90 VariableName::File.template_value(),
91 ],
92 tags: vec![
93 "ts-test".to_owned(),
94 "js-test".to_owned(),
95 "tsx-test".to_owned(),
96 ],
97 cwd: Some(TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE.template_value()),
98 ..TaskTemplate::default()
99 });
100 }
101
102 if self.vitest_package_path.is_some() {
103 task_templates.0.push(TaskTemplate {
104 label: format!("{} file test", "vitest".to_owned()),
105 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
106 args: vec![
107 "exec".to_owned(),
108 "--".to_owned(),
109 "vitest".to_owned(),
110 "run".to_owned(),
111 "--poolOptions.forks.minForks=0".to_owned(),
112 "--poolOptions.forks.maxForks=1".to_owned(),
113 VariableName::File.template_value(),
114 ],
115 cwd: Some(TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE.template_value()),
116 ..TaskTemplate::default()
117 });
118 task_templates.0.push(TaskTemplate {
119 label: format!(
120 "{} test {}",
121 "vitest".to_owned(),
122 VariableName::Symbol.template_value(),
123 ),
124 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
125 args: vec![
126 "exec".to_owned(),
127 "--".to_owned(),
128 "vitest".to_owned(),
129 "run".to_owned(),
130 "--poolOptions.forks.minForks=0".to_owned(),
131 "--poolOptions.forks.maxForks=1".to_owned(),
132 "--testNamePattern".to_owned(),
133 format!(
134 "\"{}\"",
135 TYPESCRIPT_VITEST_TEST_NAME_VARIABLE.template_value()
136 ),
137 VariableName::File.template_value(),
138 ],
139 tags: vec![
140 "ts-test".to_owned(),
141 "js-test".to_owned(),
142 "tsx-test".to_owned(),
143 ],
144 cwd: Some(TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE.template_value()),
145 ..TaskTemplate::default()
146 });
147 }
148
149 if self.mocha_package_path.is_some() {
150 task_templates.0.push(TaskTemplate {
151 label: format!("{} file test", "mocha".to_owned()),
152 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
153 args: vec![
154 "exec".to_owned(),
155 "--".to_owned(),
156 "mocha".to_owned(),
157 VariableName::File.template_value(),
158 ],
159 cwd: Some(TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE.template_value()),
160 ..TaskTemplate::default()
161 });
162 task_templates.0.push(TaskTemplate {
163 label: format!(
164 "{} test {}",
165 "mocha".to_owned(),
166 VariableName::Symbol.template_value(),
167 ),
168 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
169 args: vec![
170 "exec".to_owned(),
171 "--".to_owned(),
172 "mocha".to_owned(),
173 "--grep".to_owned(),
174 format!("\"{}\"", VariableName::Symbol.template_value()),
175 VariableName::File.template_value(),
176 ],
177 tags: vec![
178 "ts-test".to_owned(),
179 "js-test".to_owned(),
180 "tsx-test".to_owned(),
181 ],
182 cwd: Some(TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE.template_value()),
183 ..TaskTemplate::default()
184 });
185 }
186
187 if self.jasmine_package_path.is_some() {
188 task_templates.0.push(TaskTemplate {
189 label: format!("{} file test", "jasmine".to_owned()),
190 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
191 args: vec![
192 "exec".to_owned(),
193 "--".to_owned(),
194 "jasmine".to_owned(),
195 VariableName::File.template_value(),
196 ],
197 cwd: Some(TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE.template_value()),
198 ..TaskTemplate::default()
199 });
200 task_templates.0.push(TaskTemplate {
201 label: format!(
202 "{} test {}",
203 "jasmine".to_owned(),
204 VariableName::Symbol.template_value(),
205 ),
206 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
207 args: vec![
208 "exec".to_owned(),
209 "--".to_owned(),
210 "jasmine".to_owned(),
211 format!("--filter={}", VariableName::Symbol.template_value()),
212 VariableName::File.template_value(),
213 ],
214 tags: vec![
215 "ts-test".to_owned(),
216 "js-test".to_owned(),
217 "tsx-test".to_owned(),
218 ],
219 cwd: Some(TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE.template_value()),
220 ..TaskTemplate::default()
221 });
222 }
223
224 for (path, script) in &self.scripts {
225 task_templates.0.push(TaskTemplate {
226 label: format!("package.json > {script}",),
227 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
228 args: vec!["run".to_owned(), script.to_owned()],
229 tags: vec!["package-script".into()],
230 cwd: Some(
231 path.parent()
232 .unwrap_or(Path::new(""))
233 .to_string_lossy()
234 .to_string(),
235 ),
236 ..TaskTemplate::default()
237 });
238 }
239 }
240}
241
242impl TypeScriptContextProvider {
243 pub fn new() -> Self {
244 Self {
245 last_package_json: PackageJsonContents::default(),
246 }
247 }
248
249 fn combined_package_json_data(
250 &self,
251 fs: Arc<dyn Fs>,
252 worktree_root: &Path,
253 file_relative_path: &Path,
254 cx: &App,
255 ) -> Task<anyhow::Result<PackageJsonData>> {
256 let new_json_data = file_relative_path
257 .ancestors()
258 .map(|path| worktree_root.join(path))
259 .map(|parent_path| {
260 self.package_json_data(&parent_path, self.last_package_json.clone(), fs.clone(), cx)
261 })
262 .collect::<Vec<_>>();
263
264 cx.background_spawn(async move {
265 let mut package_json_data = PackageJsonData::default();
266 for new_data in join_all(new_json_data).await.into_iter().flatten() {
267 package_json_data.merge(new_data);
268 }
269 Ok(package_json_data)
270 })
271 }
272
273 fn package_json_data(
274 &self,
275 directory_path: &Path,
276 existing_package_json: PackageJsonContents,
277 fs: Arc<dyn Fs>,
278 cx: &App,
279 ) -> Task<anyhow::Result<PackageJsonData>> {
280 let package_json_path = directory_path.join("package.json");
281 let metadata_check_fs = fs.clone();
282 cx.background_spawn(async move {
283 let metadata = metadata_check_fs
284 .metadata(&package_json_path)
285 .await
286 .with_context(|| format!("getting metadata for {package_json_path:?}"))?
287 .with_context(|| format!("missing FS metadata for {package_json_path:?}"))?;
288 let mtime = DateTime::<Local>::from(metadata.mtime.timestamp_for_user());
289 let existing_data = {
290 let contents = existing_package_json.0.read().await;
291 contents
292 .get(&package_json_path)
293 .filter(|package_json| package_json.mtime == mtime)
294 .map(|package_json| package_json.data.clone())
295 };
296 match existing_data {
297 Some(existing_data) => Ok(existing_data),
298 None => {
299 let package_json_string =
300 fs.load(&package_json_path).await.with_context(|| {
301 format!("loading package.json from {package_json_path:?}")
302 })?;
303 let package_json: HashMap<String, serde_json_lenient::Value> =
304 serde_json_lenient::from_str(&package_json_string).with_context(|| {
305 format!("parsing package.json from {package_json_path:?}")
306 })?;
307 let new_data =
308 PackageJsonData::new(package_json_path.as_path().into(), package_json);
309 {
310 let mut contents = existing_package_json.0.write().await;
311 contents.insert(
312 package_json_path,
313 PackageJson {
314 mtime,
315 data: new_data.clone(),
316 },
317 );
318 }
319 Ok(new_data)
320 }
321 }
322 })
323 }
324}
325
326async fn detect_package_manager(
327 worktree_root: PathBuf,
328 fs: Arc<dyn Fs>,
329 package_json_data: Option<PackageJsonData>,
330) -> &'static str {
331 if let Some(package_json_data) = package_json_data {
332 if let Some(package_manager) = package_json_data.package_manager {
333 return package_manager;
334 }
335 }
336 if fs.is_file(&worktree_root.join("pnpm-lock.yaml")).await {
337 return "pnpm";
338 }
339 if fs.is_file(&worktree_root.join("yarn.lock")).await {
340 return "yarn";
341 }
342 "npm"
343}
344
345impl ContextProvider for TypeScriptContextProvider {
346 fn associated_tasks(
347 &self,
348 fs: Arc<dyn Fs>,
349 file: Option<Arc<dyn File>>,
350 cx: &App,
351 ) -> Task<Option<TaskTemplates>> {
352 let Some(file) = project::File::from_dyn(file.as_ref()).cloned() else {
353 return Task::ready(None);
354 };
355 let Some(worktree_root) = file.worktree.read(cx).root_dir() else {
356 return Task::ready(None);
357 };
358 let file_relative_path = file.path().clone();
359 let package_json_data =
360 self.combined_package_json_data(fs.clone(), &worktree_root, &file_relative_path, cx);
361
362 cx.background_spawn(async move {
363 let mut task_templates = TaskTemplates(Vec::new());
364 task_templates.0.push(TaskTemplate {
365 label: format!(
366 "execute selection {}",
367 VariableName::SelectedText.template_value()
368 ),
369 command: "node".to_owned(),
370 args: vec![
371 "-e".to_owned(),
372 format!("\"{}\"", VariableName::SelectedText.template_value()),
373 ],
374 ..TaskTemplate::default()
375 });
376
377 match package_json_data.await {
378 Ok(package_json) => {
379 package_json.fill_task_templates(&mut task_templates);
380 }
381 Err(e) => {
382 log::error!(
383 "Failed to read package.json for worktree {file_relative_path:?}: {e:#}"
384 );
385 }
386 }
387
388 Some(task_templates)
389 })
390 }
391
392 fn build_context(
393 &self,
394 current_vars: &task::TaskVariables,
395 location: ContextLocation<'_>,
396 _project_env: Option<HashMap<String, String>>,
397 _toolchains: Arc<dyn LanguageToolchainStore>,
398 cx: &mut App,
399 ) -> Task<Result<task::TaskVariables>> {
400 let mut vars = task::TaskVariables::default();
401
402 if let Some(symbol) = current_vars.get(&VariableName::Symbol) {
403 vars.insert(
404 TYPESCRIPT_JEST_TEST_NAME_VARIABLE,
405 replace_test_name_parameters(symbol),
406 );
407 vars.insert(
408 TYPESCRIPT_VITEST_TEST_NAME_VARIABLE,
409 replace_test_name_parameters(symbol),
410 );
411 }
412 let file_path = location
413 .file_location
414 .buffer
415 .read(cx)
416 .file()
417 .map(|file| file.path());
418
419 let args = location.worktree_root.zip(location.fs).zip(file_path).map(
420 |((worktree_root, fs), file_path)| {
421 (
422 self.combined_package_json_data(fs.clone(), &worktree_root, file_path, cx),
423 worktree_root,
424 fs,
425 )
426 },
427 );
428 cx.background_spawn(async move {
429 if let Some((task, worktree_root, fs)) = args {
430 let package_json_data = task.await.log_err();
431 vars.insert(
432 TYPESCRIPT_RUNNER_VARIABLE,
433 detect_package_manager(worktree_root, fs, package_json_data.clone())
434 .await
435 .to_owned(),
436 );
437
438 if let Some(package_json_data) = package_json_data {
439 if let Some(path) = package_json_data.jest_package_path {
440 vars.insert(
441 TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE,
442 path.parent()
443 .unwrap_or(Path::new(""))
444 .to_string_lossy()
445 .to_string(),
446 );
447 }
448
449 if let Some(path) = package_json_data.mocha_package_path {
450 vars.insert(
451 TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE,
452 path.parent()
453 .unwrap_or(Path::new(""))
454 .to_string_lossy()
455 .to_string(),
456 );
457 }
458
459 if let Some(path) = package_json_data.vitest_package_path {
460 vars.insert(
461 TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE,
462 path.parent()
463 .unwrap_or(Path::new(""))
464 .to_string_lossy()
465 .to_string(),
466 );
467 }
468
469 if let Some(path) = package_json_data.jasmine_package_path {
470 vars.insert(
471 TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE,
472 path.parent()
473 .unwrap_or(Path::new(""))
474 .to_string_lossy()
475 .to_string(),
476 );
477 }
478 }
479 }
480 Ok(vars)
481 })
482 }
483}
484
485fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
486 vec![server_path.into(), "--stdio".into()]
487}
488
489fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
490 vec![
491 "--max-old-space-size=8192".into(),
492 server_path.into(),
493 "--stdio".into(),
494 ]
495}
496
497fn replace_test_name_parameters(test_name: &str) -> String {
498 let pattern = regex::Regex::new(r"(%|\$)[0-9a-zA-Z]+").unwrap();
499
500 pattern.replace_all(test_name, "(.+?)").to_string()
501}
502
503pub struct TypeScriptLspAdapter {
504 node: NodeRuntime,
505}
506
507impl TypeScriptLspAdapter {
508 const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
509 const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
510 const SERVER_NAME: LanguageServerName =
511 LanguageServerName::new_static("typescript-language-server");
512 const PACKAGE_NAME: &str = "typescript";
513 pub fn new(node: NodeRuntime) -> Self {
514 TypeScriptLspAdapter { node }
515 }
516 async fn tsdk_path(fs: &dyn Fs, adapter: &Arc<dyn LspAdapterDelegate>) -> Option<&'static str> {
517 let is_yarn = adapter
518 .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
519 .await
520 .is_ok();
521
522 let tsdk_path = if is_yarn {
523 ".yarn/sdks/typescript/lib"
524 } else {
525 "node_modules/typescript/lib"
526 };
527
528 if fs
529 .is_dir(&adapter.worktree_root_path().join(tsdk_path))
530 .await
531 {
532 Some(tsdk_path)
533 } else {
534 None
535 }
536 }
537}
538
539struct TypeScriptVersions {
540 typescript_version: String,
541 server_version: String,
542}
543
544#[async_trait(?Send)]
545impl LspAdapter for TypeScriptLspAdapter {
546 fn name(&self) -> LanguageServerName {
547 Self::SERVER_NAME.clone()
548 }
549
550 async fn fetch_latest_server_version(
551 &self,
552 _: &dyn LspAdapterDelegate,
553 ) -> Result<Box<dyn 'static + Send + Any>> {
554 Ok(Box::new(TypeScriptVersions {
555 typescript_version: self.node.npm_package_latest_version("typescript").await?,
556 server_version: self
557 .node
558 .npm_package_latest_version("typescript-language-server")
559 .await?,
560 }) as Box<_>)
561 }
562
563 async fn check_if_version_installed(
564 &self,
565 version: &(dyn 'static + Send + Any),
566 container_dir: &PathBuf,
567 _: &dyn LspAdapterDelegate,
568 ) -> Option<LanguageServerBinary> {
569 let version = version.downcast_ref::<TypeScriptVersions>().unwrap();
570 let server_path = container_dir.join(Self::NEW_SERVER_PATH);
571
572 let should_install_language_server = self
573 .node
574 .should_install_npm_package(
575 Self::PACKAGE_NAME,
576 &server_path,
577 &container_dir,
578 version.typescript_version.as_str(),
579 )
580 .await;
581
582 if should_install_language_server {
583 None
584 } else {
585 Some(LanguageServerBinary {
586 path: self.node.binary_path().await.ok()?,
587 env: None,
588 arguments: typescript_server_binary_arguments(&server_path),
589 })
590 }
591 }
592
593 async fn fetch_server_binary(
594 &self,
595 latest_version: Box<dyn 'static + Send + Any>,
596 container_dir: PathBuf,
597 _: &dyn LspAdapterDelegate,
598 ) -> Result<LanguageServerBinary> {
599 let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
600 let server_path = container_dir.join(Self::NEW_SERVER_PATH);
601
602 self.node
603 .npm_install_packages(
604 &container_dir,
605 &[
606 (
607 Self::PACKAGE_NAME,
608 latest_version.typescript_version.as_str(),
609 ),
610 (
611 "typescript-language-server",
612 latest_version.server_version.as_str(),
613 ),
614 ],
615 )
616 .await?;
617
618 Ok(LanguageServerBinary {
619 path: self.node.binary_path().await?,
620 env: None,
621 arguments: typescript_server_binary_arguments(&server_path),
622 })
623 }
624
625 async fn cached_server_binary(
626 &self,
627 container_dir: PathBuf,
628 _: &dyn LspAdapterDelegate,
629 ) -> Option<LanguageServerBinary> {
630 get_cached_ts_server_binary(container_dir, &self.node).await
631 }
632
633 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
634 Some(vec![
635 CodeActionKind::QUICKFIX,
636 CodeActionKind::REFACTOR,
637 CodeActionKind::REFACTOR_EXTRACT,
638 CodeActionKind::SOURCE,
639 ])
640 }
641
642 async fn label_for_completion(
643 &self,
644 item: &lsp::CompletionItem,
645 language: &Arc<language::Language>,
646 ) -> Option<language::CodeLabel> {
647 use lsp::CompletionItemKind as Kind;
648 let len = item.label.len();
649 let grammar = language.grammar()?;
650 let highlight_id = match item.kind? {
651 Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
652 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
653 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
654 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
655 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
656 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
657 _ => None,
658 }?;
659
660 let text = if let Some(description) = item
661 .label_details
662 .as_ref()
663 .and_then(|label_details| label_details.description.as_ref())
664 {
665 format!("{} {}", item.label, description)
666 } else if let Some(detail) = &item.detail {
667 format!("{} {}", item.label, detail)
668 } else {
669 item.label.clone()
670 };
671
672 Some(language::CodeLabel {
673 text,
674 runs: vec![(0..len, highlight_id)],
675 filter_range: 0..len,
676 })
677 }
678
679 async fn initialization_options(
680 self: Arc<Self>,
681 fs: &dyn Fs,
682 adapter: &Arc<dyn LspAdapterDelegate>,
683 ) -> Result<Option<serde_json::Value>> {
684 let tsdk_path = Self::tsdk_path(fs, adapter).await;
685 Ok(Some(json!({
686 "provideFormatter": true,
687 "hostInfo": "zed",
688 "tsserver": {
689 "path": tsdk_path,
690 },
691 "preferences": {
692 "includeInlayParameterNameHints": "all",
693 "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
694 "includeInlayFunctionParameterTypeHints": true,
695 "includeInlayVariableTypeHints": true,
696 "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
697 "includeInlayPropertyDeclarationTypeHints": true,
698 "includeInlayFunctionLikeReturnTypeHints": true,
699 "includeInlayEnumMemberValueHints": true,
700 }
701 })))
702 }
703
704 async fn workspace_configuration(
705 self: Arc<Self>,
706 _: &dyn Fs,
707 delegate: &Arc<dyn LspAdapterDelegate>,
708 _: Arc<dyn LanguageToolchainStore>,
709 cx: &mut AsyncApp,
710 ) -> Result<Value> {
711 let override_options = cx.update(|cx| {
712 language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
713 .and_then(|s| s.settings.clone())
714 })?;
715 if let Some(options) = override_options {
716 return Ok(options);
717 }
718 Ok(json!({
719 "completions": {
720 "completeFunctionCalls": true
721 }
722 }))
723 }
724
725 fn language_ids(&self) -> HashMap<String, String> {
726 HashMap::from_iter([
727 ("TypeScript".into(), "typescript".into()),
728 ("JavaScript".into(), "javascript".into()),
729 ("TSX".into(), "typescriptreact".into()),
730 ])
731 }
732}
733
734async fn get_cached_ts_server_binary(
735 container_dir: PathBuf,
736 node: &NodeRuntime,
737) -> Option<LanguageServerBinary> {
738 maybe!(async {
739 let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
740 let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
741 if new_server_path.exists() {
742 Ok(LanguageServerBinary {
743 path: node.binary_path().await?,
744 env: None,
745 arguments: typescript_server_binary_arguments(&new_server_path),
746 })
747 } else if old_server_path.exists() {
748 Ok(LanguageServerBinary {
749 path: node.binary_path().await?,
750 env: None,
751 arguments: typescript_server_binary_arguments(&old_server_path),
752 })
753 } else {
754 anyhow::bail!("missing executable in directory {container_dir:?}")
755 }
756 })
757 .await
758 .log_err()
759}
760
761pub struct EsLintLspAdapter {
762 node: NodeRuntime,
763}
764
765impl EsLintLspAdapter {
766 const CURRENT_VERSION: &'static str = "2.4.4";
767 const CURRENT_VERSION_TAG_NAME: &'static str = "release/2.4.4";
768
769 #[cfg(not(windows))]
770 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
771 #[cfg(windows)]
772 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
773
774 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
775 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("eslint");
776
777 const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] = &[
778 "eslint.config.js",
779 "eslint.config.mjs",
780 "eslint.config.cjs",
781 "eslint.config.ts",
782 "eslint.config.cts",
783 "eslint.config.mts",
784 ];
785
786 pub fn new(node: NodeRuntime) -> Self {
787 EsLintLspAdapter { node }
788 }
789
790 fn build_destination_path(container_dir: &Path) -> PathBuf {
791 container_dir.join(format!("vscode-eslint-{}", Self::CURRENT_VERSION))
792 }
793}
794
795#[async_trait(?Send)]
796impl LspAdapter for EsLintLspAdapter {
797 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
798 Some(vec![
799 CodeActionKind::QUICKFIX,
800 CodeActionKind::new("source.fixAll.eslint"),
801 ])
802 }
803
804 async fn workspace_configuration(
805 self: Arc<Self>,
806 _: &dyn Fs,
807 delegate: &Arc<dyn LspAdapterDelegate>,
808 _: Arc<dyn LanguageToolchainStore>,
809 cx: &mut AsyncApp,
810 ) -> Result<Value> {
811 let workspace_root = delegate.worktree_root_path();
812 let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
813 .iter()
814 .any(|file| workspace_root.join(file).is_file());
815
816 let mut default_workspace_configuration = json!({
817 "validate": "on",
818 "rulesCustomizations": [],
819 "run": "onType",
820 "nodePath": null,
821 "workingDirectory": {
822 "mode": "auto"
823 },
824 "workspaceFolder": {
825 "uri": workspace_root,
826 "name": workspace_root.file_name()
827 .unwrap_or(workspace_root.as_os_str())
828 .to_string_lossy(),
829 },
830 "problems": {},
831 "codeActionOnSave": {
832 // We enable this, but without also configuring code_actions_on_format
833 // in the Zed configuration, it doesn't have an effect.
834 "enable": true,
835 },
836 "codeAction": {
837 "disableRuleComment": {
838 "enable": true,
839 "location": "separateLine",
840 },
841 "showDocumentation": {
842 "enable": true
843 }
844 },
845 "experimental": {
846 "useFlatConfig": use_flat_config,
847 },
848 });
849
850 let override_options = cx.update(|cx| {
851 language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
852 .and_then(|s| s.settings.clone())
853 })?;
854
855 if let Some(override_options) = override_options {
856 merge_json_value_into(override_options, &mut default_workspace_configuration);
857 }
858
859 Ok(json!({
860 "": default_workspace_configuration
861 }))
862 }
863
864 fn name(&self) -> LanguageServerName {
865 Self::SERVER_NAME.clone()
866 }
867
868 async fn fetch_latest_server_version(
869 &self,
870 _delegate: &dyn LspAdapterDelegate,
871 ) -> Result<Box<dyn 'static + Send + Any>> {
872 let url = build_asset_url(
873 "zed-industries/vscode-eslint",
874 Self::CURRENT_VERSION_TAG_NAME,
875 Self::GITHUB_ASSET_KIND,
876 )?;
877
878 Ok(Box::new(GitHubLspBinaryVersion {
879 name: Self::CURRENT_VERSION.into(),
880 url,
881 }))
882 }
883
884 async fn fetch_server_binary(
885 &self,
886 version: Box<dyn 'static + Send + Any>,
887 container_dir: PathBuf,
888 delegate: &dyn LspAdapterDelegate,
889 ) -> Result<LanguageServerBinary> {
890 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
891 let destination_path = Self::build_destination_path(&container_dir);
892 let server_path = destination_path.join(Self::SERVER_PATH);
893
894 if fs::metadata(&server_path).await.is_err() {
895 remove_matching(&container_dir, |entry| entry != destination_path).await;
896
897 let mut response = delegate
898 .http_client()
899 .get(&version.url, Default::default(), true)
900 .await
901 .context("downloading release")?;
902 match Self::GITHUB_ASSET_KIND {
903 AssetKind::TarGz => {
904 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
905 let archive = Archive::new(decompressed_bytes);
906 archive.unpack(&destination_path).await.with_context(|| {
907 format!("extracting {} to {:?}", version.url, destination_path)
908 })?;
909 }
910 AssetKind::Gz => {
911 let mut decompressed_bytes =
912 GzipDecoder::new(BufReader::new(response.body_mut()));
913 let mut file =
914 fs::File::create(&destination_path).await.with_context(|| {
915 format!(
916 "creating a file {:?} for a download from {}",
917 destination_path, version.url,
918 )
919 })?;
920 futures::io::copy(&mut decompressed_bytes, &mut file)
921 .await
922 .with_context(|| {
923 format!("extracting {} to {:?}", version.url, destination_path)
924 })?;
925 }
926 AssetKind::Zip => {
927 extract_zip(&destination_path, response.body_mut())
928 .await
929 .with_context(|| {
930 format!("unzipping {} to {:?}", version.url, destination_path)
931 })?;
932 }
933 }
934
935 let mut dir = fs::read_dir(&destination_path).await?;
936 let first = dir.next().await.context("missing first file")??;
937 let repo_root = destination_path.join("vscode-eslint");
938 fs::rename(first.path(), &repo_root).await?;
939
940 #[cfg(target_os = "windows")]
941 {
942 handle_symlink(
943 repo_root.join("$shared"),
944 repo_root.join("client").join("src").join("shared"),
945 )
946 .await?;
947 handle_symlink(
948 repo_root.join("$shared"),
949 repo_root.join("server").join("src").join("shared"),
950 )
951 .await?;
952 }
953
954 self.node
955 .run_npm_subcommand(&repo_root, "install", &[])
956 .await?;
957
958 self.node
959 .run_npm_subcommand(&repo_root, "run-script", &["compile"])
960 .await?;
961 }
962
963 Ok(LanguageServerBinary {
964 path: self.node.binary_path().await?,
965 env: None,
966 arguments: eslint_server_binary_arguments(&server_path),
967 })
968 }
969
970 async fn cached_server_binary(
971 &self,
972 container_dir: PathBuf,
973 _: &dyn LspAdapterDelegate,
974 ) -> Option<LanguageServerBinary> {
975 let server_path =
976 Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
977 Some(LanguageServerBinary {
978 path: self.node.binary_path().await.ok()?,
979 env: None,
980 arguments: eslint_server_binary_arguments(&server_path),
981 })
982 }
983}
984
985#[cfg(target_os = "windows")]
986async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
987 anyhow::ensure!(
988 fs::metadata(&src_dir).await.is_ok(),
989 "Directory {src_dir:?} is not present"
990 );
991 if fs::metadata(&dest_dir).await.is_ok() {
992 fs::remove_file(&dest_dir).await?;
993 }
994 fs::create_dir_all(&dest_dir).await?;
995 let mut entries = fs::read_dir(&src_dir).await?;
996 while let Some(entry) = entries.try_next().await? {
997 let entry_path = entry.path();
998 let entry_name = entry.file_name();
999 let dest_path = dest_dir.join(&entry_name);
1000 fs::copy(&entry_path, &dest_path).await?;
1001 }
1002 Ok(())
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007 use std::path::Path;
1008
1009 use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
1010 use language::language_settings;
1011 use project::{FakeFs, Project};
1012 use serde_json::json;
1013 use unindent::Unindent;
1014 use util::path;
1015
1016 use crate::typescript::{PackageJsonData, TypeScriptContextProvider};
1017
1018 #[gpui::test]
1019 async fn test_outline(cx: &mut TestAppContext) {
1020 let language = crate::language(
1021 "typescript",
1022 tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
1023 );
1024
1025 let text = r#"
1026 function a() {
1027 // local variables are omitted
1028 let a1 = 1;
1029 // all functions are included
1030 async function a2() {}
1031 }
1032 // top-level variables are included
1033 let b: C
1034 function getB() {}
1035 // exported variables are included
1036 export const d = e;
1037 "#
1038 .unindent();
1039
1040 let buffer = cx.new(|cx| language::Buffer::local(text, cx).with_language(language, cx));
1041 let outline = buffer.read_with(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
1042 assert_eq!(
1043 outline
1044 .items
1045 .iter()
1046 .map(|item| (item.text.as_str(), item.depth))
1047 .collect::<Vec<_>>(),
1048 &[
1049 ("function a()", 0),
1050 ("async function a2()", 1),
1051 ("let b", 0),
1052 ("function getB()", 0),
1053 ("const d", 0),
1054 ]
1055 );
1056 }
1057
1058 #[gpui::test]
1059 async fn test_package_json_discovery(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1060 cx.update(|cx| {
1061 settings::init(cx);
1062 Project::init_settings(cx);
1063 language_settings::init(cx);
1064 });
1065
1066 let package_json_1 = json!({
1067 "dependencies": {
1068 "mocha": "1.0.0",
1069 "vitest": "1.0.0"
1070 },
1071 "scripts": {
1072 "test": ""
1073 }
1074 })
1075 .to_string();
1076
1077 let package_json_2 = json!({
1078 "devDependencies": {
1079 "vitest": "2.0.0"
1080 },
1081 "scripts": {
1082 "test": ""
1083 }
1084 })
1085 .to_string();
1086
1087 let fs = FakeFs::new(executor);
1088 fs.insert_tree(
1089 path!("/root"),
1090 json!({
1091 "package.json": package_json_1,
1092 "sub": {
1093 "package.json": package_json_2,
1094 "file.js": "",
1095 }
1096 }),
1097 )
1098 .await;
1099
1100 let provider = TypeScriptContextProvider::new();
1101 let package_json_data = cx
1102 .update(|cx| {
1103 provider.combined_package_json_data(
1104 fs.clone(),
1105 path!("/root").as_ref(),
1106 "sub/file1.js".as_ref(),
1107 cx,
1108 )
1109 })
1110 .await
1111 .unwrap();
1112 pretty_assertions::assert_eq!(
1113 package_json_data,
1114 PackageJsonData {
1115 jest_package_path: None,
1116 mocha_package_path: Some(Path::new(path!("/root/package.json")).into()),
1117 vitest_package_path: Some(Path::new(path!("/root/sub/package.json")).into()),
1118 jasmine_package_path: None,
1119 scripts: [
1120 (
1121 Path::new(path!("/root/package.json")).into(),
1122 "test".to_owned()
1123 ),
1124 (
1125 Path::new(path!("/root/sub/package.json")).into(),
1126 "test".to_owned()
1127 )
1128 ]
1129 .into_iter()
1130 .collect(),
1131 package_manager: None,
1132 }
1133 );
1134 }
1135}