tairitsu 0.4.2

A WebAssembly runtime for running component-model based WASM modules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! Container - Generic WASM component container
//!
//! This module provides a generic container implementation that can run any WASM component.
//! Users need to implement WIT interface bindings and initialization themselves.

use anyhow::{Context as AnyhowContext, Result};

use wasmtime::{
    Store,
    component::{Component, Linker},
    error::Context,
};
use wasmtime_wasi::{ResourceTable, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};

use crate::Image;
#[cfg(feature = "dynamic")]
use crate::dynamic::host_imports::HostImportRegistry;

/// Base trait for host state
///
/// Users need to implement this trait to provide their own host functionality
pub trait HostStateImpl: WasiView + Send + 'static {
    /// Get user-defined state
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}

/// Default host state implementation
///
/// Provides basic WASI support, users can extend through inheritance or composition
pub struct HostState {
    wasi: WasiCtx,
    table: ResourceTable,
}

impl HostState {
    /// Create a new host state
    pub fn new() -> Result<Self> {
        let wasi = WasiCtxBuilder::new()
            .inherit_stdio()
            .inherit_network()
            .build();

        let table = ResourceTable::new();

        Ok(Self { wasi, table })
    }

    /// Create host state with custom WASI configuration
    pub fn with_wasi<F>(f: F) -> Result<Self>
    where
        F: FnOnce(&mut WasiCtxBuilder) -> &mut WasiCtxBuilder,
    {
        let mut builder = WasiCtxBuilder::new();
        f(&mut builder);
        let wasi = builder.build();

        let table = ResourceTable::new();

        Ok(Self { wasi, table })
    }
}

impl Default for HostState {
    fn default() -> Self {
        Self::new().expect("Failed to create default HostState")
    }
}

impl WasiView for HostState {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

impl HostStateImpl for HostState {
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// Handle to a guest instance
///
/// This type wraps the instance type generated by WIT bindings.
/// Users need to interact with it through `GuestHandlerContext`.
pub struct GuestInstance {
    // The actual WIT binding instance is provided by the user when building Container
    // Box is used here to store any type
    inner: Box<dyn std::any::Any + Send + Sync>,

    // Dynamic instance reference (optional, controlled by cfg feature)
    #[cfg(feature = "dynamic")]
    dynamic_instance: Option<wasmtime::component::Instance>,
}

impl GuestInstance {
    /// Create a new guest instance
    ///
    /// # Arguments
    /// * `instance` - Instance type generated by WIT bindgen
    pub fn new<T: 'static + Send + Sync>(instance: T) -> Self {
        Self {
            inner: Box::new(instance),
            #[cfg(feature = "dynamic")]
            dynamic_instance: None,
        }
    }

    /// Get the underlying instance
    ///
    /// # Type Parameters
    /// * `T` - Instance type generated by WIT bindgen
    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
        self.inner.downcast_ref::<T>()
    }

    /// Get mutable reference to the underlying instance
    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.inner.downcast_mut::<T>()
    }

    /// Get export function for dynamic invocation (requires `dynamic` feature)
    #[cfg(feature = "dynamic")]
    pub fn get_export_func<T: HostStateImpl>(
        &self,
        _store: &mut Store<T>,
        _func_name: &str,
    ) -> Result<Option<wasmtime::component::Func>> {
        if let Some(ref instance) = self.dynamic_instance {
            Ok(instance.get_func(_store, _func_name))
        } else {
            Ok(None)
        }
    }

    /// Get the dynamic instance reference (for internal use during Container build)
    #[cfg(feature = "dynamic")]
    pub(crate) fn get_dynamic_instance_ref(&self) -> Option<&wasmtime::component::Instance> {
        self.dynamic_instance.as_ref()
    }
}

/// Context for building guest instances
///
/// Provides Linker, Store, and Component, allowing users to register their own WIT interfaces
pub struct GuestHandlerContext<'a, T: HostStateImpl> {
    pub linker: &'a mut Linker<T>,
    pub store: &'a mut Store<T>,
    pub component: &'a Component,
}

impl<'a, T: HostStateImpl> GuestHandlerContext<'a, T> {
    /// Create new context
    pub fn new(
        linker: &'a mut Linker<T>,
        store: &'a mut Store<T>,
        component: &'a Component,
    ) -> Self {
        Self {
            linker,
            store,
            component,
        }
    }
}

