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