extism / js-pdk

Write Extism plugins in JavaScript & TypeScript
42 stars 16 forks source link

Experimental Host Function Support (and rc4 release) #39

Closed bhelx closed 5 months ago

bhelx commented 5 months ago

This builds on my last PR and adds support for Host Functions. Currently the limitation is that host functions must have 1 i64 ptr param and 1 i64 ptr result. We enforce this through validation of the typescript interface file.

To enable host functions you just need to declare another interface extism:host/user:


declare module 'main' {
  export function greet(): I32;
}

declare module 'extism:host' {
  interface user {
    myHostFunction1(ptr: I64): I64;
    myHostFunction2(ptr: i64): i64;
  }
}

These needs to have this signature for now. We will work on making different function arities work next.

To use these you need to use Host.getFunctions():

const { myHostFunction1, myHostFunction2 } = Host.getFunctions()

Calling them is a similar process to other PDKs. You need to manage the memory with the Memory object and pass across an offset as the i64 ptr. Using the return value means dereferencing the returned i64 ptr from Memory.

  let msg = "Hello from js 1"
  let mem = Memory.fromString(msg)
  let offset = myHostFunction1(mem.offset)
  let response = Memory.find(offset).readString()
  if (response != "myHostFunction1: " + msg) {
    throw Error(`wrong message came back from myHostFunction1: ${response}`)
  }

See example in examples/host_funcs

bhelx commented 5 months ago

Going to merge and get rc4 out now. Will be back next week with follow ups!