/// Container builder
///
/// Used to configure and create a WASM container instance
pub struct ContainerBuilder<T: HostStateImpl> {
    image: Image,
    host_state: T,
    #[allow(clippy::type_complexity)]
    host_linker_init: Option<Box<dyn FnOnce(&mut Linker<T>) -> Result<(), anyhow::Error> + Send>>,
    #[allow(clippy::type_complexity)]
    guest_initializer: Option<
        Box<
            dyn for<'a> FnOnce(GuestHandlerContext<'a, T>) -> Result<GuestInstance, anyhow::Error>
                + Send,
        >,
    >,
}

impl<T: HostStateImpl> ContainerBuilder<T>
where
    T: Default,
{
    /// Create builder from Image
    pub fn new(image: Image) -> Self {
        Self {
            image,
            host_state: T::default(),
            host_linker_init: None,
            guest_initializer: None,
        }
    }
}

impl<T: HostStateImpl> ContainerBuilder<T> {
    /// Use custom host state
    pub fn with_host_state(mut self, state: T) -> Self {
        self.host_state = state;
        self
    }

    /// Register additional host imports with the linker before guest instantiation.
    ///
    /// This is called after WASI is added to the linker but before the guest
    /// initializer runs, allowing host imports to be available when the component
    /// is instantiated.
    ///
    /// # Example
    /// ```ignore
    /// let container = Container::builder(image)
    ///     .with_host_linker(|linker| {
    ///         MyHostImpl::add_to_linker(linker, |state| &mut state.my_data)
    ///     })
    ///     .with_guest_initializer(|ctx| { ... })
    ///     .build();
    /// ```
    pub fn with_host_linker<F>(mut self, func: F) -> Self
    where
        F: FnOnce(&mut Linker<T>) -> Result<(), anyhow::Error> + Send + 'static,
    {
        self.host_linker_init = Some(Box::new(func));
        self
    }

    /// Set guest instance initializer
    ///
    /// # Arguments
    /// * `f` - A closure that receives `GuestHandlerContext` and returns WIT-bound instance
    ///
    /// # Example
    /// ```ignore
    /// let container = Container::builder(image)?
    ///     .with_guest_initializer(|ctx| {
    ///         // Register your WIT interface to linker
    ///         MyWit::add_to_linker(ctx.linker, |state| &mut state.my_state)?;
    ///
    ///         // Instantiate component
    ///         let instance = MyWit::instantiate(ctx.store, ctx.component, ctx.linker)?;
    ///
    ///         Ok(GuestInstance::new(instance))
    ///     })?
    ///     .build();
    /// ```
    pub fn with_guest_initializer<F>(mut self, f: F) -> Self
    where
        F: for<'a> FnOnce(GuestHandlerContext<'a, T>) -> Result<GuestInstance, anyhow::Error>
            + Send
            + 'static,
    {
        self.guest_initializer = Some(Box::new(f));
        self
    }

    /// Build container
    pub fn build(self) -> Result<Container<T>> {
        let mut store = Store::new(self.image.engine(), self.host_state);

        let mut linker = Linker::new(self.image.engine());
        wasmtime_wasi::p2::add_to_linker_sync(&mut linker)
            .context("Failed to add WASI to linker")?;

        // Apply custom host linker configuration (e.g. registering host imports).
        if let Some(linker_init) = self.host_linker_init {
            linker_init(&mut linker).context("Failed to configure host linker")?;
        }

        // Clone the component for type introspection
        // Component is reference-counted internally, so this is cheap
        let component = self.image.component().clone();

        let guest_instance = if let Some(initializer) = self.guest_initializer {
            let ctx = GuestHandlerContext::new(&mut linker, &mut store, &component);
            initializer(ctx)?
        } else {
            return Err(anyhow::anyhow!(
                "Guest initializer is required. Use with_guest_initializer() to set it."
            ));
        };

        // Extract dynamic instance from guest_instance if available
        #[cfg(feature = "dynamic")]
        let dynamic_instance = guest_instance.get_dynamic_instance_ref().cloned();

        Ok(Container {
            store,
            guest: guest_instance,
            #[cfg(feature = "dynamic")]
            dynamic_instance,
            #[cfg(feature = "dynamic")]
            host_imports: None,
        })
    }
}

/// A Container represents a running instance of an Image
///
/// Similar to Docker containers, it maintains runtime state and can be started/stopped
pub struct Container<T: HostStateImpl = HostState> {
    store: Store<T>,
    guest: GuestInstance,

    /// Dynamic instance for runtime function invocation (duplicated from guest for easier access)
    #[cfg(feature = "dynamic")]
    dynamic_instance: Option<wasmtime::component::Instance>,

