wasmhost.go raw

   1  package builder
   2  
   3  import (
   4  	"errors"
   5  	"fmt"
   6  	"os"
   7  	"path/filepath"
   8  	"strings"
   9  )
  10  
  11  // emitWasmHost stages the page-side half of a wasm bundle beside the module.
  12  //
  13  // A Moxie wasm module is half an application. The other half is the JS runtime
  14  // that instantiates it in a Worker, answers its DOM calls through the relay and
  15  // dispatches the callbacks it registered - jsruntime/ in the moxie checkout,
  16  // one copy, versioned with the compiler that built the module. The build copies
  17  // it to $runtime/ next to the .wasm and writes the bundle's page bootstrap,
  18  // <name>-wasm-host.mjs, so an app has no host files of its own to keep in sync
  19  // with the framework.
  20  //
  21  // Stage4 writes the same files from the same directory (emitWasmHost in
  22  // _mxc_stage4/main.mx): a bundle built by either compiler has to be loadable by
  23  // the same page.
  24  func emitWasmHost(root, outpath string) error {
  25  	if outpath == "" || outpath == "/dev/null" {
  26  		return nil
  27  	}
  28  	if root == "" {
  29  		return errors.New("MOXIEROOT is not set, so the JS runtime to stage beside the module cannot be found")
  30  	}
  31  	jsdir := filepath.Join(root, "jsruntime")
  32  	entries, err := os.ReadDir(jsdir)
  33  	if err != nil {
  34  		return fmt.Errorf("jsruntime: %w", err)
  35  	}
  36  	dir := filepath.Dir(outpath)
  37  	runtimeDir := filepath.Join(dir, "$runtime")
  38  	if err := os.MkdirAll(runtimeDir, 0o755); err != nil {
  39  		return err
  40  	}
  41  	staged := 0
  42  	for _, e := range entries {
  43  		if e.IsDir() || !strings.HasSuffix(e.Name(), ".mjs") {
  44  			continue
  45  		}
  46  		data, err := os.ReadFile(filepath.Join(jsdir, e.Name()))
  47  		if err != nil {
  48  			return err
  49  		}
  50  		if err := os.WriteFile(filepath.Join(runtimeDir, e.Name()), data, 0o644); err != nil {
  51  			return err
  52  		}
  53  		staged++
  54  	}
  55  	if staged == 0 {
  56  		return fmt.Errorf("no JS runtime modules under %s", jsdir)
  57  	}
  58  	// The module keeps the name it was given - an -o without .wasm is a real
  59  	// file - while the bootstrap's own name drops the extension.
  60  	moduleName := filepath.Base(outpath)
  61  	stem := strings.TrimSuffix(moduleName, ".wasm")
  62  	host := filepath.Join(dir, stem+"-wasm-host.mjs")
  63  	if err := os.WriteFile(host, []byte(wasmHostModule(stem, moduleName)), 0o644); err != nil {
  64  		return err
  65  	}
  66  	// The service worker's half: the same host file for every app, plus the
  67  	// registration glue, which finds the bundle's own directory at runtime.
  68  	swDir := filepath.Join(dir, "$sw")
  69  	if err := os.MkdirAll(swDir, 0o755); err != nil {
  70  		return err
  71  	}
  72  	swHost, err := os.ReadFile(filepath.Join(jsdir, "sw-host.mjs"))
  73  	if err != nil {
  74  		return fmt.Errorf("jsruntime/sw-host.mjs: %w", err)
  75  	}
  76  	if err := os.WriteFile(filepath.Join(swDir, "wasm-host-sw.mjs"), swHost, 0o644); err != nil {
  77  		return err
  78  	}
  79  	swReg, err := os.ReadFile(filepath.Join(jsdir, "sw-register.js"))
  80  	if err != nil {
  81  		return fmt.Errorf("jsruntime/sw-register.js: %w", err)
  82  	}
  83  	if err := os.WriteFile(filepath.Join(dir, "sw-register.js"), swReg, 0o644); err != nil {
  84  		return err
  85  	}
  86  	fmt.Fprintf(os.Stderr, "  host %s ($runtime: %d modules, $sw + sw-register.js)\n", host, staged)
  87  	return nil
  88  }
  89  
  90  // wasmHostModule is the page bootstrap for one bundle. It is deliberately
  91  // small: everything a page needs beyond it - the loader, the Worker host, the
  92  // DOM relay - is in $runtime/ and is the same code for every app. stem names
  93  // the bootstrap itself, moduleName is the file the linker wrote.
  94  func wasmHostModule(stem, moduleName string) string {
  95  	return "// " + stem + "-wasm-host.mjs - written by `moxie build -target wasm`.\n" +
  96  		"//\n" +
  97  		"// The page-side half of a Moxie wasm bundle. The module runs in a Worker\n" +
  98  		"// (channel receives block in Atomics.wait, which the page thread forbids)\n" +
  99  		"// and the page answers its DOM calls through $runtime/relay.mjs, so a page\n" +
 100  		"// only has to import this file and start it:\n" +
 101  		"//\n" +
 102  		"//   import { start } from './" + stem + "-wasm-host.mjs';\n" +
 103  		"//   await start();\n" +
 104  		"\n" +
 105  		"import { load } from './$runtime/loader.mjs';\n" +
 106  		"\n" +
 107  		"export const wasm = new URL('./" + moduleName + "', import.meta.url).href;\n" +
 108  		"\n" +
 109  		"export function start() { return load(wasm); }\n" +
 110  		"\n" +
 111  		"export default start;\n"
 112  }
 113