1use crate::wasm_host::{WasmState, wit::ToWasmtimeResult};
2use ::http_client::{AsyncBody, HttpRequestExt};
3use ::settings::{Settings, WorktreeId};
4use anyhow::{Context as _, Result, bail};
5use async_compression::futures::bufread::GzipDecoder;
6use async_tar::Archive;
7use extension::{ExtensionLanguageServerProxy, KeyValueStoreDelegate, WorktreeDelegate};
8use futures::{AsyncReadExt, lock::Mutex};
9use futures::{FutureExt as _, io::BufReader};
10use gpui::BackgroundExecutor;
11use language::LanguageName;
12use language::{BinaryStatus, language_settings::AllLanguageSettings};
13use project::project_settings::ProjectSettings;
14use semantic_version::SemanticVersion;
15use std::{
16 path::{Path, PathBuf},
17 sync::{Arc, OnceLock},
18};
19use util::rel_path::RelPath;
20use util::{archive::extract_zip, fs::make_file_executable, maybe};
21use wasmtime::component::{Linker, Resource};
22
23use super::latest;
24
25pub const MIN_VERSION: SemanticVersion = SemanticVersion::new(0, 1, 0);
26
27wasmtime::component::bindgen!({
28 async: true,
29 trappable_imports: true,
30 path: "../extension_api/wit/since_v0.1.0",
31 with: {
32 "worktree": ExtensionWorktree,
33 "key-value-store": ExtensionKeyValueStore,
34 "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream,
35 "zed:extension/github": latest::zed::extension::github,
36 "zed:extension/nodejs": latest::zed::extension::nodejs,
37 "zed:extension/platform": latest::zed::extension::platform,
38 "zed:extension/slash-command": latest::zed::extension::slash_command,
39 },
40});
41
42pub use self::zed::extension::*;
43
44mod settings {
45 include!(concat!(env!("OUT_DIR"), "/since_v0.1.0/settings.rs"));
46}
47
48pub type ExtensionWorktree = Arc<dyn WorktreeDelegate>;
49pub type ExtensionKeyValueStore = Arc<dyn KeyValueStoreDelegate>;
50pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
51
52pub fn linker(executor: &BackgroundExecutor) -> &'static Linker<WasmState> {
53 static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
54 LINKER.get_or_init(|| super::new_linker(executor, Extension::add_to_linker))
55}
56
57impl From<Command> for latest::Command {
58 fn from(value: Command) -> Self {
59 Self {
60 command: value.command,
61 args: value.args,
62 env: value.env,
63 }
64 }
65}
66
67impl From<SettingsLocation> for latest::SettingsLocation {
68 fn from(value: SettingsLocation) -> Self {
69 Self {
70 worktree_id: value.worktree_id,
71 path: value.path,
72 }
73 }
74}
75
76impl From<LanguageServerInstallationStatus> for latest::LanguageServerInstallationStatus {
77 fn from(value: LanguageServerInstallationStatus) -> Self {
78 match value {
79 LanguageServerInstallationStatus::None => Self::None,
80 LanguageServerInstallationStatus::Downloading => Self::Downloading,
81 LanguageServerInstallationStatus::CheckingForUpdate => Self::CheckingForUpdate,
82 LanguageServerInstallationStatus::Failed(message) => Self::Failed(message),
83 }
84 }
85}
86
87impl From<DownloadedFileType> for latest::DownloadedFileType {
88 fn from(value: DownloadedFileType) -> Self {
89 match value {
90 DownloadedFileType::Gzip => Self::Gzip,
91 DownloadedFileType::GzipTar => Self::GzipTar,
92 DownloadedFileType::Zip => Self::Zip,
93 DownloadedFileType::Uncompressed => Self::Uncompressed,
94 }
95 }
96}
97
98impl From<Range> for latest::Range {
99 fn from(value: Range) -> Self {
100 Self {
101 start: value.start,
102 end: value.end,
103 }
104 }
105}
106
107impl From<CodeLabelSpan> for latest::CodeLabelSpan {
108 fn from(value: CodeLabelSpan) -> Self {
109 match value {
110 CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
111 CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
112 }
113 }
114}
115
116impl From<CodeLabelSpanLiteral> for latest::CodeLabelSpanLiteral {
117 fn from(value: CodeLabelSpanLiteral) -> Self {
118 Self {
119 text: value.text,
120 highlight_name: value.highlight_name,
121 }
122 }
123}
124
125impl From<CodeLabel> for latest::CodeLabel {
126 fn from(value: CodeLabel) -> Self {
127 Self {
128 code: value.code,
129 spans: value.spans.into_iter().map(Into::into).collect(),
130 filter_range: value.filter_range.into(),
131 }
132 }
133}
134
135impl From<latest::Completion> for Completion {
136 fn from(value: latest::Completion) -> Self {
137 Self {
138 label: value.label,
139 detail: value.detail,
140 kind: value.kind.map(Into::into),
141 insert_text_format: value.insert_text_format.map(Into::into),
142 }
143 }
144}
145
146impl From<latest::lsp::CompletionKind> for lsp::CompletionKind {
147 fn from(value: latest::lsp::CompletionKind) -> Self {
148 match value {
149 latest::lsp::CompletionKind::Text => Self::Text,
150 latest::lsp::CompletionKind::Method => Self::Method,
151 latest::lsp::CompletionKind::Function => Self::Function,
152 latest::lsp::CompletionKind::Constructor => Self::Constructor,
153 latest::lsp::CompletionKind::Field => Self::Field,
154 latest::lsp::CompletionKind::Variable => Self::Variable,
155 latest::lsp::CompletionKind::Class => Self::Class,
156 latest::lsp::CompletionKind::Interface => Self::Interface,
157 latest::lsp::CompletionKind::Module => Self::Module,
158 latest::lsp::CompletionKind::Property => Self::Property,
159 latest::lsp::CompletionKind::Unit => Self::Unit,
160 latest::lsp::CompletionKind::Value => Self::Value,
161 latest::lsp::CompletionKind::Enum => Self::Enum,
162 latest::lsp::CompletionKind::Keyword => Self::Keyword,
163 latest::lsp::CompletionKind::Snippet => Self::Snippet,
164 latest::lsp::CompletionKind::Color => Self::Color,
165 latest::lsp::CompletionKind::File => Self::File,
166 latest::lsp::CompletionKind::Reference => Self::Reference,
167 latest::lsp::CompletionKind::Folder => Self::Folder,
168 latest::lsp::CompletionKind::EnumMember => Self::EnumMember,
169 latest::lsp::CompletionKind::Constant => Self::Constant,
170 latest::lsp::CompletionKind::Struct => Self::Struct,
171 latest::lsp::CompletionKind::Event => Self::Event,
172 latest::lsp::CompletionKind::Operator => Self::Operator,
173 latest::lsp::CompletionKind::TypeParameter => Self::TypeParameter,
174 latest::lsp::CompletionKind::Other(kind) => Self::Other(kind),
175 }
176 }
177}
178
179impl From<latest::lsp::InsertTextFormat> for lsp::InsertTextFormat {
180 fn from(value: latest::lsp::InsertTextFormat) -> Self {
181 match value {
182 latest::lsp::InsertTextFormat::PlainText => Self::PlainText,
183 latest::lsp::InsertTextFormat::Snippet => Self::Snippet,
184 latest::lsp::InsertTextFormat::Other(value) => Self::Other(value),
185 }
186 }
187}
188
189impl From<latest::lsp::Symbol> for lsp::Symbol {
190 fn from(value: latest::lsp::Symbol) -> Self {
191 Self {
192 name: value.name,
193 kind: value.kind.into(),
194 }
195 }
196}
197
198impl From<latest::lsp::SymbolKind> for lsp::SymbolKind {
199 fn from(value: latest::lsp::SymbolKind) -> Self {
200 match value {
201 latest::lsp::SymbolKind::File => Self::File,
202 latest::lsp::SymbolKind::Module => Self::Module,
203 latest::lsp::SymbolKind::Namespace => Self::Namespace,
204 latest::lsp::SymbolKind::Package => Self::Package,
205 latest::lsp::SymbolKind::Class => Self::Class,
206 latest::lsp::SymbolKind::Method => Self::Method,
207 latest::lsp::SymbolKind::Property => Self::Property,
208 latest::lsp::SymbolKind::Field => Self::Field,
209 latest::lsp::SymbolKind::Constructor => Self::Constructor,
210 latest::lsp::SymbolKind::Enum => Self::Enum,
211 latest::lsp::SymbolKind::Interface => Self::Interface,
212 latest::lsp::SymbolKind::Function => Self::Function,
213 latest::lsp::SymbolKind::Variable => Self::Variable,
214 latest::lsp::SymbolKind::Constant => Self::Constant,
215 latest::lsp::SymbolKind::String => Self::String,
216 latest::lsp::SymbolKind::Number => Self::Number,
217 latest::lsp::SymbolKind::Boolean => Self::Boolean,
218 latest::lsp::SymbolKind::Array => Self::Array,
219 latest::lsp::SymbolKind::Object => Self::Object,
220 latest::lsp::SymbolKind::Key => Self::Key,
221 latest::lsp::SymbolKind::Null => Self::Null,
222 latest::lsp::SymbolKind::EnumMember => Self::EnumMember,
223 latest::lsp::SymbolKind::Struct => Self::Struct,
224 latest::lsp::SymbolKind::Event => Self::Event,
225 latest::lsp::SymbolKind::Operator => Self::Operator,
226 latest::lsp::SymbolKind::TypeParameter => Self::TypeParameter,
227 latest::lsp::SymbolKind::Other(kind) => Self::Other(kind),
228 }
229 }
230}
231
232impl HostKeyValueStore for WasmState {
233 async fn insert(
234 &mut self,
235 kv_store: Resource<ExtensionKeyValueStore>,
236 key: String,
237 value: String,
238 ) -> wasmtime::Result<Result<(), String>> {
239 let kv_store = self.table.get(&kv_store)?;
240 kv_store.insert(key, value).await.to_wasmtime_result()
241 }
242
243 async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
244 // We only ever hand out borrows of key-value stores.
245 Ok(())
246 }
247}
248
249impl HostWorktree for WasmState {
250 async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
251 latest::HostWorktree::id(self, delegate).await
252 }
253
254 async fn root_path(
255 &mut self,
256 delegate: Resource<Arc<dyn WorktreeDelegate>>,
257 ) -> wasmtime::Result<String> {
258 latest::HostWorktree::root_path(self, delegate).await
259 }
260
261 async fn read_text_file(
262 &mut self,
263 delegate: Resource<Arc<dyn WorktreeDelegate>>,
264 path: String,
265 ) -> wasmtime::Result<Result<String, String>> {
266 latest::HostWorktree::read_text_file(self, delegate, path).await
267 }
268
269 async fn shell_env(
270 &mut self,
271 delegate: Resource<Arc<dyn WorktreeDelegate>>,
272 ) -> wasmtime::Result<EnvVars> {
273 latest::HostWorktree::shell_env(self, delegate).await
274 }
275
276 async fn which(
277 &mut self,
278 delegate: Resource<Arc<dyn WorktreeDelegate>>,
279 binary_name: String,
280 ) -> wasmtime::Result<Option<String>> {
281 latest::HostWorktree::which(self, delegate, binary_name).await
282 }
283
284 async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
285 // We only ever hand out borrows of worktrees.
286 Ok(())
287 }
288}
289
290impl common::Host for WasmState {}
291
292impl http_client::Host for WasmState {
293 async fn fetch(
294 &mut self,
295 request: http_client::HttpRequest,
296 ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
297 maybe!(async {
298 let url = &request.url;
299 let request = convert_request(&request)?;
300 let mut response = self.host.http_client.send(request).await?;
301
302 if response.status().is_client_error() || response.status().is_server_error() {
303 bail!("failed to fetch '{url}': status code {}", response.status())
304 }
305 convert_response(&mut response).await
306 })
307 .await
308 .to_wasmtime_result()
309 }
310
311 async fn fetch_stream(
312 &mut self,
313 request: http_client::HttpRequest,
314 ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
315 let request = convert_request(&request)?;
316 let response = self.host.http_client.send(request);
317 maybe!(async {
318 let response = response.await?;
319 let stream = Arc::new(Mutex::new(response));
320 let resource = self.table.push(stream)?;
321 Ok(resource)
322 })
323 .await
324 .to_wasmtime_result()
325 }
326}
327
328impl http_client::HostHttpResponseStream for WasmState {
329 async fn next_chunk(
330 &mut self,
331 resource: Resource<ExtensionHttpResponseStream>,
332 ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
333 let stream = self.table.get(&resource)?.clone();
334 maybe!(async move {
335 let mut response = stream.lock().await;
336 let mut buffer = vec![0; 8192]; // 8KB buffer
337 let bytes_read = response.body_mut().read(&mut buffer).await?;
338 if bytes_read == 0 {
339 Ok(None)
340 } else {
341 buffer.truncate(bytes_read);
342 Ok(Some(buffer))
343 }
344 })
345 .await
346 .to_wasmtime_result()
347 }
348
349 async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
350 Ok(())
351 }
352}
353
354impl From<http_client::HttpMethod> for ::http_client::Method {
355 fn from(value: http_client::HttpMethod) -> Self {
356 match value {
357 http_client::HttpMethod::Get => Self::GET,
358 http_client::HttpMethod::Post => Self::POST,
359 http_client::HttpMethod::Put => Self::PUT,
360 http_client::HttpMethod::Delete => Self::DELETE,
361 http_client::HttpMethod::Head => Self::HEAD,
362 http_client::HttpMethod::Options => Self::OPTIONS,
363 http_client::HttpMethod::Patch => Self::PATCH,
364 }
365 }
366}
367
368fn convert_request(
369 extension_request: &http_client::HttpRequest,
370) -> anyhow::Result<::http_client::Request<AsyncBody>> {
371 let mut request = ::http_client::Request::builder()
372 .method(::http_client::Method::from(extension_request.method))
373 .uri(&extension_request.url)
374 .follow_redirects(match extension_request.redirect_policy {
375 http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
376 http_client::RedirectPolicy::FollowLimit(limit) => {
377 ::http_client::RedirectPolicy::FollowLimit(limit)
378 }
379 http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
380 });
381 for (key, value) in &extension_request.headers {
382 request = request.header(key, value);
383 }
384 let body = extension_request
385 .body
386 .clone()
387 .map(AsyncBody::from)
388 .unwrap_or_default();
389 request.body(body).map_err(anyhow::Error::from)
390}
391
392async fn convert_response(
393 response: &mut ::http_client::Response<AsyncBody>,
394) -> anyhow::Result<http_client::HttpResponse> {
395 let mut extension_response = http_client::HttpResponse {
396 body: Vec::new(),
397 headers: Vec::new(),
398 };
399
400 for (key, value) in response.headers() {
401 extension_response
402 .headers
403 .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
404 }
405
406 response
407 .body_mut()
408 .read_to_end(&mut extension_response.body)
409 .await?;
410
411 Ok(extension_response)
412}
413
414impl lsp::Host for WasmState {}
415
416impl ExtensionImports for WasmState {
417 async fn get_settings(
418 &mut self,
419 location: Option<self::SettingsLocation>,
420 category: String,
421 key: Option<String>,
422 ) -> wasmtime::Result<Result<String, String>> {
423 self.on_main_thread(|cx| {
424 async move {
425 let location = location.as_ref().and_then(|location| {
426 Some(::settings::SettingsLocation {
427 worktree_id: WorktreeId::from_proto(location.worktree_id),
428 path: RelPath::unix(&location.path).ok()?,
429 })
430 });
431
432 cx.update(|cx| match category.as_str() {
433 "language" => {
434 let key = key.map(|k| LanguageName::new(&k));
435 let settings = AllLanguageSettings::get(location, cx).language(
436 location,
437 key.as_ref(),
438 cx,
439 );
440 Ok(serde_json::to_string(&settings::LanguageSettings {
441 tab_size: settings.tab_size,
442 })?)
443 }
444 "lsp" => {
445 let settings = key
446 .and_then(|key| {
447 ProjectSettings::get(location, cx)
448 .lsp
449 .get(&::lsp::LanguageServerName(key.into()))
450 })
451 .cloned()
452 .unwrap_or_default();
453 Ok(serde_json::to_string(&settings::LspSettings {
454 binary: settings.binary.map(|binary| settings::BinarySettings {
455 path: binary.path,
456 arguments: binary.arguments,
457 }),
458 settings: settings.settings,
459 initialization_options: settings.initialization_options,
460 })?)
461 }
462 _ => {
463 bail!("Unknown settings category: {}", category);
464 }
465 })
466 }
467 .boxed_local()
468 })
469 .await?
470 .to_wasmtime_result()
471 }
472
473 async fn set_language_server_installation_status(
474 &mut self,
475 server_name: String,
476 status: LanguageServerInstallationStatus,
477 ) -> wasmtime::Result<()> {
478 let status = match status {
479 LanguageServerInstallationStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
480 LanguageServerInstallationStatus::Downloading => BinaryStatus::Downloading,
481 LanguageServerInstallationStatus::None => BinaryStatus::None,
482 LanguageServerInstallationStatus::Failed(error) => BinaryStatus::Failed { error },
483 };
484
485 self.host
486 .proxy
487 .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
488
489 Ok(())
490 }
491
492 async fn download_file(
493 &mut self,
494 url: String,
495 path: String,
496 file_type: DownloadedFileType,
497 ) -> wasmtime::Result<Result<(), String>> {
498 maybe!(async {
499 let path = PathBuf::from(path);
500 let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
501
502 self.host.fs.create_dir(&extension_work_dir).await?;
503
504 let destination_path = self
505 .host
506 .writeable_path_from_extension(&self.manifest.id, &path)?;
507
508 let mut response = self
509 .host
510 .http_client
511 .get(&url, Default::default(), true)
512 .await
513 .context("downloading release")?;
514
515 anyhow::ensure!(
516 response.status().is_success(),
517 "download failed with status {}",
518 response.status().to_string()
519 );
520 let body = BufReader::new(response.body_mut());
521
522 match file_type {
523 DownloadedFileType::Uncompressed => {
524 futures::pin_mut!(body);
525 self.host
526 .fs
527 .create_file_with(&destination_path, body)
528 .await?;
529 }
530 DownloadedFileType::Gzip => {
531 let body = GzipDecoder::new(body);
532 futures::pin_mut!(body);
533 self.host
534 .fs
535 .create_file_with(&destination_path, body)
536 .await?;
537 }
538 DownloadedFileType::GzipTar => {
539 let body = GzipDecoder::new(body);
540 futures::pin_mut!(body);
541 self.host
542 .fs
543 .extract_tar_file(&destination_path, Archive::new(body))
544 .await?;
545 }
546 DownloadedFileType::Zip => {
547 futures::pin_mut!(body);
548 extract_zip(&destination_path, body)
549 .await
550 .with_context(|| format!("unzipping {path:?} archive"))?;
551 }
552 }
553
554 Ok(())
555 })
556 .await
557 .to_wasmtime_result()
558 }
559
560 async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
561 let path = self
562 .host
563 .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
564
565 make_file_executable(&path)
566 .await
567 .with_context(|| format!("setting permissions for path {path:?}"))
568 .to_wasmtime_result()
569 }
570}