initial commit
This commit is contained in:
115
internal/functions/registry.go
Normal file
115
internal/functions/registry.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package functions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"reichard.io/poiesis/internal/tsconvert"
|
||||
)
|
||||
|
||||
var (
|
||||
functionRegistry = make(map[string]Function)
|
||||
registryMutex sync.RWMutex
|
||||
)
|
||||
|
||||
func registerFunction[A Args, R any](name string, isAsync bool, fn GoFunc[A, R]) {
|
||||
// Lock Registry
|
||||
registryMutex.Lock()
|
||||
defer registryMutex.Unlock()
|
||||
|
||||
// Validate Args Type
|
||||
tType := reflect.TypeFor[A]()
|
||||
if tType.Kind() != reflect.Struct {
|
||||
panic(fmt.Sprintf("function %s: argument must be a struct type, got %v", name, tType))
|
||||
}
|
||||
|
||||
// Collect Types and Generate Definition
|
||||
fnType := reflect.TypeOf(fn)
|
||||
types := tsconvert.CollectTypes(tType, fnType)
|
||||
definition := tsconvert.GenerateFunctionDecl(name, tType, fnType, isAsync)
|
||||
|
||||
// Register Function
|
||||
functionRegistry[name] = &functionImpl[A, R]{
|
||||
name: name,
|
||||
fn: fn,
|
||||
types: types.All(),
|
||||
definition: definition,
|
||||
isAsync: isAsync,
|
||||
}
|
||||
}
|
||||
|
||||
func GetFunctionDeclarations() string {
|
||||
// Lock Registry
|
||||
registryMutex.RLock()
|
||||
defer registryMutex.RUnlock()
|
||||
|
||||
// Collect Type Definitions
|
||||
typeDefinitions := make(map[string]bool)
|
||||
var typeDefs []string
|
||||
var functionDecls []string
|
||||
|
||||
for _, fn := range functionRegistry {
|
||||
for _, t := range fn.Types() {
|
||||
if !typeDefinitions[t] {
|
||||
typeDefinitions[t] = true
|
||||
typeDefs = append(typeDefs, t)
|
||||
}
|
||||
}
|
||||
functionDecls = append(functionDecls, fn.Definition())
|
||||
}
|
||||
|
||||
// Build Result
|
||||
result := strings.Join(typeDefs, "\n\n")
|
||||
if len(result) > 0 && len(functionDecls) > 0 {
|
||||
result += "\n\n"
|
||||
}
|
||||
result += strings.Join(functionDecls, "\n")
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetTypeDeclarations returns all type declarations from all registered functions.
|
||||
// This is used for aggregating types across multiple functions.
|
||||
func GetTypeDeclarations() map[string]string {
|
||||
// Lock Registry
|
||||
registryMutex.RLock()
|
||||
defer registryMutex.RUnlock()
|
||||
|
||||
// Collect All Types
|
||||
allTypes := make(map[string]string)
|
||||
for _, fn := range functionRegistry {
|
||||
for name, def := range fn.Types() {
|
||||
if existing, ok := allTypes[name]; ok && existing != def {
|
||||
// Type Conflict Detected - Skip
|
||||
continue
|
||||
}
|
||||
allTypes[name] = def
|
||||
}
|
||||
}
|
||||
return allTypes
|
||||
}
|
||||
|
||||
func GetRegisteredFunctions() map[string]Function {
|
||||
// Lock Registry
|
||||
registryMutex.RLock()
|
||||
defer registryMutex.RUnlock()
|
||||
|
||||
// Copy Registry
|
||||
result := make(map[string]Function, len(functionRegistry))
|
||||
for k, v := range functionRegistry {
|
||||
result[k] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func RegisterFunction[T Args, R any](name string, fn GoFunc[T, R]) {
|
||||
// Register Sync Function
|
||||
registerFunction(name, false, fn)
|
||||
}
|
||||
|
||||
func RegisterAsyncFunction[T Args, R any](name string, fn GoFunc[T, R]) {
|
||||
// Register Async Function
|
||||
registerFunction(name, true, fn)
|
||||
}
|
||||
92
internal/functions/types.go
Normal file
92
internal/functions/types.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package functions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type Function interface {
|
||||
Name() string
|
||||
Types() map[string]string
|
||||
Definition() string
|
||||
IsAsync() bool
|
||||
Arguments() []reflect.Type
|
||||
Call(context.Context, []any) (any, error)
|
||||
}
|
||||
|
||||
type GoFunc[A Args, R any] func(context.Context, A) (R, error)
|
||||
|
||||
type Args interface {
|
||||
Validate() error
|
||||
}
|
||||
|
||||
type functionImpl[A Args, R any] struct {
|
||||
name string
|
||||
fn GoFunc[A, R]
|
||||
definition string
|
||||
types map[string]string
|
||||
isAsync bool
|
||||
}
|
||||
|
||||
func (b *functionImpl[A, R]) Name() string {
|
||||
return b.name
|
||||
}
|
||||
|
||||
func (b *functionImpl[A, R]) Types() map[string]string {
|
||||
return b.types
|
||||
}
|
||||
|
||||
func (b *functionImpl[A, R]) Definition() string {
|
||||
return b.definition
|
||||
}
|
||||
|
||||
func (b *functionImpl[A, R]) IsAsync() bool {
|
||||
return b.isAsync
|
||||
}
|
||||
|
||||
func (b *functionImpl[A, R]) Function() any {
|
||||
return b.fn
|
||||
}
|
||||
|
||||
func (b *functionImpl[A, R]) Arguments() []reflect.Type {
|
||||
// Collect Argument Types
|
||||
var allTypes []reflect.Type
|
||||
|
||||
rType := reflect.TypeFor[A]()
|
||||
for i := range rType.NumField() {
|
||||
allTypes = append(allTypes, rType.Field(i).Type)
|
||||
}
|
||||
|
||||
return allTypes
|
||||
}
|
||||
|
||||
func (b *functionImpl[A, R]) Call(ctx context.Context, allArgs []any) (any, error) {
|
||||
return b.CallGeneric(ctx, allArgs)
|
||||
}
|
||||
|
||||
func (b *functionImpl[A, R]) CallGeneric(ctx context.Context, allArgs []any) (zeroR R, err error) {
|
||||
// Populate Arguments
|
||||
var fnArgs A
|
||||
aVal := reflect.ValueOf(&fnArgs).Elem()
|
||||
|
||||
// Populate Fields
|
||||
for i := range min(aVal.NumField(), len(allArgs)) {
|
||||
field := aVal.Field(i)
|
||||
|
||||
// Validate Field is Settable
|
||||
if !field.CanSet() {
|
||||
return zeroR, errors.New("cannot set field")
|
||||
}
|
||||
|
||||
// Validate and Set Field Value
|
||||
argVal := reflect.ValueOf(allArgs[i])
|
||||
if !argVal.Type().AssignableTo(field.Type()) {
|
||||
return zeroR, errors.New("cannot assign field")
|
||||
}
|
||||
field.Set(argVal)
|
||||
}
|
||||
|
||||
// Execute Function
|
||||
return b.fn(ctx, fnArgs)
|
||||
}
|
||||
272
internal/functions/typescript_test.go
Normal file
272
internal/functions/typescript_test.go
Normal file
@@ -0,0 +1,272 @@
|
||||
package functions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
type TestBasicArgs struct {
|
||||
Name string `json:"name"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
func (t TestBasicArgs) Validate() error { return nil }
|
||||
|
||||
func TestBasicType(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction("basic", func(ctx context.Context, args TestBasicArgs) (string, error) {
|
||||
return args.Name, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function basic(name: string, age: number): string;")
|
||||
assert.Contains(t, defs, "interface TestBasicArgs")
|
||||
}
|
||||
|
||||
func resetRegistry() {
|
||||
// Lock Registry
|
||||
registryLock.Lock()
|
||||
defer registryLock.Unlock()
|
||||
|
||||
// Clear Registry
|
||||
functionRegistry = make(map[string]Function)
|
||||
}
|
||||
|
||||
var (
|
||||
registryLock sync.Mutex
|
||||
)
|
||||
|
||||
type TestComplexArgs struct {
|
||||
Items []int `json:"items"`
|
||||
Data map[string]any `json:"data"`
|
||||
Flag bool `json:"flag"`
|
||||
}
|
||||
|
||||
func (t TestComplexArgs) Validate() error { return nil }
|
||||
|
||||
func TestComplexTypes(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction("complex", func(ctx context.Context, args TestComplexArgs) (bool, error) {
|
||||
return args.Flag, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function complex(items: number[], data: Record<string, any>, flag: boolean): boolean;")
|
||||
}
|
||||
|
||||
type TestNestedArgs struct {
|
||||
User struct {
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
} `json:"user"`
|
||||
}
|
||||
|
||||
func (t TestNestedArgs) Validate() error { return nil }
|
||||
|
||||
func TestNestedStruct(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction("nested", func(ctx context.Context, args TestNestedArgs) (string, error) {
|
||||
return args.User.FirstName, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function nested(user: {}): string;")
|
||||
}
|
||||
|
||||
type TestOptionalArgs struct {
|
||||
Name string `json:"name"`
|
||||
Age *int `json:"age,omitempty"`
|
||||
Score *int `json:"score"`
|
||||
}
|
||||
|
||||
func (t TestOptionalArgs) Validate() error { return nil }
|
||||
|
||||
func TestOptionalFields(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction[TestOptionalArgs, string]("optional", func(ctx context.Context, args TestOptionalArgs) (string, error) {
|
||||
return args.Name, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function optional(name: string, age?: number | null, score?: number | null): string;")
|
||||
}
|
||||
|
||||
type TestResult struct {
|
||||
ID int `json:"id"`
|
||||
Data []byte `json:"data"`
|
||||
}
|
||||
|
||||
type TestResultArgs struct {
|
||||
Input string `json:"input"`
|
||||
}
|
||||
|
||||
func (t TestResultArgs) Validate() error { return nil }
|
||||
|
||||
func TestResultStruct(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction[TestResultArgs, TestResult]("result", func(ctx context.Context, args TestResultArgs) (TestResult, error) {
|
||||
return TestResult{ID: 1}, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function result(input: string): TestResult;")
|
||||
assert.Contains(t, defs, "interface TestResult {id: number; data: number[]}")
|
||||
}
|
||||
|
||||
type TestAsyncArgs struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
func (t TestAsyncArgs) Validate() error { return nil }
|
||||
|
||||
type TestAsyncResult struct {
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
func TestAsyncPromise(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Async Function
|
||||
RegisterAsyncFunction[TestAsyncArgs, *TestAsyncStatus]("async", func(ctx context.Context, args TestAsyncArgs) (*TestAsyncStatus, error) {
|
||||
return &TestAsyncStatus{Code: 200}, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function async(url: string): Promise<TestAsyncStatus | null>;")
|
||||
assert.Contains(t, defs, "interface TestAsyncStatus")
|
||||
}
|
||||
|
||||
type TestAsyncStatus struct {
|
||||
Code int `json:"code"`
|
||||
}
|
||||
|
||||
type TestNestedPointerResult struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type TestNestedPointerArgs struct {
|
||||
ID int `json:"id"`
|
||||
}
|
||||
|
||||
func (t TestNestedPointerArgs) Validate() error { return nil }
|
||||
|
||||
func TestNestedPointerInResult(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction[TestNestedPointerArgs, *TestNestedPointerResult]("pointerResult", func(ctx context.Context, args TestNestedPointerArgs) (*TestNestedPointerResult, error) {
|
||||
return &TestNestedPointerResult{Value: "test"}, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function pointerResult(id: number): TestNestedPointerResult | null;")
|
||||
}
|
||||
|
||||
type TestUintArgs struct {
|
||||
Value uint `json:"value"`
|
||||
}
|
||||
|
||||
func (t TestUintArgs) Validate() error { return nil }
|
||||
|
||||
func TestUintType(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction[TestUintArgs, uint]("uint", func(ctx context.Context, args TestUintArgs) (uint, error) {
|
||||
return args.Value, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function uint(value: number): number;")
|
||||
}
|
||||
|
||||
type TestFloatArgs struct {
|
||||
Amount float64 `json:"amount"`
|
||||
}
|
||||
|
||||
func (t TestFloatArgs) Validate() error { return nil }
|
||||
|
||||
func TestFloatType(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction[TestFloatArgs, float32]("float", func(ctx context.Context, args TestFloatArgs) (float32, error) {
|
||||
return float32(args.Amount), nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function float(amount: number): number;")
|
||||
}
|
||||
|
||||
type TestPointerInArgs struct {
|
||||
User *struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"user"`
|
||||
}
|
||||
|
||||
func (t TestPointerInArgs) Validate() error { return nil }
|
||||
|
||||
func TestNestedPointerStruct(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction[TestPointerInArgs, string]("nestedPointer", func(ctx context.Context, args TestPointerInArgs) (string, error) {
|
||||
return "test", nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function nestedPointer(user?: {} | null): string;")
|
||||
}
|
||||
|
||||
type TestErrorOnlyArgs struct {
|
||||
Input string `json:"input"`
|
||||
}
|
||||
|
||||
func (t TestErrorOnlyArgs) Validate() error { return nil }
|
||||
|
||||
func TestErrorOnlyReturn(t *testing.T) {
|
||||
// Reset Registry
|
||||
resetRegistry()
|
||||
|
||||
// Register Function
|
||||
RegisterFunction[TestErrorOnlyArgs, struct{}]("errorOnly", func(ctx context.Context, args TestErrorOnlyArgs) (struct{}, error) {
|
||||
return struct{}{}, nil
|
||||
})
|
||||
|
||||
// Verify Declarations
|
||||
defs := GetFunctionDeclarations()
|
||||
assert.Contains(t, defs, "declare function errorOnly(input: string): {};")
|
||||
}
|
||||
Reference in New Issue
Block a user