plugins

package
v0.13.8-0...-a8de8dd Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LogLevelQuiet        = 0 // errors and doc-change info only
	LogLevelPluginDetail = 1 // short-summary — less than summary
	LogLevelSummary      = 2 // + pipeline phase timing totals
	LogLevelVerbose      = 3 // + per-plugin spawn and per-hook timing
)
View Source
const (
	PluginOrderCore   = "core"
	PluginOrderBefore = "before"
	PluginOrderAfter  = "after"
)
View Source
const (
	PackageModeCommonJS = "commonjs"
	PackageModeESM      = "esm"
)

Variables

This section is empty.

Functions

func ArmConnectionDeadline

func ArmConnectionDeadline(d time.Duration)

ArmConnectionDeadline exits the process if no orchestrator ever connects. The count-to-zero shutdown above only protects a plugin whose connection was established: an orchestrator that dies (or errors out of setup) between spawning the plugin and dialing its websocket would otherwise leak the process forever, waiting for a connection that never comes.

func ContextWithPluginDir

func ContextWithPluginDir(ctx context.Context, directory string) context.Context

func ContextWithTaskID

func ContextWithTaskID(ctx context.Context, taskID string) context.Context

func ContextWithWSConn

func ContextWithWSConn(ctx context.Context, conn *websocket.Conn) context.Context

func ContextWithWSMessageID

func ContextWithWSMessageID(ctx context.Context, id string) context.Context

func CopyPluginRuntime

func CopyPluginRuntime[PluginConfig any](
	ctx context.Context,
	plugin HoudiniPlugin[PluginConfig],
	fs afero.Fs,
) ([]string, error)

CopyPluginRuntime handles both runtime copying and generation for a plugin. This function combines the logic that was previously split between the HTTP handler and the plugin's GenerateRuntime method.

func ForceShutdown

func ForceShutdown()

ForceShutdown closes all active WebSocket connections and exits This should only be used in emergency situations

func GetActiveConnectionCount

func GetActiveConnectionCount() int

GetActiveConnectionCount returns the number of active WebSocket connections Useful for monitoring and testing

func HandleWebSocketConnection

func HandleWebSocketConnection(conn *websocket.Conn)

func ParseFlags

func ParseFlags()

func PluginDirFromContext

func PluginDirFromContext(ctx context.Context) string

func RecursiveCopy

func RecursiveCopy(
	ctx context.Context,
	fs afero.Fs,
	from string,
	to string,
	transform func(ctx context.Context, source string, content string) (string, error),
) ([]string, error)

RecursiveCopy walks `from`, mirrors directories into `to`, and processes files in parallel. It applies `transform` to each file's textual contents and writes atomically only if changed. It returns a slice of destination file paths that were updated (created or content-changed).

func Run

func Run[PluginConfig any](plugin HoudiniPlugin[PluginConfig]) error

func StdioInvoke

func StdioInvoke(ctx context.Context, hook string, payload map[string]any, parallel bool) (map[string]any, error)

StdioInvoke sends an invoke message to Node.js and waits for the aggregated result. Used by TriggerHookSerial/Parallel when in stdio transport mode so the Go binary can trigger hooks on other plugins without direct networking.

func TaskIDFromContext

func TaskIDFromContext(ctx context.Context) *string

func TriggerHookParallel

func TriggerHookParallel[PluginConfig any](
	ctx context.Context,
	db DatabasePool[PluginConfig],
	hook string,
	payload map[string]any,
) (map[string]any, error)

func TriggerHookParallelWithConn

func TriggerHookParallelWithConn[PluginConfig any](
	ctx context.Context,
	db DatabasePool[PluginConfig],
	conn Conn,
	hook string,
	payload map[string]any,
) (map[string]any, error)

func TriggerHookSerial

func TriggerHookSerial[PluginConfig any](
	ctx context.Context,
	db DatabasePool[PluginConfig],
	hook string,
	payload map[string]any,
) (map[string]any, error)

func WSConnFromContext

func WSConnFromContext(ctx context.Context) *websocket.Conn

WSConnFromContext helper to get the conn from context Example:

 	if conn := WSConnFromContext(ctx); conn != nil {
			conn.WriteJSON(WebSocketResponse{
				ID:    ctx.Value("wsMessageID").(string),
				Type:  "1error",
				Error: "TEST: This is a simulated non-fatal error during generation",
			})
		}

func WSMessageIDFromContext

func WSMessageIDFromContext(ctx context.Context) string

func WaitForShutdown

func WaitForShutdown()

WaitForShutdown blocks until all WebSocket connections are closed This should be called from the main goroutine to wait for graceful shutdown

