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