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
+324
View File
@@ -0,0 +1,324 @@
// Example test demonstrating how to use the PDK mock for unit testing.
// This file is only compiled for non-WASM builds.
//
//go:build !wasip1
package pdk_test
import (
"testing"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
"github.com/stretchr/testify/mock"
)
// ExamplePlugin demonstrates a simple plugin that uses PDK functions.
type ExamplePlugin struct{}
// ProcessMessage reads input, logs it, and outputs a response.
func (p *ExamplePlugin) ProcessMessage() error {
// Get configuration
prefix, ok := pdk.GetConfig("message_prefix")
if !ok {
prefix = "Hello"
}
// Read input
message := pdk.InputString()
// Log the message
pdk.Log(pdk.LogInfo, "Processing: "+message)
// Output the response
pdk.OutputString(prefix + ", " + message + "!")
return nil
}
func TestExamplePlugin_ProcessMessage(t *testing.T) {
// Reset mock state before the test
pdk.ResetMock()
// Set up expectations
pdk.PDKMock.On("GetConfig", "message_prefix").Return("Hi", true)
pdk.PDKMock.On("InputString").Return("World")
pdk.PDKMock.On("Log", pdk.LogInfo, "Processing: World").Return()
pdk.PDKMock.On("OutputString", "Hi, World!").Return()
// Call the plugin function
plugin := &ExamplePlugin{}
err := plugin.ProcessMessage()
// Verify no error
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Verify all expected calls were made
pdk.PDKMock.AssertExpectations(t)
}
func TestExamplePlugin_ProcessMessage_DefaultPrefix(t *testing.T) {
// Reset mock state before the test
pdk.ResetMock()
// Set up expectations - config key not found
pdk.PDKMock.On("GetConfig", "message_prefix").Return("", false)
pdk.PDKMock.On("InputString").Return("Test")
pdk.PDKMock.On("Log", pdk.LogInfo, "Processing: Test").Return()
pdk.PDKMock.On("OutputString", "Hello, Test!").Return()
// Call the plugin function
plugin := &ExamplePlugin{}
err := plugin.ProcessMessage()
// Verify no error
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Verify all expected calls were made
pdk.PDKMock.AssertExpectations(t)
}
// Example of testing JSON input/output
type Request struct {
Name string `json:"name"`
Count int `json:"count"`
}
type Response struct {
Message string `json:"message"`
Total int `json:"total"`
}
func ProcessJSONRequest() error {
var req Request
if err := pdk.InputJSON(&req); err != nil {
pdk.SetError(err)
return err
}
resp := Response{
Message: "Hello, " + req.Name,
Total: req.Count * 2,
}
return pdk.OutputJSON(resp)
}
func TestProcessJSONRequest(t *testing.T) {
pdk.ResetMock()
// Mock InputJSON to populate the request struct
pdk.PDKMock.On("InputJSON", mock.AnythingOfType("*pdk_test.Request")).
Return(nil).
Run(func(args mock.Arguments) {
req := args.Get(0).(*Request)
req.Name = "Alice"
req.Count = 5
})
// Expect OutputJSON with the correct response
pdk.PDKMock.On("OutputJSON", Response{
Message: "Hello, Alice",
Total: 10,
}).Return(nil)
// Call the function
err := ProcessJSONRequest()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
pdk.PDKMock.AssertExpectations(t)
}
// =============================================================================
// Examples using stub types (Memory, HTTPRequest, HTTPResponse)
// =============================================================================
// FetchData demonstrates a plugin function that makes an HTTP request.
func FetchData(url string) ([]byte, error) {
// Create and configure the HTTP request
// Note: SetHeader and SetBody work directly on the stub - no mocking needed!
req := pdk.NewHTTPRequest(pdk.MethodGet, url)
req.SetHeader("Accept", "application/json")
req.SetHeader("User-Agent", "MyPlugin/1.0")
// Send the request - this is mocked because it requires host interaction
resp := req.Send()
// Check status - works directly on the stub
if resp.Status() != 200 {
return nil, nil
}
// Return body - works directly on the stub
return resp.Body(), nil
}
func TestFetchData(t *testing.T) {
pdk.ResetMock()
// Create a stub response with test data
expectedBody := []byte(`{"result": "success"}`)
stubResponse := pdk.NewStubHTTPResponse(200, map[string]string{
"Content-Type": "application/json",
}, expectedBody)
// Mock NewHTTPRequest to return a real HTTPRequest struct
// The struct methods (SetHeader, SetBody) work without mocking
pdk.PDKMock.On("NewHTTPRequest", pdk.MethodGet, "https://api.example.com/data").
Return(&pdk.HTTPRequest{})
// Mock Send to return our stub response
pdk.PDKMock.On("Send", mock.AnythingOfType("*pdk.HTTPRequest")).
Return(stubResponse)
// Call the function
body, err := FetchData("https://api.example.com/data")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(body) != string(expectedBody) {
t.Errorf("expected body %q, got %q", expectedBody, body)
}
pdk.PDKMock.AssertExpectations(t)
}
func TestFetchData_NonOKStatus(t *testing.T) {
pdk.ResetMock()
// Create a stub response with 404 status
stubResponse := pdk.NewStubHTTPResponse(404, nil, []byte("Not Found"))
pdk.PDKMock.On("NewHTTPRequest", pdk.MethodGet, "https://api.example.com/missing").
Return(&pdk.HTTPRequest{})
pdk.PDKMock.On("Send", mock.AnythingOfType("*pdk.HTTPRequest")).
Return(stubResponse)
// Call the function
body, err := FetchData("https://api.example.com/missing")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Should return nil for non-200 status
if body != nil {
t.Errorf("expected nil body for 404, got %q", body)
}
pdk.PDKMock.AssertExpectations(t)
}
// ProcessMemoryData demonstrates working with Memory type.
func ProcessMemoryData(mem pdk.Memory) string {
// Memory methods work directly on the stub - no mocking needed!
data := mem.ReadBytes()
return "Processed " + string(data) + " (length: " + formatUint64(mem.Length()) + ")"
}
func formatUint64(n uint64) string {
return string(rune('0' + n%10)) // Simplified for demo
}
func TestProcessMemoryData(t *testing.T) {
// Create stub memory with test data - no mocking needed!
mem := pdk.NewStubMemory(0, 5, []byte("hello"))
result := ProcessMemoryData(mem)
expected := "Processed hello (length: 5)"
if result != expected {
t.Errorf("expected %q, got %q", expected, result)
}
}
// StoreAndRetrieve demonstrates Memory Store/Load methods.
func TestMemoryStoreAndLoad(t *testing.T) {
// Create empty memory
mem := pdk.NewStubMemory(100, 0, nil)
// Store data - works directly, no mock needed
mem.Store([]byte("test data"))
// Verify the data was stored
if mem.Length() != 9 {
t.Errorf("expected length 9, got %d", mem.Length())
}
// Load into buffer
buffer := make([]byte, 9)
mem.Load(buffer)
if string(buffer) != "test data" {
t.Errorf("expected 'test data', got %q", buffer)
}
// Free the memory
mem.Free()
if mem.Length() != 0 {
t.Errorf("expected length 0 after free, got %d", mem.Length())
}
}
// HTTPMethodString demonstrates that HTTPMethod.String() works without mocking.
func TestHTTPMethodString(t *testing.T) {
// These work directly - no mocking needed!
tests := []struct {
method pdk.HTTPMethod
expected string
}{
{pdk.MethodGet, "GET"},
{pdk.MethodPost, "POST"},
{pdk.MethodPut, "PUT"},
{pdk.MethodDelete, "DELETE"},
}
for _, tc := range tests {
result := tc.method.String()
if result != tc.expected {
t.Errorf("expected %q for method %d, got %q", tc.expected, tc.method, result)
}
}
}
// PostJSON demonstrates a more complex HTTP request with body.
func PostJSON(url string, data []byte) (int, error) {
req := pdk.NewHTTPRequest(pdk.MethodPost, url)
req.SetHeader("Content-Type", "application/json")
req.SetBody(data) // Works directly on stub
resp := req.Send() // This is mocked
return int(resp.Status()), nil
}
func TestPostJSON(t *testing.T) {
pdk.ResetMock()
stubResponse := pdk.NewStubHTTPResponse(201, nil, nil)
pdk.PDKMock.On("NewHTTPRequest", pdk.MethodPost, "https://api.example.com/items").
Return(&pdk.HTTPRequest{})
pdk.PDKMock.On("Send", mock.AnythingOfType("*pdk.HTTPRequest")).
Return(stubResponse)
status, err := PostJSON("https://api.example.com/items", []byte(`{"name":"test"}`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if status != 201 {
t.Errorf("expected status 201, got %d", status)
}
pdk.PDKMock.AssertExpectations(t)
}
+204
View File
@@ -0,0 +1,204 @@
// 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
type HTTPMethod = extism.HTTPMethod
type HTTPRequest = extism.HTTPRequest
type HTTPRequestMeta = extism.HTTPRequestMeta
type HTTPResponse = extism.HTTPResponse
type LogLevel = extism.LogLevel
type Memory = extism.Memory
// Constants
const (
LogDebug = extism.LogDebug
LogError = extism.LogError
LogInfo = extism.LogInfo
LogTrace = extism.LogTrace
LogWarn = extism.LogWarn
)
const (
MethodConnect = extism.MethodConnect
MethodDelete = extism.MethodDelete
MethodGet = extism.MethodGet
MethodHead = extism.MethodHead
MethodOptions = extism.MethodOptions
MethodPatch = extism.MethodPatch
MethodPost = extism.MethodPost
MethodPut = extism.MethodPut
MethodTrace = extism.MethodTrace
)
// Functions
func Allocate(length int) Memory {
return extism.Allocate(length)
}
func AllocateBytes(data []byte) Memory {
return extism.AllocateBytes(data)
}
// AllocateJSON AllocateJSON allocates and saves the type `any` into Memory on the host.
func AllocateJSON(v any) (Memory, error) {
return extism.AllocateJSON(v)
}
// AllocateString AllocateString allocates and saves the UTF-8 string `data` into Memory on the host.
func AllocateString(data string) Memory {
return extism.AllocateString(data)
}
// FindMemory FindMemory finds the host memory block at the given `offset`.
func FindMemory(offset uint64) Memory {
return extism.FindMemory(offset)
}
// GetConfig GetConfig returns the config string associated with `key` (if any).
func GetConfig(key string) (string, bool) {
return extism.GetConfig(key)
}
// GetVar GetVar returns the byte slice (if any) associated with `key`.
func GetVar(key string) []byte {
return extism.GetVar(key)
}
// GetVarInt GetVarInt returns the int associated with `key` (or 0 if none).
func GetVarInt(key string) int {
return extism.GetVarInt(key)
}
// Input Input returns a slice of bytes from the host.
func Input() []byte {
return extism.Input()
}
// InputJSON InputJSON returns unmartialed JSON data from the host "input".
func InputJSON(v any) error {
return extism.InputJSON(v)
}
// InputString InputString returns the input data from the host as a UTF-8 string.
func InputString() string {
return extism.InputString()
}
// JSONFrom JSONFrom unmarshals a `Memory` block located at `offset` from the host into the provided data `v`.
func JSONFrom(offset uint64, v any) error {
return extism.JSONFrom(offset, v)
}
// Log Log logs the provided UTF-8 string `s` on the host using the provided log `level`.
func Log(level LogLevel, s string) {
extism.Log(level, s)
}
// LogMemory LogMemory logs the `memory` block on the host using the provided log `level`.
func LogMemory(level LogLevel, m Memory) {
extism.LogMemory(level, m)
}
// NewHTTPRequest NewHTTPRequest returns a new `HTTPRequest`.
func NewHTTPRequest(method HTTPMethod, url string) *HTTPRequest {
return extism.NewHTTPRequest(method, url)
}
func NewMemory(offset uint64, length uint64) Memory {
return extism.NewMemory(offset, length)
}
// Output Output sends the `data` slice of bytes to the host output.
func Output(data []byte) {
extism.Output(data)
}
// OutputJSON OutputJSON marshals the provided data `v` as output to the host.
func OutputJSON(v any) error {
return extism.OutputJSON(v)
}
// OutputMemory OutputMemory sends the `mem` Memory to the host output.
func OutputMemory(mem Memory) {
extism.OutputMemory(mem)
}
// OutputString OutputString sends the UTF-8 string `s` to the host output.
func OutputString(s string) {
extism.OutputString(s)
}
// ParamBytes ParamBytes returns bytes from Extism host memory given an offset.
func ParamBytes(offset uint64) []byte {
return extism.ParamBytes(offset)
}
// ParamString ParamString returns UTF-8 string data from Extism host memory given an offset.
func ParamString(offset uint64) string {
return extism.ParamString(offset)
}
// ParamU32 ParamU32 returns a uint32 from Extism host memory given an offset.
func ParamU32(offset uint64) uint32 {
return extism.ParamU32(offset)
}
// ParamU64 ParamU64 returns a uint64 from Extism host memory given an offset.
func ParamU64(offset uint64) uint64 {
return extism.ParamU64(offset)
}
// RemoveVar RemoveVar removes (and frees) the host variable associated with `key`.
func RemoveVar(key string) {
extism.RemoveVar(key)
}
// ResultBytes ResultBytes allocates bytes and returns the offset in Extism host memory.
func ResultBytes(d []byte) uint64 {
return extism.ResultBytes(d)
}
// ResultString ResultString allocates a UTF-8 string and returns the offset in Extism host memory.
func ResultString(s string) uint64 {
return extism.ResultString(s)
}
// ResultU32 ResultU32 allocates a uint32 and returns the offset in Extism host memory.
func ResultU32(d uint32) uint64 {
return extism.ResultU32(d)
}
// ResultU64 ResultU64 allocates a uint64 and returns the offset in Extism host memory.
func ResultU64(d uint64) uint64 {
return extism.ResultU64(d)
}
// SetError SetError sets the host error string from `err`.
func SetError(err error) {
extism.SetError(err)
}
// SetErrorString SetErrorString sets the host error string from `err`.
func SetErrorString(err string) {
extism.SetErrorString(err)
}
// SetVar SetVar sets the host variable associated with `key` to the `value` byte slice.
func SetVar(key string, value []byte) {
extism.SetVar(key, value)
}
// SetVarInt SetVarInt sets the host variable associated with `key` to the `value` int.
func SetVarInt(key string, value int) {
extism.SetVarInt(key, value)
}
+210
View File
@@ -0,0 +1,210 @@
// 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
func Allocate(length int) Memory {
args := PDKMock.Called(length)
return args.Get(0).(Memory)
}
func AllocateBytes(data []byte) Memory {
args := PDKMock.Called(data)
return args.Get(0).(Memory)
}
// AllocateJSON AllocateJSON allocates and saves the type `any` into Memory on the host.
func AllocateJSON(v any) (Memory, error) {
args := PDKMock.Called(v)
return args.Get(0).(Memory), args.Error(1)
}
// AllocateString AllocateString allocates and saves the UTF-8 string `data` into Memory on the host.
func AllocateString(data string) Memory {
args := PDKMock.Called(data)
return args.Get(0).(Memory)
}
// FindMemory FindMemory finds the host memory block at the given `offset`.
func FindMemory(offset uint64) Memory {
args := PDKMock.Called(offset)
return args.Get(0).(Memory)
}
// GetConfig GetConfig returns the config string associated with `key` (if any).
func GetConfig(key string) (string, bool) {
args := PDKMock.Called(key)
return args.String(0), args.Bool(1)
}
// GetVar GetVar returns the byte slice (if any) associated with `key`.
func GetVar(key string) []byte {
args := PDKMock.Called(key)
return args.Get(0).([]byte)
}
// GetVarInt GetVarInt returns the int associated with `key` (or 0 if none).
func GetVarInt(key string) int {
args := PDKMock.Called(key)
return args.Int(0)
}
// Input Input returns a slice of bytes from the host.
func Input() []byte {
args := PDKMock.Called()
return args.Get(0).([]byte)
}
// InputJSON InputJSON returns unmartialed JSON data from the host "input".
func InputJSON(v any) error {
args := PDKMock.Called(v)
return args.Error(0)
}
// InputString InputString returns the input data from the host as a UTF-8 string.
func InputString() string {
args := PDKMock.Called()
return args.String(0)
}
// JSONFrom JSONFrom unmarshals a `Memory` block located at `offset` from the host into the provided data `v`.
func JSONFrom(offset uint64, v any) error {
args := PDKMock.Called(offset, v)
return args.Error(0)
}
// Log Log logs the provided UTF-8 string `s` on the host using the provided log `level`.
func Log(level LogLevel, s string) {
PDKMock.Called(level, s)
}
// LogMemory LogMemory logs the `memory` block on the host using the provided log `level`.
func LogMemory(level LogLevel, m Memory) {
PDKMock.Called(level, m)
}
// NewHTTPRequest NewHTTPRequest returns a new `HTTPRequest`.
func NewHTTPRequest(method HTTPMethod, url string) *HTTPRequest {
args := PDKMock.Called(method, url)
return args.Get(0).(*HTTPRequest)
}
func NewMemory(offset uint64, length uint64) Memory {
args := PDKMock.Called(offset, length)
return args.Get(0).(Memory)
}
// Output Output sends the `data` slice of bytes to the host output.
func Output(data []byte) {
PDKMock.Called(data)
}
// OutputJSON OutputJSON marshals the provided data `v` as output to the host.
func OutputJSON(v any) error {
args := PDKMock.Called(v)
return args.Error(0)
}
// OutputMemory OutputMemory sends the `mem` Memory to the host output.
func OutputMemory(mem Memory) {
PDKMock.Called(mem)
}
// OutputString OutputString sends the UTF-8 string `s` to the host output.
func OutputString(s string) {
PDKMock.Called(s)
}
// ParamBytes ParamBytes returns bytes from Extism host memory given an offset.
func ParamBytes(offset uint64) []byte {
args := PDKMock.Called(offset)
return args.Get(0).([]byte)
}
// ParamString ParamString returns UTF-8 string data from Extism host memory given an offset.
func ParamString(offset uint64) string {
args := PDKMock.Called(offset)
return args.String(0)
}
// ParamU32 ParamU32 returns a uint32 from Extism host memory given an offset.
func ParamU32(offset uint64) uint32 {
args := PDKMock.Called(offset)
return args.Get(0).(uint32)
}
// ParamU64 ParamU64 returns a uint64 from Extism host memory given an offset.
func ParamU64(offset uint64) uint64 {
args := PDKMock.Called(offset)
return args.Get(0).(uint64)
}
// RemoveVar RemoveVar removes (and frees) the host variable associated with `key`.
func RemoveVar(key string) {
PDKMock.Called(key)
}
// ResultBytes ResultBytes allocates bytes and returns the offset in Extism host memory.
func ResultBytes(d []byte) uint64 {
args := PDKMock.Called(d)
return args.Get(0).(uint64)
}
// ResultString ResultString allocates a UTF-8 string and returns the offset in Extism host memory.
func ResultString(s string) uint64 {
args := PDKMock.Called(s)
return args.Get(0).(uint64)
}
// ResultU32 ResultU32 allocates a uint32 and returns the offset in Extism host memory.
func ResultU32(d uint32) uint64 {
args := PDKMock.Called(d)
return args.Get(0).(uint64)
}
// ResultU64 ResultU64 allocates a uint64 and returns the offset in Extism host memory.
func ResultU64(d uint64) uint64 {
args := PDKMock.Called(d)
return args.Get(0).(uint64)
}
// SetError SetError sets the host error string from `err`.
func SetError(err error) {
PDKMock.Called(err)
}
// SetErrorString SetErrorString sets the host error string from `err`.
func SetErrorString(err string) {
PDKMock.Called(err)
}
// SetVar SetVar sets the host variable associated with `key` to the `value` byte slice.
func SetVar(key string, value []byte) {
PDKMock.Called(key, value)
}
// SetVarInt SetVarInt sets the host variable associated with `key` to the `value` int.
func SetVarInt(key string, value int) {
PDKMock.Called(key, value)
}
+192
View File
@@ -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),
}
}