API 參考取自原始碼中的 Go 文件註解,以英文撰寫。
package modding
import "github.com/nsgo-dev/game/pkg/modding"概覽
Package modding loads and runs sandboxed TSX/JS game mods on top of NSGo's tsx runtime.
A mod lives in a directory containing a mod.yaml manifest (ModManifest, read by ParseManifest and written by EncodeManifest) and an entry script (such as mod.tsx or mod.js). Mods import the capability-gated "game" module to subscribe to simulation steps and events, emit events, spawn entities, read and write scoped game state, play audio, persist per-mod storage, write logs, and optionally mount TSX UI panels or HUD widgets.
Manager discovers mods from the filesystem or any io/fs.FS, installs or removes individual mods dynamically (Manager.Install, Manager.Uninstall), validates manifests, resolves dependencies in deterministic topological order, isolates faults so a broken mod never crashes the host game or sibling mods, persists enabled/disabled state via core.Storage, and drives step hooks from [game.Loop].
Workshop integrates Steam Workshop (Steamworks ISteamUGC) with Manager through a WorkshopBackend: NewSteamWorkshop binds the Steamworks flat C API via purego on macOS, Linux and Windows (returning ErrWorkshopUnavailable when Steam is absent or on web/mobile), while NewMemoryWorkshop simulates multi-user publishing, subscriptions and updates on disk for tests and offline workflows. Published mods store deterministic Workshop metadata in workshop.yaml (WorkshopMetadata).
索引
- 常數
- 變數
- func CheckConstraint(version, constraint string) (bool, error)
- func EncodeManifest(m ModManifest) ([]byte, error)
- func EncodeWorkshopMetadata(m WorkshopMetadata) ([]byte, error)
- func ValidateConstraint(constraint string) error
- func WriteGameAPIDTS(dst string) error
- type Capability
- func ParseCapability(name string) (Capability, error)
- func (c Capability) Has(req Capability) bool
- func (c Capability) MarshalJSON() ([]byte, error)
- func (c Capability) MarshalYAML() (any, error)
- func (c Capability) Names() []string
- func (c Capability) String() string
- func (c *Capability) UnmarshalJSON(data []byte) error
- func (c *Capability) UnmarshalYAML(value *yaml.Node) error
- type Event
- type GameBridge
- type InstallInfo
- type InstalledWorkshopItem
- type LogEntry
- type Manager
- func NewManager(cx *core.Scope, opts ManagerOptions) *Manager
- func (m *Manager) API(id string) (*ModAPI, bool)
- func (m *Manager) Call(id, fnName string, args []any, done func(result any, err error))
- func (m *Manager) Close()
- func (m *Manager) Disable(id string) error
- func (m *Manager) Discover(dir string) ([]ModManifest, error)
- func (m *Manager) DiscoverFS(fsys fs.FS) ([]ModManifest, error)
- func (m *Manager) Emit(name string, payload any)
- func (m *Manager) Enable(id string) error
- func (m *Manager) GetState(key string) (any, bool)
- func (m *Manager) Info(id string) (ModInfo, bool)
- func (m *Manager) Install(dir string) (ModManifest, error)
- func (m *Manager) InstallFS(fsys fs.FS, dirName string) (ModManifest, error)
- func (m *Manager) List() []ModInfo
- func (m *Manager) Load(id string) error
- func (m *Manager) LoadAll() error
- func (m *Manager) Logs(id string) []LogEntry
- func (m *Manager) Panels(slot string) []Panel
- func (m *Manager) PanelsView(slot string) core.Node
- func (m *Manager) Reload(id string) error
- func (m *Manager) SetGrant(id string, caps Capability) error
- func (m *Manager) SetState(key string, val any)
- func (m *Manager) Step(dt time.Duration)
- func (m *Manager) Uninstall(id string) error
- func (m *Manager) Unload(id string) error
- type ManagerOptions
- type MemoryWorkshop
- func NewMemoryWorkshop(rootDir string) *MemoryWorkshop
- func (m *MemoryWorkshop) AsUser(steamUserID uint64) WorkshopBackend
- func (m *MemoryWorkshop) CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)
- func (m *MemoryWorkshop) DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) error
- func (m *MemoryWorkshop) ItemContentDir(id PublishedFileID) (string, bool)
- func (m *MemoryWorkshop) ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)
- func (m *MemoryWorkshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
- func (m *MemoryWorkshop) SetNeedsLegalAgreement(userID uint64, required bool)
- func (m *MemoryWorkshop) SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)
- func (m *MemoryWorkshop) Subscribe(ctx context.Context, id PublishedFileID) error
- func (m *MemoryWorkshop) SubscribedItems(ctx context.Context) ([]PublishedFileID, error)
- func (m *MemoryWorkshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
- type ModAPI
- func (a *ModAPI) Capabilities() Capability
- func (a *ModAPI) Emit(name string, payload any) error
- func (a *ModAPI) GetState(key string) (any, bool, error)
- func (a *ModAPI) Log(msg string)
- func (a *ModAPI) Logs() []LogEntry
- func (a *ModAPI) Manifest() ModManifest
- func (a *ModAPI) MountPanel(id string, render func() core.Node, slot string) error
- func (a *ModAPI) OnEvent(name string, fn func(payload any)) (func(), error)
- func (a *ModAPI) OnStep(fn func(dt float64)) (func(), error)
- func (a *ModAPI) PlaySound(name string, opts map[string]any) error
- func (a *ModAPI) RegisterHook(event string, fn func(any)) (func(), error)
- func (a *ModAPI) SetState(key string, val any) error
- func (a *ModAPI) Spawn(prefab string, x, y float64, props map[string]any) (string, error)
- func (a *ModAPI) StorageGet(key string) (string, bool, error)
- func (a *ModAPI) StorageRemove(key string) error
- func (a *ModAPI) StorageSet(key, val string) error
- func (a *ModAPI) UnmountPanel(id string) error
- type ModInfo
- type ModManifest
- type ModState
- type Panel
- type PermissionError
- type PublishOptions
- type PublishRequest
- type PublishResult
- type PublishedFileID
- type SemVer
- type SoundRequest
- type SpawnRequest
- type SteamWorkshop
- func NewSteamWorkshop(opts SteamWorkshopOptions) (*SteamWorkshop, error)
- func (w *SteamWorkshop) Close() error
- func (w *SteamWorkshop) CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)
- func (w *SteamWorkshop) DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) error
- func (w *SteamWorkshop) ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)
- func (w *SteamWorkshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
- func (w *SteamWorkshop) SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)
- func (w *SteamWorkshop) Subscribe(ctx context.Context, id PublishedFileID) error
- func (w *SteamWorkshop) SubscribedItems(ctx context.Context) ([]PublishedFileID, error)
- func (w *SteamWorkshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
- type SteamWorkshopOptions
- type SyncResult
- type Workshop
- func NewWorkshop(backend WorkshopBackend, manager *Manager, opts WorkshopOptions) *Workshop
- func (w *Workshop) InstallSubscribed(ctx context.Context, id PublishedFileID) (InstalledWorkshopItem, error)
- func (w *Workshop) Installed() []InstalledWorkshopItem
- func (w *Workshop) Publish(ctx context.Context, dir string, opts PublishOptions) (PublishResult, error)
- func (w *Workshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
- func (w *Workshop) Subscribe(ctx context.Context, id PublishedFileID) error
- func (w *Workshop) SyncSubscribed(ctx context.Context) (SyncResult, error)
- func (w *Workshop) Unsubscribe(ctx context.Context, id PublishedFileID) error
- type WorkshopBackend
- type WorkshopItem
- type WorkshopMetadata
- type WorkshopOptions
- type WorkshopQuery
- type WorkshopVisibility
常數
const (
// WorkshopFile is the deterministic YAML metadata file stored beside mod.yaml in a mod
// directory published to Steam Workshop.
WorkshopFile = "workshop.yaml"
// WorkshopMetadataVersion is the workshop.yaml schema version this package reads and writes.
WorkshopMetadataVersion = 1
// WorkshopLegalAgreementURL is the Steam Workshop Subscriber Agreement page shown when
// Steamworks reports that the publisher must accept the legal agreement before an item
// becomes visible to other players.
WorkshopLegalAgreementURL = "https://steamcommunity.com/sharedfiles/workshoplegalagreement"
)const GameAPIDTS = `// TypeScript declarations for NSGo Game Modding API ("game" module).
declare module "game" {
export type CapabilityName =
| "readState"
| "writeState"
| "spawnEntity"
| "emitEvent"
| "ui"
| "audio"
| "storage";
export type Unsubscribe = () => void;
export interface ModInfo {
readonly id: string;
readonly name: string;
readonly version: string;
readonly author: string;
readonly description: string;
readonly capabilities: CapabilityName[];
}
export interface SoundOptions {
volume?: number;
rate?: number;
loop?: boolean;
}
export type PanelContent = unknown | (() => unknown);
/**
* Registers a hook for a named game event.
* Use "step" to subscribe to fixed-rate simulation ticks (payload is dt in seconds).
*/
export function registerHook(event: string, fn: (payload: any) => void): Unsubscribe;
/**
* Registers a callback invoked on every fixed-rate simulation step.
* @param fn Callback receiving the step duration dt in seconds.
*/
export function onStep(fn: (dt: number) => void): Unsubscribe;
/**
* Subscribes to a named game event emitted by the host or another mod.
*/
export function onEvent<T = any>(name: string, fn: (payload: T) => void): Unsubscribe;
/**
* Emits a named event to the host and subscribed mods.
* Requires the "emitEvent" capability.
*/
export function emit(name: string, payload?: any): void;
/**
* Spawns a game entity from a prefab at world coordinates (x, y).
* Returns the spawned entity ID.
* Requires the "spawnEntity" capability.
*/
export function spawn(
prefab: string,
x: number,
y: number,
props?: Record<string, any>
): string;
/**
* Reads a value from scoped game state, or null if absent.
* Requires the "readState" capability.
*/
export function getState<T = any>(key: string): T | null;
/**
* Writes a value to scoped game state.
* Requires the "writeState" or "storage" capability.
*/
export function setState(key: string, value: any): void;
/**
* Requests playback of a named sound asset.
* Requires the "audio" capability.
*/
export function playSound(name: string, opts?: SoundOptions): void;
/**
* Appends a message to this mod's captured log buffer.
*/
export function log(...args: any[]): void;
/**
* Mounts or updates a TSX UI panel or HUD widget in an optional named slot.
* Requires the "ui" capability.
*/
export function mountPanel(id: string, render: PanelContent, slot?: string): void;
/**
* Unmounts a previously mounted TSX UI panel by ID.
* Requires the "ui" capability.
*/
export function unmountPanel(id: string): void;
/**
* Reads a string from this mod's isolated persistent storage, or null if absent.
* Requires the "storage" capability.
*/
export function storageGet(key: string): string | null;
/**
* Writes a string to this mod's isolated persistent storage.
* Requires the "storage" capability.
*/
export function storageSet(key: string, value: string): void;
/**
* Removes a key from this mod's isolated persistent storage.
* Requires the "storage" capability.
*/
export function storageRemove(key: string): void;
/**
* Returns metadata and effective capabilities for the calling mod.
*/
export function modInfo(): ModInfo;
}
`GameAPIDTS is the TypeScript declaration file (game.d.ts) for the sandboxed "game" module. Mod authors can include it in their tsconfig.json to get full TypeScript type checking.
const GameModule = "game"GameModule is the module specifier mods import to reach the sandboxed game API:
import { onStep, onEvent, emit, spawn, getState, setState, log } from "game";
const ManifestFile = "mod.yaml"ManifestFile is the name of the manifest file Manager reads from each mod's directory.
const ManifestVersion = 1ManifestVersion is the mod manifest schema version this package reads and writes.
變數
var (
// ErrPermission is returned when a mod calls an API it lacks the capability for.
ErrPermission = errors.New("modding: permission denied")
// ErrNotFound is returned when a mod ID is not known to the manager.
ErrNotFound = errors.New("modding: mod not found")
// ErrDuplicateMod is returned when two discovered mods share the same ID.
ErrDuplicateMod = errors.New("modding: duplicate mod id")
// ErrMissingDependency is returned when a mod declares a dependency that was not discovered.
ErrMissingDependency = errors.New("modding: missing dependency")
// ErrVersionMismatch is returned when a dependency or game version fails a version constraint.
ErrVersionMismatch = errors.New("modding: incompatible version")
// ErrCyclicDependency is returned when mod dependencies form a cycle.
ErrCyclicDependency = errors.New("modding: cyclic dependency")
// ErrInvalidManifest is returned when a mod.yaml manifest fails parsing or validation.
ErrInvalidManifest = errors.New("modding: invalid manifest")
// ErrModDisabled is returned when attempting to load a disabled mod.
ErrModDisabled = errors.New("modding: mod is disabled")
// ErrModFailed is returned when interacting with a mod in StateFailed.
ErrModFailed = errors.New("modding: mod failed")
// ErrWebUnisolated is returned when a mod would load on the web, where its capabilities cannot be enforced, without ManagerOptions.WebUnisolated.
ErrWebUnisolated = errors.New("modding: the web cannot isolate mods from the page; set ManagerOptions.WebUnisolated to run them with the page's authority")
)var (
// ErrWorkshopUnavailable is returned when Steamworks is not available (library absent,
// Steam client not running, or unsupported platform such as web or mobile).
// ErrWorkshopNotFound is returned when a Workshop PublishedFileID does not exist.
ErrWorkshopNotFound = errors.New("modding: workshop item not found")
// ErrWorkshopNotInstalled is returned when a Workshop item is not downloaded locally
// or needs an update before it can be read from disk.
ErrWorkshopNotInstalled = errors.New("modding: workshop item not installed")
// ErrWorkshopLegalAgreementRequired is returned when Steamworks requires the author to
// accept the Steam Workshop Subscriber Agreement before the item is public.
ErrWorkshopLegalAgreementRequired = errors.New("modding: steam workshop legal agreement acceptance required")
// ErrInvalidWorkshopMetadata is returned when workshop.yaml fails parsing or validation.
ErrInvalidWorkshopMetadata = errors.New("modding: invalid workshop metadata")
// ErrWorkshopUnsafePath is returned when a Workshop directory or file escapes its
// allowed root or mod directory via path traversal or symlinks.
ErrWorkshopUnsafePath = errors.New("modding: unsafe workshop path")
)函式
func CheckConstraint(version, constraint string) (bool, error)CheckConstraint reports whether version satisfies constraint. Supported operators: *, =, >=, >, <=, <, ^, ~, and space/comma-separated conjunctions.
func EncodeManifest(m ModManifest) ([]byte, error)EncodeManifest validates m and writes it as deterministic 2-space YAML: fields in a fixed order, capabilities in canonical order and dependencies sorted by ID in byte order. A ManifestVersion of 0 (a manifest built in code) is written as ManifestVersion. ParseManifest reads the output back as an equal manifest, and encoding that again gives the same bytes.
func EncodeWorkshopMetadata(m WorkshopMetadata) ([]byte, error)EncodeWorkshopMetadata validates m and encodes it as deterministic 2-space YAML with fixed key order and tags sorted in byte order. A Version of 0 is written as WorkshopMetadataVersion.
func ValidateConstraint(constraint string) errorValidateConstraint checks that constraint is a syntactically valid version constraint.
func WriteGameAPIDTS(dst string) errorWriteGameAPIDTS writes GameAPIDTS to dst (creating parent directories as needed) so mod projects can reference game.d.ts for TypeScript type checking.
型別
type Capability uint32Capability is a bitmask of permissions granted to a mod. A mod may only call game API operations covered by both its manifest and the host's grant.
const (
// CapNone grants no privileged game API capabilities (hooks and logging remain available).
CapNone Capability = 0
// CapReadState allows reading scoped game state via getState.
CapReadState Capability = 1 << iota
// CapWriteState allows writing scoped game state via setState.
CapWriteState
// CapSpawnEntity allows spawning entities via spawn.
CapSpawnEntity
// CapEmitEvent allows emitting game events via emit.
CapEmitEvent
// CapUI allows mounting and unmounting TSX UI panels and HUD widgets.
CapUI
// CapAudio allows playing sounds through the game bridge and NSGo audio.
CapAudio
// CapStorage allows reading/writing persistent per-mod storage (and scoped state writes).
CapStorage
// CapAll includes every defined game modding capability.
CapAll = CapReadState | CapWriteState | CapSpawnEntity | CapEmitEvent | CapUI | CapAudio | CapStorage
)func ParseCapability(name string) (Capability, error)ParseCapability parses a capability name (camelCase, snake_case, or kebab-case).
func (c Capability) Has(req Capability) boolHas reports whether c contains all capabilities in req.
func (c Capability) MarshalJSON() ([]byte, error)MarshalJSON encodes c as a JSON array of canonical capability names.
func (c Capability) MarshalYAML() (any, error)MarshalYAML encodes c as a flow sequence of canonical capability names in table order, so a manifest's capabilities always serialize the same way regardless of how they were listed.
func (c Capability) Names() []stringNames returns the canonical names of the capabilities set in c, in deterministic order.
func (c Capability) String() stringString returns a comma-separated list of capability names, or "none" when empty.
func (c *Capability) UnmarshalJSON(data []byte) errorUnmarshalJSON decodes a JSON array of capability names into c.
func (c *Capability) UnmarshalYAML(value *yaml.Node) errorUnmarshalYAML decodes a YAML sequence of canonical capability names (such as readState) into c. Unknown, non-canonical and repeated names are refused.
type Event struct {
// ModID is the emitting mod's ID, or empty when emitted by the host.
ModID string
Name string
Payload any
}Event describes an event emitted by a mod or by the host game.
type GameBridge struct {
// OnSpawn handles entity spawn requests from mods with CapSpawnEntity.
// Returning an entity ID passes it back to the mod; returning an error throws in JS.
OnSpawn func(req SpawnRequest) (string, error)
// OnEmit is notified whenever a mod with CapEmitEvent emits an event.
// Events are also dispatched to subscribed mods in load order.
OnEmit func(ev Event)
// OnGetState reads a scoped state key for mods with CapReadState.
// When nil, reads from the manager's built-in state map.
OnGetState func(modID, key string) (any, bool)
// OnSetState writes a scoped state key for mods with CapWriteState or CapStorage.
// When nil, writes to the manager's built-in state map.
OnSetState func(modID, key string, val any) error
// OnPlaySound handles audio playback requests from mods with CapAudio.
OnPlaySound func(req SoundRequest) error
// OnLog is notified whenever a mod logs a message, in addition to the per-mod log buffer.
OnLog func(entry LogEntry)
// OnPanelsChange is notified whenever a mod mounts or unmounts a UI panel.
OnPanelsChange func()
}GameBridge connects sandboxed mods to the host game. All callbacks are optional: when nil, Manager supplies safe built-in defaults for scoped state, entity ID generation, event dispatch, and UI panels.
type InstallInfo struct {
ID PublishedFileID
SizeOnDisk uint64
Folder string
Timestamp time.Time
}InstallInfo describes a locally downloaded Steam Workshop item on disk.
type InstalledWorkshopItem struct {
ID PublishedFileID
ModID string
Manifest ModManifest
Folder string
Timestamp time.Time
}InstalledWorkshopItem links a Steam Workshop PublishedFileID to the mod installed in Manager.
type LogEntry struct {
ModID string
Message string
At time.Time
}LogEntry is one captured log line emitted by a mod via game.log.
type Manager struct {
// contains filtered or unexported fields
}Manager discovers, validates, loads, isolates, and steps TSX/JS game mods under a *core.Scope. All methods should be called on the engine's goroutine, as NSGo scopes and game.Loop are.
func NewManager(cx *core.Scope, opts ManagerOptions) *ManagerNewManager creates a mod manager scoped to cx. Disposing cx automatically unloads all mods.
func (m *Manager) API(id string) (*ModAPI, bool)API returns the active *ModAPI for a loaded mod.
func (m *Manager) Call(id, fnName string, args []any, done func(result any, err error))Call invokes an exported JavaScript function on loaded mod id.
func (m *Manager) Close()Close unloads all mods and releases resources held by the manager. Afterwards no mod reports StateLoaded: Manager.Info shows each loaded mod as discovered, or disabled when it is.
func (m *Manager) Disable(id string) errorDisable marks mod id as disabled, unloads it if currently loaded, and persists the preference when StorageKey is configured.
func (m *Manager) Discover(dir string) ([]ModManifest, error)Discover scans immediate subdirectories of dir for mod.yaml manifests, validates them, resolves dependency order, and registers them with the manager.
func (m *Manager) DiscoverFS(fsys fs.FS) ([]ModManifest, error)DiscoverFS scans immediate subdirectories of fsys for mod.yaml manifests (ManifestFile), validates them, checks GameVersion compatibility and entry file existence, resolves dependency order via topological sort, and registers them with the manager. Subdirectories without a manifest are skipped; one that still has only a mod.json is refused with ErrInvalidManifest.
If validation or dependency resolution fails, existing loaded mods are left untouched.
func (m *Manager) Emit(name string, payload any)Emit dispatches a host event to all loaded mods subscribed via onEvent or registerHook, in deterministic load order, with fault isolation.
func (m *Manager) Enable(id string) errorEnable marks mod id as enabled and persists the preference when StorageKey is configured.
func (m *Manager) GetState(key string) (any, bool)GetState reads a value from the manager's built-in scoped game state map.
func (m *Manager) Info(id string) (ModInfo, bool)Info returns the current ModInfo snapshot for mod id.
func (m *Manager) Install(dir string) (ModManifest, error)Install validates a single mod directory on disk and installs or updates it in the manager without disturbing unrelated mods. If a mod with the same ID is already registered, its running instance (if any) is unloaded and replaced. Call Manager.Load or Manager.LoadAll to start the installed mod.
func (m *Manager) InstallFS(fsys fs.FS, dirName string) (ModManifest, error)InstallFS validates a single mod rooted at fsys and installs or updates it in the manager without disturbing unrelated mods. dirName labels the mod directory in manifest errors. Dependency order across all registered mods is re-validated; if validation fails, existing mods remain untouched.
func (m *Manager) List() []ModInfoList returns snapshots of all discovered mods in deterministic load order.
func (m *Manager) Load(id string) errorLoad compiles and starts mod id in its sandbox. Any dependencies not yet loaded are loaded first. Compilation, entry execution, or panic failures are caught cleanly, marking the mod StateFailed without crashing the host or other mods.
func (m *Manager) LoadAll() errorLoadAll loads all enabled discovered mods in deterministic topological order. A failure in one mod is isolated (marking that mod StateFailed) and does not prevent sibling mods from loading. Returns a joined error if any mod failed.
func (m *Manager) Logs(id string) []LogEntryLogs returns a copy of the captured log buffer for mod id.
func (m *Manager) Panels(slot string) []PanelPanels returns all currently mounted UI panels across loaded mods in deterministic order. When slot is non-empty, only panels mounted for that slot are returned.
func (m *Manager) PanelsView(slot string) core.NodePanelsView returns a reactive core.Node rendering all TSX UI panels mounted for slot (or all slots when slot is empty). Each panel is wrapped in a core.Catch boundary so a render error in one mod's UI never crashes the host game or other mods.
func (m *Manager) Reload(id string) errorReload re-reads mod id's manifest if present, validates it, then unloads the mod and loads it fresh from its FS.
A manifest that cannot be read or fails validation (bad syntax, changed ID, incompatible game version or unresolvable dependencies) is reported without unloading, so the previously loaded version keeps running (#546). A mod whose mod.yaml has been replaced by a mod.json is refused the same way with ErrInvalidManifest, as Manager.DiscoverFS refuses it.
func (m *Manager) SetGrant(id string, caps Capability) errorSetGrant sets a per-mod capability grant for id, further narrowing its manifest capabilities (and ManagerOptions.Grant if set).
On a loaded mod it takes effect at once (#546): the game module checks the new capabilities from the next call, revoking CapUI removes the panels the mod mounted, and when the change reaches what the sandbox itself enforces (CapAudio, CapStorage), the mod is unloaded and loaded again with a sandbox built for them, running its entry script again. The error is that load's.
func (m *Manager) SetState(key string, val any)SetState writes a value to the manager's built-in scoped game state map.
func (m *Manager) Step(dt time.Duration)Step invokes all loaded mods' onStep (and registerHook("step", ...)) callbacks in deterministic load order. A runtime error or panic inside one mod isolates and marks that mod StateFailed without interrupting other mods.
func (m *Manager) Uninstall(id string) errorUninstall unloads mod id (if loaded) and removes it from the manager.
func (m *Manager) Unload(id string) errorUnload stops mod id, removes all of its hooks and UI panels, and disposes its sandbox scope.
type ManagerOptions struct {
// Bridge connects mod API calls to the host game.
Bridge GameBridge
// StorageKey, when non-empty, persists mod enabled/disabled state in cx.Storage()
// under "<StorageKey>.enabled.<id>" and isolates per-mod CapStorage keys under
// "<StorageKey>.mod.<id>.<key>".
StorageKey string
// GameVersion, when non-empty, checks each discovered mod's manifest.GameVersion constraint.
GameVersion string
// Grant, when non-nil, narrows every mod's manifest capabilities to (manifest.Capabilities & *Grant).
Grant *Capability
// Limits overrides tsx.DefaultLimits for each mod's sandbox.
Limits *tsx.Limits
// MaxLogs caps the number of retained log entries per mod (256 when <= 0).
MaxLogs int
// WebUnisolated lets mods run on web targets, where the browser cannot isolate a mod from the page: a mod there can use the page's own APIs (XMLHttpRequest, WebSocket, localStorage) whatever its capabilities say. Without it, loading a mod on the web fails with ErrWebUnisolated. Other targets isolate mods and ignore it. It is forwarded as tsx.Sandbox.WebUnisolated.
WebUnisolated bool
}ManagerOptions configures a Manager.
type MemoryWorkshop struct {
// contains filtered or unexported fields
}MemoryWorkshop is an in-memory and filesystem-backed WorkshopBackend that simulates Steam Workshop publishing, querying, subscribing, downloading, and updates without requiring the Steam client. It supports multiple users via MemoryWorkshop.AsUser so one user can publish a mod and another player can subscribe and install it through Manager.
func NewMemoryWorkshop(rootDir string) *MemoryWorkshopNewMemoryWorkshop creates a MemoryWorkshop storing published item snapshots and per-user downloaded copies inside rootDir.
func (m *MemoryWorkshop) AsUser(steamUserID uint64) WorkshopBackendAsUser returns a WorkshopBackend view scoped to steamUserID sharing this Workshop catalog.
func (m *MemoryWorkshop) CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)CreateItem implements WorkshopBackend for the default user (ID 0).
func (m *MemoryWorkshop) DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) errorDownloadItem implements WorkshopBackend for the default user (ID 0).
func (m *MemoryWorkshop) ItemContentDir(id PublishedFileID) (string, bool)ItemContentDir returns the stored Workshop snapshot directory for id, if published.
func (m *MemoryWorkshop) ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)ItemInstallInfo implements WorkshopBackend for the default user (ID 0).
func (m *MemoryWorkshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)QueryItems implements WorkshopBackend for the default user (ID 0).
func (m *MemoryWorkshop) SetNeedsLegalAgreement(userID uint64, required bool)SetNeedsLegalAgreement configures whether SubmitUpdate reports NeedsLegalAgreement for userID (use 0 for the default user when calling methods directly on *MemoryWorkshop).
func (m *MemoryWorkshop) SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)SubmitUpdate implements WorkshopBackend for the default user (ID 0).
func (m *MemoryWorkshop) Subscribe(ctx context.Context, id PublishedFileID) errorSubscribe implements WorkshopBackend for the default user (ID 0).
func (m *MemoryWorkshop) SubscribedItems(ctx context.Context) ([]PublishedFileID, error)SubscribedItems implements WorkshopBackend for the default user (ID 0).
func (m *MemoryWorkshop) Unsubscribe(ctx context.Context, id PublishedFileID) errorUnsubscribe implements WorkshopBackend for the default user (ID 0).
type ModAPI struct {
// contains filtered or unexported fields
}ModAPI is the capability-gated game API bound to a single loaded mod instance. TSX/JS mods access it by importing functions from the "game" module; Go code may also inspect or invoke it via Manager.API.
func (a *ModAPI) Capabilities() CapabilityCapabilities returns the effective capabilities granted to this mod.
func (a *ModAPI) Emit(name string, payload any) errorEmit emits an event to the host bridge and all loaded mods subscribed to name. Requires CapEmitEvent.
func (a *ModAPI) GetState(key string) (any, bool, error)GetState reads a key from scoped game state. Requires CapReadState.
func (a *ModAPI) Log(msg string)Log appends a message to the mod's captured log buffer and notifies Bridge.OnLog.
func (a *ModAPI) Logs() []LogEntryLogs returns a copy of the log entries captured for this mod.
func (a *ModAPI) Manifest() ModManifestManifest returns the mod's manifest.
func (a *ModAPI) MountPanel(id string, render func() core.Node, slot string) errorMountPanel mounts or replaces a TSX UI panel or HUD widget for this mod. Requires CapUI.
func (a *ModAPI) OnEvent(name string, fn func(payload any)) (func(), error)OnEvent registers a callback invoked whenever an event named name is emitted.
func (a *ModAPI) OnStep(fn func(dt float64)) (func(), error)OnStep registers a callback invoked on each Manager.Step tick with dt in seconds.
func (a *ModAPI) PlaySound(name string, opts map[string]any) errorPlaySound requests the host game to play a named sound. Requires CapAudio.
func (a *ModAPI) RegisterHook(event string, fn func(any)) (func(), error)RegisterHook subscribes fn to event. Event "step" subscribes to fixed simulation steps (receiving dt in seconds); any other name subscribes to emitted events of that name.
func (a *ModAPI) SetState(key string, val any) errorSetState writes a key to scoped game state. Requires CapWriteState or CapStorage.
func (a *ModAPI) Spawn(prefab string, x, y float64, props map[string]any) (string, error)Spawn requests the host game to spawn an entity of prefab at (x, y) with optional props. Requires CapSpawnEntity.
func (a *ModAPI) StorageGet(key string) (string, bool, error)StorageGet reads a string value from this mod's isolated persistent storage. Requires CapStorage.
func (a *ModAPI) StorageRemove(key string) errorStorageRemove removes a key from this mod's isolated persistent storage. Requires CapStorage.
func (a *ModAPI) StorageSet(key, val string) errorStorageSet writes a string value to this mod's isolated persistent storage. Requires CapStorage.
func (a *ModAPI) UnmountPanel(id string) errorUnmountPanel removes a previously mounted TSX UI panel. Requires CapUI.
type ModInfo struct {
Manifest ModManifest
State ModState
Enabled bool
Capabilities Capability
Error error
Logs []LogEntry
Order int
}ModInfo is a snapshot of a managed mod's manifest, state, effective capabilities, error, and logs.
type ModManifest struct {
// ManifestVersion is the schema version of the manifest file. A mod.yaml must state [ManifestVersion]; a manifest built in code may leave it 0, and [EncodeManifest] writes [ManifestVersion].
ManifestVersion int `yaml:"manifestVersion" json:"manifestVersion"`
// ID uniquely identifies the mod, such as com.example.boss-rush.
ID string `yaml:"id" json:"id"`
// Name is the mod's human-readable name.
Name string `yaml:"name" json:"name"`
// Version is the mod's own semantic version, which dependency constraints are checked against.
Version string `yaml:"version" json:"version"`
// Author optionally names the mod's author.
Author string `yaml:"author,omitempty" json:"author,omitempty"`
// Description optionally describes the mod.
Description string `yaml:"description,omitempty" json:"description,omitempty"`
// Entry is the entry script's slash-separated path relative to the mod's directory.
Entry string `yaml:"entry" json:"entry"`
// GameVersion optionally constrains the host game versions the mod runs on, such as ">=0.2.0".
GameVersion string `yaml:"gameVersion,omitempty" json:"gameVersion,omitempty"`
// Capabilities lists the game API capabilities the mod requests.
Capabilities Capability `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
// Dependencies maps the IDs of mods this mod requires to version constraints.
Dependencies map[string]string `yaml:"dependencies,omitempty" json:"dependencies,omitempty"`
}ModManifest describes a mod. Mod authors write it as YAML in a ManifestFile (mod.yaml) in the mod's directory; ParseManifest reads it and EncodeManifest writes it.
func ParseManifest(data []byte) (ModManifest, error)ParseManifest parses and validates a mod.yaml manifest. Unknown fields, duplicate keys, trailing YAML documents and a missing or unsupported manifestVersion are refused.
Its errors match ErrInvalidManifest (or ErrCyclicDependency) with errors.Is, and are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile, as Manager does.
func ResolveOrder(manifests []ModManifest) ([]ModManifest, error)ResolveOrder validates manifests and returns them in deterministic topological load order (every dependency precedes every mod that depends on it, with lexicographical ID tie-breaking). It rejects duplicate IDs, missing dependencies, version mismatches, and dependency cycles.
func (m ModManifest) Validate() errorValidate checks that m has a valid ID, name, version, entry path, capabilities, and version constraints. ManifestVersion may be 0 for a manifest built in code, or ManifestVersion; ParseManifest additionally requires a file to state ManifestVersion. Its errors are *loaderr.Error values that name the field at fault and how to fix it, and match ErrInvalidManifest or ErrCyclicDependency with errors.Is.
type ModState uint8ModState is the lifecycle state of a managed mod.
const (
// StateDiscovered means the mod manifest was discovered and validated, and is not loaded.
StateDiscovered ModState = iota
// StateLoaded means the mod is compiled, running in its sandbox, and receiving hooks.
StateLoaded
// StateDisabled means the mod was explicitly disabled and will not be loaded.
StateDisabled
// StateFailed means the mod failed to compile, load, or faulted at runtime.
StateFailed
)func (s ModState) String() stringString returns a human-readable state name.
type Panel struct {
ModID string
ID string
Slot string
Node core.Node
}Panel is a TSX UI panel or HUD widget mounted by a mod via game.mountPanel.
type PermissionError struct {
ModID string
Capability Capability
Action string
}PermissionError reports a blocked capability check. It unwraps to both ErrPermission and a *core.Error with core.CodeAccessDenied, so TSX catches receive error.code, error.permission, and error.resource.
func (e *PermissionError) Error() stringfunc (e *PermissionError) Unwrap() []errorUnwrap exposes ErrPermission and a structured core.Error with CodeAccessDenied.
type PublishOptions struct {
AppID uint32
Title string
Description string
Tags []string
Visibility WorkshopVisibility
Preview string // relative slash-separated path inside the mod directory
ChangeNote string
}PublishOptions customizes a single Workshop.Publish call. Non-zero fields override values from workshop.yaml and mod.yaml.
type PublishRequest struct {
AppID uint32
ID PublishedFileID
Title string
Description string
Tags []string
Visibility WorkshopVisibility
PreviewFile string // absolute path to preview image on disk, or empty
ContentDir string // absolute path to mod content directory on disk
ChangeNote string
}PublishRequest describes a Steam Workshop item update submitted via WorkshopBackend.SubmitUpdate.
type PublishResult struct {
ID PublishedFileID
NeedsLegalAgreement bool
LegalAgreementURL string
}PublishResult reports the outcome of submitting a Steam Workshop item update.
type PublishedFileID uint64PublishedFileID uniquely identifies an item on Steam Workshop (Steamworks PublishedFileId_t).
func (id PublishedFileID) String() stringString formats id as a decimal Steam Workshop item ID.
type SemVer struct {
Major int
Minor int
Patch int
Pre string
}SemVer is a parsed semantic version (MAJOR.MINOR.PATCH[-prerelease]).
func ParseSemVer(raw string) (SemVer, error)ParseSemVer parses a semantic version string such as "1.2.3" or "0.4.0-beta.1".
func (v SemVer) Compare(other SemVer) intCompare compares v and other according to SemVer 2.0.0 precedence.
func (v SemVer) String() stringString formats v as MAJOR.MINOR.PATCH[-prerelease].
type SoundRequest struct {
ModID string
Name string
Volume float64
Rate float64
Loop bool
}SoundRequest describes a sound playback requested by a mod.
type SpawnRequest struct {
ModID string
Prefab string
X, Y float64
Props map[string]any
}SpawnRequest describes an entity spawn requested by a mod.
type SteamWorkshop struct {
// contains filtered or unexported fields
}SteamWorkshop implements WorkshopBackend against the local Steamworks shared library (libsteam_api.dylib on macOS, libsteam_api.so on Linux, steam_api64.dll on Windows) using purego and the Steamworks flat C API without CGo.
func NewSteamWorkshop(opts SteamWorkshopOptions) (*SteamWorkshop, error)NewSteamWorkshop loads the Steamworks shared library via purego, initializes Steamworks (unless opts.SkipInit is set), and binds the flat ISteamUGC and ISteamUtils APIs. When the Steamworks library or running Steam client is absent, it returns an error matching ErrWorkshopUnavailable.
func (w *SteamWorkshop) Close() errorClose shuts down Steamworks (if initialized by NewSteamWorkshop) and unloads the library.
func (w *SteamWorkshop) CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)CreateItem creates a new empty Steam Workshop community item under appID.
func (w *SteamWorkshop) DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) errorDownloadItem starts downloading or updating Workshop item id and waits until Steam reports it is installed and up to date (or ctx is canceled).
func (w *SteamWorkshop) ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)ItemInstallInfo returns the local install folder, size, and update timestamp for id. If the item is not installed or needs an update, it returns ErrWorkshopNotInstalled.
func (w *SteamWorkshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)QueryItems queries Steam Workshop for items matching query.
func (w *SteamWorkshop) SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)SubmitUpdate uploads updated metadata, preview image, and content directory for req.ID.
func (w *SteamWorkshop) Subscribe(ctx context.Context, id PublishedFileID) errorSubscribe subscribes the local Steam user to Workshop item id.
func (w *SteamWorkshop) SubscribedItems(ctx context.Context) ([]PublishedFileID, error)SubscribedItems returns all Workshop item IDs the local Steam user is subscribed to.
func (w *SteamWorkshop) Unsubscribe(ctx context.Context, id PublishedFileID) errorUnsubscribe unsubscribes the local Steam user from Workshop item id.
type SteamWorkshopOptions struct {
// LibraryPath optionally specifies the exact path to the Steamworks shared library
// (libsteam_api.dylib on macOS, libsteam_api.so on Linux, steam_api64.dll on Windows).
// When empty, standard Steamworks library names are probed.
LibraryPath string
// SkipInit skips calling SteamAPI_Init and SteamAPI_Shutdown when the host game
// already manages Steamworks initialization elsewhere.
SkipInit bool
// PollInterval sets how often async SteamAPICall_t handles pump SteamAPI_RunCallbacks
// while waiting for completion. Defaults to 10ms when <= 0.
PollInterval time.Duration
}SteamWorkshopOptions configures NewSteamWorkshop.
type SyncResult struct {
Installed []InstalledWorkshopItem
Updated []InstalledWorkshopItem
Removed []InstalledWorkshopItem
Unchanged []InstalledWorkshopItem
}SyncResult summarizes the changes Workshop.SyncSubscribed applied to Manager.
type Workshop struct {
// contains filtered or unexported fields
}Workshop connects a WorkshopBackend to a *Manager so players can publish mods and levels to Steam Workshop and automatically download, validate, install, update, and remove subscribed items through the mod manager.
func NewWorkshop(backend WorkshopBackend, manager *Manager, opts WorkshopOptions) *WorkshopNewWorkshop creates a Workshop client backed by backend and installing into manager. manager may be nil for publish-only workflows (such as a mod uploader CLI).
func (w *Workshop) InstallSubscribed(ctx context.Context, id PublishedFileID) (InstalledWorkshopItem, error)InstallSubscribed ensures subscribed Workshop item id is downloaded, validates its folder and mod.yaml safely, and installs or updates it in the mod Manager.
func (w *Workshop) Installed() []InstalledWorkshopItemInstalled returns a deterministic snapshot of Workshop items currently installed in the manager.
func (w *Workshop) Publish(ctx context.Context, dir string, opts PublishOptions) (PublishResult, error)Publish validates the mod in dir, creates a Steam Workshop item if workshop.yaml does not yet record a PublishedFileID, submits the update, and writes deterministic workshop.yaml metadata back to dir so subsequent publishes update the same item.
If Steamworks reports that the author must accept the Steam Workshop Subscriber Agreement, Publish still saves the assigned PublishedFileID to workshop.yaml and returns the populated PublishResult alongside an error matching ErrWorkshopLegalAgreementRequired.
func (w *Workshop) QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)QueryItems queries Steam Workshop items matching query.
func (w *Workshop) Subscribe(ctx context.Context, id PublishedFileID) errorSubscribe subscribes the active player to Workshop item id.
func (w *Workshop) SyncSubscribed(ctx context.Context) (SyncResult, error)SyncSubscribed reconciles the mod Manager with all currently subscribed Steam Workshop items: unsubscribed items are unloaded and removed, missing or outdated items are downloaded, install folders and manifests are validated safely, and valid mods are installed in topological dependency order. Failures in individual items are isolated and returned as a joined error so healthy subscribed mods still sync.
func (w *Workshop) Unsubscribe(ctx context.Context, id PublishedFileID) errorUnsubscribe unsubscribes the active player from Workshop item id.
type WorkshopBackend interface {
CreateItem(ctx context.Context, appID uint32) (PublishedFileID, error)
SubmitUpdate(ctx context.Context, req PublishRequest) (PublishResult, error)
Subscribe(ctx context.Context, id PublishedFileID) error
Unsubscribe(ctx context.Context, id PublishedFileID) error
SubscribedItems(ctx context.Context) ([]PublishedFileID, error)
ItemInstallInfo(ctx context.Context, id PublishedFileID) (InstallInfo, error)
DownloadItem(ctx context.Context, id PublishedFileID, highPriority bool) error
QueryItems(ctx context.Context, query WorkshopQuery) ([]WorkshopItem, error)
}WorkshopBackend abstracts the Steamworks ISteamUGC workflow. Use NewSteamWorkshop to talk to the local Steam client on desktop platforms, or NewMemoryWorkshop for deterministic tests and offline workflows.
type WorkshopItem struct {
ID PublishedFileID
AppID uint32
Title string
Description string
Tags []string
Visibility WorkshopVisibility
OwnerID uint64
UpdatedAt time.Time
VotesUp uint32
VotesDown uint32
}WorkshopItem describes a Steam Workshop item returned by WorkshopBackend.QueryItems.
type WorkshopMetadata struct {
// Version is the schema version of workshop.yaml. Files must state [WorkshopMetadataVersion];
// a value built in code may leave it 0 and [EncodeWorkshopMetadata] writes [WorkshopMetadataVersion].
Version int `yaml:"version" json:"version"`
// AppID is the Steam application ID that owns this Workshop item.
AppID uint32 `yaml:"appId" json:"appId"`
// PublishedFileID is the Steam Workshop item ID assigned on first publish, or 0 before upload.
PublishedFileID PublishedFileID `yaml:"publishedFileId,omitempty" json:"publishedFileId,omitempty"`
// Title is the Steam Workshop item title (defaults to ModManifest.Name when omitted).
Title string `yaml:"title,omitempty" json:"title,omitempty"`
// Description is the Steam Workshop item description (defaults to ModManifest.Description when omitted).
Description string `yaml:"description,omitempty" json:"description,omitempty"`
// Tags lists Steam Workshop discovery tags such as "level", "gameplay", or "ui".
Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"`
// Visibility controls who can see the Workshop item (public, friendsOnly, private, unlisted).
Visibility WorkshopVisibility `yaml:"visibility,omitempty" json:"visibility,omitempty"`
// Preview is a relative slash-separated path inside the mod directory to a preview image.
Preview string `yaml:"preview,omitempty" json:"preview,omitempty"`
}WorkshopMetadata is the deterministic YAML sidecar (workshop.yaml) stored in a mod or level directory published to Steam Workshop. Storing PublishedFileID lets subsequent publishes update the existing Workshop item instead of creating duplicates.
func ParseWorkshopMetadata(data []byte) (WorkshopMetadata, error)ParseWorkshopMetadata parses and validates a workshop.yaml file. Unknown fields, duplicate keys, trailing YAML documents, invalid visibility/preview/tag values, and a missing or unsupported version are refused as ErrInvalidWorkshopMetadata.
func (m WorkshopMetadata) Validate() errorValidate checks that m has valid Steam Workshop metadata fields. Version may be 0 for a value constructed in Go, or WorkshopMetadataVersion; ParseWorkshopMetadata requires files to state version: 1.
type WorkshopOptions struct {
// AppID is the default Steam App ID used when creating or publishing items if
// workshop.yaml and PublishOptions do not specify one.
AppID uint32
// AllowedRoots optionally restricts the filesystem roots from which Workshop
// item install directories may be loaded. When non-empty, ItemInstallInfo.Folder
// must resolve inside at least one of these directories after symlink evaluation.
AllowedRoots []string
// AutoLoad automatically calls [Manager.Load] on newly installed or updated enabled
// Workshop mods during [Workshop.SyncSubscribed] and [Workshop.InstallSubscribed].
AutoLoad bool
}WorkshopOptions configures a Workshop client.
type WorkshopQuery struct {
AppID uint32
IDs []PublishedFileID
SearchText string
Tags []string
Page uint32 // 1-based page number (0 is treated as 1)
}WorkshopQuery filters items returned by WorkshopBackend.QueryItems.
type WorkshopVisibility stringWorkshopVisibility controls who can view an item on Steam Workshop.
const (
// VisibilityPublic makes the item visible to everyone on Steam Workshop.
VisibilityPublic WorkshopVisibility = "public"
// VisibilityFriendsOnly restricts visibility to the author's Steam friends.
VisibilityFriendsOnly WorkshopVisibility = "friendsOnly"
// VisibilityPrivate restricts visibility to the author and contributors.
VisibilityPrivate WorkshopVisibility = "private"
// VisibilityUnlisted hides the item from browse/search while allowing direct link access.
VisibilityUnlisted WorkshopVisibility = "unlisted"
)func (v WorkshopVisibility) Valid() boolValid reports whether v is one of the defined Workshop visibility values.