client

package module
v0.4.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2026 License: MIT Imports: 16 Imported by: 0

README ΒΆ

tinywasm Client

Project Badges

Intelligent WebAssembly compilation manager for Go with automatic project detection and a 3-mode compiler system.

πŸš€ Features

  • 3-Mode Compiler System:
    • L (Large): Standard Go compiler for fast development.
    • M (Medium): TinyGo with debug optimizations (-opt=1).
    • S (Small): TinyGo with size optimizations (-opt=z).
  • Interactive Integration: Implements DevTUI FieldHandler for real-time mode switching.
  • Smart Detection: Automatically identifies WASM projects and compiler requirements.
  • Developer Experience: Auto-configures VS Code with appropriate GOOS/GOARCH settings.
  • Flexible Output: Support for in-memory serving or physical file output.

πŸ›  Usage

Basic Initialization

client uses a combination of a Config struct for core paths and public setter methods for advanced configuration.

// 1. Create base configuration
cfg := client.NewConfig()
cfg.SourceDir = "web"
cfg.OutputDir = "web/public"

// 2. Initialize client
twc := client.New(cfg)

// 3. Fine-tune configuration via setters
twc.SetAppRootDir("/path/to/project")
twc.SetMainInputFile("app.go")      // default: "client.go"
twc.SetOutputName("app")            // default: "client"
twc.SetBuildShortcuts("L", "M", "S") // customize mode triggers

// (Optional) Enable physical wasm_exec.js output for file watchers/debug
twc.SetWasmExecJsOutputDir("web/theme/js")
Mode Switching (DevTUI Integration)

Switching modes is asynchronous and reports progress via a channel:

progress := make(chan string)
go func() {
    for p := range progress {
        fmt.Println("Status:", p)
    }
}()

// Switch to Small (Production) mode
twc.Change("S", progress)

πŸ— Core Concepts

Dual Output Architecture

client handles two types of outputs to optimize the build pipeline:

  1. WASM Binary (via OutputDir): The final WebAssembly file loaded by the browser.
  2. JavaScript Runtime: Mode-specific wasm_exec.js.
    • Dynamic: Recommended to use tw.JavascriptForInitializing() to get the content directly for embedding or serving.
    • Disk-based: Use tw.SetWasmExecJsOutputDir() if you need a physical file for external bundlers or mode-transparency for other tools.
Serving Strategies

The library automatically selects the best way to compile and serve the WASM binary:

  • In-Memory: Compiles directly to a buffer (fastest for development).
  • External: Compiles and serves from disk (useful for static integration).

Logic details are available in strategies.go.

VS Code Integration

On initialization, client can auto-create .vscode/settings.json to ensure gopls correctly recognizes the WASM environment:

{"gopls": {"env": {"GOOS": "js", "GOARCH": "wasm"}}}

βš™οΈ Configuration

client follows a hybrid configuration approach:

  • Config Struct: Used for shared dependencies (Store, Logger) and relative directory structures (SourceDir, OutputDir). See config.go.
  • Public Setters: Used for project-specific overrides (AppRootDir, MainInputFile, OutputName) and build behavioral changes. These setters are reactive and re-initialize internal state automatically.

πŸ“‹ Requirements

  • Go 1.21+
  • TinyGo (optional, required for Medium/Small modes)

Contributing

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const StoreKeySizeMode = "wasmsize_mode"

StoreKeySizeMode is the key used to store the current compiler mode in the Database

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type BuildStorage ΒΆ

type BuildStorage interface {
	// Compile performs the compilation.
	// For Memory: compiles to buffer.
	// For Disk: compiles to disk.
	Compile() error

	// RegisterRoutes registers the WASM file handler on the mux.
	RegisterRoutes(mux *http.ServeMux)

	// Name returns the storage name for logging/debugging
	Name() string
}

BuildStorage defines the behavior for compiling and serving the WASM client.

