github.com/bananabytelabs/wazero@v0.0.0-20240105073314-54b22a776da8/internal/gojs/run/gojs.go (about)

     1  // Package run exists to avoid dependency cycles when keeping most of gojs
     2  // code internal.
     3  package run
     4  
     5  import (
     6  	"context"
     7  
     8  	"github.com/bananabytelabs/wazero"
     9  	"github.com/bananabytelabs/wazero/internal/gojs"
    10  	"github.com/bananabytelabs/wazero/internal/gojs/config"
    11  	"github.com/bananabytelabs/wazero/sys"
    12  )
    13  
    14  func Run(ctx context.Context, r wazero.Runtime, compiled wazero.CompiledModule, moduleConfig wazero.ModuleConfig, config *config.Config) error {
    15  	if err := config.Init(); err != nil {
    16  		return err
    17  	}
    18  
    19  	// Instantiate the module compiled by go, noting it has no init function.
    20  	mod, err := r.InstantiateModule(ctx, compiled, moduleConfig)
    21  	if err != nil {
    22  		return err
    23  	}
    24  	defer mod.Close(ctx)
    25  
    26  	// Extract the args and env from the module Config and write it to memory.
    27  	argc, argv, err := gojs.WriteArgsAndEnviron(mod)
    28  	if err != nil {
    29  		return err
    30  	}
    31  
    32  	// Create host-side state for JavaScript values and events.
    33  	ctx = context.WithValue(ctx, gojs.StateKey{}, gojs.NewState(config))
    34  
    35  	// Invoke the run function.
    36  	_, err = mod.ExportedFunction("run").Call(ctx, uint64(argc), uint64(argv))
    37  	if se, ok := err.(*sys.ExitError); ok {
    38  		if se.ExitCode() == 0 { // Don't err on success.
    39  			err = nil
    40  		}
    41  	}
    42  	return err
    43  }