witgo

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: GPL-3.0 Imports: 28 Imported by: 0

README

art

witgo генерирует типизированный Go API из WIT-контракта для обеих сторон Component Model. Go-host может загружать WebAssembly Component-плагины, вызывать их exports и предоставлять host-функции, а guest-режим позволяет реализовать и собрать сам плагин на Go/TinyGo. Один и тот же WIT import может обслуживаться Go-кодом или другим зарегистрированным WebAssembly Component без изменения consumer-кода.

Статус: beta. Библиотека уже покрывает основной сценарий Component Model, строгую проверку контракта до запуска, version handshake с Rust bridge и end-to-end тесты для сложных типов. Перед production-использованием всё равно стоит прогнать свои контракты и плагины отдельными интеграционными тестами.

Требования

  • Go 1.18 или новее;
  • плагин в формате WebAssembly Component (.wasm), а не core Wasm module;
  • встроенный native bridge уже лежит в модуле для Linux, macOS и Windows на amd64 и arm64, отдельная установка при запуске не нужна.

Для написания Go guest-плагинов дополнительно нужны wit-bindgen-go, пакет go.bytecodealliance.org/cm и TinyGo с target wasip2. Они не нужны обычному host-приложению.

Parser, generator и generated packages также компилируются на остальных Go targets. Запуск Component зависит от native loader и Rust/Wasmtime bridge для выбранной платформы.

Установка

go get github.com/slavkiy/witgo

Быстрый старт

1. Опишите контракт в WIT

Например, wit/plugin.wit:

package example:plugins@1.0.0;

interface metadata {
    record info {
        name: string,
        version: string,
        description: string,
        author: string,
        license: string,
    }

    get: func() -> info;
}

interface host {
    process-string: func(value: string) -> string;
}

world plugin {
    import host;
    export metadata;
}

import host описывает функции, которые даёт приложение.

export metadata описывает функции, которые реализует плагин.

2. Сгенерируйте Go package

Создайте generate.go:

//go:build ignore

package main

import (
	"log"

	"github.com/slavkiy/witgo"
)

func main() {
	err := witgo.GeneratePackage(witgo.Config{
		Output:  "./internal/contract",
		Package: "contract",
	}, "./wit")
	if err != nil {
		log.Fatal(err)
	}
}

Запустите:

go run generate.go

Будет создан internal/contract/bindings.gen.go с типами Info, Host, Plugin, PluginImports, а также helper-функциями PluginPing, ValidatePlugin, CheckPlugin, OpenPlugin и OpenPluginWithOptions.

Это host-режим по умолчанию. Для кода самого плагина задайте Mode: witgo.GenerateGuest и World: "plugin". В таком package будут MetadataGuest, PluginGuest, ExportPlugin и Imports.Host, но не будет host-only функций OpenPlugin, ValidatePlugin и composition API. Полный пример находится в руководстве по Go guest-плагинам.

Для одного файла используйте GenerateFile, для явно выбранного набора файлов одного package - GenerateFiles, для рекурсивного дерева одного package - GenerateTree. Старый Generate(Config{WIT: ...}) сохранён для совместимости.

Необязательные Go-типы

Стандартный WIT можно дополнить отдельным plugin.witgo.yaml. Например, для package example:users@1.0.0 и alias timestamp в interface users WIT s64 может выглядеть в публичном Go API как time.Time, оставаясь s64 в Component ABI:

version: 1
types:
  example:users/users@1.0.0#timestamp:
    go_type: time.Time
    import: time
    codec: unix-seconds

Overlay подключается через Config.GoOverlay; без него generated output и runtime behavior остаются прежними. Полный формат описан в docs/go-overlays.md.

3. Реализуйте host-функции

type pluginHost struct{}

func (pluginHost) ProcessString(_ context.Context, value string) (string, error) {
	return "HOST:" + value, nil
}

Go-компилятор сам проверит, что реализация соответствует generated interface contract.Host.

4. Проверьте контракт и откройте плагин

package main

import (
	"context"
	"fmt"
	"log"

	contract "example.com/myapp/internal/contract"
)