type Config ΒΆ

type Config struct {
	// SourceDir specifies the directory containing the Go source for the webclient (relative to AppRootDir).
	// e.g., "web"
	SourceDir string

	// OutputDir specifies the directory for WASM and related assets (relative to AppRootDir).
	// e.g., "web/public"
	OutputDir string

	// AssetsURLPrefix is an optional URL prefix/folder for serving the WASM file.
	// e.g. "assets" -> serves at "/assets/client.wasm"
	// default: "" -> serves at "/client.wasm"
	AssetsURLPrefix string

	// gobuild integration fields
	Callback           func(error)     // Optional callback for async compilation
	CompilingArguments func() []string // Build arguments for compilation (e.g., ldflags)

	Database         KeyValueDataBase // Key-Value store for state persistence
	OnWasmExecChange func()           // Callback for wasm_exec.js changes
}

Config holds configuration for WASM compilation

func NewConfig ΒΆ

func NewConfig() *Config

NewConfig creates a WasmClient Config with sensible defaults

type KeyValueDataBase ΒΆ

type KeyValueDataBase interface {
	Get(key string) (string, error)
	Set(key, value string) error
}

KeyValueDataBase defines the interface for a key-value storage system used to persist the compiler state (e.g. current mode).

type ParameterMetadata ΒΆ

type ParameterMetadata struct {
	Name        string
	Description string
	Required    bool
	Type        string
	EnumValues  []string
	Default     any
}

ParameterMetadata describes a tool parameter

type ToolExecutor ΒΆ

type ToolExecutor func(args map[string]any)

ToolExecutor defines how a tool should be executed

type ToolMetadata ΒΆ

type ToolMetadata struct {
	Name        string
	Description string
	Parameters  []ParameterMetadata
	Execute     ToolExecutor // Execution function
}

ToolMetadata provides MCP tool configuration metadata This is the standard interface that mcpserve expects

type WasmClient ΒΆ

type WasmClient struct {
	*Config
	// contains filtered or unexported fields
}

WasmClient provides WebAssembly compilation capabilities with 3-mode compiler selection

func New ΒΆ

func New(c *Config) *WasmClient

New creates a new WasmClient instance with the provided configuration

func (*WasmClient) Change ΒΆ

func (w *WasmClient) Change(newValue string)

Change updates the compiler mode for WasmClient. Implements the HandlerEdit interface: Change(newValue string)

func (*WasmClient) ClearJavaScriptCache ΒΆ

func (h *WasmClient) ClearJavaScriptCache()

ClearJavaScriptCache clears both cached JavaScript strings to force regeneration

func (*WasmClient) CreateDefaultWasmFileClientIfNotExist ΒΆ

func (t *WasmClient) CreateDefaultWasmFileClientIfNotExist() *WasmClient

CreateDefaultWasmFileClientIfNotExist creates a default WASM main.go file from the embedded markdown template It never overwrites an existing file and returns the WasmClient instance for method chaining.

func (*WasmClient) GetMCPToolsMetadata ΒΆ

func (w *WasmClient) GetMCPToolsMetadata() []ToolMetadata

GetMCPToolsMetadata returns metadata for all WasmClient MCP tools

func (*WasmClient) GetTinyGoVersion ΒΆ

func (t *WasmClient) GetTinyGoVersion() (string, error)

GetTinyGoVersion returns the installed TinyGo version

func (*WasmClient) GetWasmExecJsPathGo ΒΆ

func (w *WasmClient) GetWasmExecJsPathGo() (string, error)

GetWasmExecJsPathGo returns the path to Go's wasm_exec.js file

func (*WasmClient) GetWasmExecJsPathTinyGo ΒΆ

func (w *WasmClient) GetWasmExecJsPathTinyGo() (string, error)

GetWasmExecJsPathTinyGo returns the path to TinyGo's wasm_exec.js file

func (*WasmClient) JavascriptForInitializing ΒΆ

