github.com/tetratelabs/wazero@v1.2.1/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/tetratelabs/wazero"
     9  	"github.com/tetratelabs/wazero/internal/gojs"
    10  	"github.com/tetratelabs/wazero/internal/gojs/config"
    11  )
    12  
    13  func RunAndReturnState(
    14  	ctx context.Context,
    15  	r wazero.Runtime,
    16  	compiled wazero.CompiledModule,
    17  	moduleConfig wazero.ModuleConfig,
    18  	config *config.Config,
    19  ) (*gojs.State, error) {
    20  	if err := config.Init(); err != nil {
    21  		return nil, err
    22  	}
    23  
    24  	// Instantiate the module compiled by go, noting it has no init function.
    25  	mod, err := r.InstantiateModule(ctx, compiled, moduleConfig)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	defer mod.Close(ctx)
    30  
    31  	// Extract the args and env from the module Config and write it to memory.
    32  	argc, argv, err := gojs.WriteArgsAndEnviron(mod)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	// Create host-side state for JavaScript values and events.
    38  	s := gojs.NewState(config)
    39  	ctx = context.WithValue(ctx, gojs.StateKey{}, s)
    40  
    41  	// Invoke the run function.
    42  	_, err = mod.ExportedFunction("run").Call(ctx, uint64(argc), uint64(argv))
    43  	return s, err
    44  }