feat(plugins): New Plugin System with multi-language PDK support (#4833)

* chore(plugins): remove the old plugins system implementation

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement new plugin system with using Extism

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add capability detection for plugins based on exported functions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add auto-reload functionality for plugins with file watcher support

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add auto-reload functionality for plugins with file watcher support

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): standardize variable names and remove superfluous wrapper functions

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): improve error handling and logging in plugin manager

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): implement plugin function call helper and refactor MetadataAgent methods

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): race condition in plugin manager

* tests(plugins): change BeforeEach to BeforeAll in MetadataAgent tests

Signed-off-by: Deluan <deluan@navidrome.org>

* tests(plugins): optimize tests

Signed-off-by: Deluan <deluan@navidrome.org>

* tests(plugins): more optimizations

Signed-off-by: Deluan <deluan@navidrome.org>

* test(plugins): ignore goroutine leaks from notify library in tests

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add Wikimedia plugin for Navidrome to fetch artist metadata

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): enhance plugin logging and set User-Agent header

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement scrobbler plugin with authorization and scrobbling capabilities

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): integrate logs

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): clean up manifest struct and improve plugin loading logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add metadata agent and scrobbler schemas for bootstrapping plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(hostgen): add hostgen tool for generating Extism host function wrappers

- Implemented hostgen tool to generate wrappers from annotated Go interfaces.
- Added command-line flags for input/output directories and package name.
- Introduced parsing and code generation logic for host services.
- Created test data for various service interfaces and expected generated code.
- Added documentation for host services and annotations for code generation.
- Implemented SubsonicAPI service with corresponding generated code.

* feat(subsonicapi): update Call method to return JSON string response

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement SubsonicAPI host function integration with permissions

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(generator): error-only methods in response handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): generate client wrappers for host functions

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(generator): remove error handling for response.Error in client templates

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(scheduler): add Scheduler service interface with host function wrappers for scheduling tasks

* feat(plugins): add WASI build constraints to client wrapper templates, to avoid lint errors

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(scheduler): implement Scheduler service with one-time and recurring scheduling capabilities

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(manifest): remove unused ConfigPermission from permissions schema

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(scheduler): add scheduler callback schema and implementation for plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(scheduler): streamline scheduling logic and remove unused callback tracking

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(scheduler): add Close method for resource cleanup on plugin unload

Signed-off-by: Deluan <deluan@navidrome.org>

* docs(scheduler): clarify SchedulerCallback requirement for scheduling functions

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: update wasm build rule to include all Go files in the directory

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: rewrite the wikimedia plugin using the XTP CLI

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(scheduler): replace uuid with id.NewRandom for schedule ID generation

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: capabilities registration

Signed-off-by: Deluan <deluan@navidrome.org>

* test: add scheduler service isolation test for plugin instances

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: update plugin manager initialization and encapsulate logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add WebSocket service definitions for plugin communication

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement WebSocket service for plugin integration and connection management

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Crypto Ticker example plugin for real-time cryptocurrency price updates via Coinbase WebSocket API

Also add the lifecycle capability

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: use context.Background() in invokeCallback for scheduled tasks

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: rename plugin.create() to plugin.instance()

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: rename pluginInstance to plugin for consistency across the codebase

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: simplify schedule cloning in Close method and enhance plugin cleanup error handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement Artwork service for generating artwork URLs in Navidrome plugins - WIP

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: moved public URL builders to avoid import cycles

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Cache service for in-memory TTL-based caching in plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Discord Rich Presence example plugin for Navidrome integration

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: host function wrappers to use structured request and response types

- Updated the host function signatures in `nd_host_artwork.go`, `nd_host_scheduler.go`, `nd_host_subsonicapi.go`, and `nd_host_websocket.go` to accept a single parameter for JSON requests.
- Introduced structured request and response types for various cache operations in `nd_host_cache.go`.
- Modified cache functions to marshal requests to JSON and unmarshal responses, improving error handling and code clarity.
- Removed redundant memory allocation for string parameters in favor of JSON marshaling.
- Enhanced error handling in WebSocket and cache operations to return structured error responses.

* refactor: error handling in various plugins to convert response.Error to Go errors

- Updated error handling in `nd_host_scheduler.go`, `nd_host_websocket.go`, `nd_host_artwork.go`, `nd_host_cache.go`, and `nd_host_subsonicapi.go` to convert string errors from responses into Go errors.
- Removed redundant error checks in test data plugins for cleaner code.
- Ensured consistent error handling across all plugins to improve reliability and maintainability.

* refactor: rename fake plugins to test plugins for clarity in integration tests

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add help target to Makefile for plugin usage instructions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Cover Art Archive plugin as an example of Python plugin

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update Makefile and README to clarify Go plugin usage

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: include plugin capabilities in loading log message

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add trace logging for plugin availability and error handling in agents

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Now Playing Logger plugin to showcase calling host functions from Python plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: generate Python client wrappers for various host services

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add generated host function wrappers for Scheduler and SubsonicAPI services

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update Python plugin documentation and usage instructions for host function wrappers

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add Webhook Scrobbler plugin in Rust to send HTTP notifications on scrobble events

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: enable parallel loading of plugins during startup

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README to include WebSocket callback schema in plugin documentation

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: extend plugin watcher with improved logging and debounce duration adjustment

Signed-off-by: Deluan <deluan@navidrome.org>

* add trace message for plugin recompiles

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement plugin cache purging functionality

Signed-off-by: Deluan <deluan@navidrome.org>

* test: move purgeCacheBySize unit tests

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): add plugin repository and database support

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): add plugin management routes and middleware

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): implement plugin synchronization with database for add, update, and remove actions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): add PluginList and PluginShow components with plugin management functionality

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): optimize plugin change detection

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins UI): improve PluginList structure

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): enhance PluginShow with author, website, and permissions display

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): refactor to use MUI and RA components

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins UI): add error handling for plugin enable/disable actions

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): inject PluginManager into native API

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update GetManager to accept DataStore parameter

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add subsonicRouter to Manager and refactor host service registration

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): enhance debug logging for plugin actions and recompile logic

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): break manager.go into smaller, focused files

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): streamline error handling and improve plugin retrieval logic

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update newWebSocketService to use WebSocketPermission for allowed hosts

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): introduce ToggleEnabledSwitch for managing plugin enable/disable state

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update READMEs

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(library): add Library service for metadata access and filesystem integration

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add Library Inspector plugin for periodic library inspection and file size logging

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README to reflect JSON configuration format for plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(build): update target to wasm32-wasip1 for improved WASI support

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement configuration management UI with key-value pairs support

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(ui): adjust grid layout in InfoRow component for improved responsiveness

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): rename ErrorIndicator to EnabledOrErrorField and enhance error handling logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(i18n): add Portuguese translations for plugin management and notifications

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add support for .ndp plugin packages and update build process

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README for .ndp plugin packaging and installation instructions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement KVStore service for persistent key-value storage

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: enhance README with Extism plugin development resources and recommendations

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): integrate event broker into plugin manager

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): update config handling in PluginShow to track last record state

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add Rust host function library and example implementation of Discord Rich Presence plugin in Rust

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): generate Rust lib.rs file to expose host function wrappers

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update JSON field names to camelCase for consistency

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: reduce cyclomatic complexity by refactoring main function

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): enhance Rust code generation with typed struct support and improved type handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add Go client library with host function wrappers and documentation

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): generate Go client stubs for non-WASM platforms

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): update client template file names for consistency

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): add initial implementation of the Navidrome Plugin Development Kit code generator - Pahse 1

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 2

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 2 (2)

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 3

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 4

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implementation of the Navidrome Plugin Development Kit with generated client wrappers and service interfaces - Phase 5

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): consistent naming/types across PDK

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): streamline plugin function signatures and error handling

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update scrobbler interface to return errors directly instead of response structs