func (h *WasmClient) JavascriptForInitializing(customizations ...string) (js string, err error)

JavascriptForInitializing returns the JavaScript code needed to initialize WASM.

Parameters (variadic):

  • customizations[0]: Custom header string to prepend to wasm_exec.js content. If not provided, defaults to "// WasmClient: mode=<current_mode>\n"
  • customizations[1]: Custom footer string to append after wasm_exec.js content. If not provided, defaults to WebAssembly initialization code with fetch and instantiate.

Examples:

  • JavascriptForInitializing() - Uses default header and footer
  • JavascriptForInitializing("// Custom Header\n") - Custom header, default footer
  • JavascriptForInitializing("// Custom Header\n", "console.log('loaded');") - Both custom

func (*WasmClient) Label ΒΆ

func (w *WasmClient) Label() string

Label returns the field label for DevTUI display

func (*WasmClient) Logger ΒΆ

func (w *WasmClient) Logger(messages ...any)

func (*WasmClient) MainInputFileRelativePath ΒΆ

func (w *WasmClient) MainInputFileRelativePath() string

MainInputFileRelativePath returns the relative path to the main WASM input file (e.g. "main.wasm.go").

func (*WasmClient) MainOutputFileAbsolutePath ΒΆ

func (w *WasmClient) MainOutputFileAbsolutePath() string

MainOutputFileAbsolutePath returns the absolute path to the main WASM output file (e.g. "main.wasm").

func (*WasmClient) Name ΒΆ

func (w *WasmClient) Name() string

Name returns the name of the WASM project

func (*WasmClient) NewFileEvent ΒΆ

func (w *WasmClient) NewFileEvent(fileName, extension, filePath, event string) error

NewFileEvent handles file events for WASM compilation with automatic project detection fileName: name of the file (e.g., main.wasm.go) extension: file extension (e.g., .go) filePath: full path to the file (e.g., ./home/userName/ProjectName/web/public/main.wasm.go) event: type of file event (e.g., create, remove, write, rename)

func (*WasmClient) OutputRelativePath ΒΆ

func (w *WasmClient) OutputRelativePath() string

OutputRelativePath returns the RELATIVE path to the final output file eg: "deploy/edgeworker/app.wasm" (relative to AppRootDir) This is used by file watchers to identify output files that should be ignored. The returned path always uses forward slashes (/) for consistency across platforms.

func (*WasmClient) RecompileMainWasm ΒΆ

func (w *WasmClient) RecompileMainWasm() error

RecompileMainWasm recompiles the main WASM file using the current storage mode.

func (*WasmClient) RegisterRoutes ΒΆ

func (w *WasmClient) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers the WASM client file route on the provided mux. It delegates to the active storage.

func (*WasmClient) SetAppRootDir ΒΆ

func (w *WasmClient) SetAppRootDir(path string)

SetAppRootDir sets the application root directory (absolute).

func (*WasmClient) SetBuildOnDisk ΒΆ

func (w *WasmClient) SetBuildOnDisk(onDisk, compileNow bool)

SetBuildOnDisk switches between In-Memory and External (Disk) storage. When compileNow is true, compilation is triggered immediately after mode switch. When compileNow is false, compilation (and directory creation) is deferred until first explicit Compile() call.

func (*WasmClient) SetBuildShortcuts ΒΆ

func (w *WasmClient) SetBuildShortcuts(large, medium, small string)

SetBuildShortcuts sets the shortcuts for the three compilation modes. If an empty string is provided for a shortcut, it remains unchanged.

func (*WasmClient) SetEnableWasmExecJsOutput ΒΆ

func (w *WasmClient) SetEnableWasmExecJsOutput(enable bool)

SetEnableWasmExecJsOutput enables automatic creation of wasm_exec.js file.

func (*WasmClient) SetLog ΒΆ

func (w *WasmClient) SetLog(f func(message ...any))

