# moonrockz/moon-lander-plugins/guest

A MoonBit `Service` as a wasm plugin. The same service value runs as a MoonBit plugin in
a host, and as a module in [the wasm package](../wasm/README.mbt.md) of another host.
The package imports only the Extism kernel functions of the host and no
`moonbitlang/core/async`, so a module has no Moonrun import. It builds for wasm only.

## Build a module

1. Make a package with `supported_targets = "wasm"` and
   `pkgtype(kind: "foreign_library")` in its `moon.pkg`, and import this package and
   the package of the service.
2. Hold one `Guest` in a top-level value. The guest makes the service at its first
   call.
3. Export one function for each operation with `#export_name`. Only the functions of
   the package itself can be exports, so each one calls `Guest::serve`.
4. Build it with `moon build --target wasm --release`. The module is in
   `_build/wasm/release/build/<module>/<package>/<package>.wasm`.

This is the heartbeat module that the conformance suite of the repository loads in a
native host and in a js host. A program that runs on wasm cannot call `Guest::serve`
itself, because only an Extism host supplies its imports
([`tests/plugins-wasm-heartbeat`](https://github.com/moonrockz/moon-lander/tree/main/tests/plugins-wasm-heartbeat)):

```moonbit notest
///|
let guest : @plugins_guest.Guest = @plugins_guest.Guest::new(
  @conformance.heartbeat,
)

///|
#export_name("moonlander_describe")
pub fn moonlander_describe() -> Int32 {
  guest.serve(Describe)
}

///|
#export_name("moonlander_start")
pub fn moonlander_start() -> Int32 {
  guest.serve(Start)
}

///|
#export_name("moonlander_handle")
pub fn moonlander_handle() -> Int32 {
  guest.serve(Handle)
}

///|
#export_name("moonlander_tick")
pub fn moonlander_tick() -> Int32 {
  guest.serve(Tick)
}

///|
#export_name("moonlander_stop")
pub fn moonlander_stop() -> Int32 {
  guest.serve(Stop)
}
```

A release module of the heartbeat has about 49 KB. It imports `input_length`,
`input_load_u8`, `alloc`, `store_u8`, `output_set`, `error_set` and the five Extism log
functions from `extism:host/env`. It needs the SIMD feature of WebAssembly, which the
MoonBit core library uses, and both engines of the wasm package have it.

The service writes its log entries to the Extism log of the host, and a failure to make
the service fails each call with the text of the error.