Signed-off-by: Deluan <deluan@navidrome.org>

* test: make all test plugins use the PDK

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): reorganize and sort type definitions for consistency

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update error handling for methods to return errors directly

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update function signatures to return values directly instead of response structs

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update request/response types to use private naming conventions

Signed-off-by: Deluan <deluan@navidrome.org>

* build: mark .wasm files as intermediate for cleanup after building .ndp

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): consolidate PDK module path and update Go version to 1.25

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement Rust PDK

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): reorganize Rust output structure to follow standard conventions

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update Discord Rich Presence and Library Inspector plugins to use nd-pdk for service calls and implement lifecycle management

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update macro names for websocket and metadata registration to improve clarity and consistency

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): rename scheduler callback methods for consistency and clarity

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update export wrappers to use `//go:wasmexport` for WebAssembly compatibility

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update plugin registration docs

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): generate host wrappers

Signed-off-by: Deluan <deluan@navidrome.org>

* test(plugins): conditionally run goleak checks based on CI environment

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README to reflect changes in plugin import paths

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(plugins): update plugin instance creation to accept context for cancellation support

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): update return types in metadata interfaces to use pointers

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): enhance type handling for Rust and XTP output in capability generation

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): update IsAuthorized method to return boolean instead of response object

Signed-off-by: Deluan <deluan@navidrome.org>

* test(plugins): add unit tests for rustOutputType and isPrimitiveRustType functions

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(plugins): implement XTP JSONSchema validation for generated schemas

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(plugins): update response types in testMetadataAgent methods to use pointers

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update Go and Rust plugin developer sections for clarity

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: correct example link for library inspector in README

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: clarify artwork URL generation capabilities in service descriptions

Signed-off-by: Deluan <deluan@navidrome.org>

* docs: update README to include Rust PDK crate information for plugin developers

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: handle URL parsing errors and use atomic upsert in plugin repository

Added proper error handling for url.Parse calls in PublicURL and AbsoluteURL
functions. When parsing fails, PublicURL now falls back to AbsoluteURL, and
AbsoluteURL logs the error and returns an empty string, preventing malformed
URLs from being generated.

Replaced the non-atomic UPDATE-then-INSERT pattern in plugin repository Put
method with a single atomic INSERT ... ON CONFLICT statement. This eliminates
potential race conditions and improves consistency with the upsert pattern
already used in host_kvstore.go.

* feat: implement mock service instances for non-WASM builds using testify/mock

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: Discord RPC struct to encapsulate WebSocket logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add support for experimental WebAssembly threads

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add PDK abstraction layer with mock support for non-WASM builds

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add unit tests for Discord plugin and RPC functionality

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: update return types in minimalPlugin and wikimediaPlugin methods to use pointers

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: context cancellation and implement WebSocket callback timeout for improved error handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: conditionally include error handling in generated client code templates

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement ConfigService for plugin configuration management

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: enhance plugin manager to support metrics recording

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: make MockPDK private

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: update interface types to use 'any' in plugin repository methods

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: rename List method to Keys for clarity in configuration management

Signed-off-by: Deluan <deluan@navidrome.org>

* test: add ndpgen plugin tests in the pipeline and update Makefile

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add users permission management to plugin system

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: streamline users integration tests and enhance plugin user management

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor: remove UserID from scrobbler request structure

Signed-off-by: Deluan <deluan@navidrome.org>

* test: add integration tests for UsersService enable gate behavior

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement user permissions for SubsonicAPI and scrobbler plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: show proper error in the UI when enabling a plugin fails

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add library permission management to plugin system

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add user permission for processing scrobbles in Discord Rich Presence plugin

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: implement dynamic loading for buffered scrobbler plugins

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: add GetAdmins method to retrieve admin users from the plugin

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update Portuguese translations for user and library permissions

Signed-off-by: Deluan <deluan@navidrome.org>

* reorder migrations

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: remove unnecessary bulkActionButtons prop from PluginList component

* feat: add manual plugin rescan functionality and corresponding UI action

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement user/library and plugin management integration with cleanup on deletion

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: replace core mock services with test-specific implementations to avoid import cycles

* feat: add ID fields to Artist and Song structs and enhance track loading logic by prioritizing ID matches

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update plugin permissions from allowedHosts to requiredHosts for better clarity and consistency

* feat: refactor plugin host permissions to use RequiredHosts directly for improved clarity

* fix: don't record metrics for plugin calls that aren't implemented at all

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: enhance connection management with improved error handling and cleanup logic

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: introduce ArtistRef struct for better artist representation and update track metadata handling

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: update user configuration handling to use user key prefix for improved clarity

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: enhance ConfigCard input fields with multiline support and vertical resizing

Signed-off-by: Deluan <deluan@navidrome.org>

* fix: rust plugin compilation error

Signed-off-by: Deluan <deluan@navidrome.org>

