1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use anyhow::{anyhow, ensure, Result};
use async_trait::async_trait;
use futures::StreamExt;
pub use language::*;
use lsp::{CodeActionKind, LanguageServerBinary};
use node_runtime::NodeRuntime;
use parking_lot::Mutex;
use serde_json::Value;
use smol::fs::{self};
use std::{
    any::Any,
    ffi::OsString,
    path::{Path, PathBuf},
    sync::Arc,
};
use util::ResultExt;

pub struct VueLspVersion {
    vue_version: String,
    ts_version: String,
}

pub struct VueLspAdapter {
    node: Arc<dyn NodeRuntime>,
    typescript_install_path: Mutex<Option<PathBuf>>,
}

impl VueLspAdapter {
    const SERVER_PATH: &'static str =
        "node_modules/@vue/language-server/bin/vue-language-server.js";
    // TODO: this can't be hardcoded, yet we have to figure out how to pass it in initialization_options.
    const TYPESCRIPT_PATH: &'static str = "node_modules/typescript/lib";
    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
        let typescript_install_path = Mutex::new(None);
        Self {
            node,
            typescript_install_path,
        }
    }
}
#[async_trait]
impl super::LspAdapter for VueLspAdapter {
    async fn name(&self) -> LanguageServerName {
        LanguageServerName("vue-language-server".into())
    }

    fn short_name(&self) -> &'static str {
        "vue-language-server"
    }

    async fn fetch_latest_server_version(
        &self,
        _: &dyn LspAdapterDelegate,
    ) -> Result<Box<dyn 'static + Send + Any>> {
        Ok(Box::new(VueLspVersion {
            vue_version: self
                .node
                .npm_package_latest_version("@vue/language-server")
                .await?,
            ts_version: self.node.npm_package_latest_version("typescript").await?,
        }) as Box<_>)
    }
    async fn initialization_options(&self) -> Option<Value> {
        let typescript_sdk_path = self.typescript_install_path.lock();
        let typescript_sdk_path = typescript_sdk_path
            .as_ref()
            .expect("initialization_options called without a container_dir for typescript");

        Some(serde_json::json!({
            "typescript": {
                "tsdk": typescript_sdk_path
            }
        }))
    }
    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
        // REFACTOR is explicitly disabled, as vue-lsp does not adhere to LSP protocol for code actions with these - it
        // sends back a CodeAction with neither `command` nor `edits` fields set, which is against the spec.
        Some(vec![
            CodeActionKind::EMPTY,
            CodeActionKind::QUICKFIX,
            CodeActionKind::REFACTOR_REWRITE,
        ])
    }
    async fn fetch_server_binary(
        &self,
        version: Box<dyn 'static + Send + Any>,
        container_dir: PathBuf,
        _: &dyn LspAdapterDelegate,
    ) -> Result<LanguageServerBinary> {
        let version = version.downcast::<VueLspVersion>().unwrap();
        let server_path = container_dir.join(Self::SERVER_PATH);
        let ts_path = container_dir.join(Self::TYPESCRIPT_PATH);
        if fs::metadata(&server_path).await.is_err() {
            self.node
                .npm_install_packages(
                    &container_dir,
                    &[("@vue/language-server", version.vue_version.as_str())],
                )
                .await?;
        }
        ensure!(
            fs::metadata(&server_path).await.is_ok(),
            "@vue/language-server package installation failed"
        );
        if fs::metadata(&ts_path).await.is_err() {
            self.node
                .npm_install_packages(
                    &container_dir,
                    &[("typescript", version.ts_version.as_str())],
                )
                .await?;
        }

        ensure!(
            fs::metadata(&ts_path).await.is_ok(),
            "typescript for Vue package installation failed"
        );
        *self.typescript_install_path.lock() = Some(ts_path);
        Ok(LanguageServerBinary {
            path: self.node.binary_path().await?,
            arguments: vue_server_binary_arguments(&server_path),
        })
    }

    async fn cached_server_binary(
        &self,
        container_dir: PathBuf,
        _: &dyn LspAdapterDelegate,
    ) -> Option<LanguageServerBinary> {
        let (server, ts_path) = get_cached_server_binary(container_dir, self.node.clone()).await?;
        *self.typescript_install_path.lock() = Some(ts_path);
        Some(server)
    }

    async fn installation_test_binary(
        &self,
        container_dir: PathBuf,
    ) -> Option<LanguageServerBinary> {
        let (server, ts_path) = get_cached_server_binary(container_dir, self.node.clone())
            .await
            .map(|(mut binary, ts_path)| {
                binary.arguments = vec!["--help".into()];
                (binary, ts_path)
            })?;
        *self.typescript_install_path.lock() = Some(ts_path);
        Some(server)
    }

    async fn label_for_completion(
        &self,
        item: &lsp::CompletionItem,
        language: &Arc<language::Language>,
    ) -> Option<language::CodeLabel> {
        use lsp::CompletionItemKind as Kind;
        let len = item.label.len();
        let grammar = language.grammar()?;
        let highlight_id = match item.kind? {
            Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("tag"),
            Kind::VARIABLE => grammar.highlight_id_for_name("type"),
            Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
            Kind::VALUE => grammar.highlight_id_for_name("tag"),
            _ => None,
        }?;

        let text = match &item.detail {
            Some(detail) => format!("{} {}", item.label, detail),
            None => item.label.clone(),
        };

        Some(language::CodeLabel {
            text,
            runs: vec![(0..len, highlight_id)],
            filter_range: 0..len,
        })
    }
}

fn vue_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
    vec![server_path.into(), "--stdio".into()]
}

type TypescriptPath = PathBuf;
async fn get_cached_server_binary(
    container_dir: PathBuf,
    node: Arc<dyn NodeRuntime>,
) -> Option<(LanguageServerBinary, TypescriptPath)> {
    (|| async move {
        let mut last_version_dir = None;
        let mut entries = fs::read_dir(&container_dir).await?;
        while let Some(entry) = entries.next().await {
            let entry = entry?;
            if entry.file_type().await?.is_dir() {
                last_version_dir = Some(entry.path());
            }
        }
        let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
        let server_path = last_version_dir.join(VueLspAdapter::SERVER_PATH);
        let typescript_path = last_version_dir.join(VueLspAdapter::TYPESCRIPT_PATH);
        if server_path.exists() && typescript_path.exists() {
            Ok((
                LanguageServerBinary {
                    path: node.binary_path().await?,
                    arguments: vue_server_binary_arguments(&server_path),
                },
                typescript_path,
            ))
        } else {
            Err(anyhow!(
                "missing executable in directory {:?}",
                last_version_dir
            ))
        }
    })()
    .await
    .log_err()
}