func WriteFile

func WriteFile(filesystem afero.Fs, dst string, data []byte, mode iofs.FileMode) error

WriteFile is a drop-in replacement for afero.WriteFile that writes atomically.

It writes data to a sibling temp file first, then renames it into place. On POSIX (Linux/macOS) rename is a single atomic syscall, so concurrent readers (e.g. Vite's dev server loading a hot-updated module) always see either the complete old content or the complete new content — never a partial write. On in-memory afero filesystems (used in tests) Rename is mutex-protected and equally safe. On Windows, os.Rename replaces the destination atomically when the destination is not open; that is sufficient for our use-case.

Use this instead of afero.WriteFile for any file in the generated output directory that Vite may load concurrently while the pipeline is running.

Types

type AfterExtract

type AfterExtract interface {
	AfterExtract(ctx context.Context) error
}

AfterExtract is called after all documents have been extracted from the project.

type AfterGenerate

type AfterGenerate interface {
	AfterGenerate(ctx context.Context) error
}

type AfterLoad

type AfterLoad interface {
	AfterLoad(ctx context.Context) error
}

Invoked after all plugins have loaded and modified config values.

type AfterValidate

type AfterValidate interface {
	AfterValidate(ctx context.Context) error
}

A hook to transform the documents after they are validated.

type ArtifactData

type ArtifactData interface {
	ArtifactData(ctx context.Context, documentName string) (map[string]string, error)
}

A hook to embed metadata at the root of the artifact.

type ArtifactEnd

type ArtifactEnd interface {
	ArtifactEnd(ctx context.Context) error
}

A hook to modify the generated artifact before it is persisted

type BeforeGenerate

type BeforeGenerate interface {
	BeforeGenerate(ctx context.Context) error
}

A hook to transform the documents before documents are generated.

type BeforeValidate

type BeforeValidate interface {
	BeforeValidate(ctx context.Context) error
}

A hook to transform the documents before they are validated.

type ClientPlugins

type ClientPlugins interface {
	ClientPlugins(ctx context.Context) (map[string]any, error)
}

Specify the plugins that should be added to the user's client because * of this plugin.

type ColumnKind

type ColumnKind int

ColumnKind mirrors sqlite column type constants without importing zombiezen.

const (
	ColumnKindInt   ColumnKind = 1
	ColumnKindFloat ColumnKind = 2
	ColumnKindText  ColumnKind = 3
	ColumnKindBlob  ColumnKind = 4
	ColumnKindNull  ColumnKind = 5 // matches SQLITE_NULL
)

type Config

type Config interface {
	Config(ctx context.Context) (string, error)
}

The path to a javascript module with an default export that sets configuration values.

type Conn

type Conn interface {
	// Prepare compiles a SQL query and returns a Stmt.
	Prepare(query string) (Stmt, error)
	// LastInsertRowID returns the row ID of the most recent successful INSERT.
	LastInsertRowID() int64
}

Conn is an opaque checked-out connection.

type DatabasePool

type DatabasePool[PC any] struct {
	*sqlitex.Pool
	PluginName string
	Test       bool
	// contains filtered or unexported fields
}

DatabasePool holds the connection pool and plugin configuration.

func NewPool

func NewPool[PC any]() (DatabasePool[PC], error)

func NewTestPool

func NewTestPool[PC any]() (DatabasePool[PC], error)

func (DatabasePool[PC]) BindStatement

func (db DatabasePool[PC]) BindStatement(stmt Stmt, args map[string]any) error

func (DatabasePool[PC]) Close

func (db DatabasePool[PC]) Close() error

Close closes the underlying pool.

func (DatabasePool[PC]) ExecQuery

func (db DatabasePool[PC]) ExecQuery(
	ctx context.Context,
	query string,
	args map[string]any,
) error

func (DatabasePool[PC]) ExecStatement

func (db DatabasePool[PC]) ExecStatement(
	statement Stmt,
	args map[string]any,
) error

func (DatabasePool[PluginConfig]) Logger

func (db DatabasePool[PluginConfig]) Logger(ctx context.Context) (*Logger, error)

Logger returns a logger seeded from the project's configured log level.

func (DatabasePool[PluginConfig]) PluginConfig

func (db DatabasePool[PluginConfig]) PluginConfig(
	ctx context.Context,
) (result PluginConfig, err error)

func (DatabasePool[PluginConfig]) ProjectConfig

func (db DatabasePool[PluginConfig]) ProjectConfig(ctx context.Context) (ProjectConfig, error)

func (DatabasePool[PC]) Put

func (db DatabasePool[PC]) Put(conn Conn)

Put returns a connection to the pool.

func (*DatabasePool[PluginConfig]) ReloadPluginConfig

func (db *DatabasePool[PluginConfig]) ReloadPluginConfig(ctx context.Context) error

func (*DatabasePool[PluginConfig]) ReloadProjectConfig

func (db *DatabasePool[PluginConfig]) ReloadProjectConfig(ctx context.Context) error

func (*DatabasePool[PC]) SetPluginConfig

func (db *DatabasePool[PC]) SetPluginConfig(config PC)

func (*DatabasePool[PC]) SetProjectConfig

func (db *DatabasePool[PC]) SetProjectConfig(config ProjectConfig)

func (DatabasePool[PC]) StepQuery

func (db DatabasePool[PC]) StepQuery(
	ctx context.Context,
	queryStr string,
	bindings map[string]any,
	rowHandler func(q Row),
) error

StepQuery wraps the common steps for executing a query. It obtains the connection, prepares the query, iterates over rows, and calls the rowHandler callback for each row.

func (DatabasePool[PC]) StepStatement

func (db DatabasePool[PC]) StepStatement(
	ctx context.Context,
	queryStatement Stmt,
	rowHandler func(),
) error

func (DatabasePool[PC]) Take

func (db DatabasePool[PC]) Take(ctx context.Context) (Conn, error)

Take checks out a connection from the pool and returns it as a Conn.

func (DatabasePool[PC]) Transaction

func (db DatabasePool[PC]) Transaction(conn Conn) func(*error)

Transaction wraps sqlitex.Transaction for use with Conn.

type DefaultConfig

type DefaultConfig[PluginConfig any] interface {
	DefaultConfig(ctx context.Context) (PluginConfig, error)
}

type Environment

type Environment interface {
	Environment(ctx context.Context, mode string) (map[string]string, error)
}

Add environment variables to the project

type Error

type Error struct {
	Message   string           `json:"message"`
	Detail    string           `json:"detail"`
	Locations []*ErrorLocation `json:"locations"`
	Kind      ErrorKind        `json:"kind"`
}

func Errorf

func Errorf(format string, args ...any) *Error

func WrapError

func WrapError(err error) *Error

func WrapFilepathError

func WrapFilepathError(filepath string, err error) *Error

func (Error) Error

func (e Error) Error() string

func (Error) WithPrefix

func (e Error) WithPrefix(prefix string) Error

type ErrorKind

type ErrorKind string
const (
	ErrorKindValidation ErrorKind = "validation"
)

type ErrorList

type ErrorList struct {
	ThreadSafeSlice[*Error]
}

func (*ErrorList) Append

func (e *ErrorList) Append(err *Error)

func (*ErrorList) Error

func (errs *ErrorList) Error() string

type ErrorLocation

type ErrorLocation struct {
	Filepath string `json:"filepath"`
	Line     int    `json:"line"`
	Column   int    `json:"column"`
}

type ExtractDocuments

type ExtractDocuments interface {
	ExtractDocuments(ctx context.Context, input ExtractDocumentsInput) error
}

Extract documents from the project

type ExtractDocumentsInput

type ExtractDocumentsInput struct {
	Filepaths []string `json:"filepaths"`
}

type GenerateDocuments

type GenerateDocuments interface {
	GenerateDocuments(ctx context.Context) ([]string, error)
}

A hook to generate custom files for every document in a project.

type GenerateRuntime

type GenerateRuntime interface {
	GenerateRuntime(ctx context.Context) ([]string, error)
}

Generate project scaffolding files that don't necessary depend on a specific task of documents. * For example, a plugin runtime

type Hash

type Hash interface {
	Hash(ctx context.Context, documentName string) (string, error)
}

A hook to customize the hash generated for your document.

type HookHandler

type HookHandler func(ctx context.Context, payload map[string]any) (any, error)

type HoudiniPlugin

type HoudiniPlugin[PluginConfig any] interface {
	Name() string
	Order() PluginOrder
	SetDatabase(DatabasePool[PluginConfig])
	Database() DatabasePool[PluginConfig]
	SetFilesystem(fs afero.Fs)
	Filesystem() afero.Fs
}

all a plugin _must_ provide is a name and its order

type IncludeRuntime

type IncludeRuntime interface {
	IncludeRuntime(ctx context.Context) (string, error)
}

A relative path from the file exporting your plugin to a runtime that will be * automatically included with your

type IndexFile

type IndexFile interface {
	IndexFile(ctx context.Context, filepath string) (string, error)
}

A hook to modify the root `index.js` of the generated runtime.

type Logger

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

func NewLogger

func NewLogger(level int) *Logger

func (*Logger) At

func (l *Logger) At(minLevel int) bool

At reports whether the logger's level is at or above minLevel.

func (*Logger) Error

func (l *Logger) Error(format string, args ...any)

Error always prints to stderr regardless of log level.

func (*Logger) Info

func (l *Logger) Info(minLevel int, format string, args ...any)

Info prints to stderr only when the logger's level is >= minLevel.

func (*Logger) Time

func (l *Logger) Time(label string)

Time starts a named timer.

func (*Logger) TimeEnd

func (l *Logger) TimeEnd(label string, minLevel int)

TimeEnd stops the named timer and prints the elapsed time if level >= minLevel.

func (*Logger) Warn

func (l *Logger) Warn(format string, args ...any)

Warn always prints to stderr regardless of log level.

type PackagMode

type PackagMode string

type Plugin

type Plugin[PluginConfig any] struct {
	DB DatabasePool[PluginConfig]
	Fs afero.Fs
}

func (*Plugin[PluginConfig]) Database

func (p *Plugin[PluginConfig]) Database() DatabasePool[PluginConfig]

func (*Plugin[PluginConfig]) Filesystem

func (p *Plugin[PluginConfig]) Filesystem() afero.Fs

func (*Plugin[PluginConfig]) SetDatabase

func (p *Plugin[PluginConfig]) SetDatabase(db DatabasePool[PluginConfig])

SetDatabase is a helper that lets Run() inject the database into the plugin.

func (*Plugin[PluginConfig]) SetFilesystem

func (p *Plugin[PluginConfig]) SetFilesystem(fs afero.Fs)

type PluginOrder

type PluginOrder string

type ProjectConfig

type ProjectConfig struct {
	Include                         []string
	Exclude                         []string
	SchemaPath                      string
	DefinitionsPath                 string
	CacheBufferSize                 int
	DefaultCachePolicy              string
	DefaultPartial                  bool
	DefaultLifetime                 int
	DefaultListPosition             string
	DefaultListTarget               string
	DefaultPaginateMode             string
	SuppressPaginationDeduplication bool
	LogLevel                        string
	DefaultFragmentMasking          bool
	DefaultKeys                     []string
	PersistedQueriesPath            string
	ProjectRoot                     string
	RuntimeDir                      string
	RuntimeScalars                  map[string]string
	Scalars                         map[string]ScalarConfig
	TypeConfig                      map[string]TypeConfig
	Filepath                        string
}

func (ProjectConfig) ArtifactDirectory

func (c ProjectConfig) ArtifactDirectory() string

func (ProjectConfig) ArtifactPath

func (c ProjectConfig) ArtifactPath(name string) string

func (ProjectConfig) ArtifactTypePath

func (c ProjectConfig) ArtifactTypePath(name string) string

func (ProjectConfig) DefinitionsDirectory

func (c ProjectConfig) DefinitionsDirectory() string

func (ProjectConfig) DefinitionsDocumentsPath

func (c ProjectConfig) DefinitionsDocumentsPath() string

func (ProjectConfig) DefinitionsEnumRuntime

func (c ProjectConfig) DefinitionsEnumRuntime() string

func (ProjectConfig) DefinitionsIndexJs

func (c ProjectConfig) DefinitionsIndexJs() string

func (ProjectConfig) DefinitionsSchemaPath

func (c ProjectConfig) DefinitionsSchemaPath() string

func (ProjectConfig) PluginDirectory

func (config ProjectConfig) PluginDirectory(name string) string

func (ProjectConfig) PluginRuntimeDirectory

func (config ProjectConfig) PluginRuntimeDirectory(name string) string

func (ProjectConfig) PluginStaticRuntimeDirectory

func (config ProjectConfig) PluginStaticRuntimeDirectory(name string) string

type RegisterFunc

type RegisterFunc func(hookName string, handler HookHandler)

type Row

type Row interface {
	ColumnText(i int) string
	GetText(col string) string
	ColumnInt(i int) int
	ColumnInt64(i int) int64
	GetInt64(col string) int64
	ColumnBool(i int) bool
	GetBool(col string) bool
	ColumnIsNull(i int) bool
	IsNull(col string) bool
	ColumnType(i int) ColumnKind
}

Row is the read-only view of a result row, satisfied by *sqlite.Stmt in zombiezen builds and by a wrapper in ncruces builds.

type ScalarConfig

type ScalarConfig struct {
	Type          string
	InputTypes    []string
	Module        string
	DefaultImport bool
}

type Schema

type Schema interface {
	Schema(ctx context.Context) error
}

Can be used to add custom definitions to your project's schema. Definitions (like directives) added * here are automatically removed from the document before they are sent to the server. Useful * in connection with artifactData or artifact_selection to embed data in the artifact.

type StaticRuntime

type StaticRuntime interface {
	StaticRuntime(ctx context.Context) (string, error)
}

A relative path from the file exporting your plugin to a runtime that can be * added to the project before generating artifacts. This is useful for plugins * that want to add third-party documents to the user's application.

type StdioInbound

type StdioInbound struct {
	ID              string         `json:"id"`
	Type            string         `json:"type"`
	Hook            string         `json:"hook"`
	Payload         map[string]any `json:"payload"`
	TaskID          string         `json:"taskId"`
	PluginDirectory string         `json:"pluginDirectory"`
	Result          any            `json:"result"`
	Error           any            `json:"error"`
}

StdioInbound covers messages received on stdin: "request" from Node.js and "invoke_result" as responses to our own invoke calls.

type StdioInvokeMsg

type StdioInvokeMsg struct {
	ID       string         `json:"id"`
	Type     string         `json:"type"` // always "invoke"
	Hook     string         `json:"hook"`
	Payload  map[string]any `json:"payload"`
	TaskID   string         `json:"taskId,omitempty"`
	Parallel bool           `json:"parallel,omitempty"`
}

StdioInvokeMsg is written to stdout to ask Node.js to call other plugins.

type StdioRegister

type StdioRegister struct {
	Type                 string   `json:"type"` // always "register"
	Name                 string   `json:"name"`
	Hooks                []string `json:"hooks"`
	Order                string   `json:"order"`
	IncludeRuntime       any      `json:"includeRuntime,omitempty"`
	IncludeStaticRuntime any      `json:"includeStaticRuntime,omitempty"`
	ConfigModule         any      `json:"configModule,omitempty"`
	ClientPlugins        any      `json:"clientPlugins,omitempty"`
}

StdioRegister is written to stdout once on startup.

type StdioResponse

type StdioResponse struct {
	ID     string `json:"id"`
	Type   string `json:"type"` // always "response"
	Result any    `json:"result,omitempty"`
	Error  any    `json:"error,omitempty"`
}

StdioResponse is written to stdout in reply to a "request" message.

type Stmt

type Stmt interface {
	Row
	SetText(param string, value string)
	SetInt64(param string, value int64)
	SetNull(param string)
	SetBool(param string, value bool)
	BindText(i int, value string)
	BindInt64(i int, value int64)
	BindParamCount() int
	BindParamName(i int) string
	Step() (bool, error)
	Reset() error
	ClearBindings() error
	Finalize() error
}

Stmt is a prepared statement — used by callers that need manual step/bind control.

type ThreadSafeSlice

type ThreadSafeSlice[val any] struct {
	sync.Mutex
	// contains filtered or unexported fields
}

thread-safe slice wrapper

func (*ThreadSafeSlice[T]) Append

func (s *ThreadSafeSlice[T]) Append(val ...T)

helper methods for SafeSlice

func (*ThreadSafeSlice[T]) GetItems

func (s *ThreadSafeSlice[T]) GetItems() []T

func (*ThreadSafeSlice[val]) Len

func (s *ThreadSafeSlice[val]) Len() int

type TransformRuntime

type TransformRuntime interface {
	TransformRuntime(ctx context.Context, source string, content string) (string, error)
}

Transform the plugin's runtime while houdini is copying it . * You must have passed a value to includeRuntime for this hook to matter.

type TransformStaticRuntime

type TransformStaticRuntime interface {
	TransformStaticRuntime(ctx context.Context, source string, content string) (string, error)
}

Transform the plugin's static runtime while houdini is copying it . * You must have passed a value to includeRuntime for this hook to matter.

type TypeConfig

type TypeConfig struct {
	ResolveQuery string
	Keys         []string
}

type Validate

type Validate interface {
	Validate(ctx context.Context) error
}

A hook to validate all of the documents in a project.

type WebSocketMessage

type WebSocketMessage struct {
	ID              string         `json:"id"`
	Type            string         `json:"type"`
	Hook            string         `json:"hook"`
	Payload         map[string]any `json:"payload"`
	TaskID          string         `json:"taskId"`
	PluginDirectory string         `json:"pluginDirectory"`
}

type WebSocketResponse

type WebSocketResponse struct {
	ID     string `json:"id"`
	Type   string `json:"type"`
	Result any    `json:"result,omitempty"`
	Error  any    `json:"error,omitempty"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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