script

package
v0.8.16-alpha Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 7 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package script provides the JavaScript runtime using goja (pure Go ES5.1+). A build tag switches to QJS+Wazero when available.

Package script provides the JavaScript runtime for Kora's extensibility system. It defines the Runner interface and types for script execution.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsAfterEvent

func IsAfterEvent(e Event) bool

IsAfterEvent returns true if the event is an after_* (best-effort) hook.

func IsBeforeEvent

func IsBeforeEvent(e Event) bool

IsBeforeEvent returns true if the event is a before_* (can reject) hook.

Types

type Dialect

type Dialect interface {
	Placeholder(n int) string
}

Dialect abstracts SQL dialect differences for script storage.

type DocProvider

type DocProvider interface {
	GetDoc(doctype, name string) (map[string]any, error)
	GetList(doctype string, filters map[string]any, orderBy string, limit, offset int) ([]map[string]any, error)
	SaveDoc(doctype string, doc map[string]any, modifiedBy string) error
	CreateDoc(doctype string, doc map[string]any, owner, modifiedBy string) (map[string]any, error)
	DeleteDoc(doctype, name string) error
}

DocProvider is the interface for document CRUD operations. Consumers that only need document access should accept this interface.

type EmbeddedConfig

type EmbeddedConfig struct {
	PoolSize int           // number of prewarmed runtimes (default: 15)
	MaxRAM   int64         // soft memory target in bytes
	Timeout  time.Duration // default execution timeout
}

EmbeddedConfig configures the embedded runner.

func DefaultEmbeddedConfig

func DefaultEmbeddedConfig() EmbeddedConfig

DefaultEmbeddedConfig returns sensible defaults.

type EmbeddedRunner

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

EmbeddedRunner executes scripts in-process using goja. It maintains a pool of prewarmed runtimes for concurrent execution.

func NewEmbeddedRunner

func NewEmbeddedRunner(cfg EmbeddedConfig) *EmbeddedRunner

NewEmbeddedRunner creates a runner with a pool of prewarmed goja runtimes.

func (*EmbeddedRunner) Close

func (r *EmbeddedRunner) Close() error

Close shuts down all runtimes in the pool.

func (*EmbeddedRunner) Execute

Execute runs a script using a runtime from the pool.

func (*EmbeddedRunner) PoolSize

func (r *EmbeddedRunner) PoolSize() int

PoolSize returns the number of runtimes in the pool.

func (*EmbeddedRunner) Validate

func (r *EmbeddedRunner) Validate(script string) error

Validate checks that a script compiles without running it.

type Event

type Event string

Event is the lifecycle hook point.

const (
	EventBeforeInsert Event = "before_insert"
	EventAfterInsert  Event = "after_insert"
	EventBeforeSave   Event = "before_save"
	EventAfterSave    Event = "after_save"
	EventBeforeDelete Event = "before_delete"
	EventAfterDelete  Event = "after_delete"
	EventBeforeSubmit Event = "before_submit"
	EventAfterSubmit  Event = "after_submit"
	EventBeforeCancel Event = "before_cancel"
	EventAfterCancel  Event = "after_cancel"
	EventValidate     Event = "validate"
	EventComputed     Event = "computed"
)

type ExecuteRequest

type ExecuteRequest struct {
	Script      string         // JavaScript source
	ScriptType  Type           // doc_event, api_method, etc.
	ScriptName  string         // from _kora_script.name
	DocType     string         // doctype being operated on
	Event       Event          // lifecycle hook point
	Document    map[string]any // current document state
	OldDocument map[string]any // previous document state (nil for inserts)
	User        string         // authenticated user email
	UserRoles   []string       // user's roles
	Site        string         // site hostname
	Timeout     time.Duration  // per-execution timeout

	// Provider bridges the JS runtime to the Kora engine.
	// If nil, kora.getDoc/kora.saveDoc etc. return safe defaults.
	Provider KoraProvider
}

ExecuteRequest carries all context for a single script execution.

type ExecuteResult

type ExecuteResult struct {
	Document map[string]any `json:"document,omitempty"` // modified document (nil if unchanged)
	Modified bool           `json:"modified"`           // true if document was changed
	Result   any            `json:"result,omitempty"`   // return value (for api_method scripts)
	Logs     []LogEntry     `json:"logs,omitempty"`     // log messages from the script
	Duration time.Duration  `json:"duration_ms"`        // execution time
}

ExecuteResult is returned by a successful script execution.

type HTTPProvider

type HTTPProvider interface {
	DoHTTP(req *HTTPRequest) (*HTTPResponse, error)
}

HTTPProvider is the interface for making external HTTP requests.

type HTTPRequest

type HTTPRequest struct {
	Method  string
	URL     string
	Headers map[string]string
	Body    string
}

HTTPRequest represents an outgoing HTTP request from a script.

type HTTPResponse

type HTTPResponse struct {
	Status     int
	StatusText string
	Headers    map[string]string
	Body       []byte
}

HTTPResponse represents an HTTP response returned to a script.

type KoraProvider

type KoraProvider interface {
	DocProvider
	SecretProvider
	HTTPProvider
}

KoraProvider is the composed interface for backward compatibility.

type LogEntry

type LogEntry struct {
	Level   string `json:"level"`   // debug, info, warn, error
	Message string `json:"message"` // log message
}

LogEntry is a single log message from a script execution.

type NoopProvider

type NoopProvider struct{}

NoopProvider is a safe default that returns errors for all operations. Used when the script runner runs without engine integration (tests, validation).