func main() {
	ctx := context.Background()
	report, err := contract.ValidatePluginContext(ctx, "./plugins/plugin.component.wasm")
	if err != nil {
		log.Fatal(err)
	}
	if !report.Compatible {
		log.Fatalf("incompatible plugin: %+v", report)
	}

	plugin, err := contract.OpenPluginContext(ctx, "./plugins/plugin.component.wasm", contract.PluginImports{
		Host: pluginHost{},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer plugin.Close()

	info, err := plugin.Metadata.Get(ctx)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(info.Name)
	fmt.Println(info.Version)
	fmt.Println(info.Author)
}

Вызовы export-функций остаются типизированными:

info, err := plugin.Metadata.Get(ctx)

5. Задайте права и топливо на хосте

Для нескольких плагинов удобнее один раз описать host policy. Нулевая policy безопасна: она запрещает ambient capabilities и загрузку зависимостей.

policy := witgo.HostPolicy{
	Public: witgo.PluginGrant{
		// Эти разрешения и лимиты получит каждый плагин.
		Permissions: witgo.Permissions{
			System: true,
			Allow: []string{"example:plugins/host@1.0.0"},
		},
		Limits: witgo.PluginLimits{
			FuelPerCall:      1_000_000,
			Timeout:          2 * time.Second,
			MemoryLimitBytes: 64 << 20,
		},
	},
	Plugins: map[string]witgo.PluginGrant{
		"downloader": {
			Permissions: witgo.Permissions{Network: true},
		},
		"orchestrator": {
			Permissions: witgo.Permissions{LoadPlugin: true},
			AllowedPluginRoots: []string{"./plugins"},
		},
	},
}

plugin, err := contract.OpenPluginWithPolicyContext(
	ctx, policy, "downloader", "./plugins/downloader.wasm",
	contract.PluginImports{Host: pluginHost{}},
)

System, Network и Files разрешают соответствующие WASI namespaces, Allow принимает точные WIT interface/function patterns, а Deny всегда имеет приоритет. LoadPlugin разрешает только зависимости из plugin manifest и ограничивается host-owned AllowedPluginRoots.

Если plugin умеет запрашивать дополнительное топливо через opt-in runtime API, хост также задаёт FuelRequests и FuelPolicy; сам plugin не может назначить себе fuel или расширить права.

Низкоуровневый вариант через RuntimeOptions тоже сохранён:

plugin, err := contract.OpenPluginWithOptionsContext(
	ctx,
	"./plugins/plugin.component.wasm",
	witgo.RuntimeOptions{
		FuelPerCall:      1_000_000,
		Timeout:          2 * time.Second,
		MemoryLimitBytes: 64 << 20,
		MaxResultBytes:   1 << 20,
		InstanceLimit:    8,
	},
	contract.PluginImports{Host: pluginHost{}},
)

6. Сгенерируйте и соберите Go-плагин

Один вызов может сначала создать guest bindings из того же WIT-контракта, а затем собрать готовый Component и встроить manifest зависимостей:

err := witgo.BuildPlugin(witgo.PluginBuildConfig{
	Generate: witgo.Config{
		WIT: "./wit", WITMode: witgo.WITInputPackage,
		World: "plugin", Output: "./internal/contract",
		Package: "contract",
	},
	Build: witgo.GuestBuildConfig{
		Main: "./cmd/plugin", World: "plugin",
		WITPackage: "./wit",
		Output: "./dist/plugin.component.wasm",
		Manifest: &witgo.PluginManifest{Dependencies: map[string]string{
			"example:plugins/cache@1.0.0": "cache.component.wasm",
		}},
	},
})

В коде плагина остаётся только реализовать generated <Interface>Guest и вызвать Export<World>; собранный файл затем открывается generated host API.

Если подробный отчёт не нужен, используйте короткую проверку:

if err := contract.CheckPlugin("./plugins/plugin.component.wasm"); err != nil {
	log.Fatal(err)
}

Ошибка от CheckPlugin поддерживает errors.Is(err, witgo.ErrContractMismatch) и errors.As к *witgo.ContractValidationError.

Что важно знать

  • runtime работает in-process через доверенный Rust bridge, а не через sidecar;
  • перед запуском всегда проверяются contract manifest и version handshake;
  • вложенные плагины связываются через WIT imports/exports, но не получают прямой доступ к registry, runtime options или чужим runtime;
  • системный vendor API witgo:runtime/runtime@1.0.0 подключается только явно через EnableRuntimeAPI и даёт guest-коду только локальное состояние вызова;
  • запрос дополнительного fuel возможен только через UnsafeRequestAdditionalFuel, а решение всегда остаётся за host policy;
  • resource, future, stream и error-context передаются как runtime-bound witgo.Handle и не могут безопасно мигрировать между независимыми runtime-box;
  • обычный Go использует purego без CGO на desktop Linux/macOS/Windows;
  • TinyGo native runtime поддерживается на Linux и Windows с CGo; TinyGo 0.41 на macOS компилирует API и generator, но не может связать dlopen backend.

Ключевые ограничения и поведение собраны в docs/capabilities.md, архитектура и модель доверия - в docs/architecture.md.

Поддерживаемые значения

Runtime покрывает bool, все WIT-числа, char, string, records, lists, options, results, tuples, maps, enums, flags и variants.

resource, future, stream и error-context передаются как witgo.Handle. Такой handle привязан к Store runtime-коробки, его можно вернуть обратно в Component, передать вложенному WebAssembly provider в той же коробке и явно закрыть через Handle.Close. Между независимыми коробками handle не копируется.

Пример

go run ./examples/contracts/basic
go run ./examples/scenarios/server

Ожидаемый вывод:

Plugin metadata
Name: HOST:image-resizer
Version: 1.4.0
Author: Example Team
Description: Resizes uploaded images and creates previews.

Как это работает

witgo загружает version-matched Wasmtime shared library прямо в Go-процесс. Нет отдельного дочернего процесса, нет stdin/stdout IPC, нет download шага во время запуска. Нативная библиотека уже встроена в Go-модуль и при первом использовании распаковывается в content-addressed cache после SHA-256 проверки.

При инициализации Go и Rust обмениваются protocol_version, witgo_version, bridge_version, wasmtime_version и обязательными feature-флагами. До запуска start bridge отвечает на contract ping отсортированными именами import/export-функций, а generated Go bindings сравнивают их с ожидаемым контрактом и зарегистрированными host imports.

Подробности:

Проверка

go test ./...

Documentation

Index

Constants

View Source
const RuntimeSystemInterfaceID = "witgo:runtime/runtime@1.0.0"

Variables

View Source
var (
	ErrPluginNotRegistered      = errors.New("plugin provider is not registered")
	ErrPluginAlreadyRegistered  = errors.New("plugin provider is already registered")
	ErrPluginDependencyMismatch = errors.New("plugin dependency contract mismatch")
	ErrPluginCallCycle          = errors.New("plugin call cycle detected")
	ErrPluginCallDepthExceeded  = errors.New("plugin call depth exceeded")
	ErrPluginProviderClosed     = errors.New("plugin provider is closed")
	ErrCrossRuntimeHandle       = errors.New("handle cannot cross plugin runtime boundary")
)
View Source
var (
	ErrHostOnlyAPI   = errors.New("witgo API is only available in a host build")
	ErrPluginOnlyAPI = errors.New("witgo API is only available in a WebAssembly plugin build")
)
View Source
var (
	ErrUnknownWasmKind        = errors.New("unknown WebAssembly kind")
	ErrCoreModule             = errors.New("core WebAssembly modules are not supported; build a Component Model component")
	ErrFuelDisabled           = errors.New("WebAssembly fuel metering is disabled")
	ErrRuntimeClosed          = errors.New("component runtime is closed")
	ErrBridgeProtocolMismatch = errors.New("component bridge protocol mismatch")
	ErrBridgeVersionMismatch  = errors.New("component bridge version mismatch")
	ErrContractMismatch       = errors.New("component function contract mismatch")
	ErrCapabilityDenied       = errors.New("component capability policy denied required host import")
	ErrHandleClosed           = errors.New("component handle is closed or unknown")
	ErrResultTooLarge         = errors.New("WebAssembly result exceeds configured limit")
	ErrNestedPluginNotFound   = errors.New("nested plugin provider was not found")
	ErrNestedPluginAmbiguous  = errors.New("multiple nested plugins provide the same import")
	ErrNestedPluginCycle      = errors.New("nested plugin dependency cycle")
	ErrNestedPluginPathDenied = errors.New("nested plugin dependency path is outside the host policy")
	ErrNestedPluginBudget     = errors.New("plugin box resource budget is too small")
)
View Source
var (
	ErrFuelRequestDisabled     = errors.New("additional fuel requests are disabled")
	ErrFuelRequestDenied       = errors.New("additional fuel request was denied")
	ErrFuelRequestTooLarge     = errors.New("additional fuel request exceeds a hard limit")
	ErrFuelRequestLimitReached = errors.New("additional fuel request limit reached")
	ErrRuntimeClosing          = errors.New("component runtime is closing")
	ErrArgumentTooLarge        = errors.New("component argument exceeds configured limit")
	ErrValueDepthExceeded      = errors.New("component value nesting exceeds configured limit")
	ErrProviderUnavailable     = errors.New("plugin provider is unavailable")
	ErrProviderClosing         = errors.New("plugin provider is closing")
	ErrCallCancelled           = errors.New("component call was cancelled")
)
View Source
var ErrCallTimeout = errors.New("WebAssembly call timed out")
View Source
var ErrFuelExhausted = errors.New("WebAssembly fuel exhausted")

Functions

func BuildGuestComponent added in v1.1.0

func BuildGuestComponent(config GuestBuildConfig) error

BuildGuestComponent builds a registered Go guest as a WASI Preview 2 WebAssembly Component. Canonical ABI glue must have been generated in guest mode before this function is called.

func BuildPlugin added in v1.1.0

func BuildPlugin(config PluginBuildConfig) error

BuildPlugin generates guest bindings and builds the loadable component.

func CloseHandles

func CloseHandles(handles ...Handle) error

CloseHandles closes every handle and returns the first error after all close operations have been attempted.

func DescriptorUsesRuntimeHandles

func DescriptorUsesRuntimeHandles(descriptor InterfaceDescriptor) bool

DescriptorUsesRuntimeHandles reports whether an interface contains values whose ownership is tied to one Component Model Store.

func EmbedPluginManifest

func EmbedPluginManifest(component []byte, manifest PluginManifest) ([]byte, error)

EmbedPluginManifest appends a witgo custom section to a binary Component Model component. It is intended for plugin build pipelines.

func Generate

func Generate(config Config) error

Generate creates Go bindings in config.Output.

func GenerateFile

func GenerateFile(config Config, filename string) error

GenerateFile creates bindings from exactly one .wit file.

func GenerateFiles

func GenerateFiles(config Config, filenames ...string) error

GenerateFiles creates one binding package from an explicit set of .wit files. Every file must belong to the same WIT package.

func GeneratePackage

func GeneratePackage(config Config, directory string) error

GeneratePackage creates bindings from all .wit files directly inside a package directory. Nested package and deps directories are not traversed.

func GenerateTree

func GenerateTree(config Config, directory string) error

GenerateTree recursively loads every .wit file below directory. It is useful for split source trees that contain one WIT package and no dependency packages.

func InspectRequiredCapabilities

func InspectRequiredCapabilities(filename string) ([]string, error)

InspectRequiredCapabilities returns sorted component imports suitable for a capability decision before startup.

func InspectRequiredCapabilitiesContext

func InspectRequiredCapabilitiesContext(ctx context.Context, filename string) ([]string, error)

func InspectRequiredCapabilitiesWithOptions

func InspectRequiredCapabilitiesWithOptions(filename string, options RuntimeOptions) ([]string, error)

InspectRequiredCapabilitiesWithOptions is InspectRequiredCapabilities with explicit bridge selection options.

func InspectRequiredCapabilitiesWithOptionsContext

func InspectRequiredCapabilitiesWithOptionsContext(ctx context.Context, filename string, options RuntimeOptions) ([]string, error)

func IsHostBuild

func IsHostBuild() bool

func IsPluginBuild

func IsPluginBuild() bool

func MatchResult

func MatchResult[T, E, Value any](r Result[T, E], ok func(T) Value, fail func(E) Value) Value

Match evaluates the callback for the active branch.

func NewWITError

func NewWITError[E any](value E) error

NewWITError wraps a canonical WIT result error payload as a Go error.

func RequireCompatible

func RequireCompatible(report ValidationReport) error

RequireCompatible returns nil when report is compatible and otherwise returns an error wrapping ErrContractMismatch.

func RequireHostBuild

func RequireHostBuild() error

RequireHostBuild rejects APIs that need the native Component Model runtime when the current binary is itself a WebAssembly plugin.

func RequirePluginBuild

func RequirePluginBuild() error

RequirePluginBuild can be used by generated guest entry points to reject an accidental native build.

func TupleValue

func TupleValue[T any](tuple Tuple, index int) (T, bool, error)

TupleValue converts one dynamic tuple item to T using the Component Model JSON representation.

Types

type CallObserver

type CallObserver interface {
	OnCallStart(PluginCallEvent)
	OnCallFinish(PluginCallEvent)
}

type CallbackFuelPolicy

type CallbackFuelPolicy func(context.Context, FuelRequest) (FuelDecision, error)

func (CallbackFuelPolicy) DecideFuel

func (p CallbackFuelPolicy) DecideFuel(ctx context.Context, request FuelRequest) (FuelDecision, error)

type CapabilityPolicy

type CapabilityPolicy struct {
	Allow []string
	Deny  []string
}

CapabilityPolicy controls which host import functions a component may require. Patterns support:

  • exact function names: namespace:pkg/interface@1.0.0#func
  • interface-level rules: namespace:pkg/interface@1.0.0
  • prefix wildcards ending in *: namespace:pkg/interface@1.0.0#read*
  • "*" to match everything

Deny rules override allow rules. If Allow is empty, every capability is allowed except those matched by Deny.

func (CapabilityPolicy) Allows

func (p CapabilityPolicy) Allows(function string) bool

Allows reports whether function is allowed by policy.

func (CapabilityPolicy) ValidateImports

func (p CapabilityPolicy) ValidateImports(imports []string) error

ValidateImports rejects required imports denied by policy.

type CapabilityPolicyError

type CapabilityPolicyError struct {
	Denied []string
}

CapabilityPolicyError reports which required capabilities were denied by a policy.

func (*CapabilityPolicyError) Error

func (e *CapabilityPolicyError) Error() string

func (*CapabilityPolicyError) Unwrap

func (e *CapabilityPolicyError) Unwrap() error

type CappedFuelAllowance

type CappedFuelAllowance struct {
	MaxGrantPerRequest uint64
	MaxTotalGrant      uint64
	MaxRequestsPerCall uint32
}

func (CappedFuelAllowance) DecideFuel

func (p CappedFuelAllowance) DecideFuel(_ context.Context, request FuelRequest) (FuelDecision, error)

type Char

type Char rune

Char is a Unicode scalar value encoded according to the WIT char ABI.

func NewChar

func NewChar(value rune) (Char, error)

NewChar validates value and constructs a Char.

func ParseChar

func ParseChar(value string) (Char, error)

ParseChar decodes a string containing exactly one Unicode scalar value.

func (Char) MarshalJSON

func (c Char) MarshalJSON() ([]byte, error)

func (Char) Rune

func (c Char) Rune() rune

Rune returns the Go rune representation.

func (Char) String

func (c Char) String() string

func (*Char) UnmarshalJSON

func (c *Char) UnmarshalJSON(data []byte) error

type ComponentComposition

type ComponentComposition struct {
	Component    string            `json:"component"`
	Dependencies []CompositionPlug `json:"dependencies,omitempty"`
}

ComponentComposition is a complete same-Store composition rooted at a consumer component.

type CompositionPlug

type CompositionPlug struct {
	Interface    string            `json:"interface"`
	Component    string            `json:"component"`
	Dependencies []CompositionPlug `json:"dependencies,omitempty"`
}

CompositionPlug describes one exact Component Model import edge. Component provides Interface; Dependencies satisfy imports of that provider itself. Paths are normalized by the runtime before they reach the native bridge.

type Config

type Config struct {
	// WIT is a .wit file or directory. WITMode controls directory traversal.
	WIT string
	// WITFiles is an explicit, ordered-independent set of .wit files. It cannot
	// be combined with WIT and is primarily used by GenerateFiles.
	WITFiles []string
	// WITMode defaults to WITInputAuto for backwards compatibility.
	WITMode WITInputMode
	// GoOverlay is an optional versioned YAML file that changes the public Go
	// representation while preserving the canonical WIT wire types.
	GoOverlay string
	// Output is the directory where generated bindings are written.
	Output string
	// Package is the Go package name. When empty, it is derived from WIT package.
	Package string
	// Filename defaults to bindings.gen.go.
	Filename string
	// EnableRuntimeAPI emits the opt-in witgo:runtime@1.0.0 guest facade and
	// enables its host binding in generated Open functions.
	EnableRuntimeAPI bool
	// Mode selects which side of the component boundary is generated. The zero
	// value is GenerateHost and preserves the historical host SDK.
	Mode GenerationMode
	// World selects the WIT world in guest mode. It may be omitted when the
	// input contains exactly one world.
	World string
	// PackageRoot is the Go import path of Output. Guest bindings use it for
	// the packages generated below Output. When empty it is derived from the
	// nearest go.mod.
	PackageRoot string
	// GuestBindgen is an optional path to wit-bindgen-go. The default searches
	// PATH. It is used only in guest mode.
	GuestBindgen string
}

type Contract

type Contract struct {
	Imports    []string
	Exports    []string
	Signatures map[string]string
}

Contract describes the functions expected by generated bindings. Names are either "interface#function" or a direct world function name. Signatures use a deterministic structural representation of Component Model value types.

func InspectComponent

func InspectComponent(filename string) (Contract, error)

InspectComponent returns the imported and exported function names exposed by a WebAssembly component without instantiating it.

func InspectComponentBytes

func InspectComponentBytes(data []byte) (Contract, error)

InspectComponentBytes inspects a component held in memory.

func InspectComponentBytesContext

func InspectComponentBytesContext(ctx context.Context, data []byte) (Contract, error)

func InspectComponentBytesWithOptions

func InspectComponentBytesWithOptions(data []byte, options RuntimeOptions) (Contract, error)

InspectComponentBytesWithOptions is InspectComponentBytes with explicit bridge options.

func InspectComponentBytesWithOptionsContext

func InspectComponentBytesWithOptionsContext(ctx context.Context, data []byte, options RuntimeOptions) (Contract, error)

func InspectComponentContext

func InspectComponentContext(ctx context.Context, filename string) (Contract, error)

func InspectComponentWithOptions

func InspectComponentWithOptions(filename string, options RuntimeOptions) (Contract, error)

InspectComponentWithOptions is InspectComponent with bridge selection and resource options. Execution limits are not consumed because inspection does not instantiate or call the component.

func InspectComponentWithOptionsContext

func InspectComponentWithOptionsContext(ctx context.Context, filename string, options RuntimeOptions) (Contract, error)

func (Contract) ExportNames

func (c Contract) ExportNames() []string

ExportNames returns a sorted copy of the provided plugin function names.

func (Contract) FunctionNames

func (c Contract) FunctionNames() []string

FunctionNames returns all imported and exported function names in sorted order without duplicates.

func (Contract) ImportNames

func (c Contract) ImportNames() []string

ImportNames returns a sorted copy of the required host function names.

func (Contract) Provides

func (c Contract) Provides(function string) bool

Provides reports whether the component exports the named plugin function.

func (Contract) Requires

func (c Contract) Requires(function string) bool

Requires reports whether the component imports the named host function.

func (Contract) Signature

func (c Contract) Signature(function string) (string, bool)

Signature returns the structural Component Model signature for a function.

type ContractDifference

type ContractDifference struct {
	Missing    []string
	Unexpected []string
}

ContractDifference describes missing and unexpected function names on one side of a component contract.

func (ContractDifference) Count

func (d ContractDifference) Count() int

Count returns the total number of missing and unexpected functions.

func (ContractDifference) Empty

func (d ContractDifference) Empty() bool

Empty reports whether there are no missing or unexpected functions.

type ContractValidationError

type ContractValidationError struct {
	Report ValidationReport
}

ContractValidationError wraps an incompatible report and supports errors.Is(err, ErrContractMismatch).

func (*ContractValidationError) Error

func (e *ContractValidationError) Error() string

func (*ContractValidationError) Unwrap

func (e *ContractValidationError) Unwrap() error

type CycleEvent

type CycleEvent struct{ CallPath []PluginCallFrame }

type DenyFuelRequests

type DenyFuelRequests struct{}

func (DenyFuelRequests) DecideFuel

type ExecutionLimitError

type ExecutionLimitError struct {
	Function string
	Limit    error
	Cause    error
}

func (*ExecutionLimitError) Error

func (e *ExecutionLimitError) Error() string

func (*ExecutionLimitError) Is

func (e *ExecutionLimitError) Is(target error) bool

func (*ExecutionLimitError) Unwrap

func (e *ExecutionLimitError) Unwrap() error

type ExecutionRole

type ExecutionRole string

ExecutionRole identifies which side of the Component Model boundary this binary implements.

const (
	ExecutionRoleHost   ExecutionRole = "host"
	ExecutionRolePlugin ExecutionRole = "plugin"
)

func CurrentExecutionRole

func CurrentExecutionRole() ExecutionRole

CurrentExecutionRole is selected at compile time. Native targets are hosts; GOARCH=wasm targets are plugins.

type FixedFuelAllowance

type FixedFuelAllowance struct{ Grant uint64 }

func (FixedFuelAllowance) DecideFuel

func (p FixedFuelAllowance) DecideFuel(_ context.Context, request FuelRequest) (FuelDecision, error)

type FuelDecision

type FuelDecision struct{ Grant uint64 }

type FuelDenialReason

type FuelDenialReason string
const (
	FuelDeniedDisabled            FuelDenialReason = "disabled"
	FuelDeniedPolicy              FuelDenialReason = "policy-denied"
	FuelDeniedRequestTooLarge     FuelDenialReason = "request-too-large"
	FuelDeniedRequestLimitReached FuelDenialReason = "request-limit-reached"
	FuelDeniedCallFinishing       FuelDenialReason = "call-finishing"
	FuelDeniedRuntimeClosing      FuelDenialReason = "runtime-closing"
	FuelDeniedInvalidReason       FuelDenialReason = "invalid-reason"
)

type FuelDisabledError

type FuelDisabledError struct{ Cause error }

func (*FuelDisabledError) Error

func (e *FuelDisabledError) Error() string

func (*FuelDisabledError) Is

func (e *FuelDisabledError) Is(target error) bool

func (*FuelDisabledError) Unwrap

func (e *FuelDisabledError) Unwrap() error

type FuelGrant

type FuelGrant struct {
	Requested uint64 `json:"requested"`
	Granted   uint64 `json:"granted"`
	Remaining uint64 `json:"remaining"`
}

type FuelRequest

type FuelRequest struct {
	CallID       string
	ParentCallID string
	PluginID     string
	ProviderID   string
	Interface    string
	Function     string
	CallDepth    int
	Requested    uint64
	Reason       string
	CurrentFuel  uint64
	InitialFuel  uint64
	TotalGranted uint64
	RequestCount uint32
	Deadline     time.Time
}

type FuelRequestError

type FuelRequestError struct {
	PluginID  string
	CallID    string
	Requested uint64
	Reason    FuelDenialReason
	Cause     error
}

func (*FuelRequestError) Error

func (e *FuelRequestError) Error() string

func (*FuelRequestError) Is

func (e *FuelRequestError) Is(target error) bool

func (*FuelRequestError) Unwrap

func (e *FuelRequestError) Unwrap() error

type FuelRequestEvent

type FuelRequestEvent struct {
	Time            time.Time
	CallID          string
	PluginID        string
	CallPath        []PluginCallFrame
	Requested       uint64
	Granted         uint64
	DenialReason    string
	GuestReason     string
	RemainingBefore uint64
	RemainingAfter  uint64
}

type FuelRequestLimits

type FuelRequestLimits struct {
	Enabled              bool
	MaxGrantPerRequest   uint64
	MaxTotalGrantPerCall uint64
	MaxRequestsPerCall   uint32
	MinRemainingTime     time.Duration
	MaxReasonBytes       int
	PolicyTimeout        time.Duration
}

type FuelRequestPolicy

type FuelRequestPolicy interface {
	DecideFuel(context.Context, FuelRequest) (FuelDecision, error)
}

type GenerationMode added in v1.1.0

type GenerationMode uint8

GenerationMode selects the API surface emitted from a WIT world.

const (
	// GenerateHost emits loaders, validation and composition clients.
	GenerateHost GenerationMode = iota
	// GenerateGuest emits Go/TinyGo Component Model guest bindings. Host-only
	// constructors such as OpenPlugin are deliberately absent.
	GenerateGuest
)

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator creates Go bindings from WIT contracts.

func NewGenerator

func NewGenerator(config Config) (*Generator, error)

NewGenerator validates the configuration and creates a reusable generator.

func (*Generator) Generate

func (g *Generator) Generate() error

Generate creates or replaces the configured generated Go file.

type GuestBuildConfig added in v1.1.0

type GuestBuildConfig struct {
	// Main is the plugin main package or .go file.
	Main string
	// WITPackage is a WIT package accepted by TinyGo --wit-package. TinyGo
	// accepts a WIT package directory; a packaged .wasm may also be used.
	WITPackage string
	// World is the implemented WIT world.
	World string
	// Output is the resulting component .wasm path.
	Output string
	// TinyGo optionally overrides the tinygo executable path.
	TinyGo string
	// NoDebug removes debug data from the component.
	NoDebug bool
	// Manifest is embedded after a successful build. A nil manifest omits the
	// witgo custom section; an empty non-nil manifest is still embedded.
	Manifest *PluginManifest
}

GuestBuildConfig describes a TinyGo WASI Preview 2 component build. The WIT package is embedded by TinyGo as Component Type metadata and used to turn the Canonical ABI core module into a WebAssembly Component.

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle is a live Component Model resource, future, stream, or error-context. Handles are bound to the Runtime that produced them and may be passed back to calls on that Runtime. Close releases the bridge-side handle explicitly. Copies of a Handle share the same lifecycle state.

func (Handle) Close

func (h Handle) Close() error

Close explicitly drops a resource or closes a future/stream. Error-context handles are removed from the bridge table. Close is idempotent.

func (Handle) ID

func (h Handle) ID() uint64

ID returns the runtime-local handle identifier. It is useful for logging, but it is not portable between Runtime values or process executions.

func (Handle) IsClosed

func (h Handle) IsClosed() bool

IsClosed reports whether the handle or its Runtime has been closed.

func (Handle) IsKind

func (h Handle) IsKind(kind HandleKind) bool

IsKind reports whether this live handle has kind.

func (Handle) Kind

func (h Handle) Kind() HandleKind

Kind returns the Component Model handle kind.

func (Handle) MarshalJSON

func (h Handle) MarshalJSON() ([]byte, error)

MarshalJSON encodes the runtime-local token understood by the native bridge.

func (Handle) Owned

func (h Handle) Owned() bool

Owned reports whether a resource handle was lifted as own<T>. It is false for borrow<T> and for handle kinds where ownership is implicit.

func (Handle) String

func (h Handle) String() string

func (*Handle) UnmarshalJSON

func (h *Handle) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects detached handle tokens. Handles must be created by a Runtime so they cannot accidentally be attached to the wrong Store.

func (Handle) Valid

func (h Handle) Valid() error

Valid checks that the handle is initialized, live, and has a known kind.

type HandleKind

type HandleKind string

HandleKind identifies an opaque Component Model handle.

const (
	HandleResource     HandleKind = "resource"
	HandleFuture       HandleKind = "future"
	HandleStream       HandleKind = "stream"
	HandleErrorContext HandleKind = "error-context"
)

type Host

type Host struct {
	// contains filtered or unexported fields
}

Host owns the provider registry and call policy. It never holds its registry mutex while user code or a component runtime is executing.

func NewHost

func NewHost(options ...HostOptions) (*Host, error)

func (*Host) AutoResolveProvider

func (h *Host) AutoResolveProvider(expected InterfaceDescriptor) (*ProviderHandle, error)

func (*Host) Close

func (h *Host) Close() error

func (*Host) RegisterProvider

func (h *Host) RegisterProvider(name string, descriptor InterfaceDescriptor, call ProviderCall, options ...RegisterOption) (*ProviderHandle, error)

func (*Host) ReplaceProvider

func (h *Host) ReplaceProvider(name string, descriptor InterfaceDescriptor, call ProviderCall, options ...RegisterOption) (*ProviderHandle, error)

func (*Host) ResolveProvider

func (h *Host) ResolveProvider(name string, expected InterfaceDescriptor) (*ProviderHandle, error)

func (*Host) UnregisterProvider

func (h *Host) UnregisterProvider(interfaceID, name string) error

type HostFunc

type HostFunc func(args []any) (any, error)

HostFunc implements one imported WIT function. Arguments and the result use ordinary Go values with the same shape as their WIT types.

type HostFuncContext

type HostFuncContext func(ctx context.Context, args []any) (any, error)

HostFuncContext implements an imported WIT function with cancellation and deadline propagation. New code should prefer it over HostFunc.

type HostImport

type HostImport struct {
	Interface   string
	Function    string
	Call        HostFunc
	CallContext HostFuncContext
}

HostImport grants a component one host capability.

type HostOptions

type HostOptions struct {
	MaxCallDepth      int
	RejectCycles      bool
	CallTimeout       time.Duration
	Observer          CallObserver
	FuelRequestPolicy FuelRequestPolicy
	FuelRequestLimits FuelRequestLimits
	SecurityObserver  RuntimeSecurityObserver
}

HostOptions controls transparent calls between registered providers.

type HostPolicy added in v1.1.0

type HostPolicy struct {
	Public       PluginGrant
	Plugins      map[string]PluginGrant
	RuntimeAPI   bool
	SearchPaths  []string
	Observer     RuntimeSecurityObserver
	BridgePath   string
	BridgeSHA256 string
}

HostPolicy is the convenient, secure entry point for configuring plugins. Public applies to every plugin; Plugins adds grants by PluginID.

func (HostPolicy) Options added in v1.1.0

func (p HostPolicy) Options(pluginID string) (RuntimeOptions, error)

Options resolves immutable runtime options for pluginID. Public and named permissions are combined, while non-zero named limits replace public ones.

type InterfaceDescriptor

type InterfaceDescriptor struct {
	ID        string
	Functions map[string]string
}

InterfaceDescriptor is the stable identity and structural contract of one generated WIT interface.

type LimitEvent

type LimitEvent struct {
	PluginID, Limit string
	Maximum, Actual uint64
}

type Map

type Map[K comparable, V any] map[K]V

Map represents a Component Model map<K,V> using its ordered pair wire form. Go map iteration order is intentionally not part of the ABI.

func NewMap

func NewMap[K comparable, V any](capacity ...int) Map[K, V]

NewMap constructs a map with optional initial capacity.

func (Map[K, V]) Clone

func (m Map[K, V]) Clone() Map[K, V]

Clone returns an independent shallow copy.

func (Map[K, V]) Delete

func (m Map[K, V]) Delete(key K) bool

Delete removes key and reports whether it was present.

func (Map[K, V]) Get

func (m Map[K, V]) Get(key K) (V, bool)

Get returns a value and whether key exists.

func (Map[K, V]) MarshalJSON

func (m Map[K, V]) MarshalJSON() ([]byte, error)

func (Map[K, V]) Put

func (m Map[K, V]) Put(key K, value V) Map[K, V]

Put stores value under key and returns the map for fluent construction.

func (*Map[K, V]) UnmarshalJSON

func (m *Map[K, V]) UnmarshalJSON(data []byte) error

type NativeBridgeBackend

type NativeBridgeBackend string

NativeBridgeBackend identifies the platform loader selected at build time.

const (
	NativeBridgeBackendPureGo      NativeBridgeBackend = "purego"
	NativeBridgeBackendCGo         NativeBridgeBackend = "cgo"
	NativeBridgeBackendUnsupported NativeBridgeBackend = "unsupported"
)

func CurrentNativeBridgeBackend

func CurrentNativeBridgeBackend() NativeBridgeBackend

CurrentNativeBridgeBackend reports which loader this binary uses.

type NestedPluginOptions

type NestedPluginOptions struct {
	Disabled bool
	// SearchPaths is only a fallback for components without PluginManifest.
	SearchPaths []string
	// AllowedRoots restricts relative dependency paths declared by plugins.
	// The zero value allows only the parent component directory tree.
	AllowedRoots  []string
	MaxCandidates int
	Resolver      NestedPluginResolver
}

NestedPluginOptions controls automatic plugin-to-plugin dependency wiring. A component requests dependencies through ordinary WIT imports. When a manual HostImport is absent, witgo searches for a component exporting the exact same function name and structural signature.

type NestedPluginRequest

type NestedPluginRequest struct {
	Parent    string
	Import    string
	Signature string
}

NestedPluginRequest describes one unresolved WIT import.

type NestedPluginResolver

type NestedPluginResolver func(ctx context.Context, request NestedPluginRequest) (string, error)

NestedPluginResolver returns a component path for an unresolved import. Returning an empty path means that no provider is available.

type Option

type Option[T any] struct {
	Value T
	Some  bool
}

Option represents a WIT option<T> without using nil as application state.

func FlatMapOption

func FlatMapOption[T, U any](option Option[T], transform func(T) Option[U]) Option[U]

FlatMapOption chains an option-producing transformation.

func MapOption

func MapOption[T, U any](option Option[T], transform func(T) U) Option[U]

MapOption transforms a present value and preserves None.

func None

func None[T any]() Option[T]

None constructs an empty option.

func OptionFromPointer

func OptionFromPointer[T any](value *T) Option[T]

OptionFromPointer converts nil to None and a non-nil pointer to Some.

func Some

func Some[T any](value T) Option[T]

Some constructs an option containing value.

func (Option[T]) Get

func (o Option[T]) Get() (T, bool)

Get returns the value and whether it is present.

func (Option[T]) IsNone

func (o Option[T]) IsNone() bool

IsNone reports whether the option is empty.

func (Option[T]) IsSome

func (o Option[T]) IsSome() bool

IsSome reports whether the option contains a value.

func (Option[T]) MarshalJSON

func (o Option[T]) MarshalJSON() ([]byte, error)

func (Option[T]) Or

func (o Option[T]) Or(fallback T) T

Or returns the contained value or fallback.

func (Option[T]) Pointer

func (o Option[T]) Pointer() *T

Pointer returns a pointer to a copy of the contained value or nil.

func (*Option[T]) UnmarshalJSON

func (o *Option[T]) UnmarshalJSON(data []byte) error

type PerPluginFuelAllowance

type PerPluginFuelAllowance map[string]FuelRequestPolicy

func (PerPluginFuelAllowance) DecideFuel

func (p PerPluginFuelAllowance) DecideFuel(ctx context.Context, request FuelRequest) (FuelDecision, error)

type Permissions added in v1.1.0

type Permissions struct {
	All        bool
	System     bool
	Network    bool
	Files      bool
	LoadPlugin bool
	Allow      []string
	Deny       []string
}

Permissions describes ambient capabilities granted by the host. Grants are additive: a plugin receives Public permissions plus its named grant. Deny rules always win. The zero value grants nothing.

type PluginBox

type PluginBox struct {
	// contains filtered or unexported fields
}

PluginBox is an isolated root runtime and all automatically loaded children.

func (*PluginBox) Close

func (b *PluginBox) Close() error

Close closes the root and every nested runtime in the box.

func (*PluginBox) PluginPaths

func (b *PluginBox) PluginPaths() []string

PluginPaths returns direct nested providers selected for the root runtime.

func (*PluginBox) Runtime

func (b *PluginBox) Runtime() *Runtime

Runtime returns the root component runtime.

type PluginBuildConfig added in v1.1.0

type PluginBuildConfig struct {
	Generate Config
	Build    GuestBuildConfig
}

PluginBuildConfig describes the complete generated-contract plugin build.

type PluginCallContext

type PluginCallContext struct {
	ID       string
	ParentID string
	Depth    int
	Path     []PluginCallFrame
	Deadline time.Time
}

PluginCallContext describes the current nested call chain.

func PluginCallContextFromContext

func PluginCallContextFromContext(ctx context.Context) (PluginCallContext, bool)

type PluginCallError

type PluginCallError struct {
	Consumer string
	Provider string
	Frame    PluginCallFrame
	Path     []PluginCallFrame
	Cause    error
}

PluginCallError preserves the routed call path and underlying runtime error.

func (*PluginCallError) Error

func (e *PluginCallError) Error() string

func (*PluginCallError) Unwrap

func (e *PluginCallError) Unwrap() error

type PluginCallEvent

type PluginCallEvent struct {
	CallID       string
	ParentCallID string
	Depth        int
	Consumer     string
	Provider     string
	Interface    string
	Function     string
	Path         []PluginCallFrame
	Started      time.Time
	Duration     time.Duration
	Err          error
}

PluginCallEvent is delivered to an observer outside registry locks.

type PluginCallFrame

type PluginCallFrame struct {
	Plugin    string
	Interface string
	Function  string
}

PluginCallFrame identifies one routed provider call.

type PluginDependencyError

type PluginDependencyError struct {
	Consumer  string
	Provider  string
	Interface string
	Report    ValidationReport
	CallPath  []PluginCallFrame
}

PluginDependencyError reports a structural mismatch before a consumer is instantiated. It supports errors.Is(err, ErrPluginDependencyMismatch).

func (*PluginDependencyError) Error

func (e *PluginDependencyError) Error() string

func (*PluginDependencyError) Unwrap

func (e *PluginDependencyError) Unwrap() error

type PluginGrant added in v1.1.0

type PluginGrant struct {
	Permissions Permissions
	Limits      PluginLimits
	// AllowedPluginRoots bounds components loaded through a plugin manifest.
	AllowedPluginRoots []string
}

PluginGrant adds permissions and optionally replaces public limits for one logical plugin ID.

type PluginHost

type PluginHost struct {
	// contains filtered or unexported fields
}

PluginHost owns immutable discovery settings. Each load performed through a host creates a separate box, so plugin instances and their state are never shared between top-level loads.

func NewPluginHost

func NewPluginHost(options NestedPluginOptions) (*PluginHost, error)

NewPluginHost creates a host-router for automatic nested dependencies.

func (*PluginHost) BoxCount

func (h *PluginHost) BoxCount() int

BoxCount returns the number of live independent root boxes.

func (*PluginHost) Close

func (h *PluginHost) Close() error

Close closes every independent box created through this host. It is safe to call more than once; a closed host rejects new boxes.

func (*PluginHost) OpenBox

func (h *PluginHost) OpenBox(filename string, options RuntimeOptions, imports []HostImport) (*PluginBox, error)

OpenBox is OpenBoxContext with context.Background().

func (*PluginHost) OpenBoxContext

func (h *PluginHost) OpenBoxContext(ctx context.Context, filename string, options RuntimeOptions, imports []HostImport) (*PluginBox, error)

OpenBoxContext creates a completely independent component box using this host's discovery policy.

type PluginLimits added in v1.1.0

type PluginLimits struct {
	Fuel             uint64
	FuelPerCall      uint64
	Timeout          time.Duration
	MemoryLimitBytes int64
	MaxResultBytes   uint64
	InstanceLimit    int64
	ValueLimits      ValueLimits
	FuelRequests     FuelRequestLimits
	FuelPolicy       FuelRequestPolicy
}

PluginLimits are host-owned execution limits for one plugin. A plugin manifest cannot increase them.

type PluginManifest

type PluginManifest struct {
	Dependencies map[string]string `json:"dependencies,omitempty"`
}

PluginManifest is metadata owned by a plugin. Dependencies map a complete WIT import or an interface name to a component path relative to the plugin. Resource limits intentionally cannot be declared here; only the host owns the box budget.

func ReadPluginManifest

func ReadPluginManifest(filename string) (PluginManifest, bool, error)

ReadPluginManifest reads an embedded manifest or the sidecar <component>.witgo.json used for textual components and development builds.

type ProviderCall

type ProviderCall func(context.Context, string, []any) (any, error)

ProviderCall is the typed-neutral core callback. Generated registration helpers create it from a strongly typed generated interface.

type ProviderEvent

type ProviderEvent struct {
	PluginID, ProviderID, Interface string
	Reason                          string
}

type ProviderHandle

type ProviderHandle struct {
	// contains filtered or unexported fields
}

ProviderHandle is a stable, concurrency-safe reference. Unregister prevents new leases and waits for calls that already acquired one.

func (*ProviderHandle) CallContext

func (p *ProviderHandle) CallContext(ctx context.Context, consumer, function string, args ...any) (any, error)

func (*ProviderHandle) CompositionPlug

func (p *ProviderHandle) CompositionPlug() (CompositionPlug, bool)

CompositionPlug returns the exact edge needed to instantiate this provider in the consumer's Store. The full interface ID prevents short-name clashes.

func (*ProviderHandle) Descriptor

func (p *ProviderHandle) Descriptor() InterfaceDescriptor

func (*ProviderHandle) Name

func (p *ProviderHandle) Name() string

type RegisterOption

type RegisterOption func(*RegisterOptions)

func ComponentProvider

func ComponentProvider(composition ComponentComposition) RegisterOption

ComponentProvider marks a provider as an export of a Component Model graph. Generated consumers use this metadata to compose the provider into their own Store instead of proxying Store-owned handles through Go.

func ExternallyOwnedProvider

func ExternallyOwnedProvider() RegisterOption

func OwnedProvider

func OwnedProvider(close func() error) RegisterOption

type RegisterOptions

type RegisterOptions struct {
	Owned       bool
	Close       func() error
	Composition ComponentComposition
}

type Result

type Result[T, E any] struct {
	// contains filtered or unexported fields
}

Result is a type-safe WIT result<OK, Err>. Exactly one branch is active.

func Err

func Err[T, E any](value E) Result[T, E]

Err constructs a failed result.

func MapResult

func MapResult[T, E, U any](result Result[T, E], transform func(T) U) Result[U, E]

MapResult transforms the successful branch.

func MapResultErr

func MapResultErr[T, E, F any](result Result[T, E], transform func(E) F) Result[T, F]

MapResultErr transforms the error branch.

func Ok

func Ok[T, E any](value T) Result[T, E]

Ok constructs a successful result.

func (Result[T, E]) GetErr

func (r Result[T, E]) GetErr() (E, bool)

GetErr returns the error value and whether that branch is active.

func (Result[T, E]) GetOK

func (r Result[T, E]) GetOK() (T, bool)

GetOK returns the success value and whether that branch is active.

func (Result[T, E]) IsErr

func (r Result[T, E]) IsErr() bool

IsErr reports whether this is the error branch.

func (Result[T, E]) IsOK

func (r Result[T, E]) IsOK() bool

IsOK reports whether this is the successful branch.

func (Result[T, E]) MarshalJSON

func (r Result[T, E]) MarshalJSON() ([]byte, error)

func (Result[T, E]) Or

func (r Result[T, E]) Or(fallback T) T

Or returns the success value or fallback.

func (*Result[T, E]) UnmarshalJSON

func (r *Result[T, E]) UnmarshalJSON(data []byte) error

type Runtime

type Runtime struct {
	Kind iwasm.Kind
	// contains filtered or unexported fields
}

func LoadRuntime

func LoadRuntime(filename string) (*Runtime, error)

func LoadRuntimeContext

func LoadRuntimeContext(ctx context.Context, filename string) (*Runtime, error)

func LoadRuntimeFromBytes

func LoadRuntimeFromBytes(data []byte) (*Runtime, error)

func LoadRuntimeFromBytesContext

func LoadRuntimeFromBytesContext(ctx context.Context, data []byte) (*Runtime, error)

func LoadRuntimeFromBytesWithContract

func LoadRuntimeFromBytesWithContract(data []byte, options RuntimeOptions, imports []HostImport, contract Contract) (*Runtime, error)

LoadRuntimeFromBytesWithContract loads an in-memory component and verifies its manifest before instantiation.

func LoadRuntimeFromBytesWithContractContext

func LoadRuntimeFromBytesWithContractContext(ctx context.Context, data []byte, options RuntimeOptions, imports []HostImport, contract Contract) (*Runtime, error)

func LoadRuntimeFromBytesWithImports

func LoadRuntimeFromBytesWithImports(data []byte, options RuntimeOptions, imports []HostImport) (*Runtime, error)

func LoadRuntimeFromBytesWithImportsContext

func LoadRuntimeFromBytesWithImportsContext(ctx context.Context, data []byte, options RuntimeOptions, imports []HostImport) (*Runtime, error)

func LoadRuntimeFromBytesWithOptions

func LoadRuntimeFromBytesWithOptions(data []byte, options RuntimeOptions) (*Runtime, error)

func LoadRuntimeFromBytesWithOptionsContext

func LoadRuntimeFromBytesWithOptionsContext(ctx context.Context, data []byte, options RuntimeOptions) (*Runtime, error)

func LoadRuntimeWithContract

func LoadRuntimeWithContract(filename string, options RuntimeOptions, imports []HostImport, contract Contract) (*Runtime, error)

LoadRuntimeWithContract loads a component and rejects it when its imported or exported function names differ from the contract embedded in generated code.

func LoadRuntimeWithContractContext

func LoadRuntimeWithContractContext(ctx context.Context, filename string, options RuntimeOptions, imports []HostImport, contract Contract) (*Runtime, error)

func LoadRuntimeWithImports

func LoadRuntimeWithImports(filename string, options RuntimeOptions, imports []HostImport) (*Runtime, error)

LoadRuntimeWithImports loads a standard WebAssembly component and exposes only the explicitly listed host functions to it.

func LoadRuntimeWithImportsContext

func LoadRuntimeWithImportsContext(ctx context.Context, filename string, options RuntimeOptions, imports []HostImport) (*Runtime, error)

func LoadRuntimeWithOptions

func LoadRuntimeWithOptions(filename string, options RuntimeOptions) (*Runtime, error)

func LoadRuntimeWithOptionsContext

func LoadRuntimeWithOptionsContext(ctx context.Context, filename string, options RuntimeOptions) (*Runtime, error)

func (*Runtime) AllPluginPaths

func (r *Runtime) AllPluginPaths() []string

AllPluginPaths returns the root and all transitive nested components in this box.

func (*Runtime) Call

func (r *Runtime) Call(name string, args ...any) (any, error)

func (*Runtime) CallContext

func (r *Runtime) CallContext(ctx context.Context, name string, args ...any) (any, error)

CallContext invokes a component export and propagates ctx to host imports. Cancellation is observed before bridge operations and between bridge messages.

func (*Runtime) Close

func (r *Runtime) Close() error

func (*Runtime) ComponentPath

func (r *Runtime) ComponentPath() string

ComponentPath returns the normalized component filename used by this runtime.

func (*Runtime) Composition

func (r *Runtime) Composition() ComponentComposition

Composition returns the exact same-Store graph used to instantiate this runtime. It is used by generated export clients when they become providers.

func (*Runtime) EffectiveOptions

func (r *Runtime) EffectiveOptions() RuntimeOptions

EffectiveOptions returns the resource share assigned to this runtime inside its box. Router pointers are omitted from the returned copy.

func (*Runtime) FuelRemaining

func (r *Runtime) FuelRemaining() (uint64, error)

func (*Runtime) IsClosed

func (r *Runtime) IsClosed() bool

IsClosed reports whether the runtime has been closed. A nil or uninitialized runtime is considered closed.

func (*Runtime) NestedPluginPaths

func (r *Runtime) NestedPluginPaths() []string

NestedPluginPaths returns the direct child components selected automatically for this runtime. The returned slice is safe to modify.

func (*Runtime) SetFuel

func (r *Runtime) SetFuel(fuel uint64) error

SetFuel replaces fuel in the current Store. This is an unsafe host-only administrative operation. Never expose it directly to untrusted guest code.

type RuntimeCallInfo

type RuntimeCallInfo struct {
	CallID            string         `json:"call-id"`
	ParentCallID      Option[string] `json:"parent-call-id"`
	Depth             uint32         `json:"depth"`
	PluginID          string         `json:"plugin-id"`
	DeadlineUnixNanos Option[int64]  `json:"deadline-unix-nanos"`
}

type RuntimeFuelInfo

type RuntimeFuelInfo struct {
	Enabled   bool           `json:"enabled"`
	Remaining Option[uint64] `json:"remaining"`
	Initial   Option[uint64] `json:"initial"`
	Consumed  Option[uint64] `json:"consumed"`
	PerCall   bool           `json:"per-call"`
}

type RuntimeLimitError

type RuntimeLimitError struct {
	Limit   string
	Maximum uint64
	Actual  uint64
	Cause   error
}

func (*RuntimeLimitError) Error

func (e *RuntimeLimitError) Error() string

func (*RuntimeLimitError) Is

func (e *RuntimeLimitError) Is(target error) bool

func (*RuntimeLimitError) Unwrap

func (e *RuntimeLimitError) Unwrap() error

type RuntimeLimits

type RuntimeLimits struct {
	MaxCallDepth       uint32         `json:"max-call-depth"`
	RemainingCallDepth uint32         `json:"remaining-call-depth"`
	MemoryLimitBytes   Option[uint64] `json:"memory-limit-bytes"`
	MaxMessageBytes    Option[uint64] `json:"max-message-bytes"`
	DeadlineUnixNanos  Option[int64]  `json:"deadline-unix-nanos"`
}

type RuntimeOptions

type RuntimeOptions struct {
	Fuel             uint64
	FuelPerCall      uint64
	Timeout          time.Duration
	MemoryLimitBytes int64
	MaxResultBytes   uint64
	InstanceLimit    int64
	// EnableRuntimeAPI binds the versioned witgo:runtime/runtime@1.0.0 vendor
	// capability. Read-only queries are safe; additional fuel remains default-deny.
	EnableRuntimeAPI bool
	// PluginID is the sanitized logical identity reported by RuntimeSystem.
	// It must not contain a path or secret. The zero value is "plugin".
	PluginID string
	// Fuel request settings are used when no CompositionHost is attached.
	FuelRequestPolicy FuelRequestPolicy
	FuelRequestLimits FuelRequestLimits
	SecurityObserver  RuntimeSecurityObserver
	ValueLimits       ValueLimits
	// BridgePath overrides the bundled library and WITGO_COMPONENT_LIBRARY.
	BridgePath string
	// BridgeSHA256 verifies BridgePath before loading. It is required when a
	// custom bridge is supplied in security-sensitive deployments.
	BridgeSHA256 string
	// DisableEmbeddedBridge prevents extraction or loading of the library
	// shipped with witgo. Set BridgePath to use an administrator-managed library.
	DisableEmbeddedBridge bool
	// Capabilities restricts which host import functions a component may require.
	// Zero value allows everything.
	Capabilities CapabilityPolicy
	// NestedPlugins controls automatic resolution of missing imports through
	// exports of sibling Component Model plugins. The zero value enables it.
	NestedPlugins NestedPluginOptions
	// PluginHost centralizes nested-plugin discovery policy. Every top-level
	// load still creates an independent box of runtime instances.
	PluginHost *PluginHost
	// CompositionHost enables transparent registered-provider routing and call
	// chain protection for this runtime.
	CompositionHost *Host
	// CompositionPlugs are exact provider edges encoded into one Component
	// Model component and instantiated in the same Store. Generated bindings
	// populate this field; ordinary applications should use their typed helpers.
	CompositionPlugs []CompositionPlug
}

RuntimeOptions controls resource limits for a Component Model runtime.

type RuntimeSecurityObserver

type RuntimeSecurityObserver interface {
	OnFuelRequest(FuelRequestEvent)
	OnCycleRejected(CycleEvent)
	OnLimitExceeded(LimitEvent)
	OnProviderRejected(ProviderEvent)
}

type SignatureMismatch

type SignatureMismatch struct {
	Function string
	Expected string
	Actual   string
}

SignatureMismatch describes a function whose Component Model type differs from the generated WIT contract.

type Tuple

type Tuple []any

Tuple is the flexible representation used for WIT tuples with more than 16 items. Smaller tuples use the fully typed Tuple0...Tuple16 families.

func NewTuple

func NewTuple(values ...any) Tuple

NewTuple constructs a dynamic tuple.

func (Tuple) At

func (t Tuple) At(index int) (any, bool)

At returns a value by index.

func (Tuple) Set

func (t Tuple) Set(index int, value any) bool

Set replaces a value by index.

func (Tuple) Values

func (t Tuple) Values() []any

Values returns an independent copy of the tuple values.

type Tuple0

type Tuple0 struct{}

func NewTuple0

func NewTuple0() Tuple0

func (Tuple0) MarshalJSON

func (t Tuple0) MarshalJSON() ([]byte, error)

func (*Tuple0) UnmarshalJSON

func (t *Tuple0) UnmarshalJSON(data []byte) error

func (Tuple0) Values

func (Tuple0) Values() []any

type Tuple1

type Tuple1[A any] struct{ V0 A }

func NewTuple1

func NewTuple1[A any](v0 A) Tuple1[A]

func (Tuple1[A]) MarshalJSON

func (t Tuple1[A]) MarshalJSON() ([]byte, error)

func (*Tuple1[A]) UnmarshalJSON

func (t *Tuple1[A]) UnmarshalJSON(data []byte) error

func (Tuple1[A]) Values

func (t Tuple1[A]) Values() []any

type Tuple2

type Tuple2[A, B any] struct {
	V0 A
	V1 B
}

func NewTuple2

func NewTuple2[A, B any](v0 A, v1 B) Tuple2[A, B]

func (Tuple2[A, B]) MarshalJSON

func (t Tuple2[A, B]) MarshalJSON() ([]byte, error)

func (*Tuple2[A, B]) UnmarshalJSON

func (t *Tuple2[A, B]) UnmarshalJSON(data []byte) error

func (Tuple2[A, B]) Values

func (t Tuple2[A, B]) Values() []any

type Tuple3

type Tuple3[A, B, C any] struct {
	V0 A
	V1 B
	V2 C
}

func NewTuple3

func NewTuple3[A, B, C any](v0 A, v1 B, v2 C) Tuple3[A, B, C]

func (Tuple3[A, B, C]) MarshalJSON

func (t Tuple3[A, B, C]) MarshalJSON() ([]byte, error)

func (*Tuple3[A, B, C]) UnmarshalJSON

func (t *Tuple3[A, B, C]) UnmarshalJSON(data []byte) error

func (Tuple3[A, B, C]) Values

func (t Tuple3[A, B, C]) Values() []any

type Tuple4

type Tuple4[A, B, C, D any] struct {
	V0 A
	V1 B
	V2 C
	V3 D
}

func NewTuple4

func NewTuple4[A, B, C, D any](v0 A, v1 B, v2 C, v3 D) Tuple4[A, B, C, D]

func (Tuple4[A, B, C, D]) MarshalJSON

func (t Tuple4[A, B, C, D]) MarshalJSON() ([]byte, error)

func (*Tuple4[A, B, C, D]) UnmarshalJSON

func (t *Tuple4[A, B, C, D]) UnmarshalJSON(data []byte) error

func (Tuple4[A, B, C, D]) Values

func (t Tuple4[A, B, C, D]) Values() []any

type Tuple5

type Tuple5[A, B, C, D, E any] struct {
	V0 A
	V1 B
	V2 C
	V3 D
	V4 E
}

func NewTuple5

func NewTuple5[A, B, C, D, E any](v0 A, v1 B, v2 C, v3 D, v4 E) Tuple5[A, B, C, D, E]

func (Tuple5[A, B, C, D, E]) MarshalJSON

func (t Tuple5[A, B, C, D, E]) MarshalJSON() ([]byte, error)

func (*Tuple5[A, B, C, D, E]) UnmarshalJSON

func (t *Tuple5[A, B, C, D, E]) UnmarshalJSON(data []byte) error

func (Tuple5[A, B, C, D, E]) Values

func (t Tuple5[A, B, C, D, E]) Values() []any

type Tuple6

type Tuple6[A, B, C, D, E, F any] struct {
	V0 A
	V1 B
	V2 C
	V3 D
	V4 E
	V5 F
}

func NewTuple6

func NewTuple6[A, B, C, D, E, F any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F) Tuple6[A, B, C, D, E, F]

func (Tuple6[A, B, C, D, E, F]) MarshalJSON

func (t Tuple6[A, B, C, D, E, F]) MarshalJSON() ([]byte, error)

func (*Tuple6[A, B, C, D, E, F]) UnmarshalJSON

func (t *Tuple6[A, B, C, D, E, F]) UnmarshalJSON(data []byte) error

func (Tuple6[A, B, C, D, E, F]) Values

func (t Tuple6[A, B, C, D, E, F]) Values() []any

type Tuple7

type Tuple7[A, B, C, D, E, F, G any] struct {
	V0 A
	V1 B
	V2 C
	V3 D
	V4 E
	V5 F
	V6 G
}

func NewTuple7

func NewTuple7[A, B, C, D, E, F, G any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G) Tuple7[A, B, C, D, E, F, G]

func (Tuple7[A, B, C, D, E, F, G]) MarshalJSON

func (t Tuple7[A, B, C, D, E, F, G]) MarshalJSON() ([]byte, error)

func (*Tuple7[A, B, C, D, E, F, G]) UnmarshalJSON

func (t *Tuple7[A, B, C, D, E, F, G]) UnmarshalJSON(data []byte) error

func (Tuple7[A, B, C, D, E, F, G]) Values

func (t Tuple7[A, B, C, D, E, F, G]) Values() []any

type Tuple8

type Tuple8[A, B, C, D, E, F, G, H any] struct {
	V0 A
	V1 B
	V2 C
	V3 D
	V4 E
	V5 F
	V6 G
	V7 H
}

func NewTuple8

func NewTuple8[A, B, C, D, E, F, G, H any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H) Tuple8[A, B, C, D, E, F, G, H]

func (Tuple8[A, B, C, D, E, F, G, H]) MarshalJSON

func (t Tuple8[A, B, C, D, E, F, G, H]) MarshalJSON() ([]byte, error)

func (*Tuple8[A, B, C, D, E, F, G, H]) UnmarshalJSON

func (t *Tuple8[A, B, C, D, E, F, G, H]) UnmarshalJSON(data []byte) error

func (Tuple8[A, B, C, D, E, F, G, H]) Values

func (t Tuple8[A, B, C, D, E, F, G, H]) Values() []any

type Tuple9

type Tuple9[A, B, C, D, E, F, G, H, I any] struct {
	V0 A
	V1 B
	V2 C
	V3 D
	V4 E
	V5 F
	V6 G
	V7 H
	V8 I
}

func NewTuple9

func NewTuple9[A, B, C, D, E, F, G, H, I any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H, v8 I) Tuple9[A, B, C, D, E, F, G, H, I]

func (Tuple9[A, B, C, D, E, F, G, H, I]) MarshalJSON

func (t Tuple9[A, B, C, D, E, F, G, H, I]) MarshalJSON() ([]byte, error)

func (*Tuple9[A, B, C, D, E, F, G, H, I]) UnmarshalJSON

func (t *Tuple9[A, B, C, D, E, F, G, H, I]) UnmarshalJSON(data []byte) error

func (Tuple9[A, B, C, D, E, F, G, H, I]) Values

func (t Tuple9[A, B, C, D, E, F, G, H, I]) Values() []any

type Tuple10

type Tuple10[A, B, C, D, E, F, G, H, I, J any] struct {
	V0 A
	V1 B
	V2 C
	V3 D
	V4 E
	V5 F
	V6 G
	V7 H
	V8 I
	V9 J
}

func NewTuple10

func NewTuple10[A, B, C, D, E, F, G, H, I, J any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H, v8 I, v9 J) Tuple10[A, B, C, D, E, F, G, H, I, J]

func (Tuple10[A, B, C, D, E, F, G, H, I, J]) MarshalJSON

func (t Tuple10[A, B, C, D, E, F, G, H, I, J]) MarshalJSON() ([]byte, error)

func (*Tuple10[A, B, C, D, E, F, G, H, I, J]) UnmarshalJSON

func (t *Tuple10[A, B, C, D, E, F, G, H, I, J]) UnmarshalJSON(data []byte) error

func (Tuple10[A, B, C, D, E, F, G, H, I, J]) Values

func (t Tuple10[A, B, C, D, E, F, G, H, I, J]) Values() []any

type Tuple11

type Tuple11[A, B, C, D, E, F, G, H, I, J, K any] struct {
	V0  A
	V1  B
	V2  C
	V3  D
	V4  E
	V5  F
	V6  G
	V7  H
	V8  I
	V9  J
	V10 K
}

func NewTuple11

func NewTuple11[A, B, C, D, E, F, G, H, I, J, K any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H, v8 I, v9 J, v10 K) Tuple11[A, B, C, D, E, F, G, H, I, J, K]

func (Tuple11[A, B, C, D, E, F, G, H, I, J, K]) MarshalJSON

func (t Tuple11[A, B, C, D, E, F, G, H, I, J, K]) MarshalJSON() ([]byte, error)

func (*Tuple11[A, B, C, D, E, F, G, H, I, J, K]) UnmarshalJSON

func (t *Tuple11[A, B, C, D, E, F, G, H, I, J, K]) UnmarshalJSON(data []byte) error

func (Tuple11[A, B, C, D, E, F, G, H, I, J, K]) Values

func (t Tuple11[A, B, C, D, E, F, G, H, I, J, K]) Values() []any

type Tuple12

type Tuple12[A, B, C, D, E, F, G, H, I, J, K, L any] struct {
	V0  A
	V1  B
	V2  C
	V3  D
	V4  E
	V5  F
	V6  G
	V7  H
	V8  I
	V9  J
	V10 K
	V11 L
}

func NewTuple12

func NewTuple12[A, B, C, D, E, F, G, H, I, J, K, L any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H, v8 I, v9 J, v10 K, v11 L) Tuple12[A, B, C, D, E, F, G, H, I, J, K, L]

func (Tuple12[A, B, C, D, E, F, G, H, I, J, K, L]) MarshalJSON

func (t Tuple12[A, B, C, D, E, F, G, H, I, J, K, L]) MarshalJSON() ([]byte, error)

func (*Tuple12[A, B, C, D, E, F, G, H, I, J, K, L]) UnmarshalJSON

func (t *Tuple12[A, B, C, D, E, F, G, H, I, J, K, L]) UnmarshalJSON(data []byte) error

func (Tuple12[A, B, C, D, E, F, G, H, I, J, K, L]) Values

func (t Tuple12[A, B, C, D, E, F, G, H, I, J, K, L]) Values() []any

type Tuple13

type Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M any] struct {
	V0  A
	V1  B
	V2  C
	V3  D
	V4  E
	V5  F
	V6  G
	V7  H
	V8  I
	V9  J
	V10 K
	V11 L
	V12 M
}

func NewTuple13

func NewTuple13[A, B, C, D, E, F, G, H, I, J, K, L, M any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H, v8 I, v9 J, v10 K, v11 L, v12 M) Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M]

