vue.rs

  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(?Send)]
 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
 90        if fs::metadata(&server_path).await.is_err() {
 91            self.node
 92                .npm_install_packages(
 93                    &container_dir,
 94                    &[("@vue/language-server", version.vue_version.as_str())],
 95                )
 96                .await?;
 97        }
 98        ensure!(
 99            fs::metadata(&server_path).await.is_ok(),
100            "@vue/language-server package installation failed"
101        );
102        if fs::metadata(&ts_path).await.is_err() {
103            self.node
104                .npm_install_packages(
105                    &container_dir,
106                    &[("typescript", version.ts_version.as_str())],
107                )
108                .await?;
109        }
110
111        ensure!(
112            fs::metadata(&ts_path).await.is_ok(),
113            "typescript for Vue package installation failed"
114        );
115        *self.typescript_install_path.lock() = Some(ts_path);
116        Ok(LanguageServerBinary {
117            path: self.node.binary_path().await?,
118            env: None,
119            arguments: vue_server_binary_arguments(&server_path),
120        })
121    }
122
123    async fn cached_server_binary(
124        &self,
125        container_dir: PathBuf,
126        _: &dyn LspAdapterDelegate,
127    ) -> Option<LanguageServerBinary> {
128        let (server, ts_path) = get_cached_server_binary(container_dir, self.node.clone()).await?;
129        *self.typescript_install_path.lock() = Some(ts_path);
130        Some(server)
131    }
132
133    async fn installation_test_binary(
134        &self,
135        container_dir: PathBuf,
136    ) -> Option<LanguageServerBinary> {
137        let (server, ts_path) = get_cached_server_binary(container_dir, self.node.clone())
138            .await
139            .map(|(mut binary, ts_path)| {
140                binary.arguments = vec!["--help".into()];
141                (binary, ts_path)
142            })?;
143        *self.typescript_install_path.lock() = Some(ts_path);
144        Some(server)
145    }
146
147    async fn label_for_completion(
148        &self,
149        item: &lsp::CompletionItem,
150        language: &Arc<language::Language>,
151    ) -> Option<language::CodeLabel> {
152        use lsp::CompletionItemKind as Kind;
153        let len = item.label.len();
154        let grammar = language.grammar()?;
155        let highlight_id = match item.kind? {
156            Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
157            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
158            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
159            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
160            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("tag"),
161            Kind::VARIABLE => grammar.highlight_id_for_name("type"),
162            Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
163            Kind::VALUE => grammar.highlight_id_for_name("tag"),
164            _ => None,
165        }?;
166
167        let text = match &item.detail {
168            Some(detail) => format!("{} {}", item.label, detail),
169            None => item.label.clone(),
170        };
171
172        Some(language::CodeLabel {
173            text,
174            runs: vec![(0..len, highlight_id)],
175            filter_range: 0..len,
176        })
177    }
178}
179
180fn vue_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
181    vec![server_path.into(), "--stdio".into()]
182}
183
184type TypescriptPath = PathBuf;
185async fn get_cached_server_binary(
186    container_dir: PathBuf,
187    node: Arc<dyn NodeRuntime>,
188) -> Option<(LanguageServerBinary, TypescriptPath)> {
189    async_maybe!({
190        let mut last_version_dir = None;
191        let mut entries = fs::read_dir(&container_dir).await?;
192        while let Some(entry) = entries.next().await {
193            let entry = entry?;
194            if entry.file_type().await?.is_dir() {
195                last_version_dir = Some(entry.path());
196            }
197        }
198        let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
199        let server_path = last_version_dir.join(VueLspAdapter::SERVER_PATH);
200        let typescript_path = last_version_dir.join(VueLspAdapter::TYPESCRIPT_PATH);
201        if server_path.exists() && typescript_path.exists() {
202            Ok((
203                LanguageServerBinary {
204                    path: node.binary_path().await?,
205                    env: None,
206                    arguments: vue_server_binary_arguments(&server_path),
207                },
208                typescript_path,
209            ))
210        } else {
211            Err(anyhow!(
212                "missing executable in directory {:?}",
213                last_version_dir
214            ))
215        }
216    })
217    .await
218    .log_err()
219}