1use crate::wasm_host::wit::since_v0_6_0::{
2 dap::{
3 AttachRequest, BuildTaskDefinition, BuildTaskDefinitionTemplatePayload, LaunchRequest,
4 StartDebuggingRequestArguments, TcpArguments, TcpArgumentsTemplate,
5 },
6 slash_command::SlashCommandOutputSection,
7};
8use crate::wasm_host::wit::{CompletionKind, CompletionLabelDetails, InsertTextFormat, SymbolKind};
9use crate::wasm_host::{WasmState, wit::ToWasmtimeResult};
10use ::http_client::{AsyncBody, HttpRequestExt};
11use ::settings::{Settings, WorktreeId};
12use anyhow::{Context as _, Result, bail};
13use async_compression::futures::bufread::GzipDecoder;
14use async_tar::Archive;
15use async_trait::async_trait;
16use extension::{
17 ExtensionLanguageServerProxy, KeyValueStoreDelegate, ProjectDelegate, WorktreeDelegate,
18};
19use futures::{AsyncReadExt, lock::Mutex};
20use futures::{FutureExt as _, io::BufReader};
21use gpui::{BackgroundExecutor, SharedString};
22use language::{BinaryStatus, LanguageName, language_settings::AllLanguageSettings};
23use project::project_settings::ProjectSettings;
24use semantic_version::SemanticVersion;
25use std::{
26 env,
27 net::Ipv4Addr,
28 path::{Path, PathBuf},
29 str::FromStr,
30 sync::{Arc, OnceLock},
31};
32use task::{SpawnInTerminal, ZedDebugConfig};
33use util::{archive::extract_zip, fs::make_file_executable, maybe};
34use wasmtime::component::{Linker, Resource};
35
36pub const MIN_VERSION: SemanticVersion = SemanticVersion::new(0, 6, 0);
37pub const MAX_VERSION: SemanticVersion = SemanticVersion::new(0, 6, 0);
38
39wasmtime::component::bindgen!({
40 async: true,
41 trappable_imports: true,
42 path: "../extension_api/wit/since_v0.6.0",
43 with: {
44 "worktree": ExtensionWorktree,
45 "project": ExtensionProject,
46 "key-value-store": ExtensionKeyValueStore,
47 "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream
48 },
49});
50
51pub use self::zed::extension::*;
52
53mod settings {
54 include!(concat!(env!("OUT_DIR"), "/since_v0.6.0/settings.rs"));
55}
56
57pub type ExtensionWorktree = Arc<dyn WorktreeDelegate>;
58pub type ExtensionProject = Arc<dyn ProjectDelegate>;
59pub type ExtensionKeyValueStore = Arc<dyn KeyValueStoreDelegate>;
60pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
61
62pub fn linker(executor: &BackgroundExecutor) -> &'static Linker<WasmState> {
63 static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
64 LINKER.get_or_init(|| super::new_linker(executor, Extension::add_to_linker))
65}
66
67impl From<Range> for std::ops::Range<usize> {
68 fn from(range: Range) -> Self {
69 let start = range.start as usize;
70 let end = range.end as usize;
71 start..end
72 }
73}
74
75impl From<Command> for extension::Command {
76 fn from(value: Command) -> Self {
77 Self {
78 command: value.command.into(),
79 args: value.args,
80 env: value.env,
81 }
82 }
83}
84
85impl From<StartDebuggingRequestArgumentsRequest>
86 for extension::StartDebuggingRequestArgumentsRequest
87{
88 fn from(value: StartDebuggingRequestArgumentsRequest) -> Self {
89 match value {
90 StartDebuggingRequestArgumentsRequest::Launch => Self::Launch,
91 StartDebuggingRequestArgumentsRequest::Attach => Self::Attach,
92 }
93 }
94}
95impl TryFrom<StartDebuggingRequestArguments> for extension::StartDebuggingRequestArguments {
96 type Error = anyhow::Error;
97
98 fn try_from(value: StartDebuggingRequestArguments) -> Result<Self, Self::Error> {
99 Ok(Self {
100 configuration: serde_json::from_str(&value.configuration)?,
101 request: value.request.into(),
102 })
103 }
104}
105impl From<TcpArguments> for extension::TcpArguments {
106 fn from(value: TcpArguments) -> Self {
107 Self {
108 host: value.host.into(),
109 port: value.port,
110 timeout: value.timeout,
111 }
112 }
113}
114
115impl From<extension::TcpArgumentsTemplate> for TcpArgumentsTemplate {
116 fn from(value: extension::TcpArgumentsTemplate) -> Self {
117 Self {
118 host: value.host.map(Ipv4Addr::to_bits),
119 port: value.port,
120 timeout: value.timeout,
121 }
122 }
123}
124
125impl From<TcpArgumentsTemplate> for extension::TcpArgumentsTemplate {
126 fn from(value: TcpArgumentsTemplate) -> Self {
127 Self {
128 host: value.host.map(Ipv4Addr::from_bits),
129 port: value.port,
130 timeout: value.timeout,
131 }
132 }
133}
134
135impl TryFrom<extension::DebugTaskDefinition> for DebugTaskDefinition {
136 type Error = anyhow::Error;
137 fn try_from(value: extension::DebugTaskDefinition) -> Result<Self, Self::Error> {
138 Ok(Self {
139 label: value.label.to_string(),
140 adapter: value.adapter.to_string(),
141 config: value.config.to_string(),
142 tcp_connection: value.tcp_connection.map(Into::into),
143 })
144 }
145}
146
147impl From<task::DebugRequest> for DebugRequest {
148 fn from(value: task::DebugRequest) -> Self {
149 match value {
150 task::DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
151 task::DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
152 }
153 }
154}
155
156impl From<DebugRequest> for task::DebugRequest {
157 fn from(value: DebugRequest) -> Self {
158 match value {
159 DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
160 DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
161 }
162 }
163}
164
165impl From<task::LaunchRequest> for LaunchRequest {
166 fn from(value: task::LaunchRequest) -> Self {
167 Self {
168 program: value.program,
169 cwd: value.cwd.map(|p| p.to_string_lossy().into_owned()),
170 args: value.args,
171 envs: value.env.into_iter().collect(),
172 }
173 }
174}
175
176impl From<task::AttachRequest> for AttachRequest {
177 fn from(value: task::AttachRequest) -> Self {
178 Self {
179 process_id: value.process_id,
180 }
181 }
182}
183
184impl From<LaunchRequest> for task::LaunchRequest {
185 fn from(value: LaunchRequest) -> Self {
186 Self {
187 program: value.program,
188 cwd: value.cwd.map(|p| p.into()),
189 args: value.args,
190 env: value.envs.into_iter().collect(),
191 }
192 }
193}
194impl From<AttachRequest> for task::AttachRequest {
195 fn from(value: AttachRequest) -> Self {
196 Self {
197 process_id: value.process_id,
198 }
199 }
200}
201
202impl From<ZedDebugConfig> for DebugConfig {
203 fn from(value: ZedDebugConfig) -> Self {
204 Self {
205 label: value.label.into(),
206 adapter: value.adapter.into(),
207 request: value.request.into(),
208 stop_on_entry: value.stop_on_entry,
209 }
210 }
211}
212impl TryFrom<DebugAdapterBinary> for extension::DebugAdapterBinary {
213 type Error = anyhow::Error;
214 fn try_from(value: DebugAdapterBinary) -> Result<Self, Self::Error> {
215 Ok(Self {
216 command: value.command,
217 arguments: value.arguments,
218 envs: value.envs.into_iter().collect(),
219 cwd: value.cwd.map(|s| s.into()),
220 connection: value.connection.map(Into::into),
221 request_args: value.request_args.try_into()?,
222 })
223 }
224}
225
226impl From<BuildTaskDefinition> for extension::BuildTaskDefinition {
227 fn from(value: BuildTaskDefinition) -> Self {
228 match value {
229 BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
230 BuildTaskDefinition::Template(build_task_template) => Self::Template {
231 task_template: build_task_template.template.into(),
232 locator_name: build_task_template.locator_name.map(SharedString::from),
233 },
234 }
235 }
236}
237
238impl From<extension::BuildTaskDefinition> for BuildTaskDefinition {
239 fn from(value: extension::BuildTaskDefinition) -> Self {
240 match value {
241 extension::BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
242 extension::BuildTaskDefinition::Template {
243 task_template,
244 locator_name,
245 } => Self::Template(BuildTaskDefinitionTemplatePayload {
246 template: task_template.into(),
247 locator_name: locator_name.map(String::from),
248 }),
249 }
250 }
251}
252impl From<BuildTaskTemplate> for extension::BuildTaskTemplate {
253 fn from(value: BuildTaskTemplate) -> Self {
254 Self {
255 label: value.label,
256 command: value.command,
257 args: value.args,
258 env: value.env.into_iter().collect(),
259 cwd: value.cwd,
260 ..Default::default()
261 }
262 }
263}
264impl From<extension::BuildTaskTemplate> for BuildTaskTemplate {
265 fn from(value: extension::BuildTaskTemplate) -> Self {
266 Self {
267 label: value.label,
268 command: value.command,
269 args: value.args,
270 env: value.env.into_iter().collect(),
271 cwd: value.cwd,
272 }
273 }
274}
275
276impl TryFrom<DebugScenario> for extension::DebugScenario {
277 type Error = anyhow::Error;
278
279 fn try_from(value: DebugScenario) -> std::result::Result<Self, Self::Error> {
280 Ok(Self {
281 adapter: value.adapter.into(),
282 label: value.label.into(),
283 build: value.build.map(Into::into),
284 config: serde_json::Value::from_str(&value.config)?,
285 tcp_connection: value.tcp_connection.map(Into::into),
286 })
287 }
288}
289
290impl From<extension::DebugScenario> for DebugScenario {
291 fn from(value: extension::DebugScenario) -> Self {
292 Self {
293 adapter: value.adapter.into(),
294 label: value.label.into(),
295 build: value.build.map(Into::into),
296 config: value.config.to_string(),
297 tcp_connection: value.tcp_connection.map(Into::into),
298 }
299 }
300}
301
302impl TryFrom<SpawnInTerminal> for ResolvedTask {
303 type Error = anyhow::Error;
304
305 fn try_from(value: SpawnInTerminal) -> Result<Self, Self::Error> {
306 Ok(Self {
307 label: value.label,
308 command: value.command.context("missing command")?,
309 args: value.args,
310 env: value.env.into_iter().collect(),
311 cwd: value.cwd.map(|s| s.to_string_lossy().into_owned()),
312 })
313 }
314}
315
316impl From<CodeLabel> for extension::CodeLabel {
317 fn from(value: CodeLabel) -> Self {
318 Self {
319 code: value.code,
320 spans: value.spans.into_iter().map(Into::into).collect(),
321 filter_range: value.filter_range.into(),
322 }
323 }
324}
325
326impl From<CodeLabelSpan> for extension::CodeLabelSpan {
327 fn from(value: CodeLabelSpan) -> Self {
328 match value {
329 CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
330 CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
331 }
332 }
333}
334
335impl From<CodeLabelSpanLiteral> for extension::CodeLabelSpanLiteral {
336 fn from(value: CodeLabelSpanLiteral) -> Self {
337 Self {
338 text: value.text,
339 highlight_name: value.highlight_name,
340 }
341 }
342}
343
344impl From<extension::Completion> for Completion {
345 fn from(value: extension::Completion) -> Self {
346 Self {
347 label: value.label,
348 label_details: value.label_details.map(Into::into),
349 detail: value.detail,
350 kind: value.kind.map(Into::into),
351 insert_text_format: value.insert_text_format.map(Into::into),
352 }
353 }
354}
355
356impl From<extension::CompletionLabelDetails> for CompletionLabelDetails {
357 fn from(value: extension::CompletionLabelDetails) -> Self {
358 Self {
359 detail: value.detail,
360 description: value.description,
361 }
362 }
363}
364
365impl From<extension::CompletionKind> for CompletionKind {
366 fn from(value: extension::CompletionKind) -> Self {
367 match value {
368 extension::CompletionKind::Text => Self::Text,
369 extension::CompletionKind::Method => Self::Method,
370 extension::CompletionKind::Function => Self::Function,
371 extension::CompletionKind::Constructor => Self::Constructor,
372 extension::CompletionKind::Field => Self::Field,
373 extension::CompletionKind::Variable => Self::Variable,
374 extension::CompletionKind::Class => Self::Class,
375 extension::CompletionKind::Interface => Self::Interface,
376 extension::CompletionKind::Module => Self::Module,
377 extension::CompletionKind::Property => Self::Property,
378 extension::CompletionKind::Unit => Self::Unit,
379 extension::CompletionKind::Value => Self::Value,
380 extension::CompletionKind::Enum => Self::Enum,
381 extension::CompletionKind::Keyword => Self::Keyword,
382 extension::CompletionKind::Snippet => Self::Snippet,
383 extension::CompletionKind::Color => Self::Color,
384 extension::CompletionKind::File => Self::File,
385 extension::CompletionKind::Reference => Self::Reference,
386 extension::CompletionKind::Folder => Self::Folder,
387 extension::CompletionKind::EnumMember => Self::EnumMember,
388 extension::CompletionKind::Constant => Self::Constant,
389 extension::CompletionKind::Struct => Self::Struct,
390 extension::CompletionKind::Event => Self::Event,
391 extension::CompletionKind::Operator => Self::Operator,
392 extension::CompletionKind::TypeParameter => Self::TypeParameter,
393 extension::CompletionKind::Other(value) => Self::Other(value),
394 }
395 }
396}
397
398impl From<extension::InsertTextFormat> for InsertTextFormat {
399 fn from(value: extension::InsertTextFormat) -> Self {
400 match value {
401 extension::InsertTextFormat::PlainText => Self::PlainText,
402 extension::InsertTextFormat::Snippet => Self::Snippet,
403 extension::InsertTextFormat::Other(value) => Self::Other(value),
404 }
405 }
406}
407
408impl From<extension::Symbol> for Symbol {
409 fn from(value: extension::Symbol) -> Self {
410 Self {
411 kind: value.kind.into(),
412 name: value.name,
413 }
414 }
415}
416
417impl From<extension::SymbolKind> for SymbolKind {
418 fn from(value: extension::SymbolKind) -> Self {
419 match value {
420 extension::SymbolKind::File => Self::File,
421 extension::SymbolKind::Module => Self::Module,
422 extension::SymbolKind::Namespace => Self::Namespace,
423 extension::SymbolKind::Package => Self::Package,
424 extension::SymbolKind::Class => Self::Class,
425 extension::SymbolKind::Method => Self::Method,
426 extension::SymbolKind::Property => Self::Property,
427 extension::SymbolKind::Field => Self::Field,
428 extension::SymbolKind::Constructor => Self::Constructor,
429 extension::SymbolKind::Enum => Self::Enum,
430 extension::SymbolKind::Interface => Self::Interface,
431 extension::SymbolKind::Function => Self::Function,
432 extension::SymbolKind::Variable => Self::Variable,
433 extension::SymbolKind::Constant => Self::Constant,
434 extension::SymbolKind::String => Self::String,
435 extension::SymbolKind::Number => Self::Number,
436 extension::SymbolKind::Boolean => Self::Boolean,
437 extension::SymbolKind::Array => Self::Array,
438 extension::SymbolKind::Object => Self::Object,
439 extension::SymbolKind::Key => Self::Key,
440 extension::SymbolKind::Null => Self::Null,
441 extension::SymbolKind::EnumMember => Self::EnumMember,
442 extension::SymbolKind::Struct => Self::Struct,
443 extension::SymbolKind::Event => Self::Event,
444 extension::SymbolKind::Operator => Self::Operator,
445 extension::SymbolKind::TypeParameter => Self::TypeParameter,
446 extension::SymbolKind::Other(value) => Self::Other(value),
447 }
448 }
449}
450
451impl From<extension::SlashCommand> for SlashCommand {
452 fn from(value: extension::SlashCommand) -> Self {
453 Self {
454 name: value.name,
455 description: value.description,
456 tooltip_text: value.tooltip_text,
457 requires_argument: value.requires_argument,
458 }
459 }
460}
461
462impl From<SlashCommandOutput> for extension::SlashCommandOutput {
463 fn from(value: SlashCommandOutput) -> Self {
464 Self {
465 text: value.text,
466 sections: value.sections.into_iter().map(Into::into).collect(),
467 }
468 }
469}
470
471impl From<SlashCommandOutputSection> for extension::SlashCommandOutputSection {
472 fn from(value: SlashCommandOutputSection) -> Self {
473 Self {
474 range: value.range.start as usize..value.range.end as usize,
475 label: value.label,
476 }
477 }
478}
479
480impl From<SlashCommandArgumentCompletion> for extension::SlashCommandArgumentCompletion {
481 fn from(value: SlashCommandArgumentCompletion) -> Self {
482 Self {
483 label: value.label,
484 new_text: value.new_text,
485 run_command: value.run_command,
486 }
487 }
488}
489
490impl TryFrom<ContextServerConfiguration> for extension::ContextServerConfiguration {
491 type Error = anyhow::Error;
492
493 fn try_from(value: ContextServerConfiguration) -> Result<Self, Self::Error> {
494 let settings_schema: serde_json::Value = serde_json::from_str(&value.settings_schema)
495 .context("Failed to parse settings_schema")?;
496
497 Ok(Self {
498 installation_instructions: value.installation_instructions,
499 default_settings: value.default_settings,
500 settings_schema,
501 })
502 }
503}
504
505impl HostKeyValueStore for WasmState {
506 async fn insert(
507 &mut self,
508 kv_store: Resource<ExtensionKeyValueStore>,
509 key: String,
510 value: String,
511 ) -> wasmtime::Result<Result<(), String>> {
512 let kv_store = self.table.get(&kv_store)?;
513 kv_store.insert(key, value).await.to_wasmtime_result()
514 }
515
516 async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
517 // We only ever hand out borrows of key-value stores.
518 Ok(())
519 }
520}
521
522impl HostProject for WasmState {
523 async fn worktree_ids(
524 &mut self,
525 project: Resource<ExtensionProject>,
526 ) -> wasmtime::Result<Vec<u64>> {
527 let project = self.table.get(&project)?;
528 Ok(project.worktree_ids())
529 }
530
531 async fn drop(&mut self, _project: Resource<Project>) -> Result<()> {
532 // We only ever hand out borrows of projects.
533 Ok(())
534 }
535}
536
537impl HostWorktree for WasmState {
538 async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
539 let delegate = self.table.get(&delegate)?;
540 Ok(delegate.id())
541 }
542
543 async fn root_path(
544 &mut self,
545 delegate: Resource<Arc<dyn WorktreeDelegate>>,
546 ) -> wasmtime::Result<String> {
547 let delegate = self.table.get(&delegate)?;
548 Ok(delegate.root_path())
549 }
550
551 async fn read_text_file(
552 &mut self,
553 delegate: Resource<Arc<dyn WorktreeDelegate>>,
554 path: String,
555 ) -> wasmtime::Result<Result<String, String>> {
556 let delegate = self.table.get(&delegate)?;
557 Ok(delegate
558 .read_text_file(path.into())
559 .await
560 .map_err(|error| error.to_string()))
561 }
562
563 async fn shell_env(
564 &mut self,
565 delegate: Resource<Arc<dyn WorktreeDelegate>>,
566 ) -> wasmtime::Result<EnvVars> {
567 let delegate = self.table.get(&delegate)?;
568 Ok(delegate.shell_env().await.into_iter().collect())
569 }
570
571 async fn which(
572 &mut self,
573 delegate: Resource<Arc<dyn WorktreeDelegate>>,
574 binary_name: String,
575 ) -> wasmtime::Result<Option<String>> {
576 let delegate = self.table.get(&delegate)?;
577 Ok(delegate.which(binary_name).await)
578 }
579
580 async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
581 // We only ever hand out borrows of worktrees.
582 Ok(())
583 }
584}
585
586impl common::Host for WasmState {}
587
588impl http_client::Host for WasmState {
589 async fn fetch(
590 &mut self,
591 request: http_client::HttpRequest,
592 ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
593 maybe!(async {
594 let url = &request.url;
595 let request = convert_request(&request)?;
596 let mut response = self.host.http_client.send(request).await?;
597
598 if response.status().is_client_error() || response.status().is_server_error() {
599 bail!("failed to fetch '{url}': status code {}", response.status())
600 }
601 convert_response(&mut response).await
602 })
603 .await
604 .to_wasmtime_result()
605 }
606
607 async fn fetch_stream(
608 &mut self,
609 request: http_client::HttpRequest,
610 ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
611 let request = convert_request(&request)?;
612 let response = self.host.http_client.send(request);
613 maybe!(async {
614 let response = response.await?;
615 let stream = Arc::new(Mutex::new(response));
616 let resource = self.table.push(stream)?;
617 Ok(resource)
618 })
619 .await
620 .to_wasmtime_result()
621 }
622}
623
624impl http_client::HostHttpResponseStream for WasmState {
625 async fn next_chunk(
626 &mut self,
627 resource: Resource<ExtensionHttpResponseStream>,
628 ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
629 let stream = self.table.get(&resource)?.clone();
630 maybe!(async move {
631 let mut response = stream.lock().await;
632 let mut buffer = vec![0; 8192]; // 8KB buffer
633 let bytes_read = response.body_mut().read(&mut buffer).await?;
634 if bytes_read == 0 {
635 Ok(None)
636 } else {
637 buffer.truncate(bytes_read);
638 Ok(Some(buffer))
639 }
640 })
641 .await
642 .to_wasmtime_result()
643 }
644
645 async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
646 Ok(())
647 }
648}
649
650impl From<http_client::HttpMethod> for ::http_client::Method {
651 fn from(value: http_client::HttpMethod) -> Self {
652 match value {
653 http_client::HttpMethod::Get => Self::GET,
654 http_client::HttpMethod::Post => Self::POST,
655 http_client::HttpMethod::Put => Self::PUT,
656 http_client::HttpMethod::Delete => Self::DELETE,
657 http_client::HttpMethod::Head => Self::HEAD,
658 http_client::HttpMethod::Options => Self::OPTIONS,
659 http_client::HttpMethod::Patch => Self::PATCH,
660 }
661 }
662}
663
664fn convert_request(
665 extension_request: &http_client::HttpRequest,
666) -> anyhow::Result<::http_client::Request<AsyncBody>> {
667 let mut request = ::http_client::Request::builder()
668 .method(::http_client::Method::from(extension_request.method))
669 .uri(&extension_request.url)
670 .follow_redirects(match extension_request.redirect_policy {
671 http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
672 http_client::RedirectPolicy::FollowLimit(limit) => {
673 ::http_client::RedirectPolicy::FollowLimit(limit)
674 }
675 http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
676 });
677 for (key, value) in &extension_request.headers {
678 request = request.header(key, value);
679 }
680 let body = extension_request
681 .body
682 .clone()
683 .map(AsyncBody::from)
684 .unwrap_or_default();
685 request.body(body).map_err(anyhow::Error::from)
686}
687
688async fn convert_response(
689 response: &mut ::http_client::Response<AsyncBody>,
690) -> anyhow::Result<http_client::HttpResponse> {
691 let mut extension_response = http_client::HttpResponse {
692 body: Vec::new(),
693 headers: Vec::new(),
694 };
695
696 for (key, value) in response.headers() {
697 extension_response
698 .headers
699 .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
700 }
701
702 response
703 .body_mut()
704 .read_to_end(&mut extension_response.body)
705 .await?;
706
707 Ok(extension_response)
708}
709
710impl nodejs::Host for WasmState {
711 async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
712 self.host
713 .node_runtime
714 .binary_path()
715 .await
716 .map(|path| path.to_string_lossy().to_string())
717 .to_wasmtime_result()
718 }
719
720 async fn npm_package_latest_version(
721 &mut self,
722 package_name: String,
723 ) -> wasmtime::Result<Result<String, String>> {
724 self.host
725 .node_runtime
726 .npm_package_latest_version(&package_name)
727 .await
728 .to_wasmtime_result()
729 }
730
731 async fn npm_package_installed_version(
732 &mut self,
733 package_name: String,
734 ) -> wasmtime::Result<Result<Option<String>, String>> {
735 self.host
736 .node_runtime
737 .npm_package_installed_version(&self.work_dir(), &package_name)
738 .await
739 .to_wasmtime_result()
740 }
741
742 async fn npm_install_package(
743 &mut self,
744 package_name: String,
745 version: String,
746 ) -> wasmtime::Result<Result<(), String>> {
747 self.host
748 .node_runtime
749 .npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
750 .await
751 .to_wasmtime_result()
752 }
753}
754
755#[async_trait]
756impl lsp::Host for WasmState {}
757
758impl From<::http_client::github::GithubRelease> for github::GithubRelease {
759 fn from(value: ::http_client::github::GithubRelease) -> Self {
760 Self {
761 version: value.tag_name,
762 assets: value.assets.into_iter().map(Into::into).collect(),
763 }
764 }
765}
766
767impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
768 fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
769 Self {
770 name: value.name,
771 download_url: value.browser_download_url,
772 }
773 }
774}
775
776impl github::Host for WasmState {
777 async fn latest_github_release(
778 &mut self,
779 repo: String,
780 options: github::GithubReleaseOptions,
781 ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
782 maybe!(async {
783 let release = ::http_client::github::latest_github_release(
784 &repo,
785 options.require_assets,
786 options.pre_release,
787 self.host.http_client.clone(),
788 )
789 .await?;
790 Ok(release.into())
791 })
792 .await
793 .to_wasmtime_result()
794 }
795
796 async fn github_release_by_tag_name(
797 &mut self,
798 repo: String,
799 tag: String,
800 ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
801 maybe!(async {
802 let release = ::http_client::github::get_release_by_tag_name(
803 &repo,
804 &tag,
805 self.host.http_client.clone(),
806 )
807 .await?;
808 Ok(release.into())
809 })
810 .await
811 .to_wasmtime_result()
812 }
813}
814
815impl platform::Host for WasmState {
816 async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
817 Ok((
818 match env::consts::OS {
819 "macos" => platform::Os::Mac,
820 "linux" => platform::Os::Linux,
821 "windows" => platform::Os::Windows,
822 _ => panic!("unsupported os"),
823 },
824 match env::consts::ARCH {
825 "aarch64" => platform::Architecture::Aarch64,
826 "x86" => platform::Architecture::X86,
827 "x86_64" => platform::Architecture::X8664,
828 _ => panic!("unsupported architecture"),
829 },
830 ))
831 }
832}
833
834impl From<std::process::Output> for process::Output {
835 fn from(output: std::process::Output) -> Self {
836 Self {
837 status: output.status.code(),
838 stdout: output.stdout,
839 stderr: output.stderr,
840 }
841 }
842}
843
844impl process::Host for WasmState {
845 async fn run_command(
846 &mut self,
847 command: process::Command,
848 ) -> wasmtime::Result<Result<process::Output, String>> {
849 maybe!(async {
850 self.capability_granter
851 .grant_exec(&command.command, &command.args)?;
852
853 let output = util::command::new_smol_command(command.command.as_str())
854 .args(&command.args)
855 .envs(command.env)
856 .output()
857 .await?;
858
859 Ok(output.into())
860 })
861 .await
862 .to_wasmtime_result()
863 }
864}
865
866#[async_trait]
867impl slash_command::Host for WasmState {}
868
869#[async_trait]
870impl context_server::Host for WasmState {}
871
872impl dap::Host for WasmState {
873 async fn resolve_tcp_template(
874 &mut self,
875 template: TcpArgumentsTemplate,
876 ) -> wasmtime::Result<Result<TcpArguments, String>> {
877 maybe!(async {
878 let (host, port, timeout) =
879 ::dap::configure_tcp_connection(task::TcpArgumentsTemplate {
880 port: template.port,
881 host: template.host.map(Ipv4Addr::from_bits),
882 timeout: template.timeout,
883 })
884 .await?;
885 Ok(TcpArguments {
886 port,
887 host: host.to_bits(),
888 timeout,
889 })
890 })
891 .await
892 .to_wasmtime_result()
893 }
894}
895
896impl ExtensionImports for WasmState {
897 async fn get_settings(
898 &mut self,
899 location: Option<self::SettingsLocation>,
900 category: String,
901 key: Option<String>,
902 ) -> wasmtime::Result<Result<String, String>> {
903 self.on_main_thread(|cx| {
904 async move {
905 let location = location
906 .as_ref()
907 .map(|location| ::settings::SettingsLocation {
908 worktree_id: WorktreeId::from_proto(location.worktree_id),
909 path: Path::new(&location.path),
910 });
911
912 cx.update(|cx| match category.as_str() {
913 "language" => {
914 let key = key.map(|k| LanguageName::new(&k));
915 let settings = AllLanguageSettings::get(location, cx).language(
916 location,
917 key.as_ref(),
918 cx,
919 );
920 Ok(serde_json::to_string(&settings::LanguageSettings {
921 tab_size: settings.tab_size,
922 })?)
923 }
924 "lsp" => {
925 let settings = key
926 .and_then(|key| {
927 ProjectSettings::get(location, cx)
928 .lsp
929 .get(&::lsp::LanguageServerName::from_proto(key))
930 })
931 .cloned()
932 .unwrap_or_default();
933 Ok(serde_json::to_string(&settings::LspSettings {
934 binary: settings.binary.map(|binary| settings::CommandSettings {
935 path: binary.path,
936 arguments: binary.arguments,
937 env: binary.env,
938 }),
939 settings: settings.settings,
940 initialization_options: settings.initialization_options,
941 })?)
942 }
943 "context_servers" => {
944 let settings = key
945 .and_then(|key| {
946 ProjectSettings::get(location, cx)
947 .context_servers
948 .get(key.as_str())
949 })
950 .cloned()
951 .unwrap_or_else(|| {
952 project::project_settings::ContextServerSettings::default_extension(
953 )
954 });
955
956 match settings {
957 project::project_settings::ContextServerSettings::Custom {
958 enabled: _,
959 command,
960 } => Ok(serde_json::to_string(&settings::ContextServerSettings {
961 command: Some(settings::CommandSettings {
962 path: command.path.to_str().map(|path| path.to_string()),
963 arguments: Some(command.args),
964 env: command.env.map(|env| env.into_iter().collect()),
965 }),
966 settings: None,
967 })?),
968 project::project_settings::ContextServerSettings::Extension {
969 enabled: _,
970 settings,
971 } => Ok(serde_json::to_string(&settings::ContextServerSettings {
972 command: None,
973 settings: Some(settings),
974 })?),
975 }
976 }
977 _ => {
978 bail!("Unknown settings category: {}", category);
979 }
980 })
981 }
982 .boxed_local()
983 })
984 .await?
985 .to_wasmtime_result()
986 }
987
988 async fn set_language_server_installation_status(
989 &mut self,
990 server_name: String,
991 status: LanguageServerInstallationStatus,
992 ) -> wasmtime::Result<()> {
993 let status = match status {
994 LanguageServerInstallationStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
995 LanguageServerInstallationStatus::Downloading => BinaryStatus::Downloading,
996 LanguageServerInstallationStatus::None => BinaryStatus::None,
997 LanguageServerInstallationStatus::Failed(error) => BinaryStatus::Failed { error },
998 };
999
1000 self.host
1001 .proxy
1002 .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
1003
1004 Ok(())
1005 }
1006
1007 async fn download_file(
1008 &mut self,
1009 url: String,
1010 path: String,
1011 file_type: DownloadedFileType,
1012 ) -> wasmtime::Result<Result<(), String>> {
1013 maybe!(async {
1014 let path = PathBuf::from(path);
1015 let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
1016
1017 self.host.fs.create_dir(&extension_work_dir).await?;
1018
1019 let destination_path = self
1020 .host
1021 .writeable_path_from_extension(&self.manifest.id, &path)?;
1022
1023 let mut response = self
1024 .host
1025 .http_client
1026 .get(&url, Default::default(), true)
1027 .await
1028 .context("downloading release")?;
1029
1030 anyhow::ensure!(
1031 response.status().is_success(),
1032 "download failed with status {}",
1033 response.status().to_string()
1034 );
1035 let body = BufReader::new(response.body_mut());
1036
1037 match file_type {
1038 DownloadedFileType::Uncompressed => {
1039 futures::pin_mut!(body);
1040 self.host
1041 .fs
1042 .create_file_with(&destination_path, body)
1043 .await?;
1044 }
1045 DownloadedFileType::Gzip => {
1046 let body = GzipDecoder::new(body);
1047 futures::pin_mut!(body);
1048 self.host
1049 .fs
1050 .create_file_with(&destination_path, body)
1051 .await?;
1052 }
1053 DownloadedFileType::GzipTar => {
1054 let body = GzipDecoder::new(body);
1055 futures::pin_mut!(body);
1056 self.host
1057 .fs
1058 .extract_tar_file(&destination_path, Archive::new(body))
1059 .await?;
1060 }
1061 DownloadedFileType::Zip => {
1062 futures::pin_mut!(body);
1063 extract_zip(&destination_path, body)
1064 .await
1065 .with_context(|| format!("unzipping {path:?} archive"))?;
1066 }
1067 }
1068
1069 Ok(())
1070 })
1071 .await
1072 .to_wasmtime_result()
1073 }
1074
1075 async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
1076 let path = self
1077 .host
1078 .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
1079
1080 make_file_executable(&path)
1081 .await
1082 .with_context(|| format!("setting permissions for path {path:?}"))
1083 .to_wasmtime_result()
1084 }
1085}