func (Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M]) MarshalJSON

func (t Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M]) MarshalJSON() ([]byte, error)

func (*Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M]) UnmarshalJSON

func (t *Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M]) UnmarshalJSON(data []byte) error

func (Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M]) Values

func (t Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M]) Values() []any

type Tuple14

type Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N any] struct {
	V0  A
	V1  B
	V2  C
	V3  D
	V4  E
	V5  F
	V6  G
	V7  H
	V8  I
	V9  J
	V10 K
	V11 L
	V12 M
	V13 N
}

func NewTuple14

func NewTuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H, v8 I, v9 J, v10 K, v11 L, v12 M, v13 N) Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N]

func (Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N]) MarshalJSON

func (t Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N]) MarshalJSON() ([]byte, error)

func (*Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N]) UnmarshalJSON

func (t *Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N]) UnmarshalJSON(data []byte) error

func (Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N]) Values

func (t Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N]) Values() []any

type Tuple15

type Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O any] struct {
	V0  A
	V1  B
	V2  C
	V3  D
	V4  E
	V5  F
	V6  G
	V7  H
	V8  I
	V9  J
	V10 K
	V11 L
	V12 M
	V13 N
	V14 O
}

func NewTuple15

func NewTuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H, v8 I, v9 J, v10 K, v11 L, v12 M, v13 N, v14 O) Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]

