# `Wasmex.Components.ComponentServer`

A GenServer wrapper for WebAssembly components. This module provides a macro to easily
create GenServer-based components with wrapper functions for the exports in the WIT definition.

## Usage

To use this module, you need to:
1. Create a WIT file defining your component's interface
2. Create a module that uses ComponentServer with the path to your WIT file
3. Use the generated functions to interact with your WebAssembly component

## Basic Example

Given a WIT file `greeter.wit` with the following content:

```wit
package example:greeter;

world greeter {
  export greet: func(who: string) -> string;
  export multi-greet: func(who: string, times: u16) -> list<string>;
}
```

You can create a GenServer wrapper like this:

```elixir
defmodule MyApp.Greeter do
  use Wasmex.Components.ComponentServer,
    wit: "path/to/greeter.wit"
end
```

This will automatically generate the following functions:

```elixir
# Start the component server
iex> {:ok, pid} = MyApp.Greeter.start_link(path: "path/to/greeter.wasm")

# Generated function wrappers:
iex> MyApp.Greeter.greet(pid, "World")  # Returns: {:ok, "Hello, World!"}
iex> MyApp.Greeter.multi_greet(pid, "World", 2) # Returns: {:ok, ["Hello, World!", "Hello, World!"]}
```

## Imports Example

When your WebAssembly component imports functions, you can provide them using the `:imports` option.
For example, given a WIT file `logger.wit`:

```wit
package example:logger;

world logger {
  import log: func(message: string);
  import get-timestamp: func() -> u64;

  export log-with-timestamp: func(message: string);
}
```

You can implement the imported functions like this:

```elixir
defmodule MyApp.Logger do
  use Wasmex.Components.ComponentServer,
    wit: "path/to/logger.wit",
    imports: %{
      "log" => {:fn, fn message ->
        IO.puts(message)
      end},
      "get-timestamp" => {:fn, fn ->
        System.system_time(:second)
      end}
    }
end
```

# Usage:
```elixir
iex> {:ok, pid} = MyApp.Logger.start_link(path: "path/to/logger.wasm")
iex> MyApp.Logger.log_with_timestamp(pid, "Hello from Wasm!")
```

Import functions must return the types defined in the WIT file. An incompatible
return value traps the component call and is returned as an error.

## Options

* `:wit` - Path to the WIT file defining the component's interface
* `:convert_field_names` - All function calls recursively convert map field names
in arguments from underscore case to kebab-case
and vice versa for return values. Defaults to true.
* `:imports` - A map of import function implementations that the component requires, where each key
  is the function name as defined in the WIT file and the value is the implementing function

---

*Consult [api-reference.md](api-reference.md) for complete listing*
