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