    /// Host import registry for dynamic host function invocation
    #[cfg(feature = "dynamic")]
    host_imports: Option<HostImportRegistry>,
}

impl Container {
    /// Create container builder from Image
    pub fn builder(image: Image) -> ContainerBuilder<HostState> {
        ContainerBuilder::new(image)
    }
}

impl<T: HostStateImpl> Container<T> {
    /// Get mutable reference to Store
    pub fn store_mut(&mut self) -> &mut Store<T> {
        &mut self.store
    }

    /// Get immutable reference to Store
    pub fn store(&self) -> &Store<T> {
        &self.store
    }

    /// Get reference to guest instance
    pub fn guest(&self) -> &GuestInstance {
        &self.guest
    }

    /// Get mutable reference to guest instance
    pub fn guest_mut(&mut self) -> &mut GuestInstance {
        &mut self.guest
    }

    /// Get mutable reference to host state
    pub fn host_state_mut(&mut self) -> &mut T {
        self.store.data_mut()
    }

    /// Get immutable reference to host state
    pub fn host_state(&self) -> &T {
        self.store.data()
    }

    /// Call a guest function by name with JSON payload
    ///
    /// This is a convenience method for dynamic invocation.
    /// Requires that the guest instance implements the appropriate interface.
    ///
    /// # Arguments
    /// * `function_name` - Name of the function to call
    /// * `json_payload` - JSON string containing function arguments
    ///
    /// # Returns
    /// JSON string containing the result
    ///
    /// # Example
    /// ```ignore
    /// let result = container.call_guest_json("process", r#"{"input":"hello"}"#)?;
    /// ```
    pub fn call_guest_json(&mut self, function_name: &str, json_payload: &str) -> Result<String> {
        // JSON invocation is superseded by the RON-based call_guest_raw_desc() which
        // preserves Rust type fidelity. This entry-point returns an error to guide
        // callers to the preferred API.
        anyhow::bail!(
            "JSON invocation is not supported. Use call_guest_raw_desc() instead with RON format for better Rust type compatibility. Function: {}, Payload: {}",
            function_name,
            json_payload
        )
    }

    /// Call a guest function by name with raw descriptor payload
    ///
    /// This is the preferred method for dynamic invocation using type descriptors at runtime.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// Uses RON format for serialization which provides better Rust type compatibility than JSON.
    ///
    /// # Arguments
    /// * `function_name` - Name of the function to call
    /// * `raw_desc_payload` - RON string containing function arguments (using type descriptors)
    ///
    /// # Returns
    /// RON string containing the result
    ///
    /// # Example
    /// ```ignore
    /// let result = container.call_guest_raw_desc("process", r#"Request { input: "hello", count: 42 }"#)?;
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn call_guest_raw_desc(
        &mut self,
        function_name: &str,
        raw_desc_payload: &str,
    ) -> Result<String> {
        use crate::dynamic::{ron_to_val, val_to_ron};
        use wasmtime::component::Val;

        // Get the function (direct field access avoids borrow checker issues)
        let instance = self
            .dynamic_instance
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Dynamic instance not available"))?;

        let func = instance
            .get_func(&mut self.store, function_name)
            .ok_or_else(|| anyhow::anyhow!("Export function not found: {}", function_name))?;

        // Get function type info
        let func_ty = func.ty(&self.store);
        let param_types: Vec<_> = func_ty.params().collect();
        let result_types: Vec<_> = func_ty.results().collect();

        // Convert raw descriptor → Val
        let mut args = Vec::new();

        if param_types.len() == 1 {
            // Single parameter - direct parsing
            // Extract just the type from the (name, type) tuple
            let param_type = &param_types[0].1;
            args.push(ron_to_val(raw_desc_payload, param_type)?);
        } else {
            // Multiple parameters - parse as sequence/array
            let ron_array = if raw_desc_payload.trim().starts_with('[') {
                raw_desc_payload.to_string()
            } else if raw_desc_payload.trim().starts_with('(') {
                // RON treats tuples differently, convert to array syntax
                raw_desc_payload.to_string()
            } else {
                format!("[{}]", raw_desc_payload)
            };

            use ron::Value as RonValue;
            let ron_value: RonValue = ron::from_str(&ron_array)?;

            if let RonValue::Seq(items) = ron_value {
                if items.len() != param_types.len() {
                    anyhow::bail!(
                        "Parameter count mismatch: expected {}, got {}",
                        param_types.len(),
                        items.len()
                    );
                }
                for (ron_val, (_param_name, param_type)) in
                    items.into_iter().zip(param_types.iter())
                {
                    args.push(ron_value_to_val(ron_val, param_type)?);
                }
            } else {
                anyhow::bail!(
                    "Invalid raw descriptor payload for function with multiple parameters"
                );
            }
        }

        // Call the function
        let mut results = vec![Val::Bool(false); result_types.len()];
        func.call(&mut self.store, &args, &mut results)
            .context("Function call failed")?;

        // Convert Val → raw descriptor (RON)
        let output_ron: Result<Vec<_>> = results.iter().map(val_to_ron).collect();
        let output_ron = output_ron.context("Failed to convert result to RON")?;

        // Format output based on return value count
        let output = match output_ron.len() {
            0 => "()".to_string(),
            1 => output_ron[0].clone(),
            _ => format!("({})", output_ron.join(", ")),
        };

        Ok(output)
    }

