1use anyhow::{anyhow, ensure, Result};
2use async_trait::async_trait;
3use futures::StreamExt;
4pub use language::*;
5use lsp::{CodeActionKind, LanguageServerBinary};
6use node_runtime::NodeRuntime;
7use parking_lot::Mutex;
8use serde_json::Value;
9use smol::fs::{self};
10use std::{
11 any::Any,
12 ffi::OsString,
13 path::{Path, PathBuf},
14 sync::Arc,
15};
16use util::{async_maybe, ResultExt};
17
18pub struct VueLspVersion {
19 vue_version: String,
20 ts_version: String,
21}
22
23pub struct VueLspAdapter {
24 node: Arc<dyn NodeRuntime>,
25 typescript_install_path: Mutex<Option<PathBuf>>,
26}
27
28impl VueLspAdapter {
29 const SERVER_PATH: &'static str =
30 "node_modules/@vue/language-server/bin/vue-language-server.js";
31 // TODO: this can't be hardcoded, yet we have to figure out how to pass it in initialization_options.
32 const TYPESCRIPT_PATH: &'static str = "node_modules/typescript/lib";
33 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
34 let typescript_install_path = Mutex::new(None);
35 Self {
36 node,
37 typescript_install_path,
38 }
39 }
40}
41#[async_trait]
42impl super::LspAdapter for VueLspAdapter {
43 fn name(&self) -> LanguageServerName {
44 LanguageServerName("vue-language-server".into())
45 }
46
47 async fn fetch_latest_server_version(
48 &self,
49 _: &dyn LspAdapterDelegate,
50 ) -> Result<Box<dyn 'static + Send + Any>> {
51 Ok(Box::new(VueLspVersion {
52 vue_version: self
53 .node
54 .npm_package_latest_version("@vue/language-server")
55 .await?,
56 ts_version: self.node.npm_package_latest_version("typescript").await?,
57 }) as Box<_>)
58 }
59 fn initialization_options(&self) -> Option<Value> {
60 let typescript_sdk_path = self.typescript_install_path.lock();
61 let typescript_sdk_path = typescript_sdk_path
62 .as_ref()
63 .expect("initialization_options called without a container_dir for typescript");
64
65 Some(serde_json::json!({
66 "typescript": {
67 "tsdk": typescript_sdk_path
68 }
69 }))
70 }
71 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
72 // REFACTOR is explicitly disabled, as vue-lsp does not adhere to LSP protocol for code actions with these - it
73 // sends back a CodeAction with neither `command` nor `edits` fields set, which is against the spec.
74 Some(vec![
75 CodeActionKind::EMPTY,
76 CodeActionKind::QUICKFIX,
77 CodeActionKind::REFACTOR_REWRITE,
78 ])
79 }
80 async fn fetch_server_binary(
81 &self,
82 version: Box<dyn 'static + Send + Any>,
83 container_dir: PathBuf,
84 _: &dyn LspAdapterDelegate,
85 ) -> Result<LanguageServerBinary> {
86 let version = version.downcast::<VueLspVersion>().unwrap();
87 let server_path = container_dir.join(Self::SERVER_PATH);
88 let ts_path = container_dir.join(Self::TYPESCRIPT_PATH);
89 if fs::metadata(&server_path).await.is_err() {
90 self.node
91 .npm_install_packages(
92 &container_dir,
93 &[("@vue/language-server", version.vue_version.as_str())],
94 )
95 .await?;
96 }
97 ensure!(
98 fs::metadata(&server_path).await.is_ok(),
99 "@vue/language-server package installation failed"
100 );
101 if fs::metadata(&ts_path).await.is_err() {
102 self.node
103 .npm_install_packages(
104 &container_dir,
105 &[("typescript", version.ts_version.as_str())],
106 )
107 .await?;
108 }
109
110 ensure!(
111 fs::metadata(&ts_path).await.is_ok(),
112 "typescript for Vue package installation failed"
113 );
114 *self.typescript_install_path.lock() = Some(ts_path);
115 Ok(LanguageServerBinary {
116 path: self.node.binary_path().await?,
117 env: None,
118 arguments: vue_server_binary_arguments(&server_path),
119 })
120 }
121
122 async fn cached_server_binary(
123 &self,
124 container_dir: PathBuf,
125 _: &dyn LspAdapterDelegate,
126 ) -> Option<LanguageServerBinary> {
127 let (server, ts_path) = get_cached_server_binary(container_dir, self.node.clone()).await?;
128 *self.typescript_install_path.lock() = Some(ts_path);
129 Some(server)
130 }
131
132 async fn installation_test_binary(
133 &self,
134 container_dir: PathBuf,
135 ) -> Option<LanguageServerBinary> {
136 let (server, ts_path) = get_cached_server_binary(container_dir, self.node.clone())
137 .await
138 .map(|(mut binary, ts_path)| {
139 binary.arguments = vec!["--help".into()];
140 (binary, ts_path)
141 })?;
142 *self.typescript_install_path.lock() = Some(ts_path);
143 Some(server)
144 }
145
146 async fn label_for_completion(
147 &self,
148 item: &lsp::CompletionItem,
149 language: &Arc<language::Language>,
150 ) -> Option<language::CodeLabel> {
151 use lsp::CompletionItemKind as Kind;
152 let len = item.label.len();
153 let grammar = language.grammar()?;
154 let highlight_id = match item.kind? {
155 Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
156 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
157 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
158 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
159 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("tag"),
160 Kind::VARIABLE => grammar.highlight_id_for_name("type"),
161 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
162 Kind::VALUE => grammar.highlight_id_for_name("tag"),
163 _ => None,
164 }?;
165
166 let text = match &item.detail {
167 Some(detail) => format!("{} {}", item.label, detail),
168 None => item.label.clone(),
169 };
170
171 Some(language::CodeLabel {
172 text,
173 runs: vec![(0..len, highlight_id)],
174 filter_range: 0..len,
175 })
176 }
177}
178
179fn vue_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
180 vec![server_path.into(), "--stdio".into()]
181}
182
183type TypescriptPath = PathBuf;
184async fn get_cached_server_binary(
185 container_dir: PathBuf,
186 node: Arc<dyn NodeRuntime>,
187) -> Option<(LanguageServerBinary, TypescriptPath)> {
188 async_maybe!({
189 let mut last_version_dir = None;
190 let mut entries = fs::read_dir(&container_dir).await?;
191 while let Some(entry) = entries.next().await {
192 let entry = entry?;
193 if entry.file_type().await?.is_dir() {
194 last_version_dir = Some(entry.path());
195 }
196 }
197 let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
198 let server_path = last_version_dir.join(VueLspAdapter::SERVER_PATH);
199 let typescript_path = last_version_dir.join(VueLspAdapter::TYPESCRIPT_PATH);
200 if server_path.exists() && typescript_path.exists() {
201 Ok((
202 LanguageServerBinary {
203 path: node.binary_path().await?,
204 env: None,
205 arguments: vue_server_binary_arguments(&server_path),
206 },
207 typescript_path,
208 ))
209 } else {
210 Err(anyhow!(
211 "missing executable in directory {:?}",
212 last_version_dir
213 ))
214 }
215 })
216 .await
217 .log_err()
218}