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