    /// Call a guest function by name with binary payload
    ///
    /// This is the high-performance path using canonical ABI directly.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// # Arguments
    /// * `function_name` - Name of the function to call
    /// * `args` - Arguments as Val types
    ///
    /// # Returns
    /// Results as Val types
    ///
    /// # Example
    /// ```ignore
    /// use wasmtime::component::Val;
    /// let args = vec![Val::String("hello".to_string()), Val::U32(42)];
    /// let results = container.call_guest_binary("process", &args)?;
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn call_guest_binary(
        &mut self,
        function_name: &str,
        args: &[wasmtime::component::Val],
    ) -> Result<Vec<wasmtime::component::Val>> {
        use wasmtime::component::Val;

        // Get the function (direct field access avoids borrow checker issues)
        let instance = self
            .dynamic_instance
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Dynamic instance not available"))?;

        let func = instance
            .get_func(&mut self.store, function_name)
            .ok_or_else(|| anyhow::anyhow!("Export function not found: {}", function_name))?;

        // Get function type info
        let func_ty = func.ty(&self.store);
        let num_results = func_ty.results().count();

        // Call the function
        let mut results = vec![Val::Bool(false); num_results];
        func.call(&mut self.store, args, &mut results)
            .context("Function call failed")?;

        Ok(results)
    }

    /// Set the host import registry
    ///
    /// # Arguments
    /// * `registry` - Host import registry to use
    #[cfg(feature = "dynamic")]
    pub fn with_host_import_registry(&mut self, registry: HostImportRegistry) {
        self.host_imports = Some(registry);
    }

    /// Get mutable reference to host import registry
    #[cfg(feature = "dynamic")]
    pub fn host_imports_mut(&mut self) -> Option<&mut HostImportRegistry> {
        self.host_imports.as_mut()
    }

    /// Call a host import function by name with raw descriptor payload
    ///
    /// This allows dynamically calling host functions that the WASM component imports.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// # Arguments
    /// * `function_name` - Name of the host import function to call
    /// * `raw_desc_payload` - RON string containing function arguments
    ///
    /// # Returns
    /// RON string containing the result
    ///
    /// # Example
    /// ```ignore
    /// let result = container.call_host_import_raw_desc("log", r#"LogMessage { level: "info", msg: "hello" }"#)?;
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn call_host_import_raw_desc(
        &mut self,
        function_name: &str,
        raw_desc_payload: &str,
    ) -> Result<String> {
        use crate::dynamic::{ron_to_val, val_to_ron};

        let registry = self
            .host_imports
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Host import registry not initialized"))?;

        // Get function signature
        let (params, _results) = registry
            .get_signature(function_name)
            .ok_or_else(|| anyhow::anyhow!("Host import not found: {}", function_name))?;

        // Convert raw descriptor → Val
        let mut args = Vec::new();
        if params.len() == 1 {
            args.push(ron_to_val(raw_desc_payload, &params[0])?);
        } else {
            // Multiple parameters - parse as sequence/array
            let payload = raw_desc_payload.trim();
            let ron_array = if payload.starts_with('[') || payload.starts_with('(') {
                raw_desc_payload.to_string()
            } else {
                format!("[{}]", raw_desc_payload)
            };

            use ron::Value as RonValue;
            let ron_value: RonValue = ron::from_str(&ron_array)?;

            if let RonValue::Seq(items) = ron_value {
                if items.len() != params.len() {
                    anyhow::bail!(
                        "Parameter count mismatch: expected {}, got {}",
                        params.len(),
                        items.len()
                    );
                }
                for (ron_val, param_type) in items.into_iter().zip(params.iter()) {
                    args.push(ron_value_to_val(ron_val, param_type)?);
                }
            } else {
                anyhow::bail!(
                    "Invalid raw descriptor payload for function with multiple parameters"
                );
            }
        }

        // Call the function
        let result_vals = registry.call(function_name, &args)?;

        // Convert Val → raw descriptor (RON)
        let output_ron: Result<Vec<_>> = result_vals.iter().map(val_to_ron).collect();
        let output_ron = output_ron.context("Failed to convert result to RON")?;
        let output = match output_ron.len() {
            0 => "()".to_string(),
            1 => output_ron[0].clone(),
            _ => format!("({})", output_ron.join(", ")),
        };

        Ok(output)
    }

