tinywasm

package module
v0.0.41 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2025 License: MIT Imports: 11 Imported by: 1

README

tinywasm

Project Badges

Go package for intelligent WebAssembly compilation with automatic file detection and 3-mode compiler system.

Features

  • 3-Mode Compiler System: Coding ("c"), Debug ("d"), Production ("p")
  • DevTUI Integration: FieldHandler interface for interactive mode switching
  • Smart file detection via prefixes (frontend/backend separation)
  • Triple compiler support: Go standard (fast dev), TinyGo debug (-opt=1), TinyGo production (-opt=z)
  • VS Code auto-configuration for WASM development
  • Single output: All files → main.wasm

Quick Start

// Basic usage
config := tinywasm.NewConfig() // Pre-configured with defaults
config.WebFilesRootRelative = "web"
config.WebFilesSubRelative = "public"

tw := tinywasm.New(config)
tw.NewFileEvent("web/main.wasm.go", ".go", "web/main.wasm.go", "write")

// DevTUI Integration - 3 Mode System
fmt.Println("Current mode:", tw.Value())    // "c" (coding)
msg, err := tw.Change("d")                  // Switch to debug mode
fmt.Println("Status:", msg)                 // "Switching to debugging mode"

// Advanced configuration
config := &tinywasm.Config{
    WebFilesRootRelative: "web",
    WebFilesSubRelative:  "public",
    CodingShortcut:      "c",  // Customizable shortcuts
    DebuggingShortcut:   "d",
    ProductionShortcut:  "p",
}

DevTUI FieldHandler Interface

TinyWasm implements the DevTUI FieldHandler interface for interactive development:

// DevTUI Integration
label := tw.Label()           // "Compiler Mode"
current := tw.Value()         // Current mode shortcut ("c", "d", "p")
canEdit := tw.Editable()      // true
timeout := tw.Timeout()       // 0 (no timeout)

// Interactive mode change with validation
msg, err := tw.Change("d")
if err != nil {
    // Handle validation errors (invalid mode, missing TinyGo, etc.)
}
// msg contains success message or warning if auto-compilation fails

VS Code Integration

Auto-creates .vscode/settings.json with WASM environment:

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

API

Core:

  • New(config *Config) *TinyWasm
  • NewConfig() *Config - Pre-configured with sensible defaults
  • NewFileEvent(fileName, ext, path, event string) error
  • ShouldCompileToWasm(fileName, path string) bool

DevTUI FieldHandler Interface:

  • Label() string - Returns "Compiler Mode"
  • Value() string - Current mode shortcut ("c", "d", "p")
  • Editable() bool - Returns true (field is editable)
  • Change(newValue any) (string, error) - Switch compiler mode with validation
  • Timeout() time.Duration - Returns 0 (no timeout)

Legacy Compiler Methods (deprecated):

  • TinyGoCompiler() bool - Use Value() instead
  • SetTinyGoCompiler(bool) error - Use Change() instead
  • VerifyTinyGoInstallation() error

Utils:

  • MainInputFileRelativePath() string
  • UnobservedFiles() []string
  • JavascriptForInitializing() (string, error)

Config

type Config struct {
	WebFilesRootRelative string    // root web folder (relative) eg: "web"
	WebFilesSubRelative  string    // subfolder under root (relative) eg: "public"
	Logger               func(message ...any) // For logging output to external systems (e.g., TUI, console)
	// NOTE: `TinyGoCompiler` was removed from the public `Config` to avoid
	// confusion. The compiler selection is controlled at runtime via the
	// TinyWasm instance. Use `tw.Change("c"|"d"|"p")` to switch modes and
	// `tw.Value()` to inspect the current mode. The internal boolean
	// `tinyGoCompiler` remains a private implementation detail.

	// NEW: Shortcut configuration (default: "c", "d", "p")
	CodingShortcut     string // coding "c" compile fast with go
	DebuggingShortcut  string // debugging "d" compile with tinygo debug
	ProductionShortcut string // production "p" compile with tinygo minimal binary size

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

}

// Pre-configured constructor (recommended)
func NewConfig() *Config

Mode Switching

tw.Change("p")  // production mode with TinyGo -opt=z
tw.Change("d")  // debug mode with TinyGo -opt=1
tw.Change("c")  // coding mode with Go standard

Requirements

  • Go 1.20+
  • TinyGo (optional, required for debug/production modes)
  • DevTUI (optional, for interactive development)

Migration Guide

From TinyWasm v1.x:

Old API New API Notes
SetTinyGoCompiler(true) Change("p") Production mode
SetTinyGoCompiler(false) Change("c") Coding mode
TinyGoCompiler() Value() == "p" || Value() == "d" Check if using TinyGo
config.Log config.Writer Field renamed

Benefits:

  • 🎯 3 optimized modes instead of binary choice
  • 🔧 DevTUI integration for interactive development
  • 📦 Smaller debug builds with TinyGo -opt=1
  • Auto-recompilation on mode switch
  • 🛠️ Better error handling with validation

Contributing

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config added in v0.0.7

type Config struct {

	// AppRootDir specifies the application root directory (absolute).
	// e.g., "/home/user/project". If empty, defaults to "." to preserve existing behavior.
	AppRootDir                  string
	WebFilesRootRelative        string // root web folder (relative) eg: "web"
	WebFilesSubRelative         string // subfolder under root (relative) eg: "public"
	WebFilesSubRelativeJsOutput string // output path for js files (relative) eg: "theme/js"
	Logger                      func(message ...any)

	// NEW: Shortcut configuration (default: "c", "d", "p")
	CodingShortcut     string // coding "c" compile fast with go
	DebuggingShortcut  string // debugging "d" compile with tinygo debug
	ProductionShortcut string // production "p" compile with tinygo minimal binary size

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

Config holds configuration for WASM compilation

func NewConfig added in v0.0.11

func NewConfig() *Config

NewConfig creates a TinyWasm Config with sensible defaults

type TinyWasm

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

TinyWasm provides WebAssembly compilation capabilities with 3-mode compiler selection

func New

func New(c *Config) *TinyWasm

New creates a new TinyWasm instance with the provided configuration Timeout is set to 40 seconds maximum as TinyGo compilation can be slow Default values: mainInputFile="main.wasm.go"

func (*TinyWasm) Change added in v0.0.11

func (w *TinyWasm) Change(newValue string, progress func(msgs ...any))

Change updates the compiler mode for TinyWasm and reports progress via the provided callback. Implements the HandlerEdit interface: Change(newValue string, progress func(msgs ...any))

func (*TinyWasm) ClearJavaScriptCache added in v0.0.32

func (h *TinyWasm) ClearJavaScriptCache()

ClearJavaScriptCache clears both cached JavaScript strings to force regeneration

func (*TinyWasm) GetTinyGoVersion

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

GetTinyGoVersion returns the installed TinyGo version

func (*TinyWasm) GetWasmExecJsPathGo added in v0.0.32

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

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

func (*TinyWasm) GetWasmExecJsPathTinyGo added in v0.0.32

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

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

func (*TinyWasm) Label added in v0.0.11

func (w *TinyWasm) Label() string

Label returns the field label for DevTUI display

func (*TinyWasm) MainInputFileRelativePath added in v0.0.26

func (w *TinyWasm) MainInputFileRelativePath() string

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

func (*TinyWasm) MainOutputFileAbsolutePath added in v0.0.32

func (w *TinyWasm) MainOutputFileAbsolutePath() string

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

func (*TinyWasm) Name added in v0.0.10

func (w *TinyWasm) Name() string

Name returns the name of the WASM project

func (*TinyWasm) NewFileEvent

func (w *TinyWasm) 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 (*TinyWasm) Shortcuts added in v0.0.41

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

func (*TinyWasm) ShouldCompileToWasm added in v0.0.4

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

ShouldCompileToWasm determines if a file should trigger WASM compilation

func (*TinyWasm) SupportedExtensions added in v0.0.32

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

func (*TinyWasm) TinyGoCompiler

func (w *TinyWasm) TinyGoCompiler() bool

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

func (*TinyWasm) UnobservedFiles

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

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

func (*TinyWasm) Value added in v0.0.11

func (w *TinyWasm) Value() string

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

func (*TinyWasm) VerifyTinyGoInstallation

func (t *TinyWasm) VerifyTinyGoInstallation() error

VerifyTinyGoInstallation checks if TinyGo is properly installed

func (*TinyWasm) VerifyTinyGoProjectCompatibility

func (w *TinyWasm) VerifyTinyGoProjectCompatibility()

VerifyTinyGoProjectCompatibility checks if the project is compatible with TinyGo compilation

func (*TinyWasm) VisualStudioCodeWasmEnvConfig added in v0.0.7

func (w *TinyWasm) 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 (*TinyWasm) WasmProjectTinyGoJsUse

func (w *TinyWasm) WasmProjectTinyGoJsUse() (bool, 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