func (Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]) MarshalJSON

func (t Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]) MarshalJSON() ([]byte, error)

func (*Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]) UnmarshalJSON

func (t *Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]) UnmarshalJSON(data []byte) error

func (Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]) Values

func (t Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]) Values() []any

type Tuple16

type Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P any] struct {
	V0  A
	V1  B
	V2  C
	V3  D
	V4  E
	V5  F
	V6  G
	V7  H
	V8  I
	V9  J
	V10 K
	V11 L
	V12 M
	V13 N
	V14 O
	V15 P
}

func NewTuple16

func NewTuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P any](v0 A, v1 B, v2 C, v3 D, v4 E, v5 F, v6 G, v7 H, v8 I, v9 J, v10 K, v11 L, v12 M, v13 N, v14 O, v15 P) Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]

func (Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]) MarshalJSON

func (t Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]) MarshalJSON() ([]byte, error)

func (*Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]) UnmarshalJSON

func (t *Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]) UnmarshalJSON(data []byte) error

func (Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]) Values

func (t Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]) Values() []any

type TypeCodec

type TypeCodec[Wire, Go any] interface {
	Encode(Go) (Wire, error)
	Decode(Wire) (Go, error)
}

TypeCodec converts between a canonical WIT wire value and its optional public Go representation. Generated built-in codecs use direct functions, so component calls do not need reflection or a runtime registry.

