navidrome/plugins/cmd/ndpgen
Deluan Quintão 1072e9f7eb
chore(plugins): document requiredHosts rules and deprecate pdk.NewHTTPRequest (#6129)
* fix(plugins): align the Python HTTP example with the repo's host-call pattern

Bind http_send with raw memory offsets like nowplaying-py does, drop
guards for fields the host always sends, and document how plugins
without a PDK call host services and which built-in HTTP APIs are
disabled.

* docs(plugins): document the private-address rules for HTTP requiredHosts

Explain in the README and manifest schema that named hosts can't reach
private addresses while IP/CIDR entries and a bare "*" can.

* docs(plugins): document the private-address rules for requiredHosts

Explain in the README and manifest schema that named hosts can't reach
private addresses while IP/CIDR entries and a bare "*" can, for both
HTTP and WebSocket. Inline the single-use HTTP isHostAllowed wrapper.

* feat(plugins): derive Default for Rust host service structs

The ndpgen client.rs template now adds Default to the derive list of host
service structs, as the capability and shared types templates already do.
Plugin authors can now set only the fields they need, for example
HTTPRequest { method, url, ..Default::default() }. The webhook-rs and
discord-rich-presence-rs examples use this form now. The golden files and
the generated nd-pdk-host crate are updated to match.

* feat(plugins): deprecate pdk.NewHTTPRequest in the Go PDK

Navidrome no longer enables extism's http_request host function, so a
request built with pdk.NewHTTPRequest always fails. ndpgen now reads a small
deprecation table and writes a Deprecated: paragraph for the listed extism
functions, in both the WASM wrapper and the native stub. Linters and IDEs
now point plugin authors to host.HTTPSend. The PDK example tests used to
teach NewHTTPRequest. They now use host.HTTPSend and host.HTTPMock.

* docs(plugins): correct requiredHosts rules for websocket and private addresses

Two statements in the plugin docs did not match the code.

The WebSocket section claimed requiredHosts behaves like HTTP. It does not:
host_httpclient.go only consults the allowlist when the list is non-empty and
otherwise falls back to allowing public addresses, while host_websocket.go
always calls isHostInAllowlist, so an absent list blocks every connection.

The HTTP section claimed a named host can never reach a private address.
checkPrivateDial scans the whole requiredHosts list, so a named host does
reach a private address when the same list also holds a covering IP or CIDR.

Reworded both, plus the matching requiredHosts descriptions in
manifest-schema.json, and regenerated manifest_gen.go.
2026-09-12 13:59:46 -04:00
..
internal chore(plugins): document requiredHosts rules and deprecate pdk.NewHTTPRequest (#6129) 2026-09-12 13:59:46 -04:00
testdata chore(plugins): document requiredHosts rules and deprecate pdk.NewHTTPRequest (#6129) 2026-09-12 13:59:46 -04:00
.gitignore feat(plugins): New Plugin System with multi-language PDK support (#4833) 2026-01-14 19:22:48 -05:00
go.mod chore(deps): bump golang.org/x/net in /plugins/cmd/ndpgen (#5698) 2026-07-01 19:24:47 -04:00
go.sum chore(deps): bump golang.org/x/net in /plugins/cmd/ndpgen (#5698) 2026-07-01 19:24:47 -04:00
integration_test.go test(plugins): build test plugins in Go instead of shelling out to make (#6060) 2026-08-31 21:42:10 -04:00
main.go feat(plugins): share plugin DTOs via a types package (#5655) 2026-06-29 21:20:33 -04:00
ndpgen_suite_test.go feat(plugins): New Plugin System with multi-language PDK support (#4833) 2026-01-14 19:22:48 -05:00
README.md feat(plugins): share plugin DTOs via a types package (#5655) 2026-06-29 21:20:33 -04:00
tools.go feat(plugins): New Plugin System with multi-language PDK support (#4833) 2026-01-14 19:22:48 -05:00

ndpgen

Navidrome Plugin Development Kit (PDK) code generator. It reads Go interface definitions with special annotations and generates client wrappers for WASM plugins.

This tool is the unified code generator that handle both host function wrappers and capability wrappers.

Usage

ndpgen -input <dir> -output <dir> [-package <name>] [-v] [-dry-run] [-host-only] [-go] [-rust]

Flags

Flag Description Default
-input Directory containing Go source files with annotated interfaces Required
-output Directory where generated files will be written Same as input
-package Package name for generated files Inferred from output
-v Verbose output false
-dry-run Parse and validate without writing files false
-host-only Generate only host function wrappers (capability support TBD) true
-go Generate Go client wrappers true*
-rust Generate Rust client wrappers false

* -go is enabled by default when -rust is not specified. Use -go -rust to generate both languages.

Example

go run ./plugins/cmd/ndpgen \
  -input ./plugins/host \
  -output ./plugins/pdk

Annotations

//nd:hostservice

Marks an interface as a host service that will have wrappers generated.

//nd:hostservice name=<ServiceName> permission=<permission>
type MyService interface { ... }
Parameter Description Required
name Service name used in generated type names and function prefixes Yes
permission Permission required by plugins to use this service Yes

//nd:hostfunc

Marks a method within a host service interface for export to plugins.

//nd:hostfunc [name=<export_name>]
MethodName(ctx context.Context, ...) (result Type, err error)
Parameter Description Required
name Custom export name (default: <servicename>_<methodname> in lowercase) No

Input Format

Host service interfaces must follow these conventions:

  1. First parameter must be context.Context - Required for all methods
  2. Last return value should be error - For proper error handling
  3. Annotations must be on consecutive lines - No blank comment lines between doc and annotation

Example Interface

package host

import "context"

// SubsonicAPIService provides access to Navidrome's Subsonic API.
// This documentation becomes part of the generated code.
//nd:hostservice name=SubsonicAPI permission=subsonicapi
type SubsonicAPIService interface {
    // Call executes a Subsonic API request and returns the response.
    //nd:hostfunc
    Call(ctx context.Context, uri string) (response string, err error)
}

Generated Output

Go Client Library (Go/TinyGo WASM)

Generated files are named nd_host_<servicename>.go (lowercase) and placed in $output/go/host/. The $output/go/ directory becomes a complete Go module (github.com/navidrome/navidrome/plugins/pdk/go) with package name host, intended for import by Navidrome plugins built with TinyGo.

The generator creates:

  • nd_host_<servicename>.go - Client wrapper code (WASM build)
  • nd_host_<servicename>_stub.go - Mock implementations for non-WASM platforms (testing)
  • doc.go - Package documentation listing all available services
  • go.mod - Go module file with required dependencies

Each service file includes:

  • // Code generated by ndpgen. DO NOT EDIT. header
  • Required imports (encoding/json, errors, github.com/extism/go-pdk)
  • //go:wasmimport declarations for each host function
  • Response struct types and any struct definitions from the service
  • Wrapper functions that handle memory allocation and JSON parsing

Testing Plugins with Mocks

The stub files (*_stub.go) contain testify/mock implementations that allow plugin authors to unit test their code on non-WASM platforms.

Each host service has:

  • A private mock struct embedding mock.Mock
  • An exported auto-instantiated mock instance (e.g., host.CacheMock, host.ArtworkMock)
  • Wrapper functions that delegate to the mock

Example: Testing a plugin that uses the Cache service

package myplugin

import (
    "testing"
    
    "github.com/navidrome/navidrome/plugins/pdk/go/host"
)

func TestMyPluginFunction(t *testing.T) {
    // Set expectations on the mock
    host.CacheMock.On("GetString", "my-key").Return("cached-value", true, nil)
    host.CacheMock.On("SetString", "new-key", "new-value", int64(3600)).Return(nil)
    
    // Call your plugin code that uses host.CacheGetString and host.CacheSetString
    result := myPluginFunction()
    
    // Assert the result
    if result != "expected" {
        t.Errorf("unexpected result: %s", result)
    }
    
    // Verify all expected calls were made
    host.CacheMock.AssertExpectations(t)
}

Resetting mocks between tests:

If you need to reset mock state between tests, testify's mock doesn't have a built-in reset. Either use separate test functions (testify automatically resets between test runs), or create a helper to set up fresh expectations.

Rust Client Library

When using -rust, Rust client files are generated in a rust/ subdirectory.

Supported Types

ndpgen supports these Go types in method signatures:

Type JSON Representation
string, int, bool, etc. Native JSON types
[]T (slices) JSON arrays
map[K]V (maps) JSON objects
*T (pointers) Nullable fields
interface{} / any Converts to any
Custom structs JSON objects (must be JSON-serializable)

Multiple Return Values

Methods can return multiple values (plus error):

//nd:hostfunc
Search(ctx context.Context, query string) (results []string, total int, hasMore bool, err error)

Generates:

type ServiceSearchResponse struct {
    Results []string `json:"results,omitempty"`
    Total   int      `json:"total,omitempty"`
    HasMore bool     `json:"hasMore,omitempty"`
    Error   string   `json:"error,omitempty"`
}

Running Tests

go test ./plugins/cmd/ndpgen/...