* feat: implement IsOptionPattern method for better return type handling in Rust PDK generation

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: Deluan <deluan@navidrome.org>
This commit is contained in:
Deluan Quintão
2026-01-14 19:22:48 -05:00
committed by GitHub
parent fd4a04339e
commit 03a45753e9
518 changed files with 49456 additions and 34933 deletions
@@ -0,0 +1,223 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains export wrappers for the {{.Capability.Interface}} capability.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package {{.Package}}
import (
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
{{- /* Generate type alias definitions */ -}}
{{- range .Capability.TypeAliases}}
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
type {{.Name}} {{.Type}}
{{- end}}
{{- /* Generate const definitions */ -}}
{{- range .Capability.Consts}}
{{- if .Values}}
const (
{{- $type := .Type}}
{{- range $i, $v := .Values}}
{{- if $v.Doc}}
{{formatDoc $v.Doc | indent 1}}
{{- end}}
{{- if $type}}
{{$v.Name}} {{$type}} = {{$v.Value}}
{{- else}}
{{$v.Name}} = {{$v.Value}}
{{- end}}
{{- end}}
)
{{- end}}
{{- end}}
{{- /* Generate Error() methods for string type aliases with const values (implements error interface) */ -}}
{{- $consts := .Capability.Consts}}
{{- range .Capability.TypeAliases}}
{{- if eq .Type "string"}}
{{- $typeName := .Name}}
{{- range $consts}}
{{- if eq .Type $typeName}}
// Error implements the error interface for {{$typeName}}.
func (e {{$typeName}}) Error() string { return string(e) }
{{- end}}
{{- end}}
{{- end}}
{{- end}}
{{- /* Generate struct definitions */ -}}
{{- range .Capability.Structs}}
{{- if .Doc}}
{{formatDoc .Doc}}
{{- else}}
// {{.Name}} represents the {{.Name}} data structure.
{{- end}}
type {{.Name}} struct {
{{- range .Fields}}
{{- if .Doc}}
{{formatDoc .Doc | indent 1}}
{{- end}}
{{.Name}} {{.Type}} `json:"{{.JSONTag}}{{if .OmitEmpty}},omitempty{{end}}"`
{{- end}}
}
{{- end}}
{{- /* Generate main interface based on required flag */ -}}
{{if .Capability.Required}}
// {{agentName .Capability}} requires all methods to be implemented.
{{- if .Capability.Doc}}
{{formatDoc .Capability.Doc}}
{{- end}}
type {{agentName .Capability}} interface {
{{- range .Capability.Methods}}
// {{.Name}}{{if .Doc}} - {{.Doc}}{{end}}
{{- if and .HasInput .HasOutput}}
{{.Name}}({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{.Name}}({{.Input.Type}}) error
{{- else if .HasOutput}}
{{.Name}}() ({{.Output.Type}}, error)
{{- else}}
{{.Name}}() error
{{- end}}
{{- end}}
}
{{- else}}
// {{agentName .Capability}} is the marker interface for {{.Package}} plugins.
// Implement one or more of the provider interfaces below.
{{- if .Capability.Doc}}
{{formatDoc .Capability.Doc}}
{{- end}}
type {{agentName .Capability}} interface{}
{{- end}}
{{- /* Generate optional provider interfaces for non-required capabilities */ -}}
{{- if not .Capability.Required}}
{{- range .Capability.Methods}}
// {{providerInterface .}} provides the {{.Name}} function.
type {{providerInterface .}} interface {
{{- if and .HasInput .HasOutput}}
{{.Name}}({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{.Name}}({{.Input.Type}}) error
{{- else if .HasOutput}}
{{.Name}}() ({{.Output.Type}}, error)
{{- else}}
{{.Name}}() error
{{- end}}
}
{{- end}}
{{- end}}
{{- /* Generate implementation function holders */ -}}
// Internal implementation holders
var (
{{- range .Capability.Methods}}
{{- if and .HasInput .HasOutput}}
{{implVar .}} func({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{implVar .}} func({{.Input.Type}}) error
{{- else if .HasOutput}}
{{implVar .}} func() ({{.Output.Type}}, error)
{{- else}}
{{implVar .}} func() error
{{- end}}
{{- end}}
)
// Register registers a {{.Package}} implementation.
{{- if .Capability.Required}}
// All methods are required.
func Register(impl {{agentName .Capability}}) {
{{- range .Capability.Methods}}
{{implVar .}} = impl.{{.Name}}
{{- end}}
}
{{- else}}
// The implementation is checked for optional provider interfaces.
func Register(impl {{agentName .Capability}}) {
{{- range .Capability.Methods}}
if p, ok := impl.({{providerInterface .}}); ok {
{{implVar .}} = p.{{.Name}}
}
{{- end}}
}
{{- end}}
// NotImplementedCode is the standard return code for unimplemented functions.
// The host recognizes this and skips the plugin gracefully.
const NotImplementedCode int32 = -2
{{- /* Generate export wrappers */ -}}
{{range .Capability.Methods}}
//go:wasmexport {{.ExportName}}
func {{exportFunc .}}() int32 {
if {{implVar .}} == nil {
// Return standard code - host will skip this plugin gracefully
return NotImplementedCode
}
{{- if .HasInput}}
var input {{.Input.Type}}
if err := pdk.InputJSON(&input); err != nil {
pdk.SetError(err)
return -1
}
{{- end}}
{{- if and .HasInput .HasOutput}}
output, err := {{implVar .}}(input)
if err != nil {
pdk.SetError(err)
return -1
}
if err := pdk.OutputJSON(output); err != nil {
pdk.SetError(err)
return -1
}
{{- else if .HasInput}}
if err := {{implVar .}}(input); err != nil {
pdk.SetError(err)
return -1
}
{{- else if .HasOutput}}
output, err := {{implVar .}}()
if err != nil {
pdk.SetError(err)
return -1
}
if err := pdk.OutputJSON(output); err != nil {
pdk.SetError(err)
return -1
}
{{- else}}
if err := {{implVar .}}(); err != nil {
pdk.SetError(err)
return -1
}
{{- end}}
return 0
}
{{- end}}
@@ -0,0 +1,184 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains export wrappers for the {{.Capability.Interface}} capability.
// It is intended for use in Navidrome plugins built with extism-pdk.
{{if .Capability.Structs}}
use serde::{Deserialize, Serialize};
{{- if hasHashMap .Capability}}
use std::collections::HashMap;
{{- end}}
{{- end}}
{{- /* Generate type alias definitions */ -}}
{{- range .Capability.TypeAliases}}
{{- if .Doc}}
{{rustDocComment .Doc}}
{{- end}}
pub type {{.Name}} = {{rustTypeAlias .Type}};
{{- end}}
{{- /* Generate const definitions */ -}}
{{- range .Capability.Consts}}
{{- if .Values}}
{{- $type := .Type}}
{{- range $i, $v := .Values}}
{{- if $v.Doc}}
{{rustDocComment $v.Doc}}
{{- end}}
{{- /* Use the type alias name if a named type is provided, otherwise use &'static str */ -}}
{{- if $type}}
pub const {{rustConstName $v.Name}}: {{$type}} = {{$v.Value}};
{{- else}}
pub const {{rustConstName $v.Name}}: &'static str = {{$v.Value}};
{{- end}}
{{- end}}
{{- end}}
{{- end}}
{{- /* Generate struct definitions */ -}}
{{- range .Capability.Structs}}
{{- if .Doc}}
{{rustDocComment .Doc}}
{{- else}}
/// {{.Name}} represents the {{.Name}} data structure.
{{- end}}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct {{.Name}} {
{{- range .Fields}}
{{- if .Doc}}
{{rustDocComment .Doc | indent 4}}
{{- end}}
{{- if .OmitEmpty}}
#[serde(default, skip_serializing_if = "{{skipSerializingFunc .Type}}")]
{{- else}}
#[serde(default)]
{{- end}}
pub {{rustFieldName .Name}}: {{fieldRustType .}},
{{- end}}
}
{{- end}}
/// Error represents an error from a capability method.
#[derive(Debug)]
pub struct Error {
pub message: String,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for Error {}
impl Error {
pub fn new(message: impl Into<String>) -> Self {
Self { message: message.into() }
}
}
{{- /* Generate main interface based on required flag */ -}}
{{if .Capability.Required}}
/// {{agentName .Capability}} requires all methods to be implemented.
{{- if .Capability.Doc}}
{{rustDocComment .Capability.Doc}}
{{- end}}
pub trait {{agentName .Capability}} {
{{- range .Capability.Methods}}
/// {{.Name}}{{if .Doc}} - {{.Doc}}{{end}}
{{- if and .HasInput .HasOutput}}
fn {{rustMethodName .Name}}(&self, req: {{rustOutputType .Input.Type}}) -> Result<{{rustOutputType .Output.Type}}, Error>;
{{- else if .HasInput}}
fn {{rustMethodName .Name}}(&self, req: {{rustOutputType .Input.Type}}) -> Result<(), Error>;
{{- else if .HasOutput}}
fn {{rustMethodName .Name}}(&self) -> Result<{{rustOutputType .Output.Type}}, Error>;
{{- else}}
fn {{rustMethodName .Name}}(&self) -> Result<(), Error>;
{{- end}}
{{- end}}
}
/// Register all exports for the {{agentName .Capability}} capability.
/// This macro generates the WASM export functions for all trait methods.
#[macro_export]
macro_rules! register_{{snakeCase .Package}} {
($plugin_type:ty) => {
{{- range .Capability.Methods}}
#[extism_pdk::plugin_fn]
pub fn {{.ExportName}}(
{{- if .HasInput}}
req: extism_pdk::Json<$crate::{{snakeCase $.Package}}::{{rustOutputType .Input.Type}}>
{{- end}}
) -> extism_pdk::FnResult<{{if .HasOutput}}extism_pdk::Json<{{if isPrimitiveRust .Output.Type}}{{rustOutputType .Output.Type}}{{else}}$crate::{{snakeCase $.Package}}::{{rustOutputType .Output.Type}}{{end}}>{{else}}(){{end}}> {
let plugin = <$plugin_type>::default();
{{- if and .HasInput .HasOutput}}
let result = $crate::{{snakeCase $.Package}}::{{agentName $.Capability}}::{{rustMethodName .Name}}(&plugin, req.into_inner())?;
Ok(extism_pdk::Json(result))
{{- else if .HasInput}}
$crate::{{snakeCase $.Package}}::{{agentName $.Capability}}::{{rustMethodName .Name}}(&plugin, req.into_inner())?;
Ok(())
{{- else if .HasOutput}}
let result = $crate::{{snakeCase $.Package}}::{{agentName $.Capability}}::{{rustMethodName .Name}}(&plugin)?;
Ok(extism_pdk::Json(result))
{{- else}}
$crate::{{snakeCase $.Package}}::{{agentName $.Capability}}::{{rustMethodName .Name}}(&plugin)?;
Ok(())
{{- end}}
}
{{- end}}
};
}
{{- else}}
{{- /* Generate optional provider interfaces for non-required capabilities */ -}}
{{- range .Capability.Methods}}
/// {{providerInterface .}} provides the {{.Name}} function.
pub trait {{providerInterface .}} {
{{- if and .HasInput .HasOutput}}
fn {{rustMethodName .Name}}(&self, req: {{rustOutputType .Input.Type}}) -> Result<{{rustOutputType .Output.Type}}, Error>;
{{- else if .HasInput}}
fn {{rustMethodName .Name}}(&self, req: {{rustOutputType .Input.Type}}) -> Result<(), Error>;
{{- else if .HasOutput}}
fn {{rustMethodName .Name}}(&self) -> Result<{{rustOutputType .Output.Type}}, Error>;
{{- else}}
fn {{rustMethodName .Name}}(&self) -> Result<(), Error>;
{{- end}}
}
/// Register the {{rustMethodName .Name}} export.
/// This macro generates the WASM export function for this method.
#[macro_export]
macro_rules! {{registerMacroName .Name}} {
($plugin_type:ty) => {
#[extism_pdk::plugin_fn]
pub fn {{.ExportName}}(
{{- if .HasInput}}
req: extism_pdk::Json<$crate::{{snakeCase $.Package}}::{{rustOutputType .Input.Type}}>
{{- end}}
) -> extism_pdk::FnResult<{{if .HasOutput}}extism_pdk::Json<{{if isPrimitiveRust .Output.Type}}{{rustOutputType .Output.Type}}{{else}}$crate::{{snakeCase $.Package}}::{{rustOutputType .Output.Type}}{{end}}>{{else}}(){{end}}> {
let plugin = <$plugin_type>::default();
{{- if and .HasInput .HasOutput}}
let result = $crate::{{snakeCase $.Package}}::{{providerInterface .}}::{{rustMethodName .Name}}(&plugin, req.into_inner())?;
Ok(extism_pdk::Json(result))
{{- else if .HasInput}}
$crate::{{snakeCase $.Package}}::{{providerInterface .}}::{{rustMethodName .Name}}(&plugin, req.into_inner())?;
Ok(())
{{- else if .HasOutput}}
let result = $crate::{{snakeCase $.Package}}::{{providerInterface .}}::{{rustMethodName .Name}}(&plugin)?;
Ok(extism_pdk::Json(result))
{{- else}}
$crate::{{snakeCase $.Package}}::{{providerInterface .}}::{{rustMethodName .Name}}(&plugin)?;
Ok(())
{{- end}}
}
};
}
{{- end}}
{{- end}}
@@ -0,0 +1,132 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file provides stub implementations for non-WASM platforms.
// It allows Go plugins to compile and run tests outside of WASM,
// but the actual functionality is only available in WASM builds.
//
//go:build !wasip1
package {{.Package}}
{{- /* Generate type alias definitions */ -}}
{{- range .Capability.TypeAliases}}
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
type {{.Name}} {{.Type}}
{{- end}}
{{- /* Generate const definitions */ -}}
{{- range .Capability.Consts}}
{{- if .Values}}
const (
{{- $type := .Type}}
{{- range $i, $v := .Values}}
{{- if $v.Doc}}
{{formatDoc $v.Doc | indent 1}}
{{- end}}
{{- if $type}}
{{$v.Name}} {{$type}} = {{$v.Value}}
{{- else}}
{{$v.Name}} = {{$v.Value}}
{{- end}}
{{- end}}
)
{{- end}}
{{- end}}
{{- /* Generate Error() methods for string type aliases with const values (implements error interface) */ -}}
{{- $consts := .Capability.Consts}}
{{- range .Capability.TypeAliases}}
{{- if eq .Type "string"}}
{{- $typeName := .Name}}
{{- range $consts}}
{{- if eq .Type $typeName}}
// Error implements the error interface for {{$typeName}}.
func (e {{$typeName}}) Error() string { return string(e) }
{{- end}}
{{- end}}
{{- end}}
{{- end}}
{{- /* Generate struct definitions */ -}}
{{- range .Capability.Structs}}
{{- if .Doc}}
{{formatDoc .Doc}}
{{- else}}
// {{.Name}} represents the {{.Name}} data structure.
{{- end}}
type {{.Name}} struct {
{{- range .Fields}}
{{- if .Doc}}
{{formatDoc .Doc | indent 1}}
{{- end}}
{{.Name}} {{.Type}} `json:"{{.JSONTag}}{{if .OmitEmpty}},omitempty{{end}}"`
{{- end}}
}
{{- end}}
{{- /* Generate main interface based on required flag */ -}}
{{if .Capability.Required}}
// {{agentName .Capability}} requires all methods to be implemented.
{{- if .Capability.Doc}}
{{formatDoc .Capability.Doc}}
{{- end}}
type {{agentName .Capability}} interface {
{{- range .Capability.Methods}}
// {{.Name}}{{if .Doc}} - {{.Doc}}{{end}}
{{- if and .HasInput .HasOutput}}
{{.Name}}({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{.Name}}({{.Input.Type}}) error
{{- else if .HasOutput}}
{{.Name}}() ({{.Output.Type}}, error)
{{- else}}
{{.Name}}() error
{{- end}}
{{- end}}
}
{{- else}}
// {{agentName .Capability}} is the marker interface for {{.Package}} plugins.
// Implement one or more of the provider interfaces below.
{{- if .Capability.Doc}}
{{formatDoc .Capability.Doc}}
{{- end}}
type {{agentName .Capability}} interface{}
{{- end}}
{{- /* Generate optional provider interfaces for non-required capabilities */ -}}
{{- if not .Capability.Required}}
{{- range .Capability.Methods}}
// {{providerInterface .}} provides the {{.Name}} function.
type {{providerInterface .}} interface {
{{- if and .HasInput .HasOutput}}
{{.Name}}({{.Input.Type}}) ({{.Output.Type}}, error)
{{- else if .HasInput}}
{{.Name}}({{.Input.Type}}) error
{{- else if .HasOutput}}
{{.Name}}() ({{.Output.Type}}, error)
{{- else}}
{{.Name}}() error
{{- end}}
}
{{- end}}
{{- end}}
// NotImplementedCode is the standard return code for unimplemented functions.
const NotImplementedCode int32 = -2
// Register is a no-op on non-WASM platforms.
// This stub allows code to compile outside of WASM.
{{- if .Capability.Required}}
func Register(_ {{agentName .Capability}}) {}
{{- else}}
func Register(_ {{agentName .Capability}}) {}
{{- end}}
@@ -0,0 +1,129 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the {{.Service.Name}} host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1
package {{.Package}}
import (
"encoding/json"
{{- if .Service.HasErrors}}
"errors"
{{- end}}
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
{{- /* Generate struct definitions */ -}}
{{- range .Service.Structs}}
// {{.Name}} represents the {{.Name}} data structure.
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
type {{.Name}} struct {
{{- range .Fields}}
{{.Name}} {{.Type}} `json:"{{.JSONTag}}"`
{{- end}}
}
{{- end}}
{{- /* Generate wasmimport declarations for each method */ -}}
{{range .Service.Methods}}
// {{exportName .}} is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user {{exportName .}}
func {{exportName .}}(uint64) uint64
{{- end}}
{{- /* Generate request/response types for all methods (private) */ -}}
{{range .Service.Methods}}
{{- if .HasParams}}
type {{requestType .}} struct {
{{- range .Params}}
{{title .Name}} {{.Type}} `json:"{{.JSONName}}"`
{{- end}}
}
{{- end}}
{{- if not .IsErrorOnly}}
type {{responseType .}} struct {
{{- range .Returns}}
{{title .Name}} {{.Type}} `json:"{{.JSONName}},omitempty"`
{{- end}}
{{- if .HasError}}
Error string `json:"error,omitempty"`
{{- end}}
}
{{- end}}
{{- end}}
{{- /* Generate wrapper functions */ -}}
{{range .Service.Methods}}
// {{$.Service.Name}}{{.Name}} calls the {{exportName .}} host function.
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
func {{$.Service.Name}}{{.Name}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}} {{$p.Type}}{{end}}) {{.ReturnSignature}} {
{{- if .HasParams}}
// Marshal request to JSON
req := {{requestType .}}{
{{- range .Params}}
{{title .Name}}: {{.Name}},
{{- end}}
}
reqBytes, err := json.Marshal(req)
if err != nil {
return {{if .HasReturns}}{{.ZeroValues}}{{end}}{{if and .HasReturns .HasError}}, {{end}}{{if .HasError}}err{{end}}
}
reqMem := pdk.AllocateBytes(reqBytes)
defer reqMem.Free()
{{- else}}
// No parameters - allocate empty JSON object
reqMem := pdk.AllocateBytes([]byte("{}"))
defer reqMem.Free()
{{- end}}
// Call the host function
responsePtr := {{exportName .}}(reqMem.Offset())
// Read the response from memory
responseMem := pdk.FindMemory(responsePtr)
responseBytes := responseMem.ReadBytes()
{{- if .IsErrorOnly}}
// Parse error-only response
var response struct {
Error string `json:"error,omitempty"`
}
if err := json.Unmarshal(responseBytes, &response); err != nil {
return err
}
if response.Error != "" {
return errors.New(response.Error)
}
return nil
{{- else}}
// Parse the response
var response {{responseType .}}
if err := json.Unmarshal(responseBytes, &response); err != nil {
return {{if .HasReturns}}{{.ZeroValues}}{{end}}{{if and .HasReturns .HasError}}, {{end}}{{if .HasError}}err{{end}}
}
{{- if .HasError}}
// Convert Error field to Go error
if response.Error != "" {
return {{if .HasReturns}}{{.ZeroValues}}, {{end}}errors.New(response.Error)
}
{{- end}}
return {{range $i, $r := .Returns}}{{if $i}}, {{end}}response.{{title $r.Name}}{{end}}{{if and .HasReturns .HasError}}, {{end}}{{if .HasError}}nil{{end}}
{{- end}}
}
{{- end}}
@@ -0,0 +1,96 @@
# Code generated by ndpgen. DO NOT EDIT.
#
# This file contains client wrappers for the {{.Service.Name}} host service.
# It is intended for use in Navidrome plugins built with extism-py.
#
# IMPORTANT: Due to a limitation in extism-py, you cannot import this file directly.
# The @extism.import_fn decorators are only detected when defined in the plugin's
# main __init__.py file. Copy the needed functions from this file into your plugin.
from dataclasses import dataclass
from typing import Any
import extism
import json
class HostFunctionError(Exception):
"""Raised when a host function returns an error."""
pass
{{- /* Generate raw host function imports */ -}}
{{range .Service.Methods}}
@extism.import_fn("extism:host/user", "{{exportName .}}")
def _{{exportName .}}(offset: int) -> int:
"""Raw host function - do not call directly."""
...
{{- end}}
{{- /* Generate dataclasses for multi-value returns */ -}}
{{range .Service.Methods}}
{{- if .NeedsResultClass}}
@dataclass
class {{pythonResultType .}}:
"""Result type for {{pythonFunc .}}."""
{{- range .Returns}}
{{.PythonName}}: {{.PythonType}}
{{- end}}
{{- end}}
{{- end}}
{{- /* Generate wrapper functions */ -}}
{{range .Service.Methods}}
def {{pythonFunc .}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.PythonName}}: {{$p.PythonType}}{{end}}){{if .NeedsResultClass}} -> {{pythonResultType .}}{{else if .HasReturns}} -> {{(index .Returns 0).PythonType}}{{else}} -> None{{end}}:
"""{{if .Doc}}{{.Doc}}{{else}}Call the {{exportName .}} host function.{{end}}
{{- if .HasParams}}
Args:
{{- range .Params}}
{{.PythonName}}: {{.PythonType}} parameter.
{{- end}}
{{- end}}
{{- if .HasReturns}}
Returns:
{{- if .NeedsResultClass}}
{{pythonResultType .}} containing{{range .Returns}} {{.PythonName}},{{end}}.
{{- else}}
{{(index .Returns 0).PythonType}}: The result value.
{{- end}}
{{- end}}
Raises:
HostFunctionError: If the host function returns an error.
"""
{{- if .HasParams}}
request = {
{{- range .Params}}
"{{.JSONName}}": {{.PythonName}},
{{- end}}
}
request_bytes = json.dumps(request).encode("utf-8")
{{- else}}
request_bytes = b"{}"
{{- end}}
request_mem = extism.memory.alloc(request_bytes)
response_offset = _{{exportName .}}(request_mem.offset)
response_mem = extism.memory.find(response_offset)
response = json.loads(extism.memory.string(response_mem))
{{if .HasError}}
if response.get("error"):
raise HostFunctionError(response["error"])
{{end}}
{{- if .NeedsResultClass}}
return {{pythonResultType .}}(
{{- range .Returns}}
{{.PythonName}}=response.get("{{.JSONName}}"{{pythonDefault .}}),
{{- end}}
)
{{- else if .HasReturns}}
return response.get("{{(index .Returns 0).JSONName}}"{{pythonDefault (index .Returns 0)}})
{{- end}}
{{- end}}
@@ -0,0 +1,134 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the {{.Service.Name}} host service.
// It is intended for use in Navidrome plugins built with extism-pdk.
use extism_pdk::*;
use serde::{Deserialize, Serialize};
{{- /* Generate struct definitions */ -}}
{{- range .Service.Structs}}
{{if .Doc}}
{{rustDocComment .Doc}}
{{else}}
{{end}}#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct {{.Name}} {
{{- range .Fields}}
{{- if .NeedsDefault}}
#[serde(default)]
{{- end}}
pub {{.RustName}}: {{fieldRustType .}},
{{- end}}
}
{{- end}}
{{- /* Generate request/response types */ -}}
{{- range .Service.Methods}}
{{- if .HasParams}}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct {{requestType .}} {
{{- range .Params}}
{{.RustName}}: {{rustType .}},
{{- end}}
}
{{- end}}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct {{responseType .}} {
{{- range .Returns}}
#[serde(default)]
{{.RustName}}: {{rustType .}},
{{- end}}
{{- if .HasError}}
#[serde(default)]
error: Option<String>,
{{- end}}
}
{{- end}}
#[host_fn]
extern "ExtismHost" {
{{- range .Service.Methods}}
fn {{exportName .}}(input: Json<{{if .HasParams}}{{requestType .}}{{else}}serde_json::Value{{end}}>) -> Json<{{responseType .}}>;
{{- end}}
}
{{- /* Generate wrapper functions */ -}}
{{range .Service.Methods}}
{{if .Doc}}{{rustDocComment .Doc}}{{else}}/// Calls the {{exportName .}} host function.{{end}}
{{- if .HasParams}}
///
/// # Arguments
{{- range .Params}}
/// * `{{.RustName}}` - {{rustType .}} parameter.
{{- end}}
{{- end}}
{{- if .HasReturns}}
///
/// # Returns
{{- if .IsOptionPattern}}
/// `Some({{(index .Returns 0).RustName}})` if found, `None` otherwise.
{{- else if eq (len .Returns) 1}}
/// The {{(index .Returns 0).RustName}} value.
{{- else}}
/// A tuple of ({{range $i, $r := .Returns}}{{if $i}}, {{end}}{{$r.RustName}}{{end}}).
{{- end}}
{{- end}}
///
/// # Errors
/// Returns an error if the host function call fails.
{{- if .IsOptionPattern}}
pub fn {{rustFunc .}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.RustName}}: {{rustParamType $p}}{{end}}) -> Result<Option<{{rustType (index .Returns 0)}}>, Error> {
let response = unsafe {
{{- if .HasParams}}
{{exportName .}}(Json({{requestType .}} {
{{- range .Params}}
{{.RustName}}: {{.RustName}}{{if .NeedsToOwned}}.to_owned(){{end}},
{{- end}}
}))?
{{- else}}
{{exportName .}}(Json(serde_json::json!({})))?
{{- end}}
};
{{if .HasError}}
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
{{end}}
if response.0.{{(index .Returns 1).RustName}} {
Ok(Some(response.0.{{(index .Returns 0).RustName}}))
} else {
Ok(None)
}
}
{{- else}}
pub fn {{rustFunc .}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.RustName}}: {{rustParamType $p}}{{end}}) -> Result<{{if eq (len .Returns) 0}}(){{else if eq (len .Returns) 1}}{{rustType (index .Returns 0)}}{{else}}({{range $i, $r := .Returns}}{{if $i}}, {{end}}{{rustType $r}}{{end}}){{end}}, Error> {
let response = unsafe {
{{- if .HasParams}}
{{exportName .}}(Json({{requestType .}} {
{{- range .Params}}
{{.RustName}}: {{.RustName}}{{if .NeedsToOwned}}.to_owned(){{end}},
{{- end}}
}))?
{{- else}}
{{exportName .}}(Json(serde_json::json!({})))?
{{- end}}
};
{{if .HasError}}
if let Some(err) = response.0.error {
return Err(Error::msg(err));
}
{{end}}
{{- if eq (len .Returns) 0}}
Ok(())
{{- else if eq (len .Returns) 1}}
Ok(response.0.{{(index .Returns 0).RustName}})
{{- else}}
Ok(({{range $i, $r := .Returns}}{{if $i}}, {{end}}response.0.{{$r.RustName}}{{end}}))
{{- end}}
}
{{- end}}
{{- end}}
@@ -0,0 +1,50 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains mock implementations for non-WASM builds.
// These mocks allow IDE support, compilation, and unit testing on non-WASM platforms.
// Plugin authors can use the exported mock instances to set expectations in tests.
//
//go:build !wasip1
package {{.Package}}
import "github.com/stretchr/testify/mock"
{{- /* Generate struct definitions (same as main file, needed for type references in function signatures) */ -}}
{{- range .Service.Structs}}
// {{.Name}} represents the {{.Name}} data structure.
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
type {{.Name}} struct {
{{- range .Fields}}
{{.Name}} {{.Type}} `json:"{{.JSONTag}}"`
{{- end}}
}
{{- end}}
// mock{{.Service.Name}}Service is the mock implementation for testing.
type mock{{.Service.Name}}Service struct {
mock.Mock
}
// {{.Service.Name}}Mock is the auto-instantiated mock instance for testing.
// Use this to set expectations: host.{{.Service.Name}}Mock.On("MethodName", args...).Return(values...)
var {{.Service.Name}}Mock = &mock{{.Service.Name}}Service{}
{{range .Service.Methods}}
// {{.Name}} is the mock method for {{$.Service.Name}}{{.Name}}.
func (m *mock{{$.Service.Name}}Service) {{.Name}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}} {{$p.Type}}{{end}}) {{.ReturnSignature}} {
args := m.Called({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}}{{end}})
return {{mockReturnValues .}}
}
// {{$.Service.Name}}{{.Name}} delegates to the mock instance.
{{- if .Doc}}
{{formatDoc .Doc}}
{{- end}}
func {{$.Service.Name}}{{.Name}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}} {{$p.Type}}{{end}}) {{.ReturnSignature}} {
return {{$.Service.Name}}Mock.{{.Name}}({{range $i, $p := .Params}}{{if $i}}, {{end}}{{$p.Name}}{{end}})
}
{{- end}}
@@ -0,0 +1,49 @@
// Code generated by ndpgen. DO NOT EDIT.
/*
Package {{.Package}} provides Navidrome Plugin Development Kit wrappers for Go/TinyGo plugins.
This package is auto-generated by the ndpgen tool and should not be edited manually.
# Usage
Add this module as a dependency in your plugin's go.mod:
require github.com/navidrome/navidrome/plugins/pdk/go/host v0.0.0
Then import the package in your plugin code:
import {{.Package}} "github.com/navidrome/navidrome/plugins/pdk/go/host"
func myPluginFunction() error {
// Use the cache service
_, err := {{.Package}}.CacheSetString("my_key", "my_value", 3600)
if err != nil {
return err
}
// Schedule a recurring task
_, err = {{.Package}}.SchedulerScheduleRecurring("@every 5m", "payload", "task_id")
if err != nil {
return err
}
return nil
}
# Available Services
The following host services are available:
{{range .Services}}
- {{.Name}}: {{if .Doc}}{{.Doc | firstLine}}{{else}}{{.Name}} service{{end}}
{{- end}}
# Building Plugins
Go plugins must be compiled to WebAssembly using TinyGo:
tinygo build -o plugin.wasm -target=wasip1 -buildmode=c-shared .
See the examples directory for complete plugin implementations.
*/
package {{.Package}}
@@ -0,0 +1,8 @@
module github.com/navidrome/navidrome/plugins/pdk/go
go 1.25
require (
github.com/extism/go-pdk v1.1.3
github.com/stretchr/testify v1.11.1
)
@@ -0,0 +1,121 @@
// Code generated by ndpgen. DO NOT EDIT.
package {{.Package}}
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
)
{{- /* Generate request/response types for all methods */ -}}
{{range .Service.Methods}}
{{- if .HasParams}}
// {{requestType .}} is the request type for {{$.Service.Name}}.{{.Name}}.
type {{requestType .}} struct {
{{- range .Params}}
{{title .Name}} {{.Type}} `json:"{{.JSONName}}"`
{{- end}}
}
{{- end}}
// {{responseType .}} is the response type for {{$.Service.Name}}.{{.Name}}.
type {{responseType .}} struct {
{{- range .Returns}}
{{title .Name}} {{.Type}} `json:"{{.JSONName}},omitempty"`
{{- end}}
{{- if .HasError}}
Error string `json:"error,omitempty"`
{{- end}}
}
{{end}}
// Register{{.Service.Name}}HostFunctions registers {{.Service.Name}} service host functions.
// The returned host functions should be added to the plugin's configuration.
func Register{{.Service.Name}}HostFunctions(service {{.Service.Interface}}) []extism.HostFunction {
return []extism.HostFunction{
{{- range .Service.Methods}}
new{{$.Service.Name}}{{.Name}}HostFunction(service),
{{- end}}
}
}
{{range .Service.Methods}}
func new{{$.Service.Name}}{{.Name}}HostFunction(service {{$.Service.Interface}}) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"{{exportName .}}",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
{{- if .HasParams}}
// Read JSON request from plugin memory
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
{{$.Service.Name | lower}}WriteError(p, stack, err)
return
}
var req {{requestType .}}
if err := json.Unmarshal(reqBytes, &req); err != nil {
{{$.Service.Name | lower}}WriteError(p, stack, err)
return
}
{{- end}}
// Call the service method
{{- if .HasReturns}}
{{- if .HasError}}
{{range $i, $r := .Returns}}{{if $i}}, {{end}}{{lower $r.Name}}{{end}}, svcErr := service.{{.Name}}(ctx{{range .Params}}, req.{{title .Name}}{{end}})
if svcErr != nil {
{{$.Service.Name | lower}}WriteError(p, stack, svcErr)
return
}
{{- else}}
{{range $i, $r := .Returns}}{{if $i}}, {{end}}{{lower $r.Name}}{{end}} := service.{{.Name}}(ctx{{range .Params}}, req.{{title .Name}}{{end}})
{{- end}}
{{- else if .HasError}}
if svcErr := service.{{.Name}}(ctx{{range .Params}}, req.{{title .Name}}{{end}}); svcErr != nil {
{{$.Service.Name | lower}}WriteError(p, stack, svcErr)
return
}
{{- else}}
service.{{.Name}}(ctx{{range .Params}}, req.{{title .Name}}{{end}})
{{- end}}
// Write JSON response to plugin memory
resp := {{responseType .}}{
{{- range .Returns}}
{{title .Name}}: {{lower .Name}},
{{- end}}
}
{{$.Service.Name | lower}}WriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
{{end}}
// {{.Service.Name | lower}}WriteResponse writes a JSON response to plugin memory.
func {{.Service.Name | lower}}WriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
{{.Service.Name | lower}}WriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
// {{.Service.Name | lower}}WriteError writes an error response to plugin memory.
func {{.Service.Name | lower}}WriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}
@@ -0,0 +1,47 @@
// Code generated by ndpgen. DO NOT EDIT.
//
//! Navidrome Host Function Wrappers for Rust Plugins
//!
//! This crate provides idiomatic Rust wrappers for all Navidrome host services.
//! It is auto-generated by the ndpgen tool and should not be edited manually.
//!
//! # Usage
//!
//! Add this crate as a dependency in your plugin's Cargo.toml:
//!
//! ```toml
//! [dependencies]
//! nd-host = { path = "../../host/rust" }
//! ```
//!
//! Then import the services you need:
//!
//! ```ignore
//! use nd_host::{cache, scheduler};
//!
//! fn my_plugin_function() -> Result<(), extism_pdk::Error> {
//! // Use the cache service
//! cache::set_string("my_key", "my_value", 3600)?;
//!
//! // Schedule a recurring task
//! scheduler::schedule_recurring("@every 5m", "payload", "task_id")?;
//!
//! Ok(())
//! }
//! ```
//!
//! # Available Services
//!
{{- range .Services}}
//! - [`{{.Name | lower}}`] - {{if .Doc}}{{.Doc | firstLine}}{{else}}{{.Name}} service{{end}}
{{- end}}
{{range .Services}}
#[doc(hidden)]
mod nd_host_{{.Name | lower}};
/// {{if .Doc}}{{.Doc | firstLine}}{{else}}{{.Name}} host service wrappers.{{end}}
pub mod {{.Name | lower}} {
pub use super::nd_host_{{.Name | lower}}::*;
}
{{end}}
// Re-export commonly used types from extism-pdk for convenience
pub use extism_pdk::Error;
@@ -0,0 +1,50 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains wrapper functions for the extism/go-pdk package.
// For WASM builds, it provides type aliases and function wrappers that delegate
// to the real extism/go-pdk package with zero overhead.
//
//go:build wasip1
package pdk
import (
extism "github.com/extism/go-pdk"
)
// Type aliases - zero overhead, full compatibility
{{- range .Types}}
type {{.Name}} = extism.{{.Name}}
{{- end}}
// Constants
{{- $prevType := ""}}
{{- range .Consts}}
{{- if ne .Type $prevType}}
{{- if ne $prevType ""}}
)
{{- end}}
const (
{{- end}}
{{.Name}} = extism.{{.Name}}
{{- $prevType = .Type}}
{{- end}}
{{- if ne $prevType ""}}
)
{{- end}}
// Functions
{{- range .Functions}}
{{- if .Doc}}
// {{.Name}} {{firstSentence .Doc}}
{{- end}}
func {{.Name}}({{paramList .Params}}){{returnList .Returns}} {
{{- if .Returns}}
return extism.{{.Name}}({{argList .Params}})
{{- else}}
extism.{{.Name}}({{argList .Params}})
{{- end}}
}
{{- end}}
@@ -0,0 +1,42 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains mock implementations for non-WASM builds.
// These mocks allow IDE support, compilation, and unit testing on non-WASM platforms.
// Plugin authors can use the exported PDKMock instance to set expectations in tests.
//
//go:build !wasip1
package pdk
import "github.com/stretchr/testify/mock"
// mockPDK is the mock implementation for testing PDK functions.
type mockPDK struct {
mock.Mock
}
// PDKMock is the auto-instantiated mock instance for testing.
// Use this to set expectations: pdk.PDKMock.On("GetConfig", "key").Return("value", true)
var PDKMock = &mockPDK{}
// ResetMock resets the mock to its initial state.
// Call this in test setup/teardown to ensure clean state between tests.
func ResetMock() {
PDKMock = &mockPDK{}
}
// Functions
{{- range .Functions}}
{{- if .Doc}}
// {{.Name}} {{firstSentence .Doc}}
{{- end}}
func {{.Name}}({{paramList .Params}}){{returnList .Returns}} {
{{- if .Returns}}
args := PDKMock.Called({{argList .Params}})
return {{mockReturns .Returns}}
{{- else}}
PDKMock.Called({{argList .Params}})
{{- end}}
}
{{- end}}
@@ -0,0 +1,192 @@
// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains type definitions for non-WASM builds.
// These types match the extism/go-pdk signatures to allow compilation and testing
// on native platforms without importing the WASM-only extism package.
//
//go:build !wasip1
package pdk
// LogLevel represents a logging level.
type LogLevel int
// Log level constants
const (
LogTrace LogLevel = iota
LogDebug
LogInfo
LogWarn
LogError
)
// HTTPMethod represents an HTTP method.
type HTTPMethod int32
// HTTP method constants
const (
MethodGet HTTPMethod = iota
MethodHead
MethodPost
MethodPut
MethodPatch
MethodDelete
MethodConnect
MethodOptions
MethodTrace
)
// String returns the string representation of the HTTP method.
func (m HTTPMethod) String() string {
switch m {
case MethodGet:
return "GET"
case MethodHead:
return "HEAD"
case MethodPost:
return "POST"
case MethodPut:
return "PUT"
case MethodPatch:
return "PATCH"
case MethodDelete:
return "DELETE"
case MethodConnect:
return "CONNECT"
case MethodOptions:
return "OPTIONS"
case MethodTrace:
return "TRACE"
default:
return "UNKNOWN"
}
}
// Memory represents memory allocated by (and shared with) the host.
// This is a stub implementation for non-WASM platforms.
type Memory struct {
offset uint64
length uint64
data []byte
}
// Offset returns the offset of the memory block.
func (m Memory) Offset() uint64 {
return m.offset
}
// Length returns the length of the memory block.
func (m Memory) Length() uint64 {
return m.length
}
// ReadBytes reads all bytes from the memory block.
func (m Memory) ReadBytes() []byte {
return m.data
}
// Load reads the memory block into the provided buffer.
func (m *Memory) Load(buffer []byte) {
copy(buffer, m.data)
}
// Store writes data to the memory block.
func (m *Memory) Store(data []byte) {
m.data = make([]byte, len(data))
copy(m.data, data)
m.length = uint64(len(data))
}
// Free frees the memory block.
func (m *Memory) Free() {
m.data = nil
m.length = 0
}
// NewStubMemory creates a new stub Memory for testing.
// This is a helper function not present in the real PDK.
func NewStubMemory(offset, length uint64, data []byte) Memory {
return Memory{
offset: offset,
length: length,
data: data,
}
}
// HTTPRequest represents an HTTP request sent by the host.
// This is a stub implementation for non-WASM platforms.
type HTTPRequest struct {
method HTTPMethod
url string
headers map[string]string
body []byte
}
// SetHeader sets an HTTP header key to value.
func (r *HTTPRequest) SetHeader(key string, value string) *HTTPRequest {
if r.headers == nil {
r.headers = make(map[string]string)
}
r.headers[key] = value
return r
}
// SetBody sets the HTTP request body.
func (r *HTTPRequest) SetBody(body []byte) *HTTPRequest {
r.body = body
return r
}
// Send sends the HTTP request and returns the response.
// In the stub implementation, this delegates to the mock.
func (r *HTTPRequest) Send() HTTPResponse {
args := PDKMock.Called(r)
return args.Get(0).(HTTPResponse)
}
// HTTPRequestMeta represents the metadata associated with an HTTP request.
type HTTPRequestMeta struct {
URL string `json:"url"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
}
// HTTPResponse represents an HTTP response returned from the host.
// This is a stub implementation for non-WASM platforms.
type HTTPResponse struct {
status uint16
headers map[string]string
body []byte
memory Memory
}
// Status returns the status code from the response.
func (r HTTPResponse) Status() uint16 {
return r.status
}
// Headers returns the HTTP response headers.
func (r *HTTPResponse) Headers() map[string]string {
return r.headers
}
// Body returns the body byte slice from the response.
func (r HTTPResponse) Body() []byte {
return r.body
}
// Memory returns the memory associated with the response.
func (r HTTPResponse) Memory() Memory {
return r.memory
}
// NewStubHTTPResponse creates a new stub HTTPResponse for testing.
// This is a helper function not present in the real PDK.
func NewStubHTTPResponse(status uint16, headers map[string]string, body []byte) HTTPResponse {
return HTTPResponse{
status: status,
headers: headers,
body: body,
memory: NewStubMemory(0, uint64(len(body)), body),
}
}