type TypeCodecFuncs

type TypeCodecFuncs[Wire, Go any] struct {
	EncodeFunc func(Go) (Wire, error)
	DecodeFunc func(Wire) (Go, error)
}

TypeCodecFuncs adapts two typed functions to TypeCodec.

func (TypeCodecFuncs[Wire, Go]) Decode

func (c TypeCodecFuncs[Wire, Go]) Decode(value Wire) (Go, error)

func (TypeCodecFuncs[Wire, Go]) Encode

func (c TypeCodecFuncs[Wire, Go]) Encode(value Go) (Wire, error)

type Unit

type Unit struct{}

Unit represents a WIT type slot without a payload.

func UnitValue

func UnitValue() Unit

UnitValue constructs a WIT unit value.

func (Unit) MarshalJSON

func (Unit) MarshalJSON() ([]byte, error)

func (*Unit) UnmarshalJSON

func (u *Unit) UnmarshalJSON(data []byte) error

type ValidationReport

type ValidationReport struct {
	Compatible bool
	Expected   Contract
	Actual     Contract
	Imports    ContractDifference
	Exports    ContractDifference
	Signatures []SignatureMismatch
}

ValidationReport is the result of inspecting a component without instantiating it or running guest code.

func CompareContracts

func CompareContracts(expected, actual Contract) (ValidationReport, error)