    /// List all guest export functions
    ///
    /// Returns information about all functions exported by the WASM component.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// # Returns
    /// Vector of export information including function names and types
    ///
    /// # Example
    /// ```ignore
    /// let exports = container.list_guest_exports()?;
    /// for export in exports {
    ///     println!("Function: {}", export.name);
    ///     println!("  Params: {:?}", export.params);
    ///     println!("  Results: {:?}", export.results);
    /// }
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn list_guest_exports(&mut self) -> Result<Vec<ExportInfo>> {
        if let Some(instance) = &self.dynamic_instance {
            let mut exports = Vec::new();

            // Try to get common export function names
            // This is a pragmatic approach since we can't easily iterate all exports
            // without knowing their names beforehand
            let potential_exports = vec![
                "init",
                "process",
                "getname",
                "getversion",
                "getfeatures",
                "shutdown",
                "notify",
                "add",
                "sub",
                "mul",
                "div",
                "to-upper",
                "to-lower",
                "reverse",
                "length",
                "process-numbers",
                "transform",
            ];

            for export_name in potential_exports {
                // Try to get the function
                if let Some(func) = instance.get_func(&mut self.store, export_name) {
                    // Get function type information
                    let func_ty = func.ty(&self.store);
                    let mut params = Vec::new();
                    let mut results = Vec::new();

                    // Extract parameter types (they come as (name, type) tuples)
                    for (param_name, param_type) in func_ty.params() {
                        params.push((param_name.to_string(), param_type.clone()));
                    }

                    // Extract result types
                    for result_type in func_ty.results() {
                        results.push(result_type.clone());
                    }

                    exports.push(ExportInfo {
                        name: export_name.to_string(),
                        params,
                        results,
                    });
                }
            }

            Ok(exports)
        } else {
            // No dynamic instance available, return empty list
            Ok(Vec::new())
        }
    }

    /// List all host import functions
    ///
    /// Returns information about all registered host import functions.
    /// Requires the `dynamic` feature to be enabled.
    ///
    /// # Returns
    /// Vector of import information including function names and types
    ///
    /// # Example
    /// ```ignore
    /// if let Some(imports) = container.list_host_imports()? {
    ///     for import in imports {
    ///         println!("Function: {}", import.name);
    ///     }
    /// }
    /// ```
    #[cfg(feature = "dynamic")]
    pub fn list_host_imports(&self) -> Result<Vec<ImportInfo>> {
        if let Some(ref registry) = self.host_imports {
            let imports = registry.list_imports();
            imports
                .into_iter()
                .map(|name| {
                    let (params, results) = registry.get_signature(name).unwrap();
                    Ok(ImportInfo {
                        name: name.to_string(),
                        params,
                        results,
                    })
                })
                .collect()
        } else {
            Ok(Vec::new())
        }
    }
}

/// Export function information
#[derive(Debug, Clone)]
pub struct ExportInfo {
    pub name: String,
    pub params: Vec<(String, wasmtime::component::Type)>,
    pub results: Vec<wasmtime::component::Type>,
}

/// Import function information
#[derive(Debug, Clone)]
pub struct ImportInfo {
    pub name: String,
    pub params: Vec<wasmtime::component::Type>,
    pub results: Vec<wasmtime::component::Type>,
}

/// Helper: RON Value to Val (for use in Container)
#[cfg(feature = "dynamic")]
fn ron_value_to_val(
    ron_value: ron::Value,
    target_type: &wasmtime::component::Type,
) -> Result<wasmtime::component::Val> {
    use crate::dynamic::ron_to_val;
    // Convert ron::Value to RON string, then use ron_to_val
    let ron_str = ron::to_string(&ron_value)?;
    ron_to_val(&ron_str, target_type)
}

impl<T: HostStateImpl> std::fmt::Debug for Container<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Container").finish()
    }
}