main.go raw

   1  //go:build js && wasm
   2  
   3  // Package main provides the WASM entry point for the WasmDB database.
   4  // It initializes the IndexedDB-backed Nostr event store and exposes
   5  // the database API to JavaScript via the global `wasmdb` object.
   6  //
   7  // Build with:
   8  //   GOOS=js GOARCH=wasm go build -o wasmdb.wasm ./cmd/wasmdb
   9  //
  10  // Usage in JavaScript:
  11  //   // Load wasm_exec.js first (Go WASM runtime)
  12  //   const go = new Go();
  13  //   const result = await WebAssembly.instantiateStreaming(fetch('wasmdb.wasm'), go.importObject);
  14  //   go.run(result.instance);
  15  //
  16  //   // Wait for ready
  17  //   while (!wasmdb.isReady()) {
  18  //     await new Promise(resolve => setTimeout(resolve, 100));
  19  //   }
  20  //
  21  //   // Use the API
  22  //   await wasmdb.saveEvent(JSON.stringify(event));
  23  //   const events = await wasmdb.queryEvents(JSON.stringify({kinds: [1], limit: 10}));
  24  package main
  25  
  26  import (
  27  	"context"
  28  	"fmt"
  29  
  30  	"next.orly.dev/pkg/database"
  31  	"next.orly.dev/pkg/wasmdb"
  32  )
  33  
  34  func main() {
  35  	// Create context for the database
  36  	ctx, cancel := context.WithCancel(context.Background())
  37  
  38  	// Initialize the database with default config
  39  	cfg := &database.DatabaseConfig{
  40  		DataDir:  ".",
  41  		LogLevel: "info",
  42  	}
  43  
  44  	db, err := wasmdb.NewWithConfig(ctx, cancel, cfg)
  45  	if err != nil {
  46  		fmt.Printf("Failed to initialize WasmDB: %v\n", err)
  47  		return
  48  	}
  49  
  50  	// Register the JavaScript bridge
  51  	wasmdb.RegisterJSBridge(db, ctx, cancel)
  52  
  53  	fmt.Println("WasmDB initialized and JavaScript bridge registered")
  54  
  55  	// Wait for the database to be ready
  56  	<-db.Ready()
  57  	fmt.Println("WasmDB ready to serve requests")
  58  
  59  	// Keep the WASM module running
  60  	// This is necessary because Go's main() returning would terminate the WASM instance
  61  	select {}
  62  }
  63