func (*WasmClient) SetMainInputFile ΒΆ

func (w *WasmClient) SetMainInputFile(file string)

SetMainInputFile sets the main input file for WASM compilation (default: "client.go").

func (*WasmClient) SetOutputName ΒΆ

func (w *WasmClient) SetOutputName(name string)

SetOutputName sets the output name for WASM file (default: "client").

func (*WasmClient) SetShouldCreateIDEConfig ΒΆ

func (w *WasmClient) SetShouldCreateIDEConfig(f func() bool)

SetShouldCreateIDEConfig sets a function that determines if IDE configuration files (like .vscode) should be created.

func (*WasmClient) SetShouldGenerateDefaultFile ΒΆ

func (w *WasmClient) SetShouldGenerateDefaultFile(f func() bool)

SetShouldGenerateDefaultFile sets a function that determines if the default WASM client source file (usually client.go) should be created if it doesn't exist.

func (*WasmClient) SetWasmExecJsOutputDir ΒΆ

func (w *WasmClient) SetWasmExecJsOutputDir(path string)

SetWasmExecJsOutputDir sets the output directory for wasm_exec.js. This is primarily intended for tests/debug where physical file output is required. Setting a non-empty path will trigger a write/update of the wasm_exec.js file to that directory.

func (*WasmClient) Shortcuts ΒΆ

func (w *WasmClient) Shortcuts() []map[string]string

func (*WasmClient) ShouldCompileToWasm ΒΆ

func (w *WasmClient) ShouldCompileToWasm(fileName, filePath string) bool

ShouldCompileToWasm determines if a file should trigger WASM compilation

func (*WasmClient) SupportedExtensions ΒΆ

func (w *WasmClient) SupportedExtensions() []string

func (*WasmClient) TinyGoCompiler ΒΆ

func (w *WasmClient) TinyGoCompiler() bool

TinyGoCompiler returns if TinyGo compiler should be used (dynamic based on configuration)

func (*WasmClient) UnobservedFiles ΒΆ

func (w *WasmClient) UnobservedFiles() []string

UnobservedFiles returns files that should not be watched for changes e.g: main.wasm

func (*WasmClient) Value ΒΆ

func (w *WasmClient) Value() string

Value returns the current compiler mode shortcut (c, d, or p)

func (*WasmClient) VerifyTinyGoInstallation ΒΆ

func (t *WasmClient) VerifyTinyGoInstallation() error

VerifyTinyGoInstallation checks if TinyGo is properly installed

func (*WasmClient) VerifyTinyGoProjectCompatibility ΒΆ

func (w *WasmClient) VerifyTinyGoProjectCompatibility()

VerifyTinyGoProjectCompatibility checks if the project is compatible with TinyGo compilation

func (*WasmClient) VisualStudioCodeWasmEnvConfig ΒΆ

func (w *WasmClient) VisualStudioCodeWasmEnvConfig()

VisualStudioCodeWasmEnvConfig automatically creates and configures VS Code settings for WASM development. This method resolves the "could not import syscall/js" error by setting proper environment variables in .vscode/settings.json file. On Windows, the .vscode directory is made hidden for a cleaner project view. This configuration enables VS Code's Go extension to properly recognize WASM imports and provide accurate IntelliSense, error detection, and code completion for syscall/js and other WASM-specific packages.

func (*WasmClient) WasmExecJsOutputPath ΒΆ

func (w *WasmClient) WasmExecJsOutputPath() string

WasmExecJsOutputPath returns the output path for wasm_exec.js

func (*WasmClient) WasmProjectTinyGoJsUse ΒΆ

func (w *WasmClient) WasmProjectTinyGoJsUse(mode ...string) (isWasmProject bool, useTinyGo bool)

WasmProjectTinyGoJsUse returns dynamic state based on current configuration

Directories ΒΆ

Path Synopsis
benchmark
shared command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL