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