func (NoopProvider) CreateDoc

func (NoopProvider) CreateDoc(doctype string, doc map[string]any, owner, modifiedBy string) (map[string]any, error)

func (NoopProvider) DeleteDoc

func (NoopProvider) DeleteDoc(doctype, name string) error

func (NoopProvider) DoHTTP

func (NoopProvider) DoHTTP(req *HTTPRequest) (*HTTPResponse, error)

func (NoopProvider) GetDoc

func (NoopProvider) GetDoc(doctype, name string) (map[string]any, error)

func (NoopProvider) GetList

func (NoopProvider) GetList(doctype string, filters map[string]any, orderBy string, limit, offset int) ([]map[string]any, error)

func (NoopProvider) GetSecret

func (NoopProvider) GetSecret(key string) (string, error)

func (NoopProvider) SaveDoc

func (NoopProvider) SaveDoc(doctype string, doc map[string]any, modifiedBy string) error

type Runner

type Runner interface {
	// Execute runs a script and returns the result or an error.
	Execute(ctx context.Context, req ExecuteRequest) (*ExecuteResult, error)

	// Validate checks whether a script compiles without executing it.
	Validate(script string) error

	// Close releases resources held by the runner.
	Close() error
}

Runner executes JavaScript scripts with sandboxing.

type ScriptRecord

type ScriptRecord struct {
	Name           string     `json:"name"`
	Site           string     `json:"site"`
	ScriptType     Type       `json:"script_type"`
	DocType        string     `json:"doctype"`
	Event          Event      `json:"event"`
	MethodPath     string     `json:"method_path"`
	WorkflowAction string     `json:"workflow_action"`
	Schedule       string     `json:"schedule"`
	Priority       int        `json:"priority"`
	IsActive       bool       `json:"is_active"`
	RunAs          string     `json:"run_as"`
	TimeoutMs      int        `json:"timeout_ms"`
	Script         string     `json:"script"`
	CompiledAt     *time.Time `json:"compiled_at,omitempty"`
	CompileError   string     `json:"compile_error,omitempty"`
	CreatedBy      string     `json:"created_by"`
	UpdatedBy      string     `json:"updated_by"`
	CreatedAt      time.Time  `json:"creation"`
	UpdatedAt      time.Time  `json:"modified"`
}

ScriptRecord mirrors a _kora_script row.

type ScriptUpdateRequest

type ScriptUpdateRequest struct {
	ScriptType     *string `json:"script_type,omitempty"`
	DocType        *string `json:"doctype,omitempty"`
	Event          *string `json:"event,omitempty"`
	MethodPath     *string `json:"method_path,omitempty"`
	WorkflowAction *string `json:"workflow_action,omitempty"`
	Schedule       *string `json:"schedule,omitempty"`
	Priority       *int    `json:"priority,omitempty"`
	IsActive       *bool   `json:"is_active,omitempty"`
	RunAs          *string `json:"run_as,omitempty"`
	TimeoutMs      *int    `json:"timeout_ms,omitempty"`
	Script         *string `json:"script,omitempty"`
}

ScriptUpdateRequest carries the fields that can be updated on a script.

type SecretProvider

type SecretProvider interface {
	GetSecret(key string) (string, error)
}

SecretProvider is the interface for retrieving secrets.

type Store

type Store struct {
	DB      *sql.DB
	Dialect Dialect
}

Store persists and retrieves script definitions.

func (*Store) Delete

func (s *Store) Delete(site, name string) error

Delete removes a script by site and name.

func (*Store) Insert

func (s *Store) Insert(r ScriptRecord) error

Insert creates a new script record.

func (*Store) LoadActiveScripts

func (s *Store) LoadActiveScripts(site string, doctype string, event Event) ([]ScriptRecord, error)

LoadActiveScripts returns all active scripts for a site, filtered by optional doctype+event.

func (*Store) LoadAllForSite

func (s *Store) LoadAllForSite(site string) ([]ScriptRecord, error)

LoadAllForSite returns all scripts for a site.

func (*Store) LoadByName

func (s *Store) LoadByName(site, name string) (*ScriptRecord, error)

LoadByName returns a single script by site and name.

func (*Store) LoadExecutions

func (s *Store) LoadExecutions(site, name string, limit int) ([]map[string]any, error)

LoadExecutions returns recent executions for a script.

func (*Store) LoadMethodScript

func (s *Store) LoadMethodScript(site string, methodPath string) (*ScriptRecord, error)

LoadMethodScript returns the active api_method script for a given method path, or nil.

func (*Store) LoadWorkflowActionScripts

func (s *Store) LoadWorkflowActionScripts(site string, actionName string) ([]ScriptRecord, error)

LoadWorkflowActionScripts returns active workflow_action scripts for a given workflow action name.

func (*Store) LogExecution

func (s *Store) LogExecution(site string, rec ScriptRecord, docType, docName string, event Event, triggerUser string, durationMs int, status string, errMsg string) error

LogExecution records a script execution in _kora_script_execution.

func (*Store) Update

func (s *Store) Update(site, name string, req ScriptUpdateRequest, updatedBy string) error

Update modifies an existing script record. Only non-nil fields are applied.

type Type

type Type string

Type classifies the kind of script.

const (
	TypeDocEvent       Type = "doc_event"
	TypeAPIMethod      Type = "api_method"
	TypeWorkflowAction Type = "workflow_action"
	TypeScheduled      Type = "scheduled"
)

Jump to

Keyboard shortcuts

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