CompareContracts compares two already-inspected manifests without loading a bridge or touching the filesystem.

func ValidateComponent

func ValidateComponent(filename string, expected Contract) (ValidationReport, error)

ValidateComponent compares a component with a generated contract without instantiating it or running guest code. Incompatibility is returned in the report; err is reserved for inspection and bridge failures.

func ValidateComponentBytes

func ValidateComponentBytes(data []byte, expected Contract) (ValidationReport, error)

ValidateComponentBytes compares an in-memory component with a contract.

func ValidateComponentBytesContext

func ValidateComponentBytesContext(ctx context.Context, data []byte, expected Contract) (ValidationReport, error)

func ValidateComponentBytesWithOptions

func ValidateComponentBytesWithOptions(data []byte, options RuntimeOptions, expected Contract) (ValidationReport, error)

ValidateComponentBytesWithOptions is ValidateComponentBytes with explicit bridge options.

func ValidateComponentBytesWithOptionsContext

func ValidateComponentBytesWithOptionsContext(ctx context.Context, data []byte, options RuntimeOptions, expected Contract) (ValidationReport, error)

func ValidateComponentContext

func ValidateComponentContext(ctx context.Context, filename string, expected Contract) (ValidationReport, error)

func ValidateComponentWithOptions

func ValidateComponentWithOptions(filename string, options RuntimeOptions, expected Contract) (ValidationReport, error)

ValidateComponentWithOptions is ValidateComponent with explicit runtime options controlling bridge selection and inspection limits.

func ValidateComponentWithOptionsContext

func ValidateComponentWithOptionsContext(ctx context.Context, filename string, options RuntimeOptions, expected Contract) (ValidationReport, error)

func (ValidationReport) Err

func (r ValidationReport) Err() error

Err converts an incompatible report into an error. It returns nil for a compatible report.

func (ValidationReport) ProblemCount

func (r ValidationReport) ProblemCount() int

ProblemCount returns the number of missing, unexpected, and type-mismatched functions in the report.

func (ValidationReport) Summary

func (r ValidationReport) Summary() string

Summary returns a concise deterministic description suitable for logs.

type ValueLimits

type ValueLimits struct {
	MaxArgumentBytes uint64
	MaxResultBytes   uint64
	MaxCollectionLen uint64
	MaxValueDepth    uint32
	MaxStringBytes   uint64
}

type WITError

type WITError[E any] struct {
	Value E
}

WITError preserves a structured WIT result error payload while implementing Go's error interface. Use errors.As to recover Value without losing its type.

func (WITError[E]) Error

func (e WITError[E]) Error() string

type WITInputMode

type WITInputMode uint8

WITInputMode controls how a WIT input path is expanded.

const (
	// WITInputAuto accepts a file or recursively scans a directory. This keeps
	// the behaviour of Config.WIT from earlier releases.
	WITInputAuto WITInputMode = iota
	// WITInputFile requires exactly one .wit file.
	WITInputFile
	// WITInputPackage loads .wit files directly inside one package directory.
	// Nested directories such as deps are package boundaries and are ignored.
	WITInputPackage
	// WITInputTree recursively loads every .wit file and requires them all to
	// declare the same WIT package.
	WITInputTree
)

Directories

Path Synopsis
examples
components/basic command
Command plugin prints the expected output path for the shared example component binary.
Command plugin prints the expected output path for the shared example component binary.
contracts/basic command
Package generator turns WIT contracts into Go bindings.
Package generator turns WIT contracts into Go bindings.
internal
bridgebin
Package bridgebin contains platform-specific Wasmtime shared libraries.
Package bridgebin contains platform-specific Wasmtime shared libraries.
ast
ir

Jump to

Keyboard shortcuts

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