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