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