Merge branch 'worktree-agent-a88b86b51f454341b' into worktree-giggly-marinating-lamport
This commit is contained in:
38 files changed
+4178
-757
No files matched your search
@@ -254,6 +254,10 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
||||
deps.Bindings = b.eda
|
||||
deps.BindingDispatcher = b.eda
|
||||
deps.PlaybookDispatcher = b.eda
|
||||
// Only the Postgres EDA store holds event types.
|
||||
if eventTypes, ok := any(b.eda).(storecontract.EventTypeStore); ok {
|
||||
deps.EventTypes = eventTypes
|
||||
}
|
||||
}
|
||||
// tool_call events project into the tool_calls collection on the same
|
||||
// event-capture store: this process legitimately owns both, so the
|
||||
|
||||
@@ -103,6 +103,9 @@ func compose(d deps) *webui.Server {
|
||||
if bindings, ok := d.Store.(storecontract.BindingStore); ok {
|
||||
srv.Bindings = bindings
|
||||
}
|
||||
if eventTypes, ok := d.Store.(storecontract.EventTypeStore); ok {
|
||||
srv.EventTypes = eventTypes
|
||||
}
|
||||
if d.Chat != nil {
|
||||
srv.Chat = &webui.ChatService{Contract: d.Chat}
|
||||
}
|
||||
|
||||
+1322
-697
File diff suppressed because it is too large.
Load diff
@@ -73,6 +73,10 @@ const (
|
||||
StateStoreService_ListMappings_FullMethodName = "/state.v1.StateStoreService/ListMappings"
|
||||
StateStoreService_UpdateMapping_FullMethodName = "/state.v1.StateStoreService/UpdateMapping"
|
||||
StateStoreService_DeleteMapping_FullMethodName = "/state.v1.StateStoreService/DeleteMapping"
|
||||
StateStoreService_InsertEventType_FullMethodName = "/state.v1.StateStoreService/InsertEventType"
|
||||
StateStoreService_UpdateEventType_FullMethodName = "/state.v1.StateStoreService/UpdateEventType"
|
||||
StateStoreService_DeleteEventType_FullMethodName = "/state.v1.StateStoreService/DeleteEventType"
|
||||
StateStoreService_ListEventTypes_FullMethodName = "/state.v1.StateStoreService/ListEventTypes"
|
||||
StateStoreService_InsertBinding_FullMethodName = "/state.v1.StateStoreService/InsertBinding"
|
||||
StateStoreService_GetBinding_FullMethodName = "/state.v1.StateStoreService/GetBinding"
|
||||
StateStoreService_ListBindings_FullMethodName = "/state.v1.StateStoreService/ListBindings"
|
||||
@@ -197,6 +201,12 @@ type StateStoreServiceClient interface {
|
||||
ListMappings(ctx context.Context, in *ListMappingsRequest, opts ...grpc.CallOption) (*ListMappingsResponse, error)
|
||||
UpdateMapping(ctx context.Context, in *UpdateMappingRequest, opts ...grpc.CallOption) (*UpdateMappingResponse, error)
|
||||
DeleteMapping(ctx context.Context, in *DeleteMappingRequest, opts ...grpc.CallOption) (*DeleteMappingResponse, error)
|
||||
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
|
||||
// Update refuse an overlapping or malformed type.
|
||||
InsertEventType(ctx context.Context, in *InsertEventTypeRequest, opts ...grpc.CallOption) (*InsertEventTypeResponse, error)
|
||||
UpdateEventType(ctx context.Context, in *UpdateEventTypeRequest, opts ...grpc.CallOption) (*UpdateEventTypeResponse, error)
|
||||
DeleteEventType(ctx context.Context, in *DeleteEventTypeRequest, opts ...grpc.CallOption) (*DeleteEventTypeResponse, error)
|
||||
ListEventTypes(ctx context.Context, in *ListEventTypesRequest, opts ...grpc.CallOption) (*ListEventTypesResponse, error)
|
||||
// Binding
|
||||
InsertBinding(ctx context.Context, in *InsertBindingRequest, opts ...grpc.CallOption) (*InsertBindingResponse, error)
|
||||
GetBinding(ctx context.Context, in *GetBindingRequest, opts ...grpc.CallOption) (*GetBindingResponse, error)
|
||||
@@ -789,6 +799,46 @@ func (c *stateStoreServiceClient) DeleteMapping(ctx context.Context, in *DeleteM
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) InsertEventType(ctx context.Context, in *InsertEventTypeRequest, opts ...grpc.CallOption) (*InsertEventTypeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(InsertEventTypeResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_InsertEventType_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) UpdateEventType(ctx context.Context, in *UpdateEventTypeRequest, opts ...grpc.CallOption) (*UpdateEventTypeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(UpdateEventTypeResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_UpdateEventType_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) DeleteEventType(ctx context.Context, in *DeleteEventTypeRequest, opts ...grpc.CallOption) (*DeleteEventTypeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DeleteEventTypeResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_DeleteEventType_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ListEventTypes(ctx context.Context, in *ListEventTypesRequest, opts ...grpc.CallOption) (*ListEventTypesResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListEventTypesResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ListEventTypes_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) InsertBinding(ctx context.Context, in *InsertBindingRequest, opts ...grpc.CallOption) (*InsertBindingResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(InsertBindingResponse)
|
||||
@@ -1038,6 +1088,12 @@ type StateStoreServiceServer interface {
|
||||
ListMappings(context.Context, *ListMappingsRequest) (*ListMappingsResponse, error)
|
||||
UpdateMapping(context.Context, *UpdateMappingRequest) (*UpdateMappingResponse, error)
|
||||
DeleteMapping(context.Context, *DeleteMappingRequest) (*DeleteMappingResponse, error)
|
||||
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
|
||||
// Update refuse an overlapping or malformed type.
|
||||
InsertEventType(context.Context, *InsertEventTypeRequest) (*InsertEventTypeResponse, error)
|
||||
UpdateEventType(context.Context, *UpdateEventTypeRequest) (*UpdateEventTypeResponse, error)
|
||||
DeleteEventType(context.Context, *DeleteEventTypeRequest) (*DeleteEventTypeResponse, error)
|
||||
ListEventTypes(context.Context, *ListEventTypesRequest) (*ListEventTypesResponse, error)
|
||||
// Binding
|
||||
InsertBinding(context.Context, *InsertBindingRequest) (*InsertBindingResponse, error)
|
||||
GetBinding(context.Context, *GetBindingRequest) (*GetBindingResponse, error)
|
||||
@@ -1233,6 +1289,18 @@ func (UnimplementedStateStoreServiceServer) UpdateMapping(context.Context, *Upda
|
||||
func (UnimplementedStateStoreServiceServer) DeleteMapping(context.Context, *DeleteMappingRequest) (*DeleteMappingResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteMapping not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) InsertEventType(context.Context, *InsertEventTypeRequest) (*InsertEventTypeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method InsertEventType not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) UpdateEventType(context.Context, *UpdateEventTypeRequest) (*UpdateEventTypeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method UpdateEventType not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) DeleteEventType(context.Context, *DeleteEventTypeRequest) (*DeleteEventTypeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteEventType not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ListEventTypes(context.Context, *ListEventTypesRequest) (*ListEventTypesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListEventTypes not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) InsertBinding(context.Context, *InsertBindingRequest) (*InsertBindingResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method InsertBinding not implemented")
|
||||
}
|
||||
@@ -2251,6 +2319,78 @@ func _StateStoreService_DeleteMapping_Handler(srv interface{}, ctx context.Conte
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_InsertEventType_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(InsertEventTypeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).InsertEventType(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_InsertEventType_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).InsertEventType(ctx, req.(*InsertEventTypeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_UpdateEventType_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(UpdateEventTypeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).UpdateEventType(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_UpdateEventType_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).UpdateEventType(ctx, req.(*UpdateEventTypeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_DeleteEventType_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(DeleteEventTypeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).DeleteEventType(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_DeleteEventType_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).DeleteEventType(ctx, req.(*DeleteEventTypeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ListEventTypes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListEventTypesRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ListEventTypes(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ListEventTypes_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ListEventTypes(ctx, req.(*ListEventTypesRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_InsertBinding_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(InsertBindingRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -2693,6 +2833,22 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "DeleteMapping",
|
||||
Handler: _StateStoreService_DeleteMapping_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "InsertEventType",
|
||||
Handler: _StateStoreService_InsertEventType_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "UpdateEventType",
|
||||
Handler: _StateStoreService_UpdateEventType_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "DeleteEventType",
|
||||
Handler: _StateStoreService_DeleteEventType_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListEventTypes",
|
||||
Handler: _StateStoreService_ListEventTypes_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "InsertBinding",
|
||||
Handler: _StateStoreService_InsertBinding_Handler,
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
// Package eventtype owns event types: named kinds of event from one source,
|
||||
// each defined by a match rule over headers and payload. It infers a
|
||||
// structural signature per capture, groups a source's captures into proposed
|
||||
// types, evaluates rules, and refuses two types on one source whose rules can
|
||||
// match the same event. An event that matches no type is unidentified and is
|
||||
// never dispatched. See docs/prds/event-automation.md, "Event types".
|
||||
package eventtype
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalid marks an event type that cannot be saved as written.
|
||||
ErrInvalid = errors.New("eventtype: invalid event type")
|
||||
// ErrOverlap marks an event type whose rule can match an event another
|
||||
// type on the same source also matches.
|
||||
ErrOverlap = errors.New("eventtype: rule overlaps another event type on the source")
|
||||
)
|
||||
|
||||
// Operator is a payload condition's test.
|
||||
type Operator string
|
||||
|
||||
const (
|
||||
OpEquals Operator = "equals"
|
||||
OpPresent Operator = "present"
|
||||
)
|
||||
|
||||
// HeaderCondition holds when the named header (case-insensitive) has Value.
|
||||
type HeaderCondition struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// PayloadCondition holds when Path is present or, for OpEquals, when a value
|
||||
// at Path renders as Value ("7", "true", "null", or the string itself).
|
||||
type PayloadCondition struct {
|
||||
Path string `json:"path"`
|
||||
Op Operator `json:"op"`
|
||||
Value string `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
// Rule is a conjunction: every condition must hold. An empty rule matches
|
||||
// every event from its source.
|
||||
type Rule struct {
|
||||
Headers []HeaderCondition `json:"headers"`
|
||||
Payload []PayloadCondition `json:"payload"`
|
||||
}
|
||||
|
||||
// EventType is a named kind of event from one source. Schema is the inferred
|
||||
// structure (path to type) of the payload it was created from.
|
||||
type EventType struct {
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Rule Rule `json:"rule"`
|
||||
Schema map[string]ValueType `json:"schema"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Validate refuses an event type that has no name or source or carries a
|
||||
// malformed condition.
|
||||
func (t EventType) Validate() error {
|
||||
if strings.TrimSpace(t.Name) == "" {
|
||||
return fmt.Errorf("%w: name is required", ErrInvalid)
|
||||
}
|
||||
if strings.TrimSpace(t.Source) == "" {
|
||||
return fmt.Errorf("%w: source is required", ErrInvalid)
|
||||
}
|
||||
for _, h := range t.Rule.Headers {
|
||||
if strings.TrimSpace(h.Name) == "" {
|
||||
return fmt.Errorf("%w: header condition has no name", ErrInvalid)
|
||||
}
|
||||
}
|
||||
for _, p := range t.Rule.Payload {
|
||||
if strings.TrimSpace(p.Path) == "" {
|
||||
return fmt.Errorf("%w: payload condition has no path", ErrInvalid)
|
||||
}
|
||||
if p.Op != OpEquals && p.Op != OpPresent {
|
||||
return fmt.Errorf("%w: unknown operator %q", ErrInvalid, p.Op)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Matches reports whether every condition of r holds for s.
|
||||
func (r Rule) Matches(s Sample) bool {
|
||||
for _, h := range r.Headers {
|
||||
got, ok := headerLookup(s.Headers, h.Name)
|
||||
if !ok || headerValue(h.Name, got) != headerValue(h.Name, h.Value) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if len(r.Payload) == 0 {
|
||||
return true
|
||||
}
|
||||
root, ok := decode(s.Body)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for _, p := range r.Payload {
|
||||
if !payloadHolds(root, p) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func headerLookup(headers map[string]string, name string) (string, bool) {
|
||||
for k, v := range headers {
|
||||
if strings.EqualFold(k, name) {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func payloadHolds(root any, p PayloadCondition) bool {
|
||||
values := lookup(root, p.Path)
|
||||
if p.Op == OpPresent {
|
||||
return len(values) > 0
|
||||
}
|
||||
for _, v := range values {
|
||||
if text, ok := scalarText(v); ok && text == p.Value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Overlaps reports whether some event could satisfy both rules. Two rules are
|
||||
// disjoint only when they demand different values of one header, or different
|
||||
// values at one payload path outside any array; anything else is treated as
|
||||
// overlapping, which errs towards refusing a save rather than towards an event
|
||||
// two types both claim.
|
||||
func Overlaps(a, b Rule) bool {
|
||||
for _, ha := range a.Headers {
|
||||
for _, hb := range b.Headers {
|
||||
if strings.EqualFold(ha.Name, hb.Name) && headerValue(ha.Name, ha.Value) != headerValue(hb.Name, hb.Value) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, pa := range a.Payload {
|
||||
for _, pb := range b.Payload {
|
||||
if pa.Op == OpEquals && pb.Op == OpEquals && pa.Path == pb.Path &&
|
||||
!strings.Contains(pa.Path, "[]") && pa.Value != pb.Value {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CheckOverlap refuses candidate when its rule overlaps another type on the
|
||||
// same source. A type is not compared with itself, so an update passes.
|
||||
func CheckOverlap(existing []EventType, candidate EventType) error {
|
||||
for _, t := range existing {
|
||||
if t.Source != candidate.Source || (candidate.ID != "" && t.ID == candidate.ID) {
|
||||
continue
|
||||
}
|
||||
if Overlaps(t.Rule, candidate.Rule) {
|
||||
return fmt.Errorf("%w: %q", ErrOverlap, t.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Identify returns the one type on source whose rule matches s. No match, or
|
||||
// more than one (which overlap refusal prevents), is unidentified.
|
||||
func Identify(types []EventType, source string, s Sample) (EventType, bool) {
|
||||
var found []EventType
|
||||
for _, t := range types {
|
||||
if t.Source == source && t.Rule.Matches(s) {
|
||||
found = append(found, t)
|
||||
}
|
||||
}
|
||||
if len(found) != 1 {
|
||||
return EventType{}, false
|
||||
}
|
||||
return found[0], true
|
||||
}
|
||||
|
||||
// FromExample builds an event type from a pasted payload: its schema is the
|
||||
// example's structure, and its rule is the example's discriminator headers or,
|
||||
// when it has none, the presence of each top-level payload key.
|
||||
func FromExample(source, name string, s Sample) EventType {
|
||||
sig := Sign(s)
|
||||
t := EventType{Source: source, Name: name, Schema: sig.Paths}
|
||||
t.Rule.Headers = headerConditions(sig.Headers)
|
||||
if len(t.Rule.Headers) == 0 {
|
||||
for _, path := range slices.Sorted(maps.Keys(sig.Paths)) {
|
||||
if !strings.ContainsAny(path, ".[") {
|
||||
t.Rule.Payload = append(t.Rule.Payload, PayloadCondition{Path: path, Op: OpPresent})
|
||||
}
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func headerConditions(headers map[string]string) []HeaderCondition {
|
||||
var out []HeaderCondition
|
||||
for _, name := range slices.Sorted(maps.Keys(headers)) {
|
||||
out = append(out, HeaderCondition{Name: name, Value: headers[name]})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package eventtype
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func sample(headers map[string]string, body string) Sample {
|
||||
return Sample{Headers: headers, Body: []byte(body)}
|
||||
}
|
||||
|
||||
func TestParseHeaders(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
want map[string]string
|
||||
}{
|
||||
{"http header json", `{"X-Github-Event":["push"],"Content-Type":["application/json"]}`, map[string]string{"x-github-event": "push", "content-type": "application/json"}},
|
||||
{"empty", ``, map[string]string{}},
|
||||
{"not json", `nope`, map[string]string{}},
|
||||
{"empty value list", `{"X-A":[]}`, map[string]string{}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := ParseHeaders(tt.raw); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Fatalf("ParseHeaders = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSign(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in Sample
|
||||
wantPaths map[string]ValueType
|
||||
wantHeaders map[string]string
|
||||
}{
|
||||
{
|
||||
name: "paths with types and discriminator headers",
|
||||
in: sample(map[string]string{
|
||||
"x-github-event": "pull_request",
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
"user-agent": "GitHub-Hookshot",
|
||||
}, `{"action":"opened","number":7,"draft":false,"pull_request":{"labels":[{"name":"x"}],"body":null},"tags":[]}`),
|
||||
wantPaths: map[string]ValueType{
|
||||
"action": TypeString,
|
||||
"number": TypeNumber,
|
||||
"draft": TypeBool,
|
||||
"pull_request": TypeObject,
|
||||
"pull_request.labels": TypeArray,
|
||||
"pull_request.labels[]": TypeObject,
|
||||
"pull_request.labels[].name": TypeString,
|
||||
"pull_request.body": TypeNull,
|
||||
"tags": TypeArray,
|
||||
},
|
||||
wantHeaders: map[string]string{"x-github-event": "pull_request", "content-type": "application/json"},
|
||||
},
|
||||
{
|
||||
name: "non-json body has no paths",
|
||||
in: sample(map[string]string{"x-kind-type": "blocked"}, `plain text`),
|
||||
wantPaths: map[string]ValueType{},
|
||||
wantHeaders: map[string]string{"x-kind-type": "blocked"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := Sign(tt.in)
|
||||
if !reflect.DeepEqual(got.Paths, tt.wantPaths) {
|
||||
t.Errorf("paths = %v, want %v", got.Paths, tt.wantPaths)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Headers, tt.wantHeaders) {
|
||||
t.Errorf("headers = %v, want %v", got.Headers, tt.wantHeaders)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignatureKeyIgnoresValuesButNotShape(t *testing.T) {
|
||||
a := Sign(sample(nil, `{"a":1,"b":"x"}`))
|
||||
b := Sign(sample(nil, `{"b":"y","a":2}`))
|
||||
c := Sign(sample(nil, `{"a":"1","b":"x"}`))
|
||||
if a.Key() != b.Key() {
|
||||
t.Errorf("same shape, different keys: %q vs %q", a.Key(), b.Key())
|
||||
}
|
||||
if a.Key() == c.Key() {
|
||||
t.Errorf("different types share key %q", a.Key())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuleMatches(t *testing.T) {
|
||||
ev := sample(map[string]string{"x-github-event": "pull_request", "content-type": "application/json; charset=utf-8"},
|
||||
`{"action":"opened","number":7,"merged":false,"labels":[{"name":"bug"},{"name":"ui"}]}`)
|
||||
tests := []struct {
|
||||
name string
|
||||
rule Rule
|
||||
want bool
|
||||
}{
|
||||
{"empty rule matches", Rule{}, true},
|
||||
{"header equal, name case-insensitive", Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "pull_request"}}}, true},
|
||||
{"header differs", Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "push"}}}, false},
|
||||
{"header absent", Rule{Headers: []HeaderCondition{{Name: "X-Gitea-Event", Value: "push"}}}, false},
|
||||
{"content type compared by media type", Rule{Headers: []HeaderCondition{{Name: "Content-Type", Value: "application/json"}}}, true},
|
||||
{"path equals string", Rule{Payload: []PayloadCondition{{Path: "action", Op: OpEquals, Value: "opened"}}}, true},
|
||||
{"path equals other string", Rule{Payload: []PayloadCondition{{Path: "action", Op: OpEquals, Value: "closed"}}}, false},
|
||||
{"path equals number", Rule{Payload: []PayloadCondition{{Path: "number", Op: OpEquals, Value: "7"}}}, true},
|
||||
{"path equals bool", Rule{Payload: []PayloadCondition{{Path: "merged", Op: OpEquals, Value: "false"}}}, true},
|
||||
{"path present", Rule{Payload: []PayloadCondition{{Path: "number", Op: OpPresent}}}, true},
|
||||
{"path missing", Rule{Payload: []PayloadCondition{{Path: "sender.login", Op: OpPresent}}}, false},
|
||||
{"array element equals", Rule{Payload: []PayloadCondition{{Path: "labels[].name", Op: OpEquals, Value: "ui"}}}, true},
|
||||
{"all conditions must hold", Rule{
|
||||
Headers: []HeaderCondition{{Name: "x-github-event", Value: "pull_request"}},
|
||||
Payload: []PayloadCondition{{Path: "action", Op: OpEquals, Value: "closed"}},
|
||||
}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tt.rule.Matches(ev); got != tt.want {
|
||||
t.Fatalf("Matches = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverlaps(t *testing.T) {
|
||||
gh := func(v string) HeaderCondition { return HeaderCondition{Name: "X-GitHub-Event", Value: v} }
|
||||
eq := func(p, v string) PayloadCondition { return PayloadCondition{Path: p, Op: OpEquals, Value: v} }
|
||||
present := func(p string) PayloadCondition { return PayloadCondition{Path: p, Op: OpPresent} }
|
||||
tests := []struct {
|
||||
name string
|
||||
a, b Rule
|
||||
want bool
|
||||
}{
|
||||
{"different header values are disjoint", Rule{Headers: []HeaderCondition{gh("push")}}, Rule{Headers: []HeaderCondition{gh("pull_request")}}, false},
|
||||
{"header names compared case-insensitively", Rule{Headers: []HeaderCondition{gh("push")}}, Rule{Headers: []HeaderCondition{{Name: "x-github-event", Value: "issues"}}}, false},
|
||||
{"same header overlaps", Rule{Headers: []HeaderCondition{gh("push")}}, Rule{Headers: []HeaderCondition{gh("push")}}, true},
|
||||
{"empty rule overlaps everything", Rule{}, Rule{Headers: []HeaderCondition{gh("push")}}, true},
|
||||
{"different equals on a path are disjoint", Rule{Payload: []PayloadCondition{eq("action", "opened")}}, Rule{Payload: []PayloadCondition{eq("action", "closed")}}, false},
|
||||
{"equals and present on one path overlap", Rule{Payload: []PayloadCondition{eq("action", "opened")}}, Rule{Payload: []PayloadCondition{present("action")}}, true},
|
||||
{"unrelated conditions overlap", Rule{Payload: []PayloadCondition{present("a")}}, Rule{Payload: []PayloadCondition{present("b")}}, true},
|
||||
{"array paths never prove disjointness", Rule{Payload: []PayloadCondition{eq("l[].n", "x")}}, Rule{Payload: []PayloadCondition{eq("l[].n", "y")}}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := Overlaps(tt.a, tt.b); got != tt.want {
|
||||
t.Fatalf("Overlaps = %v, want %v", got, tt.want)
|
||||
}
|
||||
if got := Overlaps(tt.b, tt.a); got != tt.want {
|
||||
t.Fatalf("Overlaps (swapped) = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeValidate(t *testing.T) {
|
||||
ok := EventType{Source: "gh", Name: "push", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "push"}}}}
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*EventType)
|
||||
valid bool
|
||||
}{
|
||||
{"valid", func(*EventType) {}, true},
|
||||
{"missing name", func(e *EventType) { e.Name = " " }, false},
|
||||
{"missing source", func(e *EventType) { e.Source = "" }, false},
|
||||
{"header without name", func(e *EventType) { e.Rule.Headers = []HeaderCondition{{Value: "x"}} }, false},
|
||||
{"payload without path", func(e *EventType) { e.Rule.Payload = []PayloadCondition{{Op: OpPresent}} }, false},
|
||||
{"unknown operator", func(e *EventType) { e.Rule.Payload = []PayloadCondition{{Path: "a", Op: "like"}} }, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
e := ok
|
||||
e.Rule = Rule{Headers: append([]HeaderCondition(nil), ok.Rule.Headers...)}
|
||||
tt.mutate(&e)
|
||||
err := e.Validate()
|
||||
if (err == nil) != tt.valid {
|
||||
t.Fatalf("Validate = %v, valid want %v", err, tt.valid)
|
||||
}
|
||||
if err != nil && !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("Validate error %v is not ErrInvalid", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckOverlap(t *testing.T) {
|
||||
push := EventType{ID: "1", Source: "gh", Name: "push", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "push"}}}}
|
||||
tests := []struct {
|
||||
name string
|
||||
candidate EventType
|
||||
wantErr bool
|
||||
}{
|
||||
{"disjoint on same source", EventType{Source: "gh", Name: "pr", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "pull_request"}}}}, false},
|
||||
{"overlapping on same source", EventType{Source: "gh", Name: "any", Rule: Rule{}}, true},
|
||||
{"overlapping on another source", EventType{Source: "fw", Name: "any", Rule: Rule{}}, false},
|
||||
{"an update does not overlap itself", EventType{ID: "1", Source: "gh", Name: "push2", Rule: Rule{}}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := CheckOverlap([]EventType{push}, tt.candidate)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("CheckOverlap = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err != nil && !errors.Is(err, ErrOverlap) {
|
||||
t.Fatalf("error %v is not ErrOverlap", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentify(t *testing.T) {
|
||||
types := []EventType{
|
||||
{ID: "push", Source: "gh", Name: "push", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "push"}}}},
|
||||
{ID: "pr", Source: "gh", Name: "pr", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "pull_request"}}}},
|
||||
{ID: "fw", Source: "fw", Name: "any", Rule: Rule{}},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
in Sample
|
||||
want string
|
||||
}{
|
||||
{"matches its type", "gh", sample(map[string]string{"x-github-event": "push"}, `{}`), "push"},
|
||||
{"no type matches", "gh", sample(map[string]string{"x-github-event": "issues"}, `{}`), ""},
|
||||
{"types from other sources are ignored", "other", sample(nil, `{}`), ""},
|
||||
{"catch-all on its source", "fw", sample(nil, `{"x":1}`), "fw"},
|
||||
{"two matches is unidentified", "gh", sample(map[string]string{"x-github-event": "push"}, `{}`), ""},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ts := types
|
||||
if i == len(tests)-1 {
|
||||
ts = append(ts, EventType{ID: "dup", Source: "gh", Name: "dup", Rule: Rule{}})
|
||||
}
|
||||
got, ok := Identify(ts, tt.source, tt.in)
|
||||
if got.ID != tt.want || ok != (tt.want != "") {
|
||||
t.Fatalf("Identify = %q,%v want %q", got.ID, ok, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromExample(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in Sample
|
||||
wantRule Rule
|
||||
}{
|
||||
{
|
||||
name: "discriminator headers become the rule",
|
||||
in: sample(map[string]string{"X-GitHub-Event": "push", "User-Agent": "x"}, `{"ref":"main"}`),
|
||||
wantRule: Rule{Headers: []HeaderCondition{{Name: "x-github-event", Value: "push"}}},
|
||||
},
|
||||
{
|
||||
name: "without discriminators the top-level paths must be present",
|
||||
in: sample(nil, `{"src":"1.2.3.4","action":{"k":1}}`),
|
||||
wantRule: Rule{Payload: []PayloadCondition{{Path: "action", Op: OpPresent}, {Path: "src", Op: OpPresent}}},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := FromExample("s", "n", tt.in)
|
||||
if !reflect.DeepEqual(got.Rule, tt.wantRule) {
|
||||
t.Fatalf("rule = %+v, want %+v", got.Rule, tt.wantRule)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Schema, Sign(tt.in).Paths) {
|
||||
t.Fatalf("schema = %v, want the example's paths", got.Schema)
|
||||
}
|
||||
if !got.Rule.Matches(tt.in) {
|
||||
t.Fatal("a type made from an example must match that example")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPropose(t *testing.T) {
|
||||
gh := func(id, ev, body string) Capture {
|
||||
return Capture{ID: id, Source: "gh", Sample: sample(map[string]string{"x-github-event": ev}, body)}
|
||||
}
|
||||
captures := []Capture{
|
||||
gh("c1", "push", `{"ref":"a"}`),
|
||||
gh("c2", "pull_request", `{"action":"opened"}`),
|
||||
gh("c3", "push", `{"ref":"b"}`),
|
||||
{ID: "f1", Source: "fw", Sample: sample(nil, `{"src":"1.1.1.1","port":22}`)},
|
||||
{ID: "f2", Source: "fw", Sample: sample(nil, `{"src":"1.1.1.1","port":22,"extra":true}`)},
|
||||
}
|
||||
got := Propose(captures)
|
||||
type summary struct {
|
||||
source, sample string
|
||||
count int
|
||||
rule Rule
|
||||
}
|
||||
var sums []summary
|
||||
for _, p := range got {
|
||||
sums = append(sums, summary{p.Source, p.SampleID, p.Count, p.Rule})
|
||||
}
|
||||
want := []summary{
|
||||
{"fw", "f1", 1, Rule{}},
|
||||
{"fw", "f2", 1, Rule{Payload: []PayloadCondition{{Path: "extra", Op: OpPresent}}}},
|
||||
{"gh", "c1", 2, Rule{Headers: []HeaderCondition{{Name: "x-github-event", Value: "push"}}}},
|
||||
{"gh", "c2", 1, Rule{Headers: []HeaderCondition{{Name: "x-github-event", Value: "pull_request"}}}},
|
||||
}
|
||||
if !reflect.DeepEqual(sums, want) {
|
||||
t.Fatalf("Propose =\n%+v\nwant\n%+v", sums, want)
|
||||
}
|
||||
for _, p := range got {
|
||||
if len(p.Schema) == 0 {
|
||||
t.Errorf("proposal %s has no schema", p.SampleID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package eventtype
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Capture is one stored event as proposal grouping reads it.
|
||||
type Capture struct {
|
||||
ID string
|
||||
Source string
|
||||
ReceivedAt time.Time
|
||||
Sample Sample
|
||||
}
|
||||
|
||||
// Proposal is a group of one source's captures sharing a signature, offered
|
||||
// to the operator as an event type to name. Rule is the set of
|
||||
// discriminators that separates the group from its siblings on the source.
|
||||
type Proposal struct {
|
||||
Source string `json:"source"`
|
||||
Key string `json:"key"`
|
||||
Schema map[string]ValueType `json:"schema"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Count int `json:"count"`
|
||||
SampleID string `json:"sample_id"`
|
||||
Rule Rule `json:"rule"`
|
||||
}
|
||||
|
||||
// Propose groups captures by source and signature. Groups are ordered by
|
||||
// source, then largest first, then first seen; the sample is the group's first
|
||||
// capture in input order.
|
||||
func Propose(captures []Capture) []Proposal {
|
||||
var groups []*Proposal
|
||||
sigs := map[*Proposal]Signature{}
|
||||
index := map[string]*Proposal{}
|
||||
for _, c := range captures {
|
||||
sig := Sign(c.Sample)
|
||||
key := sig.Key()
|
||||
id := c.Source + "\x00" + key
|
||||
if g, ok := index[id]; ok {
|
||||
g.Count++
|
||||
continue
|
||||
}
|
||||
g := &Proposal{Source: c.Source, Key: key, Schema: sig.Paths, Headers: sig.Headers, Count: 1, SampleID: c.ID}
|
||||
index[id] = g
|
||||
sigs[g] = sig
|
||||
groups = append(groups, g)
|
||||
}
|
||||
slices.SortStableFunc(groups, func(a, b *Proposal) int {
|
||||
if c := strings.Compare(a.Source, b.Source); c != 0 {
|
||||
return c
|
||||
}
|
||||
return b.Count - a.Count
|
||||
})
|
||||
out := make([]Proposal, 0, len(groups))
|
||||
for _, g := range groups {
|
||||
var siblings []Signature
|
||||
for _, s := range groups {
|
||||
if s != g && s.Source == g.Source {
|
||||
siblings = append(siblings, sigs[s])
|
||||
}
|
||||
}
|
||||
g.Rule = separatingRule(sigs[g], siblings)
|
||||
out = append(out, *g)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// separatingRule demands the group's discriminator headers, then, for each
|
||||
// sibling those do not already rule out, the presence of the first path the
|
||||
// group has and the sibling lacks. A group whose paths are a subset of a
|
||||
// sibling's cannot be separated by presence alone; saving it as proposed is
|
||||
// then refused as an overlap, and the operator edits the rule.
|
||||
func separatingRule(g Signature, siblings []Signature) Rule {
|
||||
rule := Rule{Headers: headerConditions(g.Headers)}
|
||||
paths := slices.Sorted(maps.Keys(g.Paths))
|
||||
for _, s := range siblings {
|
||||
if headersSeparate(g.Headers, s.Headers) || rulePathsSeparate(rule, s) {
|
||||
continue
|
||||
}
|
||||
for _, path := range paths {
|
||||
if _, ok := s.Paths[path]; !ok {
|
||||
rule.Payload = append(rule.Payload, PayloadCondition{Path: path, Op: OpPresent})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return rule
|
||||
}
|
||||
|
||||
func headersSeparate(g, s map[string]string) bool {
|
||||
for name, value := range g {
|
||||
if other, ok := s[name]; !ok || other != value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func rulePathsSeparate(rule Rule, s Signature) bool {
|
||||
for _, p := range rule.Payload {
|
||||
if _, ok := s.Paths[p.Path]; !ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package eventtype
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"mime"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ValueType is the JSON shape of one payload path. The names match
|
||||
// mapping.FieldType so a mapping can be checked against a type's schema.
|
||||
type ValueType string
|
||||
|
||||
const (
|
||||
TypeString ValueType = "string"
|
||||
TypeNumber ValueType = "number"
|
||||
TypeBool ValueType = "bool"
|
||||
TypeObject ValueType = "object"
|
||||
TypeArray ValueType = "array"
|
||||
TypeNull ValueType = "null"
|
||||
)
|
||||
|
||||
// Sample is one event as the rules see it: headers keyed by lower-case name
|
||||
// (first value only) and the raw body.
|
||||
type Sample struct {
|
||||
Headers map[string]string
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// Signature is the structure of one event: every JSON path with its value
|
||||
// type, plus the discriminator headers with their values. Array elements share
|
||||
// one path segment, "[]", so two payloads differing only in list length have
|
||||
// the same signature.
|
||||
type Signature struct {
|
||||
Paths map[string]ValueType `json:"paths"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
}
|
||||
|
||||
// ParseHeaders reads a capture's stored headers (an encoded http.Header) into
|
||||
// the lower-case, first-value form a Sample carries. Anything unreadable is no
|
||||
// headers, not an error: a capture's headers are evidence, not input.
|
||||
func ParseHeaders(raw string) map[string]string {
|
||||
out := map[string]string{}
|
||||
var h map[string][]string
|
||||
if json.Unmarshal([]byte(raw), &h) != nil {
|
||||
return out
|
||||
}
|
||||
for name, values := range h {
|
||||
if len(values) > 0 {
|
||||
out[strings.ToLower(name)] = values[0]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// isDiscriminator reports whether a header names the kind of event rather than
|
||||
// describing its transport: X-GitHub-Event, X-Gitea-Event-Type, Content-Type.
|
||||
func isDiscriminator(name string) bool {
|
||||
name = strings.ToLower(name)
|
||||
return strings.HasSuffix(name, "-event") || strings.HasSuffix(name, "-type")
|
||||
}
|
||||
|
||||
// headerValue normalises a header value for comparison. Content-Type compares
|
||||
// by media type, so a charset parameter does not split one kind of event in two.
|
||||
func headerValue(name, value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.EqualFold(name, "content-type") {
|
||||
if mt, _, err := mime.ParseMediaType(value); err == nil {
|
||||
return mt
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// Sign computes an event's structural signature. A body that is not JSON has
|
||||
// no paths; its headers still discriminate it.
|
||||
func Sign(s Sample) Signature {
|
||||
sig := Signature{Paths: map[string]ValueType{}, Headers: map[string]string{}}
|
||||
for name, value := range s.Headers {
|
||||
if isDiscriminator(name) {
|
||||
sig.Headers[strings.ToLower(name)] = headerValue(name, value)
|
||||
}
|
||||
}
|
||||
if root, ok := decode(s.Body); ok {
|
||||
collectPaths(root, "", sig.Paths)
|
||||
}
|
||||
return sig
|
||||
}
|
||||
|
||||
// Key is a stable string that is equal for two signatures exactly when their
|
||||
// paths, path types and discriminator headers are equal.
|
||||
func (s Signature) Key() string {
|
||||
var b strings.Builder
|
||||
for _, name := range slices.Sorted(maps.Keys(s.Headers)) {
|
||||
b.WriteString("h:" + name + "=" + s.Headers[name] + "\n")
|
||||
}
|
||||
for _, path := range slices.Sorted(maps.Keys(s.Paths)) {
|
||||
b.WriteString("p:" + path + "=" + string(s.Paths[path]) + "\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func decode(body []byte) (any, bool) {
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.UseNumber()
|
||||
var v any
|
||||
if err := dec.Decode(&v); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
func valueType(v any) ValueType {
|
||||
switch v.(type) {
|
||||
case string:
|
||||
return TypeString
|
||||
case json.Number:
|
||||
return TypeNumber
|
||||
case bool:
|
||||
return TypeBool
|
||||
case map[string]any:
|
||||
return TypeObject
|
||||
case []any:
|
||||
return TypeArray
|
||||
default:
|
||||
return TypeNull
|
||||
}
|
||||
}
|
||||
|
||||
// collectPaths records every path below v. The root itself has no path.
|
||||
func collectPaths(v any, prefix string, out map[string]ValueType) {
|
||||
switch typed := v.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range typed {
|
||||
path := key
|
||||
if prefix != "" {
|
||||
path = prefix + "." + key
|
||||
}
|
||||
out[path] = valueType(child)
|
||||
collectPaths(child, path, out)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range typed {
|
||||
path := prefix + "[]"
|
||||
out[path] = valueType(child)
|
||||
collectPaths(child, path, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lookup returns every value at path; "[]" segments fan out over array
|
||||
// elements, so a path inside a list yields one value per element that has it.
|
||||
func lookup(root any, path string) []any {
|
||||
current := []any{root}
|
||||
for seg := range strings.SplitSeq(path, ".") {
|
||||
name, arrays := seg, 0
|
||||
for strings.HasSuffix(name, "[]") {
|
||||
name, arrays = strings.TrimSuffix(name, "[]"), arrays+1
|
||||
}
|
||||
var next []any
|
||||
for _, node := range current {
|
||||
obj, ok := node.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if child, ok := obj[name]; ok {
|
||||
next = append(next, child)
|
||||
}
|
||||
}
|
||||
for range arrays {
|
||||
var elems []any
|
||||
for _, node := range next {
|
||||
if arr, ok := node.([]any); ok {
|
||||
elems = append(elems, arr...)
|
||||
}
|
||||
}
|
||||
next = elems
|
||||
}
|
||||
current = next
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
// scalarText renders a scalar the way an operator types it into an equals
|
||||
// condition; objects and arrays have no text and never equal anything.
|
||||
func scalarText(v any) (string, bool) {
|
||||
switch typed := v.(type) {
|
||||
case string:
|
||||
return typed, true
|
||||
case json.Number:
|
||||
return typed.String(), true
|
||||
case bool:
|
||||
if typed {
|
||||
return "true", true
|
||||
}
|
||||
return "false", true
|
||||
case nil:
|
||||
return "null", true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
@@ -177,6 +178,18 @@ type MappingStore interface {
|
||||
DeleteMapping(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// EventTypeStore persists event types (docs/prds/event-automation.md, "Event
|
||||
// types"). Insert and Update refuse a type whose rule overlaps another on the
|
||||
// same source with eventtype.ErrOverlap, and a malformed one with
|
||||
// eventtype.ErrInvalid. Update rewrites the name and rule; the schema is the
|
||||
// one the type was created with.
|
||||
type EventTypeStore interface {
|
||||
InsertEventType(ctx context.Context, t eventtype.EventType) (string, error)
|
||||
UpdateEventType(ctx context.Context, t eventtype.EventType) error
|
||||
DeleteEventType(ctx context.Context, id string) error
|
||||
ListEventTypes(ctx context.Context) ([]eventtype.EventType, error)
|
||||
}
|
||||
|
||||
// BindingStore persists playbook bindings (t2db.4 Phase B): CRUD and the
|
||||
// draft -> pending_approval -> armed state machine. Split off from
|
||||
// TaskStore and MappingStore so the webui binding editor does not acquire
|
||||
@@ -271,6 +284,10 @@ type CapturedEvent struct {
|
||||
Headers string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
// EventType is the ID of the event type the capture was identified as
|
||||
// when it arrived, or empty when it matched none. An unidentified capture
|
||||
// is never dispatched.
|
||||
EventType string `json:"event_type"`
|
||||
}
|
||||
|
||||
// ConfigSnapshot is the running configuration as the dashboard renders it,
|
||||
@@ -370,6 +387,8 @@ var (
|
||||
ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture")
|
||||
// ErrMappingNotFound is returned when a mapping ID does not exist.
|
||||
ErrMappingNotFound = errors.New("store: mapping not found")
|
||||
// ErrEventTypeNotFound is returned when an event type ID does not exist.
|
||||
ErrEventTypeNotFound = errors.New("store: event type not found")
|
||||
|
||||
// ErrResourceNotFound is returned when a control-plane resource kind has
|
||||
// no stored document. It is in-process only (not on the gRPC wire): the
|
||||
|
||||
@@ -76,7 +76,8 @@ func newRecordID() string { return uuid.NewString() }
|
||||
|
||||
// --- captures ---
|
||||
|
||||
// InsertCapture stores one inbound event verbatim. retention and maxEvents are
|
||||
// InsertCapture stores one inbound event verbatim, tagged with the event type
|
||||
// it is identified as on arrival (empty when unidentified). retention and maxEvents are
|
||||
// accepted for contract compatibility and applied as a prune after the insert,
|
||||
// exactly as the PocketBase store does.
|
||||
func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent, retention time.Duration, maxEvents int) (string, error) {
|
||||
@@ -84,6 +85,10 @@ func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent,
|
||||
if received.IsZero() {
|
||||
received = time.Now()
|
||||
}
|
||||
eventType, err := s.identifyCapture(ctx, c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
id := newRecordID()
|
||||
if err := s.q.InsertCapture(ctx, postgresdb.InsertCaptureParams{
|
||||
ID: id,
|
||||
@@ -94,6 +99,7 @@ func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent,
|
||||
Body: c.Body,
|
||||
Authenticated: c.Authenticated,
|
||||
ReceivedAt: received.UTC(),
|
||||
EventType: eventType,
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("edastore: insert capture: %w", err)
|
||||
}
|
||||
@@ -127,6 +133,7 @@ func captureValue(r postgresdb.Capture) storecontract.CapturedEvent {
|
||||
Headers: r.Headers,
|
||||
Body: r.Body,
|
||||
Authenticated: r.Authenticated,
|
||||
EventType: r.EventType,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,8 +150,9 @@ func (s *EDA) ListCaptures(ctx context.Context, limit int) ([]storecontract.Capt
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListUndispatchedCaptures returns recent captures for the given sources that
|
||||
// no binding has dispatched yet.
|
||||
// ListUndispatchedCaptures returns recent identified captures for the given
|
||||
// sources that no binding has dispatched yet. An unidentified capture is
|
||||
// never returned, so it never dispatches.
|
||||
func (s *EDA) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) {
|
||||
if len(sources) == 0 || limit <= 0 {
|
||||
return nil, nil
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
func githubType(name, event string) eventtype.EventType {
|
||||
return eventtype.EventType{
|
||||
Source: "gh", Name: name,
|
||||
Rule: eventtype.Rule{Headers: []eventtype.HeaderCondition{{Name: "X-GitHub-Event", Value: event}}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeSaveRefusals(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
pushID, err := s.InsertEventType(t.Context(), githubType("push", "push"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType(push) error = %v", err)
|
||||
}
|
||||
prID, err := s.InsertEventType(t.Context(), githubType("pr", "pull_request"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType(pr) error = %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
save func() error
|
||||
wantErr error
|
||||
}{
|
||||
{"insert overlapping rule", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("push-again", "push"))
|
||||
return err
|
||||
}, eventtype.ErrOverlap},
|
||||
{"insert catch-all beside typed", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "gh", Name: "all"})
|
||||
return err
|
||||
}, eventtype.ErrOverlap},
|
||||
{"insert duplicate name", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("push", "issues"))
|
||||
return err
|
||||
}, eventtype.ErrInvalid},
|
||||
{"insert without name", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("", "issues"))
|
||||
return err
|
||||
}, eventtype.ErrInvalid},
|
||||
{"update into overlap", func() error {
|
||||
pr := githubType("pr", "push")
|
||||
pr.ID = prID
|
||||
return s.UpdateEventType(t.Context(), pr)
|
||||
}, eventtype.ErrOverlap},
|
||||
{"update missing", func() error {
|
||||
missing := githubType("x", "x")
|
||||
missing.ID = "missing"
|
||||
return s.UpdateEventType(t.Context(), missing)
|
||||
}, storecontract.ErrEventTypeNotFound},
|
||||
{"delete missing", func() error { return s.DeleteEventType(t.Context(), "missing") }, storecontract.ErrEventTypeNotFound},
|
||||
{"other source is independent", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "all"})
|
||||
return err
|
||||
}, nil},
|
||||
{"update keeps itself out of the overlap check", func() error {
|
||||
push := githubType("push-renamed", "push")
|
||||
push.ID = pushID
|
||||
return s.UpdateEventType(t.Context(), push)
|
||||
}, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.save()
|
||||
if tt.wantErr == nil && err != nil {
|
||||
t.Fatalf("error = %v, want nil", err)
|
||||
}
|
||||
if tt.wantErr != nil && !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
types, err := s.ListEventTypes(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ListEventTypes() error = %v", err)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, et := range types {
|
||||
names[et.Source+"/"+et.Name] = true
|
||||
}
|
||||
for _, want := range []string{"gh/push-renamed", "gh/pr", "fw/all"} {
|
||||
if !names[want] {
|
||||
t.Errorf("ListEventTypes() lacks %s: %v", want, names)
|
||||
}
|
||||
}
|
||||
if len(types) != 3 {
|
||||
t.Errorf("ListEventTypes() = %d types, want 3", len(types))
|
||||
}
|
||||
}
|
||||
|
||||
// A type made from a pasted payload has that payload's schema, and a later
|
||||
// matching capture is identified as it and becomes dispatchable; a capture
|
||||
// matching no type stays unidentified and is never listed for dispatch.
|
||||
func TestPastedTypeIdentifiesLaterCaptures(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
pasted := eventtype.Sample{
|
||||
Headers: map[string]string{"X-GitHub-Event": "pull_request"},
|
||||
Body: []byte(`{"action":"opened","number":1}`),
|
||||
}
|
||||
id, err := s.InsertEventType(t.Context(), eventtype.FromExample("gh", "pull_request", pasted))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
types, err := s.ListEventTypes(t.Context())
|
||||
if err != nil || len(types) != 1 {
|
||||
t.Fatalf("ListEventTypes() = %v (err %v)", types, err)
|
||||
}
|
||||
if got := types[0].Schema; got["action"] != eventtype.TypeString || got["number"] != eventtype.TypeNumber {
|
||||
t.Fatalf("schema = %v, want the pasted payload's", got)
|
||||
}
|
||||
|
||||
for _, c := range []storecontract.CapturedEvent{
|
||||
{Source: "gh", Headers: `{"X-Github-Event":["pull_request"]}`, Body: `{"action":"closed","number":9}`},
|
||||
{Source: "gh", Headers: `{"X-Github-Event":["push"]}`, Body: `{"ref":"main"}`},
|
||||
} {
|
||||
if _, err := s.InsertCapture(t.Context(), c, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
}
|
||||
all, err := s.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures() error = %v", err)
|
||||
}
|
||||
byBody := map[string]string{}
|
||||
for _, c := range all {
|
||||
byBody[c.Body] = c.EventType
|
||||
}
|
||||
if byBody[`{"action":"closed","number":9}`] != id {
|
||||
t.Errorf("matching capture event type = %q, want %q", byBody[`{"action":"closed","number":9}`], id)
|
||||
}
|
||||
if byBody[`{"ref":"main"}`] != "" {
|
||||
t.Errorf("unmatched capture event type = %q, want unidentified", byBody[`{"ref":"main"}`])
|
||||
}
|
||||
|
||||
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"gh"}, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
|
||||
}
|
||||
if len(undispatched) != 1 || undispatched[0].EventType != id {
|
||||
t.Fatalf("ListUndispatchedCaptures() = %+v, want only the identified capture", undispatched)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var _ storecontract.EventTypeStore = (*EDA)(nil)
|
||||
|
||||
func eventTypeValue(r postgresdb.EventType) (eventtype.EventType, error) {
|
||||
t := eventtype.EventType{ID: r.ID, Source: r.Source, Name: r.Name, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
|
||||
if err := json.Unmarshal([]byte(r.Rule), &t.Rule); err != nil {
|
||||
return eventtype.EventType{}, fmt.Errorf("edastore: decode event type rule: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(r.Schema), &t.Schema); err != nil {
|
||||
return eventtype.EventType{}, fmt.Errorf("edastore: decode event type schema: %w", err)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func eventTypeValues(rows []postgresdb.EventType) ([]eventtype.EventType, error) {
|
||||
out := make([]eventtype.EventType, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
t, err := eventTypeValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// identifyCapture returns the ID of the one event type on the capture's
|
||||
// source that matches it, or "" when it is unidentified.
|
||||
func (s *EDA) identifyCapture(ctx context.Context, c storecontract.CapturedEvent) (string, error) {
|
||||
rows, err := s.q.EventTypesForSource(ctx, c.Source)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("edastore: load event types: %w", err)
|
||||
}
|
||||
types, err := eventTypeValues(rows)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
t, _ := eventtype.Identify(types, c.Source, eventtype.Sample{
|
||||
Headers: eventtype.ParseHeaders(c.Headers),
|
||||
Body: []byte(c.Body),
|
||||
})
|
||||
return t.ID, nil
|
||||
}
|
||||
|
||||
// saveEventType validates t, then, under a per-source lock, refuses it if its
|
||||
// rule overlaps another type on the source and runs write.
|
||||
func (s *EDA) saveEventType(ctx context.Context, t eventtype.EventType, write func(*postgresdb.Queries, string) error) error {
|
||||
if err := t.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
rule, err := json.Marshal(t.Rule)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: encode event type rule: %w", err)
|
||||
}
|
||||
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
q := s.q.WithTx(tx)
|
||||
if err := q.LockEventTypeSource(ctx, t.Source); err != nil {
|
||||
return fmt.Errorf("edastore: lock event types: %w", err)
|
||||
}
|
||||
rows, err := q.EventTypesForSource(ctx, t.Source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: load event types: %w", err)
|
||||
}
|
||||
existing, err := eventTypeValues(rows)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := eventtype.CheckOverlap(existing, t); err != nil {
|
||||
return err
|
||||
}
|
||||
err = write(q, string(rule))
|
||||
if isUniqueViolation(err) {
|
||||
return fmt.Errorf("%w: name %q is taken on source %q", eventtype.ErrInvalid, t.Name, t.Source)
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// InsertEventType stores a new event type.
|
||||
func (s *EDA) InsertEventType(ctx context.Context, t eventtype.EventType) (string, error) {
|
||||
t.ID = ""
|
||||
schema, err := json.Marshal(t.Schema)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("edastore: encode event type schema: %w", err)
|
||||
}
|
||||
id := newRecordID()
|
||||
err = s.saveEventType(ctx, t, func(q *postgresdb.Queries, rule string) error {
|
||||
return q.InsertEventType(ctx, postgresdb.InsertEventTypeParams{
|
||||
ID: id, Source: t.Source, Name: t.Name, Rule: rule, Schema: string(schema),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// UpdateEventType rewrites a type's name and rule. Its source and schema are
|
||||
// the stored ones.
|
||||
func (s *EDA) UpdateEventType(ctx context.Context, t eventtype.EventType) error {
|
||||
stored, err := s.q.GetEventType(ctx, t.ID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.Source = stored.Source
|
||||
return s.saveEventType(ctx, t, func(q *postgresdb.Queries, rule string) error {
|
||||
n, err := q.UpdateEventType(ctx, postgresdb.UpdateEventTypeParams{ID: t.ID, Name: t.Name, Rule: rule})
|
||||
if err == nil && n == 0 {
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteEventType removes a type. Captures already identified as it keep the
|
||||
// ID they were stored with.
|
||||
func (s *EDA) DeleteEventType(ctx context.Context, id string) error {
|
||||
n, err := s.q.DeleteEventType(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListEventTypes returns every event type, by source then name.
|
||||
func (s *EDA) ListEventTypes(ctx context.Context) ([]eventtype.EventType, error) {
|
||||
rows, err := s.q.ListEventTypes(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list event types: %w", err)
|
||||
}
|
||||
return eventTypeValues(rows)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
@@ -222,6 +223,9 @@ func TestBindingLifecycle(t *testing.T) {
|
||||
// out of the undispatched listing.
|
||||
func TestCaptureRoundTripAndUndispatched(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if _, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "sentry", Name: "any"}); err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
body := `{"action":"created"}`
|
||||
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
Source: "sentry", Body: body, Headers: `{"X-Hook":"1"}`, ContentType: "application/json",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
-- Event types: named kinds of event from one source, each defined by a match
|
||||
-- rule (docs/prds/event-automation.md, "Event types"). rule and schema are the
|
||||
-- JSON encodings of eventtype.Rule and the inferred path-to-type schema; the
|
||||
-- store evaluates them in Go, so they are opaque text here.
|
||||
--
|
||||
-- captures.event_type records the type a capture was identified as when it
|
||||
-- arrived. Empty means unidentified, and an unidentified capture is never
|
||||
-- listed for dispatch. It is a plain text column, not a foreign key: deleting
|
||||
-- a type must not rewrite what past captures were identified as.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE event_types (
|
||||
id text PRIMARY KEY,
|
||||
source text NOT NULL,
|
||||
name text NOT NULL,
|
||||
rule text NOT NULL,
|
||||
schema text NOT NULL DEFAULT '{}',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX idx_event_types_source_name ON event_types (source, name);
|
||||
|
||||
ALTER TABLE captures ADD COLUMN event_type text NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
ALTER TABLE captures DROP COLUMN event_type;
|
||||
DROP TABLE event_types;
|
||||
@@ -80,6 +80,18 @@ func (q *Queries) DeleteCapturesOlderThan(ctx context.Context, receivedAt time.T
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteEventType = `-- name: DeleteEventType :execrows
|
||||
DELETE FROM event_types WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteEventType(ctx context.Context, id string) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteEventType, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const deleteMapping = `-- name: DeleteMapping :execrows
|
||||
DELETE FROM mappings WHERE id = $1
|
||||
`
|
||||
@@ -101,6 +113,39 @@ func (q *Queries) DeletePlaybookDispatches(ctx context.Context, playbookID strin
|
||||
return err
|
||||
}
|
||||
|
||||
const eventTypesForSource = `-- name: EventTypesForSource :many
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types WHERE source = $1 ORDER BY name
|
||||
`
|
||||
|
||||
func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]EventType, error) {
|
||||
rows, err := q.db.Query(ctx, eventTypesForSource, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []EventType
|
||||
for rows.Next() {
|
||||
var i EventType
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Source,
|
||||
&i.Name,
|
||||
&i.Rule,
|
||||
&i.Schema,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const getBinding = `-- name: GetBinding :one
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
FROM bindings WHERE id = $1
|
||||
@@ -126,6 +171,26 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getEventType = `-- name: GetEventType :one
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetEventType(ctx context.Context, id string) (EventType, error) {
|
||||
row := q.db.QueryRow(ctx, getEventType, id)
|
||||
var i EventType
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Source,
|
||||
&i.Name,
|
||||
&i.Rule,
|
||||
&i.Schema,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getMapping = `-- name: GetMapping :one
|
||||
SELECT id, name, source_hint, fields, created_at, updated_at
|
||||
FROM mappings WHERE id = $1
|
||||
@@ -201,8 +266,8 @@ func (q *Queries) InsertBindingDispatch(ctx context.Context, arg InsertBindingDi
|
||||
|
||||
const insertCapture = `-- name: InsertCapture :exec
|
||||
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
`
|
||||
|
||||
type InsertCaptureParams struct {
|
||||
@@ -214,6 +279,7 @@ type InsertCaptureParams struct {
|
||||
Body string
|
||||
Authenticated bool
|
||||
ReceivedAt time.Time
|
||||
EventType string
|
||||
}
|
||||
|
||||
// EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls.
|
||||
@@ -227,6 +293,31 @@ func (q *Queries) InsertCapture(ctx context.Context, arg InsertCaptureParams) er
|
||||
arg.Body,
|
||||
arg.Authenticated,
|
||||
arg.ReceivedAt,
|
||||
arg.EventType,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertEventType = `-- name: InsertEventType :exec
|
||||
INSERT INTO event_types (id, source, name, rule, schema)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
type InsertEventTypeParams struct {
|
||||
ID string
|
||||
Source string
|
||||
Name string
|
||||
Rule string
|
||||
Schema string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertEventType(ctx context.Context, arg InsertEventTypeParams) error {
|
||||
_, err := q.db.Exec(ctx, insertEventType,
|
||||
arg.ID,
|
||||
arg.Source,
|
||||
arg.Name,
|
||||
arg.Rule,
|
||||
arg.Schema,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -342,7 +433,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
|
||||
}
|
||||
|
||||
const listCaptures = `-- name: ListCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
|
||||
FROM captures
|
||||
ORDER BY received_at DESC
|
||||
LIMIT $1
|
||||
@@ -366,6 +457,40 @@ func (q *Queries) ListCaptures(ctx context.Context, limit int32) ([]Capture, err
|
||||
&i.Body,
|
||||
&i.Authenticated,
|
||||
&i.ReceivedAt,
|
||||
&i.EventType,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listEventTypes = `-- name: ListEventTypes :many
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types ORDER BY source, name
|
||||
`
|
||||
|
||||
func (q *Queries) ListEventTypes(ctx context.Context) ([]EventType, error) {
|
||||
rows, err := q.db.Query(ctx, listEventTypes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []EventType
|
||||
for rows.Next() {
|
||||
var i EventType
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Source,
|
||||
&i.Name,
|
||||
&i.Rule,
|
||||
&i.Schema,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -410,9 +535,11 @@ func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, error) {
|
||||
}
|
||||
|
||||
const listUndispatchedCaptures = `-- name: ListUndispatchedCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
|
||||
FROM captures
|
||||
WHERE source = ANY($1::text[])
|
||||
-- An unidentified capture is never dispatched.
|
||||
AND event_type <> ''
|
||||
AND id NOT IN (SELECT capture FROM binding_dispatches)
|
||||
ORDER BY received_at DESC
|
||||
LIMIT $2
|
||||
@@ -441,6 +568,7 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
|
||||
&i.Body,
|
||||
&i.Authenticated,
|
||||
&i.ReceivedAt,
|
||||
&i.EventType,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -452,6 +580,17 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockEventTypeSource = `-- name: LockEventTypeSource :exec
|
||||
SELECT pg_advisory_xact_lock(hashtext('event_types:' || $1::text))
|
||||
`
|
||||
|
||||
// Serialises saves per source so two concurrent saves cannot each pass the
|
||||
// overlap check against a set that excludes the other.
|
||||
func (q *Queries) LockEventTypeSource(ctx context.Context, source string) error {
|
||||
_, err := q.db.Exec(ctx, lockEventTypeSource, source)
|
||||
return err
|
||||
}
|
||||
|
||||
const setBindingArmed = `-- name: SetBindingArmed :execrows
|
||||
UPDATE bindings SET status = 'armed', updated_at = now() WHERE id = $1
|
||||
`
|
||||
@@ -549,6 +688,24 @@ func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (i
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const updateEventType = `-- name: UpdateEventType :execrows
|
||||
UPDATE event_types SET name = $2, rule = $3, updated_at = now() WHERE id = $1
|
||||
`
|
||||
|
||||
type UpdateEventTypeParams struct {
|
||||
ID string
|
||||
Name string
|
||||
Rule string
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateEventType(ctx context.Context, arg UpdateEventTypeParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updateEventType, arg.ID, arg.Name, arg.Rule)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const updateMapping = `-- name: UpdateMapping :execrows
|
||||
UPDATE mappings
|
||||
SET name = $2, source_hint = $3, fields = $4, updated_at = now()
|
||||
|
||||
@@ -48,6 +48,7 @@ type Capture struct {
|
||||
Body string
|
||||
Authenticated bool
|
||||
ReceivedAt time.Time
|
||||
EventType string
|
||||
}
|
||||
|
||||
type ChannelStatus struct {
|
||||
@@ -84,6 +85,16 @@ type Event struct {
|
||||
Data string
|
||||
}
|
||||
|
||||
type EventType struct {
|
||||
ID string
|
||||
Source string
|
||||
Name string
|
||||
Rule string
|
||||
Schema string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Identity struct {
|
||||
ID string
|
||||
Kind string
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
-- EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls.
|
||||
|
||||
-- name: InsertCapture :exec
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8);
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
|
||||
|
||||
-- name: ListCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
|
||||
FROM captures
|
||||
ORDER BY received_at DESC
|
||||
LIMIT $1;
|
||||
|
||||
-- name: ListUndispatchedCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
|
||||
FROM captures
|
||||
WHERE source = ANY(@sources::text[])
|
||||
-- An unidentified capture is never dispatched.
|
||||
AND event_type <> ''
|
||||
AND id NOT IN (SELECT capture FROM binding_dispatches)
|
||||
ORDER BY received_at DESC
|
||||
LIMIT @entry_limit;
|
||||
@@ -97,3 +99,30 @@ VALUES ($1, $2, $3, $4, $5, $6, $7);
|
||||
-- name: TaskToolCalls :many
|
||||
SELECT id, task_id, attempt, tool, result, error, called_at
|
||||
FROM tool_calls WHERE task_id = $1 ORDER BY called_at ASC;
|
||||
|
||||
-- name: InsertEventType :exec
|
||||
INSERT INTO event_types (id, source, name, rule, schema)
|
||||
VALUES ($1, $2, $3, $4, $5);
|
||||
|
||||
-- name: GetEventType :one
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types WHERE id = $1;
|
||||
|
||||
-- name: ListEventTypes :many
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types ORDER BY source, name;
|
||||
|
||||
-- name: EventTypesForSource :many
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types WHERE source = $1 ORDER BY name;
|
||||
|
||||
-- name: UpdateEventType :execrows
|
||||
UPDATE event_types SET name = $2, rule = $3, updated_at = now() WHERE id = $1;
|
||||
|
||||
-- name: DeleteEventType :execrows
|
||||
DELETE FROM event_types WHERE id = $1;
|
||||
|
||||
-- name: LockEventTypeSource :exec
|
||||
-- Serialises saves per source so two concurrent saves cannot each pass the
|
||||
-- overlap check against a set that excludes the other.
|
||||
SELECT pg_advisory_xact_lock(hashtext('event_types:' || sqlc.arg(source)::text));
|
||||
@@ -0,0 +1,116 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// fakeEventTypes records what crossed the wire and answers with err.
|
||||
type fakeEventTypes struct {
|
||||
saved eventtype.EventType
|
||||
list []eventtype.EventType
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeEventTypes) InsertEventType(_ context.Context, t eventtype.EventType) (string, error) {
|
||||
f.saved = t
|
||||
return "et-1", f.err
|
||||
}
|
||||
|
||||
func (f *fakeEventTypes) UpdateEventType(_ context.Context, t eventtype.EventType) error {
|
||||
f.saved = t
|
||||
return f.err
|
||||
}
|
||||
|
||||
func (f *fakeEventTypes) DeleteEventType(context.Context, string) error { return f.err }
|
||||
|
||||
func (f *fakeEventTypes) ListEventTypes(context.Context) ([]eventtype.EventType, error) {
|
||||
return f.list, f.err
|
||||
}
|
||||
|
||||
func remoteEventTypes(t *testing.T, store storecontract.EventTypeStore) *Client {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
RegisterServer(server, Deps{EventTypes: store})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///state",
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return NewClient(conn)
|
||||
}
|
||||
|
||||
func TestEventTypeRoundTrip(t *testing.T) {
|
||||
stamp := time.Date(2026, 9, 24, 9, 0, 0, 0, time.UTC)
|
||||
want := eventtype.EventType{
|
||||
ID: "et-1", Source: "gh", Name: "pull_request",
|
||||
Rule: eventtype.Rule{
|
||||
Headers: []eventtype.HeaderCondition{{Name: "x-github-event", Value: "pull_request"}},
|
||||
Payload: []eventtype.PayloadCondition{{Path: "action", Op: eventtype.OpEquals, Value: "opened"}},
|
||||
},
|
||||
Schema: map[string]eventtype.ValueType{"action": eventtype.TypeString},
|
||||
CreatedAt: stamp, UpdatedAt: stamp.Add(time.Hour),
|
||||
}
|
||||
fake := &fakeEventTypes{list: []eventtype.EventType{want}}
|
||||
c := remoteEventTypes(t, fake)
|
||||
|
||||
got, err := c.ListEventTypes(t.Context())
|
||||
if err != nil || len(got) != 1 || !reflect.DeepEqual(got[0], want) {
|
||||
t.Fatalf("ListEventTypes() = %+v (err %v), want %+v", got, err, want)
|
||||
}
|
||||
id, err := c.InsertEventType(t.Context(), want)
|
||||
if err != nil || id != "et-1" {
|
||||
t.Fatalf("InsertEventType() = %q, %v", id, err)
|
||||
}
|
||||
if !reflect.DeepEqual(fake.saved, want) {
|
||||
t.Fatalf("server received %+v, want %+v", fake.saved, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeErrorsCrossTheWire(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
}{
|
||||
{"overlap", eventtype.ErrOverlap},
|
||||
{"invalid", eventtype.ErrInvalid},
|
||||
{"not found", storecontract.ErrEventTypeNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := remoteEventTypes(t, &fakeEventTypes{err: tt.err})
|
||||
if _, err := c.InsertEventType(t.Context(), eventtype.EventType{}); !errors.Is(err, tt.err) {
|
||||
t.Errorf("InsertEventType error = %v, want %v", err, tt.err)
|
||||
}
|
||||
if err := c.UpdateEventType(t.Context(), eventtype.EventType{}); !errors.Is(err, tt.err) {
|
||||
t.Errorf("UpdateEventType error = %v, want %v", err, tt.err)
|
||||
}
|
||||
if err := c.DeleteEventType(t.Context(), "x"); !errors.Is(err, tt.err) {
|
||||
t.Errorf("DeleteEventType error = %v, want %v", err, tt.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapturedEventCarriesEventType(t *testing.T) {
|
||||
in := storecontract.CapturedEvent{ID: "c", Source: "gh", EventType: "et-1"}
|
||||
if got := capturedEventValue(capturedEventProto(in)); got.EventType != "et-1" {
|
||||
t.Fatalf("EventType after round trip = %q, want et-1", got.EventType)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
var (
|
||||
_ storecontract.EventTypeStore = (*Client)(nil)
|
||||
|
||||
errEventTypeUnavailable = status.Error(codes.Unavailable, "event type store unavailable")
|
||||
)
|
||||
|
||||
func eventTypeProto(t eventtype.EventType) *pb.EventType {
|
||||
out := &pb.EventType{
|
||||
Id: t.ID, Source: t.Source, Name: t.Name,
|
||||
CreatedAt: timestamp(t.CreatedAt), UpdatedAt: timestamp(t.UpdatedAt),
|
||||
}
|
||||
for _, h := range t.Rule.Headers {
|
||||
out.HeaderConditions = append(out.HeaderConditions, &pb.EventTypeHeaderCondition{Name: h.Name, Value: h.Value})
|
||||
}
|
||||
for _, p := range t.Rule.Payload {
|
||||
out.PayloadConditions = append(out.PayloadConditions, &pb.EventTypePayloadCondition{Path: p.Path, Op: string(p.Op), Value: p.Value})
|
||||
}
|
||||
if len(t.Schema) > 0 {
|
||||
out.Schema = make(map[string]string, len(t.Schema))
|
||||
for path, vt := range t.Schema {
|
||||
out.Schema[path] = string(vt)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func eventTypeValue(t *pb.EventType) eventtype.EventType {
|
||||
if t == nil {
|
||||
return eventtype.EventType{}
|
||||
}
|
||||
out := eventtype.EventType{
|
||||
ID: t.Id, Source: t.Source, Name: t.Name,
|
||||
CreatedAt: timeValue(t.CreatedAt), UpdatedAt: timeValue(t.UpdatedAt),
|
||||
}
|
||||
for _, h := range t.HeaderConditions {
|
||||
out.Rule.Headers = append(out.Rule.Headers, eventtype.HeaderCondition{Name: h.Name, Value: h.Value})
|
||||
}
|
||||
for _, p := range t.PayloadConditions {
|
||||
out.Rule.Payload = append(out.Rule.Payload, eventtype.PayloadCondition{Path: p.Path, Op: eventtype.Operator(p.Op), Value: p.Value})
|
||||
}
|
||||
if len(t.Schema) > 0 {
|
||||
out.Schema = make(map[string]eventtype.ValueType, len(t.Schema))
|
||||
for path, vt := range t.Schema {
|
||||
out.Schema[path] = eventtype.ValueType(vt)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Server
|
||||
|
||||
func (s *server) eventTypes() (storecontract.EventTypeStore, error) {
|
||||
if s.deps.EventTypes == nil {
|
||||
return nil, errEventTypeUnavailable
|
||||
}
|
||||
return s.deps.EventTypes, nil
|
||||
}
|
||||
|
||||
func (s *server) InsertEventType(ctx context.Context, r *pb.InsertEventTypeRequest) (*pb.InsertEventTypeResponse, error) {
|
||||
et, err := s.eventTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := et.InsertEventType(ctx, eventTypeValue(r.EventType))
|
||||
if err != nil {
|
||||
return nil, s.logErr("InsertEventType", err)
|
||||
}
|
||||
return &pb.InsertEventTypeResponse{Id: id}, nil
|
||||
}
|
||||
|
||||
func (s *server) UpdateEventType(ctx context.Context, r *pb.UpdateEventTypeRequest) (*pb.UpdateEventTypeResponse, error) {
|
||||
et, err := s.eventTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := et.UpdateEventType(ctx, eventTypeValue(r.EventType)); err != nil {
|
||||
return nil, s.logErr("UpdateEventType", err)
|
||||
}
|
||||
return &pb.UpdateEventTypeResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) DeleteEventType(ctx context.Context, r *pb.DeleteEventTypeRequest) (*pb.DeleteEventTypeResponse, error) {
|
||||
et, err := s.eventTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := et.DeleteEventType(ctx, r.Id); err != nil {
|
||||
return nil, s.logErr("DeleteEventType", err)
|
||||
}
|
||||
return &pb.DeleteEventTypeResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListEventTypes(ctx context.Context, _ *pb.ListEventTypesRequest) (*pb.ListEventTypesResponse, error) {
|
||||
et, err := s.eventTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
types, err := et.ListEventTypes(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ListEventTypes", err)
|
||||
}
|
||||
return &pb.ListEventTypesResponse{EventTypes: mapValues(types, eventTypeProto)}, nil
|
||||
}
|
||||
|
||||
// Client
|
||||
|
||||
func (c *Client) InsertEventType(ctx context.Context, t eventtype.EventType) (string, error) {
|
||||
r, err := c.client.InsertEventType(ctx, &pb.InsertEventTypeRequest{EventType: eventTypeProto(t)})
|
||||
if err != nil {
|
||||
return "", unmapError(err)
|
||||
}
|
||||
return r.Id, nil
|
||||
}
|
||||
|
||||
func (c *Client) UpdateEventType(ctx context.Context, t eventtype.EventType) error {
|
||||
_, err := c.client.UpdateEventType(ctx, &pb.UpdateEventTypeRequest{EventType: eventTypeProto(t)})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteEventType(ctx context.Context, id string) error {
|
||||
_, err := c.client.DeleteEventType(ctx, &pb.DeleteEventTypeRequest{Id: id})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) ListEventTypes(ctx context.Context) ([]eventtype.EventType, error) {
|
||||
r, err := c.client.ListEventTypes(ctx, &pb.ListEventTypesRequest{})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return mapValues(r.EventTypes, eventTypeValue), nil
|
||||
}
|
||||
@@ -76,6 +76,7 @@ type Deps struct {
|
||||
ChannelStatus storecontract.ChannelStatusStore
|
||||
ApplyStatus storecontract.ApplyStatusStore
|
||||
Mappings storecontract.MappingStore
|
||||
EventTypes storecontract.EventTypeStore
|
||||
Bindings storecontract.BindingStore
|
||||
BindingDispatcher storecontract.BindingDispatcher
|
||||
BindingTaskCreator storecontract.BindingTaskCreator
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
@@ -149,7 +150,7 @@ func capturedEventProto(c storecontract.CapturedEvent) *pb.CapturedEvent {
|
||||
return &pb.CapturedEvent{
|
||||
Id: c.ID, ReceivedAt: timestamp(c.ReceivedAt), Source: c.Source,
|
||||
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
|
||||
Body: c.Body, Authenticated: c.Authenticated,
|
||||
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +161,7 @@ func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent {
|
||||
return storecontract.CapturedEvent{
|
||||
ID: c.Id, ReceivedAt: timeValue(c.ReceivedAt), Source: c.Source,
|
||||
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
|
||||
Body: c.Body, Authenticated: c.Authenticated,
|
||||
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,6 +268,9 @@ const (
|
||||
msgStaleTransition = "stale transition"
|
||||
msgBindingNotFound = "binding not found"
|
||||
msgMappingNotFound = "mapping not found"
|
||||
msgEventTypeNotFound = "event type not found"
|
||||
msgEventTypeOverlap = "event type overlap"
|
||||
msgEventTypeInvalid = "event type invalid"
|
||||
msgBindingOverlap = "binding overlap"
|
||||
msgBindingTransition = "binding transition rejected"
|
||||
msgAlreadyDispatched = "already dispatched"
|
||||
@@ -309,6 +313,12 @@ func mapError(err error) error {
|
||||
return status.Error(codes.NotFound, msgBindingNotFound)
|
||||
case errors.Is(err, storecontract.ErrMappingNotFound):
|
||||
return status.Error(codes.NotFound, msgMappingNotFound)
|
||||
case errors.Is(err, storecontract.ErrEventTypeNotFound):
|
||||
return status.Error(codes.NotFound, msgEventTypeNotFound)
|
||||
case errors.Is(err, eventtype.ErrOverlap):
|
||||
return status.Error(codes.FailedPrecondition, msgEventTypeOverlap)
|
||||
case errors.Is(err, eventtype.ErrInvalid):
|
||||
return status.Error(codes.InvalidArgument, msgEventTypeInvalid)
|
||||
case errors.Is(err, storecontract.ErrBindingOverlap):
|
||||
return status.Error(codes.FailedPrecondition, msgBindingOverlap)
|
||||
case errors.Is(err, storecontract.ErrBindingTransition):
|
||||
@@ -364,33 +374,27 @@ func unmapError(err error) error {
|
||||
// are part of the wire contract (§4). A code whose message is not one this
|
||||
// package defines returns nil, so the caller falls back to the wrapped form.
|
||||
func sentinelForStatus(st *status.Status) error {
|
||||
switch st.Code() {
|
||||
case codes.FailedPrecondition:
|
||||
switch st.Message() {
|
||||
case msgStaleTransition:
|
||||
return storecontract.ErrStaleTransition
|
||||
case msgBindingOverlap:
|
||||
return storecontract.ErrBindingOverlap
|
||||
case msgBindingTransition:
|
||||
return storecontract.ErrBindingTransition
|
||||
}
|
||||
case codes.NotFound:
|
||||
switch st.Message() {
|
||||
case msgBindingNotFound:
|
||||
return storecontract.ErrBindingNotFound
|
||||
case msgMappingNotFound:
|
||||
return storecontract.ErrMappingNotFound
|
||||
}
|
||||
case codes.AlreadyExists:
|
||||
if st.Message() == msgAlreadyDispatched {
|
||||
return storecontract.ErrAlreadyDispatched
|
||||
}
|
||||
case codes.Unavailable:
|
||||
if st.Message() == msgTaskLogsUnavailable {
|
||||
return logging.ErrTaskLogsUnavailable
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return wireSentinels[wireStatus{st.Code(), st.Message()}]
|
||||
}
|
||||
|
||||
type wireStatus struct {
|
||||
code codes.Code
|
||||
message string
|
||||
}
|
||||
|
||||
// wireSentinels is the (code, canonical message) to sentinel table
|
||||
// sentinelForStatus reads.
|
||||
var wireSentinels = map[wireStatus]error{
|
||||
{codes.FailedPrecondition, msgStaleTransition}: storecontract.ErrStaleTransition,
|
||||
{codes.FailedPrecondition, msgBindingOverlap}: storecontract.ErrBindingOverlap,
|
||||
{codes.FailedPrecondition, msgBindingTransition}: storecontract.ErrBindingTransition,
|
||||
{codes.FailedPrecondition, msgEventTypeOverlap}: eventtype.ErrOverlap,
|
||||
{codes.InvalidArgument, msgEventTypeInvalid}: eventtype.ErrInvalid,
|
||||
{codes.NotFound, msgBindingNotFound}: storecontract.ErrBindingNotFound,
|
||||
{codes.NotFound, msgMappingNotFound}: storecontract.ErrMappingNotFound,
|
||||
{codes.NotFound, msgEventTypeNotFound}: storecontract.ErrEventTypeNotFound,
|
||||
{codes.AlreadyExists, msgAlreadyDispatched}: storecontract.ErrAlreadyDispatched,
|
||||
{codes.Unavailable, msgTaskLogsUnavailable}: logging.ErrTaskLogsUnavailable,
|
||||
}
|
||||
|
||||
// configSnapshotProto and configSnapshotValue carry the dashboard's
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// proposalScanLimit bounds how many recent captures are grouped into
|
||||
// proposals on one read.
|
||||
const proposalScanLimit = 500
|
||||
|
||||
// eventTypeExample is a pasted (or sampled) event: headers by name and the
|
||||
// raw body. The type's schema is inferred from it.
|
||||
type eventTypeExample struct {
|
||||
Headers map[string]string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// eventTypeRequest is POST /api/event-types. Rule, when absent, is the one
|
||||
// inferred from the example.
|
||||
type eventTypeRequest struct {
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Rule *eventtype.Rule `json:"rule"`
|
||||
Example eventTypeExample `json:"example"`
|
||||
}
|
||||
|
||||
// eventTypeUpdate is PUT /api/event-types/{id}: the name and rule are the
|
||||
// editable parts of a type.
|
||||
type eventTypeUpdate struct {
|
||||
Name string `json:"name"`
|
||||
Rule eventtype.Rule `json:"rule"`
|
||||
}
|
||||
|
||||
// handleEventTypes lists the named event types and the proposals grouped from
|
||||
// recent captures that were unidentified on arrival and still match no type.
|
||||
func (s *Server) handleEventTypes(w http.ResponseWriter, r *http.Request) {
|
||||
if s.EventTypes == nil {
|
||||
writeJSON(w, map[string]any{"enabled": false, "event_types": []any{}, "proposals": []any{}})
|
||||
return
|
||||
}
|
||||
types, err := s.EventTypes.ListEventTypes(r.Context())
|
||||
if err != nil {
|
||||
s.Log.Error("list event types", "err", err)
|
||||
http.Error(w, "list event types failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
proposals := []eventtype.Proposal{}
|
||||
if s.Captures != nil {
|
||||
captures, err := s.Captures.ListCaptures(r.Context(), proposalScanLimit)
|
||||
if err != nil {
|
||||
s.Log.Error("list captures for proposals", "err", err)
|
||||
http.Error(w, "list captures failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
proposals = append(proposals, eventtype.Propose(unmatchedCaptures(types, captures))...)
|
||||
}
|
||||
if types == nil {
|
||||
types = []eventtype.EventType{}
|
||||
}
|
||||
writeJSON(w, map[string]any{"enabled": true, "event_types": types, "proposals": proposals})
|
||||
}
|
||||
|
||||
// unmatchedCaptures keeps the captures that were unidentified on arrival and
|
||||
// that no current type would identify either. A capture a newer type now
|
||||
// matches stays unidentified (it was never dispatched) but is no longer
|
||||
// proposed.
|
||||
func unmatchedCaptures(types []eventtype.EventType, captures []storecontract.CapturedEvent) []eventtype.Capture {
|
||||
var out []eventtype.Capture
|
||||
for _, c := range captures {
|
||||
if c.EventType != "" {
|
||||
continue
|
||||
}
|
||||
sample := eventtype.Sample{Headers: eventtype.ParseHeaders(c.Headers), Body: []byte(c.Body)}
|
||||
if _, ok := eventtype.Identify(types, c.Source, sample); ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, eventtype.Capture{ID: c.ID, Source: c.Source, ReceivedAt: c.ReceivedAt, Sample: sample})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req eventTypeRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
t := eventtype.FromExample(req.Source, req.Name, eventtype.Sample{
|
||||
Headers: req.Example.Headers,
|
||||
Body: []byte(req.Example.Body),
|
||||
})
|
||||
if req.Rule != nil {
|
||||
t.Rule = *req.Rule
|
||||
}
|
||||
id, err := s.EventTypes.InsertEventType(r.Context(), t)
|
||||
if err != nil {
|
||||
s.writeEventTypeError(w, "create", err)
|
||||
return
|
||||
}
|
||||
t.ID = id
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, t)
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req eventTypeUpdate
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Source is not editable: the store validates against the stored one.
|
||||
t := eventtype.EventType{ID: r.PathValue("id"), Name: req.Name, Rule: req.Rule}
|
||||
if err := s.EventTypes.UpdateEventType(r.Context(), t); err != nil {
|
||||
s.writeEventTypeError(w, "update", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]string{"id": t.ID})
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err := s.EventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
|
||||
s.writeEventTypeError(w, "delete", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) writeEventTypeError(w http.ResponseWriter, action string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, eventtype.ErrOverlap):
|
||||
http.Error(w, "this rule can match events another type on the source already matches", http.StatusConflict)
|
||||
case errors.Is(err, eventtype.ErrInvalid):
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
case errors.Is(err, storecontract.ErrEventTypeNotFound):
|
||||
http.Error(w, "event type not found", http.StatusNotFound)
|
||||
default:
|
||||
s.Log.Error(action+" event type", "err", err)
|
||||
http.Error(w, action+" event type failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type memCaptures struct{ list []storecontract.CapturedEvent }
|
||||
|
||||
func (m *memCaptures) InsertCapture(_ context.Context, c storecontract.CapturedEvent, _ time.Duration, _ int) (string, error) {
|
||||
m.list = append(m.list, c)
|
||||
return c.ID, nil
|
||||
}
|
||||
|
||||
func (m *memCaptures) ListCaptures(context.Context, int) ([]storecontract.CapturedEvent, error) {
|
||||
return m.list, nil
|
||||
}
|
||||
|
||||
// memEventTypes applies the domain's validation and overlap refusal, as the
|
||||
// real store does.
|
||||
type memEventTypes struct{ types []eventtype.EventType }
|
||||
|
||||
func (m *memEventTypes) InsertEventType(_ context.Context, t eventtype.EventType) (string, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := eventtype.CheckOverlap(m.types, t); err != nil {
|
||||
return "", err
|
||||
}
|
||||
t.ID = "et-" + t.Name
|
||||
m.types = append(m.types, t)
|
||||
return t.ID, nil
|
||||
}
|
||||
|
||||
func (m *memEventTypes) UpdateEventType(_ context.Context, t eventtype.EventType) error {
|
||||
for i, existing := range m.types {
|
||||
if existing.ID == t.ID {
|
||||
t.Source, t.Schema = existing.Source, existing.Schema
|
||||
if err := eventtype.CheckOverlap(m.types, t); err != nil {
|
||||
return err
|
||||
}
|
||||
m.types[i] = t
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
|
||||
func (m *memEventTypes) DeleteEventType(_ context.Context, id string) error {
|
||||
for i, existing := range m.types {
|
||||
if existing.ID == id {
|
||||
m.types = append(m.types[:i], m.types[i+1:]...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
|
||||
func (m *memEventTypes) ListEventTypes(context.Context) ([]eventtype.EventType, error) {
|
||||
return m.types, nil
|
||||
}
|
||||
|
||||
func eventTypeServer(captures ...storecontract.CapturedEvent) (*Server, *memEventTypes) {
|
||||
types := &memEventTypes{}
|
||||
return &Server{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Captures: &memCaptures{list: captures},
|
||||
EventTypes: types,
|
||||
}, types
|
||||
}
|
||||
|
||||
func serve(t *testing.T, srv *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), method, path, strings.NewReader(body))
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
type eventTypesView struct {
|
||||
EventTypes []eventtype.EventType `json:"event_types"`
|
||||
Proposals []eventtype.Proposal `json:"proposals"`
|
||||
}
|
||||
|
||||
func listEventTypes(t *testing.T, srv *Server) eventTypesView {
|
||||
t.Helper()
|
||||
w := serve(t, srv, http.MethodGet, "/api/event-types", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d; body %s", w.Code, w.Body.String())
|
||||
}
|
||||
var v eventTypesView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func ghCapture(id, event, body string) storecontract.CapturedEvent {
|
||||
return storecontract.CapturedEvent{ID: id, Source: "gh", Headers: `{"X-Github-Event":["` + event + `"]}`, Body: body}
|
||||
}
|
||||
|
||||
// Two GitHub events with different X-GitHub-Event headers are two proposals,
|
||||
// and a firewall payload is a third.
|
||||
func TestEventTypesProposesGroupsFromUnidentifiedCaptures(t *testing.T) {
|
||||
srv, _ := eventTypeServer(
|
||||
ghCapture("c1", "push", `{"ref":"a"}`),
|
||||
ghCapture("c2", "pull_request", `{"action":"opened"}`),
|
||||
storecontract.CapturedEvent{ID: "f1", Source: "fw", Body: `{"src":"1.1.1.1"}`},
|
||||
// Already identified on arrival: not a proposal.
|
||||
func() storecontract.CapturedEvent {
|
||||
c := ghCapture("c3", "issues", `{}`)
|
||||
c.EventType = "et-x"
|
||||
return c
|
||||
}(),
|
||||
)
|
||||
v := listEventTypes(t, srv)
|
||||
var samples []string
|
||||
for _, p := range v.Proposals {
|
||||
samples = append(samples, p.SampleID)
|
||||
}
|
||||
if strings.Join(samples, ",") != "f1,c1,c2" {
|
||||
t.Fatalf("proposal samples = %v, want f1,c1,c2", samples)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeCreateFromProposalRemovesIt(t *testing.T) {
|
||||
srv, types := eventTypeServer(ghCapture("c1", "push", `{"ref":"a"}`), ghCapture("c2", "pull_request", `{"action":"opened"}`))
|
||||
w := serve(t, srv, http.MethodPost, "/api/event-types", `{
|
||||
"source":"gh","name":"push",
|
||||
"rule":{"headers":[{"name":"x-github-event","value":"push"}]},
|
||||
"example":{"headers":{"x-github-event":"push"},"body":"{\"ref\":\"a\"}"}}`)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("POST status = %d; body %s", w.Code, w.Body.String())
|
||||
}
|
||||
if got := types.types[0].Schema["ref"]; got != eventtype.TypeString {
|
||||
t.Fatalf("schema[ref] = %q, want string", got)
|
||||
}
|
||||
v := listEventTypes(t, srv)
|
||||
if len(v.EventTypes) != 1 || len(v.Proposals) != 1 || v.Proposals[0].SampleID != "c2" {
|
||||
t.Fatalf("after naming push: types %d, proposals %+v", len(v.EventTypes), v.Proposals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeWriteStatuses(t *testing.T) {
|
||||
srv, _ := eventTypeServer()
|
||||
pasted := `{"source":"gh","name":"%s","example":{"headers":{"X-GitHub-Event":"push"},"body":"{}"}}`
|
||||
tests := []struct {
|
||||
name, method, path, body string
|
||||
want int
|
||||
}{
|
||||
{"create from pasted payload", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "push", 1), http.StatusCreated},
|
||||
{"overlapping type is refused", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "push2", 1), http.StatusConflict},
|
||||
{"nameless type is refused", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "", 1), http.StatusBadRequest},
|
||||
{"bad json", http.MethodPost, "/api/event-types", `{`, http.StatusBadRequest},
|
||||
{"rename", http.MethodPut, "/api/event-types/et-push", `{"name":"pushed","rule":{"headers":[{"name":"X-GitHub-Event","value":"push"}]}}`, http.StatusOK},
|
||||
{"update missing", http.MethodPut, "/api/event-types/nope", `{"name":"x","rule":{}}`, http.StatusNotFound},
|
||||
{"delete", http.MethodDelete, "/api/event-types/et-push", ``, http.StatusNoContent},
|
||||
{"delete missing", http.MethodDelete, "/api/event-types/et-push", ``, http.StatusNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if w := serve(t, srv, tt.method, tt.path, tt.body); w.Code != tt.want {
|
||||
t.Fatalf("status = %d, want %d; body %s", w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypesDisabledWithoutStore(t *testing.T) {
|
||||
srv := &Server{Log: slog.New(slog.DiscardHandler)}
|
||||
w := serve(t, srv, http.MethodGet, "/api/event-types", "")
|
||||
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"enabled":false`) {
|
||||
t.Fatalf("GET without store = %d %s, want 200 with enabled false", w.Code, w.Body.String())
|
||||
}
|
||||
if w := serve(t, srv, http.MethodPost, "/api/event-types", `{}`); w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("POST without store = %d, want 503", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -146,6 +146,10 @@ type Server struct {
|
||||
// the dashboard failing to start.
|
||||
Mappings storecontract.MappingStore
|
||||
|
||||
// EventTypes persists event types (docs/prds/event-automation.md). Optional:
|
||||
// nil reports the inspector's event types as disabled.
|
||||
EventTypes storecontract.EventTypeStore
|
||||
|
||||
// Bindings persists playbook bindings: matcher + mapping + workflow
|
||||
// triples that turn a captured webhook into an archie task
|
||||
// (docs/prds/webhook-intake-security.md). Optional: nil makes every
|
||||
@@ -254,6 +258,10 @@ func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
|
||||
func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/event-types", s.handleEventTypes)
|
||||
mux.HandleFunc("POST /api/event-types", s.handleEventTypeCreate)
|
||||
mux.HandleFunc("PUT /api/event-types/{id}", s.handleEventTypeUpdate)
|
||||
mux.HandleFunc("DELETE /api/event-types/{id}", s.handleEventTypeDelete)
|
||||
mux.HandleFunc("GET /api/mappings", s.handleMappingsList)
|
||||
mux.HandleFunc("POST /api/mappings", s.handleMappingCreate)
|
||||
mux.HandleFunc("GET /api/mappings/{id}", s.handleMappingGet)
|
||||
|
||||
@@ -120,6 +120,13 @@ service StateStoreService {
|
||||
rpc UpdateMapping(UpdateMappingRequest) returns (UpdateMappingResponse);
|
||||
rpc DeleteMapping(DeleteMappingRequest) returns (DeleteMappingResponse);
|
||||
|
||||
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
|
||||
// Update refuse an overlapping or malformed type.
|
||||
rpc InsertEventType(InsertEventTypeRequest) returns (InsertEventTypeResponse);
|
||||
rpc UpdateEventType(UpdateEventTypeRequest) returns (UpdateEventTypeResponse);
|
||||
rpc DeleteEventType(DeleteEventTypeRequest) returns (DeleteEventTypeResponse);
|
||||
rpc ListEventTypes(ListEventTypesRequest) returns (ListEventTypesResponse);
|
||||
|
||||
// Binding
|
||||
rpc InsertBinding(InsertBindingRequest) returns (InsertBindingResponse);
|
||||
rpc GetBinding(GetBindingRequest) returns (GetBindingResponse);
|
||||
@@ -308,6 +315,35 @@ message CapturedEvent {
|
||||
string headers = 6;
|
||||
string body = 7;
|
||||
bool authenticated = 8;
|
||||
// event_type is the ID of the event type the capture was identified as on
|
||||
// arrival; empty is unidentified.
|
||||
string event_type = 9;
|
||||
}
|
||||
|
||||
// EventTypeHeaderCondition mirrors internal/domain/eventtype.HeaderCondition.
|
||||
message EventTypeHeaderCondition {
|
||||
string name = 1;
|
||||
string value = 2;
|
||||
}
|
||||
|
||||
// EventTypePayloadCondition mirrors internal/domain/eventtype.PayloadCondition.
|
||||
message EventTypePayloadCondition {
|
||||
string path = 1;
|
||||
string op = 2;
|
||||
string value = 3;
|
||||
}
|
||||
|
||||
// EventType mirrors internal/domain/eventtype.EventType. header_conditions and
|
||||
// payload_conditions are its rule; schema maps each payload path to its type.
|
||||
message EventType {
|
||||
string id = 1;
|
||||
string source = 2;
|
||||
string name = 3;
|
||||
repeated EventTypeHeaderCondition header_conditions = 4;
|
||||
repeated EventTypePayloadCondition payload_conditions = 5;
|
||||
map<string, string> schema = 6;
|
||||
google.protobuf.Timestamp created_at = 7;
|
||||
google.protobuf.Timestamp updated_at = 8;
|
||||
}
|
||||
|
||||
// MappingField mirrors internal/domain/mapping.Field.
|
||||
@@ -688,6 +724,18 @@ message UpdateMappingResponse {}
|
||||
message DeleteMappingRequest { string id = 1; }
|
||||
message DeleteMappingResponse {}
|
||||
|
||||
message InsertEventTypeRequest { EventType event_type = 1; }
|
||||
message InsertEventTypeResponse { string id = 1; }
|
||||
|
||||
message UpdateEventTypeRequest { EventType event_type = 1; }
|
||||
message UpdateEventTypeResponse {}
|
||||
|
||||
message DeleteEventTypeRequest { string id = 1; }
|
||||
message DeleteEventTypeResponse {}
|
||||
|
||||
message ListEventTypesRequest {}
|
||||
message ListEventTypesResponse { repeated EventType event_types = 1; }
|
||||
|
||||
message InsertBindingRequest { Binding binding = 1; }
|
||||
message InsertBindingResponse { string id = 1; }
|
||||
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
.identities-page[data-v-8ab739de]{max-width:960px}.identity-create[data-v-8ab739de]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-8ab739de]{flex:1}.identity-create input[data-v-8ab739de],.identity-create select[data-v-8ab739de],.identity-create button[data-v-8ab739de],.actions button[data-v-8ab739de]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-8ab739de]{border-top:1px solid var(--border)}.identity-row[data-v-8ab739de]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-8ab739de]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-8ab739de]{gap:.5rem;display:flex}.actions .danger[data-v-8ab739de],.error[data-v-8ab739de]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer theme{:root,:host{--font-sans:"Geist Variable", sans-serif;--color-black:#000;--spacing:.25rem;--container-xs:20rem;--container-sm:24remLine truncated
|
||||
.identities-page[data-v-8ab739de]{max-width:960px}.identity-create[data-v-8ab739de]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-8ab739de]{flex:1}.identity-create input[data-v-8ab739de],.identity-create select[data-v-8ab739de],.identity-create button[data-v-8ab739de],.actions button[data-v-8ab739de]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-8ab739de]{border-top:1px solid var(--border)}.identity-row[data-v-8ab739de]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-8ab739de]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-8ab739de]{gap:.5rem;display:flex}.actions .danger[data-v-8ab739de],.error[data-v-8ab739de]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer thLine truncated
|
||||
Vendored
+13
-12
@@ -1,19 +1,20 @@
|
||||
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=window.location.hash;if(n.startsWith(`#/`)){let e=n.slice(1);window.history.replaceState(null,``,e+window.location.search)}function r(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var i={},a=[],o=()=>{},s=()=>!1,c=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),l=e=>e.startsWith(`onUpdate:`),u=Object.assign,d=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},f=Object.prototype.hasOwnProperty,p=(e,t)=>f.call(e,t),m=Array.isArray,h=e=>T(e)===`[object Map]`,g=e=>T(e)===`[object Set]`,_=e=>T(e)===`[object Date]`,v=e=>T(e)===`[object RegExp]`,y=e=>typeof e==`function`,b=e=>typeof e==`string`,x=e=>typeof e==`symbol`,S=e=>typeof e==`object`&&!!e,C=e=>(S(e)||y(e))&&y(e.then)&&y(e.catch),w=Object.prototype.toString,T=e=>w.call(e),ee=e=>T(e).slice(8,-1),te=e=>T(e)===`[object Object]`,ne=e=>b(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,re=r(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),ie=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},ae=/-\w/g,oe=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),se=/\B([A-Z])/g,ce=ie(e=>e.replace(se,`-$1`).toLowerCase()),le=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),E=ie(e=>e?`on${le(e)}`:``),ue=(e,t)=>!Object.is(e,t),de=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},fe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},pe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},me=e=>{let t=b(e)?Number(e):NaN;return isNaN(t)?e:t},he,ge=()=>he||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},_e=r(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function ve(e){if(m(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=b(r)?Se(r):ve(r);if(i)for(let e in i)t[e]=i[e]}return t}if(b(e)||S(e))return e}var ye=/;(?![^(]*\))/g,be=/:([^]+)/,xe=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Se(e){let t={};return e.replace(xe,e=>e.startsWith(`/*`)?``:e).split(ye).forEach(e=>{if(e){let n=e.split(be);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function D(e){let t=``;if(b(e))t=e;else if(m(e))for(let n=0;n<e.length;n++){let r=D(e[n]);r&&(t+=r+` `)}else if(S(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function Ce(e){if(!e)return null;let{class:t,style:n}=e;return t&&!b(t)&&(e.class=D(t)),n&&(e.style=ve(n)),e}var we=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,Te=r(we);we+``;function Ee(e){return!!e||e===``}function De(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=je(e[i],t[i],n);return r}function Oe(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&je(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function ke(e,t,n){let r=h(e),i=h(t);if(r||i||(r=g(e),i=g(t),r||i))return r&&i?Oe(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=e.hasOwnProperty(r),a=t.hasOwnProperty(r);if(i&&!a||!i&&a||!je(e[r],t[r],n))return!1}return String(e)===String(t)}function Ae(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function je(e,t,n){if(e===t)return!0;let r=_(e),i=_(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=x(e),i=x(t),r||i?e===t:(r=m(e),i=m(t),r||i?r&&i?Ae(e,t,n,De):!1:(r=S(e),i=S(t),r||i?!r||!i?!1:Ae(e,t,n,ke):String(e)===String(t))))}function Me(e,t){return e.findIndex(e=>je(e,t))}var Ne=e=>!!(e&&e.__v_isRef===!0),O=e=>b(e)?e:e==null?``:m(e)||S(e)&&(e.toString===w||!y(e.toString))?Ne(e)?O(e.value):JSON.stringify(e,Pe,2):String(e),Pe=(e,t)=>Ne(t)?Pe(e,t.value):h(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Fe(t,r)+` =>`]=n,e),{})}:g(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Fe(e))}:x(t)?FLine truncated
|
||||
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=window.location.hash;if(n.startsWith(`#/`)){let e=n.slice(1);window.history.replaceState(null,``,e+window.location.search)}function r(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var i={},a=[],o=()=>{},s=()=>!1,c=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),l=e=>e.startsWith(`onUpdate:`),u=Object.assign,d=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},f=Object.prototype.hasOwnProperty,p=(e,t)=>f.call(e,t),m=Array.isArray,h=e=>ee(e)===`[object Map]`,g=e=>ee(e)===`[object Set]`,_=e=>ee(e)===`[object Date]`,v=e=>ee(e)===`[object RegExp]`,y=e=>typeof e==`function`,b=e=>typeof e==`string`,x=e=>typeof e==`symbol`,S=e=>typeof e==`object`&&!!e,C=e=>(S(e)||y(e))&&y(e.then)&&y(e.catch),w=Object.prototype.toString,ee=e=>w.call(e),te=e=>ee(e).slice(8,-1),ne=e=>ee(e)===`[object Object]`,re=e=>b(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ie=r(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),ae=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},oe=/-\w/g,se=ae(e=>e.replace(oe,e=>e.slice(1).toUpperCase())),ce=/\B([A-Z])/g,le=ae(e=>e.replace(ce,`-$1`).toLowerCase()),ue=ae(e=>e.charAt(0).toUpperCase()+e.slice(1)),T=ae(e=>e?`on${ue(e)}`:``),de=(e,t)=>!Object.is(e,t),fe=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},pe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},me=e=>{let t=parseFloat(e);return isNaN(t)?e:t},he=e=>{let t=b(e)?Number(e):NaN;return isNaN(t)?e:t},ge,_e=()=>ge||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},ve=r(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function ye(e){if(m(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=b(r)?Ce(r):ye(r);if(i)for(let e in i)t[e]=i[e]}return t}if(b(e)||S(e))return e}var be=/;(?![^(]*\))/g,xe=/:([^]+)/,Se=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Ce(e){let t={};return e.replace(Se,e=>e.startsWith(`/*`)?``:e).split(be).forEach(e=>{if(e){let n=e.split(xe);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function E(e){let t=``;if(b(e))t=e;else if(m(e))for(let n=0;n<e.length;n++){let r=E(e[n]);r&&(t+=r+` `)}else if(S(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function we(e){if(!e)return null;let{class:t,style:n}=e;return t&&!b(t)&&(e.class=E(t)),n&&(e.style=ye(n)),e}var Te=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,Ee=r(Te);Te+``;function De(e){return!!e||e===``}function Oe(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=Me(e[i],t[i],n);return r}function ke(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&Me(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function Ae(e,t,n){let r=h(e),i=h(t);if(r||i||(r=g(e),i=g(t),r||i))return r&&i?ke(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=e.hasOwnProperty(r),a=t.hasOwnProperty(r);if(i&&!a||!i&&a||!Me(e[r],t[r],n))return!1}return String(e)===String(t)}function je(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function Me(e,t,n){if(e===t)return!0;let r=_(e),i=_(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=x(e),i=x(t),r||i?e===t:(r=m(e),i=m(t),r||i?r&&i?je(e,t,n,Oe):!1:(r=S(e),i=S(t),r||i?!r||!i?!1:je(e,t,n,Ae):String(e)===String(t))))}function Ne(e,t){return e.findIndex(e=>Me(e,t))}var Pe=e=>!!(e&&e.__v_isRef===!0),D=e=>b(e)?e:e==null?``:m(e)||S(e)&&(e.toString===w||!y(e.toString))?Pe(e)?D(e.value):JSON.stringify(e,Fe,2):String(e),Fe=(e,t)=>Pe(t)?Fe(e,t.value):h(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Ie(t,r)+` =>`]=n,e),{})}:g(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Ie(e))}Line truncated
|
||||
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
|
||||
`)&&(ki(e,0)||yi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||c(a)&&!re(a)||a[0]===`.`||t&&!re(a)||u&&u.includes(a)){if(Ei(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&cn(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ns(x,n,t),h&&wr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&ls(()=>{x&&Ns(x,n,t),l&&g.enter(e),h&&wr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=As(d[t]),g=h.type===fs;e?(g&&!u&&t+1<p&&As(d[t+1]).type===fs&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,ki(r,1)||yi()),n(null,h,r,null,o,s,Si(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&Ci(f)&&f.data===`]`?a(t.anchor=f):(yi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,c,l)=>{if(ji(e,t)||yi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)s(n);else break}}let u=a(e),d=o(e);return s(e),n(null,t,d,u,r,i,Si(d),c),r&&(r.vnode.el=t.el,So(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&Ci(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ti=new Set([`src`,`srcset`,`href`,`poster`]);function Ei(e,t,n){return Ti.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Di=`data-allow-mismatch`,Oi={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function ki(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Di);)e=e.parentElement;return Ai(e&&e.getAttribute(Di),t)}function Ai(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(Oi[t])}}function ji(e,t){return ki(e.parentElement,1)||Mi(e)||Ni(t)}function Mi(e){return e.nodeType===1&&Ai(e.getAttribute(Di),1)}function Ni({props:e}){let t=e&&e[Di];return typeof t==`string`&&Ai(t,1)}var Pi=ge().requestIdleCallback||(e=>setTimeout(e,1)),Fi=ge().cancelIdleCallback||(e=>clearTimeout(e)),Ii=(e=1e4)=>t=>{let n=Pi(t,{timeout:e});return()=>Fi(n)};function Li(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var Ri=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(Li(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},zi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Bi=(e=[])=>(t,n)=>{b(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Vi(e,t){if(Ci(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(Ci(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Hi=e=>!!e.type.__asyncLoader;function Ui(e){y(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return N({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Vi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Ls;if(fi(e),u)return()=>Wi(u,e);let t=t=>{l=null,Xn(t,e,13,!r)};if(s&&e.suspense||Ws)return p().then(t=>()=>Wi(t,e)).catch(e=>(t(e),()=>r?V(r,{error:e}):null));let a=k(!1),c=k(),d=k(!!i),f,m;return sa(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Gi(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Wi(u,e);if(c.value&&r)return V(r,{error:c.value});if(n&&
Line truncated
|
||||
`))),e[Gl]=Hl(i);let a=r||i.props&&i.props.type===`number`;ll(e,t?`change`:`input`,t=>{t.target.composing||e[Gl](ql(e.value,n,a))}),(n||a)&&ll(e,`change`,()=>{e.value=ql(e.value,n,a)}),t||(ll(e,`compositionstart`,Ul),ll(e,`compositionend`,Wl),ll(e,`change`,Wl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[Kl];delete e[Kl],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Gl](ql(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Gl]=Hl(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?pe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Yl={deep:!0,created(e,t,n){e[Gl]=Hl(n),ll(e,`change`,()=>{let t=e._modelValue,n=tu(e),r=e.checked,i=e[Gl];if(m(t)){let e=Me(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(g(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(nu(e,r))})},mounted:Xl,beforeUpdate(e,t,n){e[Gl]=Hl(n),Xl(e,t,n)}};function Xl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Me(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=je(t,nu(e,!0))}e.checked!==i&&(e.checked=i)}var Zl={created(e,{value:t},n){e.checked=je(t,n.props.value),e[Gl]=Hl(n),ll(e,`change`,()=>{e[Gl](tu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Gl]=Hl(r),t!==n&&(e.checked=je(t,r.props.value))}},Ql={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ll(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?pe(tu(e)):tu(e)),r=e.multiple,i=r?g(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?m(i)?t.slice():t:i];try{e[Gl](i)}finally{ar(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Gl]=Hl(r)},mounted(e,{value:t}){eu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Gl]=Hl(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!$l(t,n[1],n[0]))&&eu(e,t)}};function $l(e,t,n){if(!n||m(e))return je(e,t);if(g(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function eu(e,t){let n=e.multiple,r=m(t);if(!n||r||g(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=tu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Me(t,o)>-1}else a.selected=t.has(o)}else if(je(tu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function tu(e){return`_value`in e?e._value:e.value}function nu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var ru={created(e,t,n){au(e,t,n,null,`created`)},mounted(e,t,n){au(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){au(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){au(e,t,n,r,`updated`)}};function iu(e,t){switch(e){case`SELECT`:return Ql;case`TEXTAREA`:return Jl;default:switch(t){case`checkbox`:return Yl;case`radio`:return Zl;default:return Jl}}}function au(e,t,n,r,i){let a=iu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function ou(){Jl.getSSRProps=({value:e})=>({value:e}),Zl.getSSRProps=({value:e},t)=>{if(t.props&&je(t.props.value,e))return{checked:!0}},Yl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Me(e,t.props.value)>-1)return{checked:!0}}else if(g(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},ru.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=iu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var su=[`ctrl`,`shift`,`alt`,`meta`],cu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>su.some(n=>e[`${n}Key`]&&!t.includes(n))},lu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=cu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},uu={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},du=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=ce(n.key);if(t.some(e=>e===r||uu[e]===r))return e(n)}))},fu=u({patchProp:xl},xc),pu,mu=!1;function hu(){return pu||=Ho(fu)}function gu(){return pu=mu?pu:Uo(fu),mu=!0,pu}var _u=((...e)=>{hu().render(...e)}),vu=((...e)=>{gu().hydrate(...e)}),yu=((...e)=>{let t=hu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Su(e);if(!r)return;let i=t._component;!y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,xu(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),bu=((
Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var kp;function Ap(e){kp=e}var jp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Mp(e){let t=e instanceof jp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Np(e,t){let n=await fetch(e,t);if(kp?.(n.status===401),!n.ok)throw new jp(await Op(n),n.status);return n}async function Pp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Ep,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Np(e,s);return a?await c.json():void 0}var Y={health:()=>Pp(`/health/detailed`),summary:()=>Pp(`/api/summary`),tasks:()=>Pp(`/api/tasks`),taskMeta:()=>Pp(`/api/task-meta`),task:e=>Pp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Pp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/changes`+Dp(t)),taskDebug:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/debug`+Dp(t)),taskAction:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Pp(`/api/setup`),capabilities:()=>Pp(`/api/capabilities`),workflows:()=>Pp(`/api/workflows`),workRequest:e=>Pp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Pp(`/api/skills`),channels:()=>Pp(`/api/channels`),curators:()=>Pp(`/api/curators`),channelReload:e=>Pp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Pp(`/api/config`),logs:e=>Pp(`/api/logs`+Dp(e)),taskLogs:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/logs`+Dp(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Pp(`/api/version`),updateSnapshot:()=>Pp(`/api/chat/update`),updateInstall:e=>Pp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Pp(`/api/captures`+Dp({limit:e})),mappings:()=>Pp(`/api/mappings`),mappingCreate:e=>Pp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Pp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Pp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Pp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Pp(`/api/bindings`),bindingCreate:e=>Pp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Pp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Pp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Pp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),chatSessions:()=>Pp(`/api/chat/sessions`),chatMessages:e=>Pp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Pp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Pp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Pp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Tp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Pp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Pp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Pp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Pp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Np(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Fp(e,t){let n=new EventSource(`/api/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Ip(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(wp(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Lp=`archie.web.chat.channel`;function Rp(){let e=localStorage.getItem(Lp);return e||(e=Tp(),localStorage.setItem(Lp,e)),e}var zp=/(?:^|\s)\/([^\s]*)$/,Bp=/(?:^|\s)\/[^\s]*$/,Vp=8;function Hp(e,t,n){let r=t.slice(0,n).match(zp);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,Vp)}function Up(e,t,n){let r=e.slice(0,t),i=e.slice(t),a=r.search(Bp),o=a<0?r.length:a+ +(r[a]===` `);return{text:`${r.slice(0,o)}${n} ${i}`,cursor:o+n.length+1}}function Wp(e,t){let n=t.trim();return e.some(e=>e.command===n)}function Gp(e){return{text:e,sourceID:Tp()}}function Kp(e){return{...e}}function qp(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.tri
Line truncated
|
||||
`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||c(a)&&!ie(a)||a[0]===`.`||t&&!ie(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ps(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&us(()=>{x&&Ps(x,n,t),l&&g.enter(e),h&&Tr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=js(d[t]),g=h.type===ps;e?(g&&!u&&t+1<p&&js(d[t+1]).type===ps&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,Ai(r,1)||bi()),n(null,h,r,null,o,s,Ci(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,c,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)s(n);else break}}let u=a(e),d=o(e);return s(e),n(null,t,d,u,r,i,Ci(d),c),r&&(r.vnode.el=t.el,Co(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=_e().requestIdleCallback||(e=>setTimeout(e,1)),Ii=_e().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var zi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(Ri(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{b(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){y(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return M({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Rs;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Zn(t,e,13,!r)};if(s&&e.suspense||Gs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?B(r,{error:e}):null));let a=O(!1),c=O(),d=O(!!i),f,m;return ca(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Ki(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Gi(u,e);if(c.value&&r)return B(r,{error:c.value});if(n&&
Line truncated
|
||||
`))),e[Kl]=Ul(i);let a=r||i.props&&i.props.type===`number`;ul(e,t?`change`:`input`,t=>{t.target.composing||e[Kl](Jl(e.value,n,a))}),(n||a)&&ul(e,`change`,()=>{e.value=Jl(e.value,n,a)}),t||(ul(e,`compositionstart`,Wl),ul(e,`compositionend`,Gl),ul(e,`change`,Gl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[ql];delete e[ql],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Kl](Jl(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Kl]=Ul(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?me(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Xl={deep:!0,created(e,t,n){e[Kl]=Ul(n),ul(e,`change`,()=>{let t=e._modelValue,n=nu(e),r=e.checked,i=e[Kl];if(m(t)){let e=Ne(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(g(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(ru(e,r))})},mounted:Zl,beforeUpdate(e,t,n){e[Kl]=Ul(n),Zl(e,t,n)}};function Zl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Ne(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=Me(t,ru(e,!0))}e.checked!==i&&(e.checked=i)}var Ql={created(e,{value:t},n){e.checked=Me(t,n.props.value),e[Kl]=Ul(n),ul(e,`change`,()=>{e[Kl](nu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Kl]=Ul(r),t!==n&&(e.checked=Me(t,r.props.value))}},$l={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ul(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?me(nu(e)):nu(e)),r=e.multiple,i=r?g(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?m(i)?t.slice():t:i];try{e[Kl](i)}finally{or(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Kl]=Ul(r)},mounted(e,{value:t}){tu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Kl]=Ul(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!eu(t,n[1],n[0]))&&tu(e,t)}};function eu(e,t,n){if(!n||m(e))return Me(e,t);if(g(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function tu(e,t){let n=e.multiple,r=m(t);if(!n||r||g(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=nu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Ne(t,o)>-1}else a.selected=t.has(o)}else if(Me(nu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function nu(e){return`_value`in e?e._value:e.value}function ru(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var iu={created(e,t,n){ou(e,t,n,null,`created`)},mounted(e,t,n){ou(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){ou(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){ou(e,t,n,r,`updated`)}};function au(e,t){switch(e){case`SELECT`:return $l;case`TEXTAREA`:return Yl;default:switch(t){case`checkbox`:return Xl;case`radio`:return Ql;default:return Yl}}}function ou(e,t,n,r,i){let a=au(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function su(){Yl.getSSRProps=({value:e})=>({value:e}),Ql.getSSRProps=({value:e},t)=>{if(t.props&&Me(t.props.value,e))return{checked:!0}},Xl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Ne(e,t.props.value)>-1)return{checked:!0}}else if(g(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},iu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=au(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var cu=[`ctrl`,`shift`,`alt`,`meta`],lu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>cu.some(n=>e[`${n}Key`]&&!t.includes(n))},uu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=lu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},du={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},fu=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=le(n.key);if(t.some(e=>e===r||du[e]===r))return e(n)}))},pu=u({patchProp:Sl},Sc),mu,hu=!1;function gu(){return mu||=Uo(pu)}function _u(){return mu=hu?mu:Wo(pu),hu=!0,mu}var vu=((...e)=>{gu().render(...e)}),yu=((...e)=>{_u().hydrate(...e)}),bu=((...e)=>{let t=gu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Cu(e);if(!r)return;let i=t._component;!y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,Su(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),xu=((
Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Mp;function Np(e){Mp=e}var Pp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Fp(e){let t=e instanceof Pp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ip(e,t){let n=await fetch(e,t);if(Mp?.(n.status===401),!n.ok)throw new Pp(await jp(n),n.status);return n}async function Lp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=kp,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Ip(e,s);return a?await c.json():void 0}var J={health:()=>Lp(`/health/detailed`),summary:()=>Lp(`/api/summary`),tasks:()=>Lp(`/api/tasks`),taskMeta:()=>Lp(`/api/task-meta`),task:e=>Lp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Lp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/changes`+Ap(t)),taskDebug:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/debug`+Ap(t)),taskAction:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Lp(`/api/setup`),capabilities:()=>Lp(`/api/capabilities`),workflows:()=>Lp(`/api/workflows`),workRequest:e=>Lp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Lp(`/api/skills`),channels:()=>Lp(`/api/channels`),curators:()=>Lp(`/api/curators`),channelReload:e=>Lp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Lp(`/api/config`),logs:e=>Lp(`/api/logs`+Ap(e)),taskLogs:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/logs`+Ap(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Lp(`/api/version`),updateSnapshot:()=>Lp(`/api/chat/update`),updateInstall:e=>Lp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Lp(`/api/captures`+Ap({limit:e})),eventTypes:()=>Lp(`/api/event-types`),eventTypeCreate:e=>Lp(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>Lp(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>Lp(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>Lp(`/api/mappings`),mappingCreate:e=>Lp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Lp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Lp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Lp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Lp(`/api/bindings`),bindingCreate:e=>Lp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Lp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Lp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Lp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),chatSessions:()=>Lp(`/api/chat/sessions`),chatMessages:e=>Lp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Lp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Lp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Lp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Op(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Lp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Lp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Lp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Lp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Ip(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Rp(e,t){let n=new EventSource(`/api/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function zp(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Dp(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Bp=`archie.web.chat.channel`;function Vp(){let e=localStorage.getItem(Bp);return e||(e=Op(),localStorage.setItem(Bp,e)),e}var Hp=/(?:^|\s)\/([^\s]*)$/,Up=/(?:^|\s)\/[^\s]*$/,Wp=8;function Gp(e,t,n){let r=t.slice(0,n).match(Hp);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,Wp)}function Kp(e,t,n){let r=e.slice(0,t),i=e.slice(t),a=r.search(Up),o=a<0?r.length:a+ +(r[a]===` `);return{text:`$Line truncated
|
||||
|
||||
`);u=r.pop()||``;for(let e of r){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(Zp.value=n.session_id),n.type===`delta`&&(o+=n.text,nm.value=nm.value?{...nm.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],nm.value=nm.value?{...nm.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);Qp.value=[...Qp.value,{from:`assistant`,text:o,tool_calls:a}],nm.value=null,em.value=`Ready`,await _m()}catch(e){let t=e;t.name===`AbortError`&&!c?(nm.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},em.value=`Stopped`):(nm.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Kp(r):void 0,isRetry:i},em.value=`Error — retry available`)}finally{clearTimeout(l),hm=null,tm.value=!1}}function Am(){em.value=`Stopping…`,Zp.value&&Y.chatCancel(Zp.value).catch(()=>{}),gm()}function jm(){ra(()=>{_m().catch(e=>{em.value=e.message||`Chat unavailable`})}),sa(()=>{gm()})}var Mm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Nm=N({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return J(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(L(),R(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":A(Jp),onClick:i[0]||=e=>n(`toggle`)},[B(`span`,{"aria-hidden":`true`,class:D(r(!e.open))},[V(A(Md),{size:22})],2),B(`span`,{"aria-hidden":`true`,class:D(r(e.open))},[V(A(Jd),{size:22})],2)],8,Mm))}});function Pm(e){return typeof e==`string`?`'${e}'`:new Rm().serialize(e)}var Fm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Im=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Fm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Lm(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&Im[n]?Im[n]:n+128,s=a<128&&Im[a]?Im[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var Rm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Lm(e,t):n===`number`&&r===`number`?e-t:Lm(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(Lm),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`InLine truncated
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(em.value=n.session_id),n.type===`delta`&&(o+=n.text,am.value=am.value?{...am.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],am.value=am.value?{...am.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);tm.value=[...tm.value,{from:`assistant`,text:o,tool_calls:a}],am.value=null,rm.value=`Ready`,await bm()}catch(e){let t=e;t.name===`AbortError`&&!c?(am.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},rm.value=`Stopped`):(am.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Yp(r):void 0,isRetry:i},rm.value=`Error — retry available`)}finally{clearTimeout(l),vm=null,im.value=!1}}function Nm(){rm.value=`Stopping…`,em.value&&J.chatCancel(em.value).catch(()=>{}),ym()}function Pm(){ia(()=>{bm().catch(e=>{rm.value=e.message||`Chat unavailable`})}),ca(()=>{ym()})}var Fm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Im=M({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return q(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(I(),L(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":k(Zp),onClick:i[0]||=e=>n(`toggle`)},[z(`span`,{"aria-hidden":`true`,class:E(r(!e.open))},[B(k(Pd),{size:22})],2),z(`span`,{"aria-hidden":`true`,class:E(r(e.open))},[B(k(Zd),{size:22})],2)],8,Fm))}});function Lm(e){return typeof e==`string`?`'${e}'`:new Vm().serialize(e)}var Rm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,zm=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Rm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Bm(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&zm[n]?zm[n]:n+128,s=a<128&&zm[a]?zm[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var Vm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Bm(e,t):n===`number`&&r===`number`?e-t:Bm(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(Bm),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`InLine truncated
|
||||
`)].join(`
|
||||
`))}return()=>i.value||r.value||o.value?ic(t.default({present:o.value})[0],{ref:e=>{let t=fh(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),vg=N({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=xh(n.default()),r=e.findIndex(e=>e.type!==ps);if(r===-1)return e;let i=e[r];delete i.props?.ref;let a=i.props?W(t,i.props):t,o=Os({...i,props:{}},a);return e.length===1?o:(e[r]=o,e)}}}),yg=[`area`,`img`,`input`],Z=N({name:`Primitive`,inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:`div`}},setup(e,{attrs:t,slots:n}){let r=e.asChild?`template`:e.as;return typeof r==`string`&&yg.includes(r)?()=>ic(r,t):r===`template`?()=>ic(vg,t,{default:n.default}):()=>ic(e.as,t,{default:n.default})}});function bg(){let e=k();return{primitiveElement:e,currentElement:G(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:fh(e))}}function xg({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function Sg({type:e,defaultValue:t,modelValue:n}){return e||xg({type:e,defaultValue:t,modelValue:n})}function Cg({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function wg(e,t){let n=G(()=>Sg(e)),r=bh(e,`modelValue`,t,{defaultValue:Cg(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=zm(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Gm(t,e)){let n=t.findIndex(t=>zm(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:G(()=>n.value===`single`)}}var[Tg,Eg]=Vm(`DialogRoot`),Dg=N({inheritAttrs:!1,__name:`DialogRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1,default:!1},modal:{type:Boolean,required:!1,default:!0},unmountOnHide:{type:Boolean,required:!1,default:!0}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=bh(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=k(),a=k(),{modal:o,unmountOnHide:s}=En(n);return Eg({open:r,modal:o,unmountOnHide:s,openModal:()=>{r.value=!0},onOpenChange:e=>{r.value=e},onOpenToggle:()=>{r.value=!r.value},contentId:``,titleId:``,descriptionId:``,triggerElement:i,contentElement:a}),(e,t)=>F(e.$slots,`default`,{open:A(r),close:()=>r.value=!1})}}),Og=N({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;X();let n=Tg();return(e,r)=>(L(),z(A(Z),W(t,{type:e.as===`button`?`button`:void 0,onClick:r[0]||=e=>A(n).onOpenChange(!1)}),{default:j(()=>[F(e.$slots,`default`)]),_:3},16,[`type`]))}}),kg=`dismissableLayer.pointerDownOutside`,Ag=`dismissableLayer.focusOutside`;function jg(e,t){if(!(t instanceof Element))return!1;let n=t.closest(`[data-dismissable-layer]`),r=e.dataset.dismissableLayer===``?e:e.querySelector(`[data-dismissable-layer]`),i=Array.from(e.ownerDocument.querySelectorAll(`[data-dismissable-layer]`));return!!(n&&(r===n||i.indexOf(r)<i.indexOf(n)))}function Mg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=k(!1),a=k(()=>{});return Ar(o=>{if(!Ym||!xn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if(jg(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){Um(kg,e,t)}n.pointerType===`touch`?(r.removeEventListener(`click`,a.value),a.value=i,r.addEventListener(`click`,a.value,{once:!0})):i()}else r.removeEventListener(`click`,a.value);i.value=!1}},c=window.setTimeout(()=>{r.addEventListener(`pointerdown`,s)},0);o(()=>{window.clearTimeout(c),r.removeEventListener(`pointerdown`,s),r.removeEventListener(`click`,a.value)})}),{onPointerDownCapture:()=>{xn(n)&&(i.value=!0)}}}function Ng(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=k(!1);return Ar(a=>{if(!Ym||!xn(n))return;let o=async n=>{if(!t?.value)return;await ar(),await ar();let r=n.target;t.value&&r&&!jg(t.value,r)&&n.target&&!i.value&&Um(Ag,e,{originalEvent:n})};r.addEventListener(`focusin`,o),a(()=>r.removeEventListener(`focusin`,o))}),{onFocusCapture:()=>{xn(n)&&(i.value=!0)},onBlurCapture:()=>{xn(n)&&(i.value=!1)}}}var Pg=N({__name:`DismissableLayer`,props:{disableOutsidePointerEvents:{type:Boolean,required:!1,default:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},present:{type:Boolean,required:!1,default:!0}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`,`dismiss`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=X(),o=G(()=>a.value?.ownerDocument??globalThis.document),s=G(()=>Dh.layersRoot),c=G(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=G(()=>Dh.layersWithOutsidePointerEventsDisabled.size>0),u=G(()=>{let e=Array.from(s.value),[t]=[...Dh.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=Mg
Line truncated
|
||||
`))}return()=>i.value||r.value||o.value?ac(t.default({present:o.value})[0],{ref:e=>{let t=hh(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),xg=M({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=wh(n.default()),r=e.findIndex(e=>e.type!==ms);if(r===-1)return e;let i=e[r];delete i.props?.ref;let a=i.props?U(t,i.props):t,o=ks({...i,props:{}},a);return e.length===1?o:(e[r]=o,e)}}}),Sg=[`area`,`img`,`input`],X=M({name:`Primitive`,inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:`div`}},setup(e,{attrs:t,slots:n}){let r=e.asChild?`template`:e.as;return typeof r==`string`&&Sg.includes(r)?()=>ac(r,t):r===`template`?()=>ac(xg,t,{default:n.default}):()=>ac(e.as,t,{default:n.default})}});function Cg(){let e=O();return{primitiveElement:e,currentElement:W(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:hh(e))}}function wg({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function Tg({type:e,defaultValue:t,modelValue:n}){return e||wg({type:e,defaultValue:t,modelValue:n})}function Eg({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function Dg(e,t){let n=W(()=>Tg(e)),r=Ch(e,`modelValue`,t,{defaultValue:Eg(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=Hm(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Jm(t,e)){let n=t.findIndex(t=>Hm(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:W(()=>n.value===`single`)}}var[Og,kg]=Wm(`DialogRoot`),Ag=M({inheritAttrs:!1,__name:`DialogRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1,default:!1},modal:{type:Boolean,required:!1,default:!0},unmountOnHide:{type:Boolean,required:!1,default:!0}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=Ch(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=O(),a=O(),{modal:o,unmountOnHide:s}=Dn(n);return kg({open:r,modal:o,unmountOnHide:s,openModal:()=>{r.value=!0},onOpenChange:e=>{r.value=e},onOpenToggle:()=>{r.value=!r.value},contentId:``,titleId:``,descriptionId:``,triggerElement:i,contentElement:a}),(e,t)=>P(e.$slots,`default`,{open:k(r),close:()=>r.value=!1})}}),jg=M({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;Y();let n=Og();return(e,r)=>(I(),R(k(X),U(t,{type:e.as===`button`?`button`:void 0,onClick:r[0]||=e=>k(n).onOpenChange(!1)}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`type`]))}}),Mg=`dismissableLayer.pointerDownOutside`,Ng=`dismissableLayer.focusOutside`;function Pg(e,t){if(!(t instanceof Element))return!1;let n=t.closest(`[data-dismissable-layer]`),r=e.dataset.dismissableLayer===``?e:e.querySelector(`[data-dismissable-layer]`),i=Array.from(e.ownerDocument.querySelectorAll(`[data-dismissable-layer]`));return!!(n&&(r===n||i.indexOf(r)<i.indexOf(n)))}function Fg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1),a=O(()=>{});return jr(o=>{if(!Qm||!Sn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if(Pg(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){Km(Mg,e,t)}n.pointerType===`touch`?(r.removeEventListener(`click`,a.value),a.value=i,r.addEventListener(`click`,a.value,{once:!0})):i()}else r.removeEventListener(`click`,a.value);i.value=!1}},c=window.setTimeout(()=>{r.addEventListener(`pointerdown`,s)},0);o(()=>{window.clearTimeout(c),r.removeEventListener(`pointerdown`,s),r.removeEventListener(`click`,a.value)})}),{onPointerDownCapture:()=>{Sn(n)&&(i.value=!0)}}}function Ig(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1);return jr(a=>{if(!Qm||!Sn(n))return;let o=async n=>{if(!t?.value)return;await or(),await or();let r=n.target;t.value&&r&&!Pg(t.value,r)&&n.target&&!i.value&&Km(Ng,e,{originalEvent:n})};r.addEventListener(`focusin`,o),a(()=>r.removeEventListener(`focusin`,o))}),{onFocusCapture:()=>{Sn(n)&&(i.value=!0)},onBlurCapture:()=>{Sn(n)&&(i.value=!1)}}}var Lg=M({__name:`DismissableLayer`,props:{disableOutsidePointerEvents:{type:Boolean,required:!1,default:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},present:{type:Boolean,required:!1,default:!0}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`,`dismiss`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=Y(),o=W(()=>a.value?.ownerDocument??globalThis.document),s=W(()=>Ah.layersRoot),c=W(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=W(()=>Ah.layersWithOutsidePointerEventsDisabled.size>0),u=W(()=>{let e=Array.from(s.value),[t]=[...Ah.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=Fg
Line truncated
|
||||
- a positive number
|
||||
- less than the value passed to \`max\` (or ${xx} if no \`max\` prop is set)
|
||||
- less than the value passed to \`max\` (or ${wx} if no \`max\` prop is set)
|
||||
- \`null\` or \`undefined\` if the progress is indeterminate.
|
||||
|
||||
Defaulting to \`null\`.`),null)}function Ex(e){return wx(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${xx}\`.`),xx)}var Dx=N({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:xx},getValueLabel:{type:Function,required:!1,default:(e,t)=>wx(e)?`${Math.round(e/t*xx)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;X();let i=bh(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=bh(n,`max`,r,{passive:n.max===void 0});M(()=>i.value,async e=>{let t=Tx(e,n.max);t!==e&&(await ar(),i.value=t)},{immediate:!0}),M(()=>n.max,e=>{let t=Ex(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=G(()=>Wm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Cx({modelValue:i,max:a,progressState:o}),(e,t)=>(L(),z(A(Z),{"as-child":e.asChild,as:e.as,"aria-valuemax":A(a),"aria-valuemin":0,"aria-valuenow":wx(A(i))?A(i):void 0,"aria-valuetext":e.getValueText?.(A(i),A(a)),"aria-label":e.getValueLabel(A(i),A(a)),role:`progressbar`,"data-state":o.value,"data-value":A(i)??void 0,"data-max":A(a)},{default:j(()=>[F(e.$slots,`default`,{modelValue:A(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Ox=N({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Sx();return X(),(e,r)=>(L(),z(A(Z),W(t,{"data-state":A(n).progressState.value,"data-value":A(n).modelValue?.value??void 0,"data-max":A(n).max.value}),{default:j(()=>[F(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),kx=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Ax=[` `,`Enter`];function jx(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Mx(e,t,n)):Mx(e,t,n)}function Mx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:zm(e,t)}function Nx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Px=[`value`],[Fx,Ix]=Vm(`SelectRoot`),Lx=N({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=En(n),c=bh(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=bh(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=k(),d=k(),f=k({x:0,y:0}),p=G(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Wm(c.value));O_({isProvider:!0});let m=Ih(s),h=Vh(u),g=k(new Set),_=G(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Mx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>jx(e,t.value,n.by))}return Ix({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(L(),z(A(V_),null,{default:j(()=>[F(e.$slots,`default`,{modelValue:A(c),open:A(l)}),A(h)&&e.name?(L(),z(Rx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:A(o),required:A(i),name:e.name,autocomplete:e.autocomplete,disabled:A(a),value:A(c)},{default:j(()=>[A(Wm)(A(c))?(L(),R(`option`,{key:0,value:e.nullableValue},null,8,Px)):U(`v-if`,!0),(L(!0),R(I,null,P(Array.from(g.value),e=>(L(),R(`option`,W({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):U(`v-if`,!0)]),_:3}))}}),Rx=N({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=k(),r=Fx();M(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:rT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>rT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
|
||||
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=aT(c),u=e+1<n.length?aT(n[e+1]):null;if(l&&u&&oT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=aT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>rT(e)),rows:r.map(e=>e.map(e=>rT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:rT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:rT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
|
||||
`)}),t}function aT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function oT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var sT={class:`[overflow-wrap:anywhere]`},cT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},lT={class:`font-mono text-[0.85em]`},uT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},dT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},fT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},pT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},mT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},hT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},gT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},_T={key:8,class:`mb-2.5 last:mb-0`},vT=N({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>iT(t.text));return(e,t)=>(L(),R(`div`,sT,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,cT,[B(`code`,lT,O(e.code),1)])):e.kind===`table`?(L(),R(`table`,uT,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(tT,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(tT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,dT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,fT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,pT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,mT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,hT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(tT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,gT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(tT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,_T,[V(tT,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),yT={class:`truncate`},bT=N({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ma(`RouterLink`);return L(),z(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[V(A(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,yT,O(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),xT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},ST={class:`font-semibold text-foreground`},CT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},wT=N({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(L(),z(bT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,xT,[V(A(qd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,ST,O(n.value),1),r.value?(L(),R(`code`,CT,O(r.value),1)):U(``,!0),B(`span`,{class:D(A(J)(`text-fg-muted`,i.value&&`text-danger`))},O(a.value),3)]))}}),TT={key:0,class:`mb-2 grid gap-0.5 text-xs`},ET={key:2,class:`whitespace-pre-wrap`},DT=N({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:D([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:D(A(J)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(L(),R(`div`,TT,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(wT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.assistant?(L(),z(vT,{key:1,text:e.text},null,8,[`text`])):(L(),R(`div`,ET,O(e.text),1)),F(t.$slots,`default`)],2)],2))}}),OT={class:`w-full self-center justify-self-center py-6 text-center`},kT={class:`grid gap-2`},AT=[`onClick`],jT=N({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(L(),R(`div`,OT,[t[0]||=B(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>tA?`${n.slice(0,tA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var rA=[`title`],iA=N({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>Ok(n.event)),a=G(()=>nA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?yO(n.event.at):`—`);return(e,t)=>(L(),z(A(Qk),{class:D(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[du(lu(o,[`prevent`]),[`enter`]),du(lu(o,[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[H(O(n.event.kind||n.event.type||`event`),1)]),_:1}),V(A($),{class:`font-mono`},{default:j(()=>[H(O(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},O(a.value.text),9,rA)]),_:1}),V(A($),null,{default:j(()=>[H(O(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function aA(e,t){return`${e}:${t??0}`}function oA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=aA(nA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var sA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},cA={class:`max-h-[28rem] overflow-y-auto`},lA=[`aria-expanded`,`aria-label`,`onClick`],uA=[`title`],dA=N({__name:`LiveActivityCard`,setup(e){let t=eE(),{activity:n,streamKind:r,streamState:i}=ad(tk()),a=nn(new Set),o=G(()=>oA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return nA(e.representative)}function u(e){return e.representative.at?yO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(A(dO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[V(A(_O),null,{default:j(()=>[...t[0]||=[H(`Live activity`,-1)]]),_:1}),V(A(fO),null,{default:j(()=>[V(A(ZD),{variant:A(r)},{default:j(()=>[H(O(A(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(A(pO),null,{default:j(()=>[B(`div`,sA,[B(`div`,cA,[V(A(Xk),null,{default:j(()=>[V(A(eA),{class:`sticky top-0 z-10 bg-card`},{default:j(()=>[V(A(Qk),null,{default:j(()=>[V(A($k),null,{default:j(()=>[...t[1]||=[H(`Event`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[2]||=[H(`Task`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[3]||=[H(`Detail`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[4]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(A(Zk),null,{default:j(()=>[A(n).length?U(``,!0):(L(),z(A(Qk),{key:0},{default:j(()=>[V(A($),{colspan:`4`},{default:j(()=>[V(A(UD),null,{default:j(()=>[V(A(KD),null,{default:j(()=>[V(A(YD),null,{default:j(()=>[...t[5]||=[H(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),A(n).length?(L(!0),R(I,{key:1},P(o.value,e=>(L(),R(I,{key:e.key},[e.count===1?(L(),z(iA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(L(),R(I,{key:1},[V(A(Qk),{class:D(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[B(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:lu(t=>s(e.key),[`stop`])},[c(e)?(L(),z(A(xd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(L(),z(A(Cd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),H(` `+O(e.label)+` `,1),V(A(ZD),{variant:`idle`},{default:j(()=>[H(`×`+O(e.count),1)]),_:2},1024)],8,lA)]),_:2},1024),V(A($),{class:`font-mono`},{default:j(()=>[H(O(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},O(l(e).text),9,uA)]),_:2},1024),V(A($),null,{default:j(()=>[H(O(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(L(!0),R(I,{key:0},P(e.events,(t,n)=>(L(),z(iA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):U(``,!0)],64))],64))),128)):U(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),fA=N({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=$S(t,`class`);return(e,r)=>(L(),z(A(Dx),W({"data-slot":`progress`},A(n),{class:A(J)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:j(()=>[V(A(Ox),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ve(`tLine truncated
|
||||
Defaulting to \`null\`.`),null)}function kx(e){return Dx(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${wx}\`.`),wx)}var Ax=M({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:wx},getValueLabel:{type:Function,required:!1,default:(e,t)=>Dx(e)?`${Math.round(e/t*wx)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;Y();let i=Ch(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=Ch(n,`max`,r,{passive:n.max===void 0});j(()=>i.value,async e=>{let t=Ox(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),j(()=>n.max,e=>{let t=kx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=W(()=>qm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Ex({modelValue:i,max:a,progressState:o}),(e,t)=>(I(),R(k(X),{"as-child":e.asChild,as:e.as,"aria-valuemax":k(a),"aria-valuemin":0,"aria-valuenow":Dx(k(i))?k(i):void 0,"aria-valuetext":e.getValueText?.(k(i),k(a)),"aria-label":e.getValueLabel(k(i),k(a)),role:`progressbar`,"data-state":o.value,"data-value":k(i)??void 0,"data-max":k(a)},{default:A(()=>[P(e.$slots,`default`,{modelValue:k(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),jx=M({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Tx();return Y(),(e,r)=>(I(),R(k(X),U(t,{"data-state":k(n).progressState.value,"data-value":k(n).modelValue?.value??void 0,"data-max":k(n).max.value}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Mx=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Nx=[` `,`Enter`];function Px(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Fx(e,t,n)):Fx(e,t,n)}function Fx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Hm(e,t)}function Ix(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Lx=[`value`],[Rx,zx]=Wm(`SelectRoot`),Bx=M({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=Dn(n),c=Ch(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=Ch(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=O(),d=O(),f=O({x:0,y:0}),p=W(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:qm(c.value));j_({isProvider:!0});let m=zh(s),h=Wh(u),g=O(new Set),_=W(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Fx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Px(e,t.value,n.by))}return zx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(I(),R(k(W_),null,{default:A(()=>[P(e.$slots,`default`,{modelValue:k(c),open:k(l)}),k(h)&&e.name?(I(),R(Vx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:k(o),required:k(i),name:e.name,autocomplete:e.autocomplete,disabled:k(a),value:k(c)},{default:A(()=>[k(qm)(k(c))?(I(),L(`option`,{key:0,value:e.nullableValue},null,8,Lx)):H(`v-if`,!0),(I(!0),L(F,null,N(Array.from(g.value),e=>(I(),L(`option`,U({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):H(`v-if`,!0)]),_:3}))}}),Vx=M({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=O(),r=Rx();j(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:oT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>oT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
|
||||
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=cT(c),u=e+1<n.length?cT(n[e+1]):null;if(l&&u&&lT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=cT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>oT(e)),rows:r.map(e=>e.map(e=>oT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:oT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:oT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
|
||||
`)}),t}function cT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function lT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var uT={class:`[overflow-wrap:anywhere]`},dT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},fT={class:`font-mono text-[0.85em]`},pT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},mT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},hT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},gT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},_T={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},vT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},yT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},bT={key:8,class:`mb-2.5 last:mb-0`},xT=M({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=W(()=>sT(t.text));return(e,t)=>(I(),L(`div`,uT,[(I(!0),L(F,null,N(n.value,(e,t)=>(I(),L(F,{key:t},[e.kind===`pre`?(I(),L(`pre`,dT,[z(`code`,fT,D(e.code),1)])):e.kind===`table`?(I(),L(`table`,pT,[z(`thead`,null,[z(`tr`,null,[(I(!0),L(F,null,N(e.head,(e,t)=>(I(),L(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[B(iT,{inline:e},null,8,[`inline`])]))),128))])]),z(`tbody`,null,[(I(!0),L(F,null,N(e.rows,(e,t)=>(I(),L(`tr`,{key:t},[(I(!0),L(F,null,N(e,(e,t)=>(I(),L(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[B(iT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(I(),L(`blockquote`,mT,[B(iT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(I(),L(`h1`,hT,[B(iT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(I(),L(`h2`,gT,[B(iT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(I(),L(`h3`,_T,[B(iT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(I(),L(`ul`,vT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(iT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(I(),L(`ol`,yT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(iT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(I(),L(`p`,bT,[B(iT,{inline:e.inline},null,8,[`inline`])])):H(``,!0)],64))),128))]))}}),ST={class:`truncate`},CT=M({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return I(),R(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:A(()=>[B(k(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),z(`span`,ST,D(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),wT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},TT={class:`font-semibold text-foreground`},ET={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},DT=M({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=W(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=W(()=>t.tool.parameters||t.tool.Parameters||``),i=W(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=W(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(I(),R(CT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(I(),L(`div`,wT,[B(k(Xd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),z(`span`,TT,D(n.value),1),r.value?(I(),L(`code`,ET,D(r.value),1)):H(``,!0),z(`span`,{class:E(k(q)(`text-fg-muted`,i.value&&`text-danger`))},D(a.value),3)]))}}),OT={key:0,class:`mb-2 grid gap-0.5 text-xs`},kT={key:2,class:`whitespace-pre-wrap`},AT=M({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(I(),L(`div`,{class:E([`flex`,e.assistant?`justify-start`:`justify-end`])},[z(`div`,{class:E(k(q)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(I(),L(`div`,OT,[(I(!0),L(F,null,N(e.tools,(t,n)=>(I(),R(DT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):H(``,!0),e.assistant?(I(),R(xT,{key:1,text:e.text},null,8,[`text`])):(I(),L(`div`,kT,D(e.text),1)),P(t.$slots,`default`)],2)],2))}}),jT={class:`w-full self-center justify-self-center py-6 text-center`},MT={class:`grid gap-2`},NT=[`onClick`],PT=M({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(I(),L(`div`,jT,[t[0]||=z(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>rA?`${n.slice(0,rA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var aA=[`title`],oA=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=W(()=>jk(n.event)),a=W(()=>iA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=W(()=>n.event.at?SO(n.event.at):`—`);return(e,t)=>(I(),R(k(tA),{class:E(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[V(D(n.event.kind||n.event.type||`event`),1)]),_:1}),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(i.value>0?`#${i.value}`:`—`),1)]),_:1}),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},D(a.value.text),9,aA)]),_:1}),B(k(Q),null,{default:A(()=>[V(D(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function sA(e,t){return`${e}:${t??0}`}function cA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=sA(iA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var lA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},uA={class:`max-h-[28rem] overflow-y-auto`},dA=[`aria-expanded`,`aria-label`,`onClick`],fA=[`title`],pA=M({__name:`LiveActivityCard`,setup(e){let t=rE(),{activity:n,streamKind:r,streamState:i}=od(ik()),a=rn(new Set),o=W(()=>cA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return iA(e.representative)}function u(e){return e.representative.at?SO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(I(),R(k(mO),null,{default:A(()=>[B(k(yO),null,{default:A(()=>[B(k(bO),null,{default:A(()=>[...t[0]||=[V(`Live activity`,-1)]]),_:1}),B(k(hO),null,{default:A(()=>[B(k(eO),{variant:k(r)},{default:A(()=>[V(D(k(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),B(k(gO),null,{default:A(()=>[z(`div`,lA,[z(`div`,uA,[B(k($k),null,{default:A(()=>[B(k(nA),{class:`sticky top-0 z-10 bg-card`},{default:A(()=>[B(k(tA),null,{default:A(()=>[B(k($),null,{default:A(()=>[...t[1]||=[V(`Event`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[2]||=[V(`Task`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[3]||=[V(`Detail`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[4]||=[V(`When`,-1)]]),_:1})]),_:1})]),_:1}),B(k(eA),null,{default:A(()=>[k(n).length?H(``,!0):(I(),R(k(tA),{key:0},{default:A(()=>[B(k(Q),{colspan:`4`},{default:A(()=>[B(k(KD),null,{default:A(()=>[B(k(YD),null,{default:A(()=>[B(k(QD),null,{default:A(()=>[...t[5]||=[V(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),k(n).length?(I(!0),L(F,{key:1},N(o.value,e=>(I(),L(F,{key:e.key},[e.count===1?(I(),R(oA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(I(),L(F,{key:1},[B(k(tA),{class:E(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[z(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(I(),R(k(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(I(),R(k(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),V(` `+D(e.label)+` `,1),B(k(eO),{variant:`idle`},{default:A(()=>[V(`×`+D(e.count),1)]),_:2},1024)],8,dA)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},D(l(e).text),9,fA)]),_:2},1024),B(k(Q),null,{default:A(()=>[V(D(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(I(!0),L(F,{key:0},N(e.events,(t,n)=>(I(),R(oA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):H(``,!0)],64))],64))),128)):H(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),mA=M({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=nC(t,`class`);return(e,r)=>(I(),R(k(Ax),U({"data-slot":`progress`},k(n),{class:k(q)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:A(()=>[B(k(jx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
|
||||
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function SM(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function CM(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function wM(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var TM=O([]),EM=O([]),DM=O(!0),OM=O(null),kM=O(null),AM=O(!1),jM=O(null);async function MM(){try{let e=await J.eventTypes();DM.value=e.enabled!==!1,TM.value=e.event_types||[],EM.value=e.proposals||[],OM.value=null}catch(e){OM.value=e.message||String(e)}}function NM(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function PM(e){jM.value=null,kM.value=e}function FM(e){let t=UM.value.find(t=>String(t.id)===e.sample_id);PM({mode:`proposal`,id:null,source:e.source,name:``,rule:NM(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function IM(e=``){PM({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function LM(e){PM({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:NM(e.rule),headersText:``,body:``,exampleHeaders:{}})}function RM(){kM.value=null}async function zM(){let e=kM.value;if(e){AM.value=!0;try{if(e.mode===`edit`&&e.id)await J.eventTypeUpdate(e.id,{name:e.name,rule:wM(e.rule)});else{let t=e.mode===`paste`?xM(e.headersText):e.exampleHeaders;await J.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:wM(e.rule),example:{headers:t,body:e.body}})}kM.value=null,await MM()}catch(e){jM.value=e.message||String(e)}finally{AM.value=!1}}}var BM=O(null);async function VM(){let e=BM.value;if(BM.value=null,e)try{await J.eventTypeDelete(e.id),await MM()}catch(e){OM.value=e.message||String(e)}}var HM=100,UM=O([]),WM=O(!0),GM=O(null),KM=O(!0),qM=O(null);async function JM(){try{let e=await J.captures(HM);WM.value=e.enabled!==!1,UM.value=e.captures||[],GM.value=null}catch(e){GM.value=e.message||String(e)}finally{KM.value=!1}}function YM(e){let t=UM.value.find(t=>t.id===e);return t&&(qM.value=t),!!t}function XM(){UM.value.length&&(qM.value=UM.value[0])}function ZM(){ak(`captures`,()=>{JM(),MM()})}var QM={class:`flex flex-col gap-5`},$M=M({__name:`CaptureDetail`,props:{maxHeight:{}},setup(e){let t=e,n=O(null),r=dC(`(max-width: 1099px)`),i=W(()=>r.value||!t.maxHeight?void 0:`${t.maxHeight}px`),a=W(()=>{let e=qM.value;return e?[SO(e.received_at),e.content_type||`no content type`,e.remote_addr].filter(Boolean).join(` · `):``});return j(qM,()=>{r.value&&n.value?.scrollIntoView({block:`start`,behavior:`smooth`})}),(e,t)=>k(qM)?(I(),L(`div`,{key:0,ref_key:`pane`,ref:n,class:`min-w-0`},[B(k(mO),{class:`flex flex-col`,style:ye(i.value?{maxHeight:i.value}:void 0)},{default:A(()=>[B(k(yO),null,{default:A(()=>[B(k(bO),{class:`font-mono`},{default:A(()=>[V(D(k(qM).source||`Unknown source`),1)]),_:1}),B(k(_O),null,{default:A(()=>[V(D(a.value),1)]),_:1})]),_:1}),B(k(gO),{class:`min-h-0 max-h-[62vh] overflow-y-auto min-[1100px]:max-h-none`},{default:A(()=>[z(`div`,QM,[B(bM,{label:`Payload`,raw:k(qM).body},null,8,[`raw`]),B(bM,{label:`Headers`,raw:k(qM).headers},null,8,[`raw`])])]),_:1})]),_:1},8,[`style`])],512)):H(``,!0)}}),eN=M({__name:`CaptureStatus`,setup(e){let{streamKind:t,streamState:n}=od(ik());return(e,r)=>(I(),R(k(eO),{variant:k(t)},{default:A(()=>[V(D(k(n)),1)]),_:1},8,[`variant`]))}}),tN={class:`truncate`},nN=M({__name:`CaptureRow`,props:{capture:{}},setup(e){let t=e,n=W(()=>SM(t.capture,TM.value)),r=W(()=>qM.value?.id===t.capture.id),i=W(()=>`Show the payload received from ${t.capture.source||`an unknown source`}`);function a(){qM.value=t.capture}return(e,o)=>(I(),R(k(tA),{"data-state":r.value?`selected`:void 0,role:`button`,tabindex:`0`,"aria-current":r.value?`true`:void 0,"aria-label":i.value,class:`cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring`,onClick:a,onKeydown:[fu(uu(a,[`prevent`]),[`enter`]),fu(uu(a,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(t.capture.source||`(unknown)`),1)]),_:1}),B(k(Q),{title:t.capture.received_at||``},{default:A(()=>[V(D(k(SO)(t.capture.received_at)),1)]),_:1},8,[`title`]),B(k(Q),null,{default:A(()=>[B(k(eO),{variant:n.value.identified?`ok`:`warn`,class:`max-w-40`},{default:A(()=>[z(`span`,tN,D(n.value.label),1)]),_:1},8,[`variant`])]),_:1}),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(t.capture.content_type||`—`),1)]),_:1}),B(k(Q),{class:`text-right`},{default:A(()=>[B(k(wd),{class:`size-4 text-fg-sLine truncated
|
||||
@@ -5,6 +5,8 @@ import { computed } from "vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { TableCell, TableRow } from "@/components/ui/table";
|
||||
import { ago } from "@/lib/format";
|
||||
import { eventTypes } from "./event-type-state";
|
||||
import { captureIdentity } from "./event-types";
|
||||
import { selected, type Capture } from "./state";
|
||||
|
||||
/**
|
||||
@@ -15,6 +17,8 @@ import { selected, type Capture } from "./state";
|
||||
*/
|
||||
const props = defineProps<{ capture: Capture }>();
|
||||
|
||||
const identity = computed(() => captureIdentity(props.capture, eventTypes.value));
|
||||
|
||||
const isSelected = computed(() => selected.value?.id === props.capture.id);
|
||||
|
||||
// The name is set here because role="button" makes the cells presentational:
|
||||
@@ -40,10 +44,12 @@ function open(): void {
|
||||
>
|
||||
<TableCell class="font-mono">{{ props.capture.source || "(unknown)" }}</TableCell>
|
||||
<TableCell :title="props.capture.received_at || ''">{{ ago(props.capture.received_at) }}</TableCell>
|
||||
<!-- A stored capture carries no claim from a binding, so this reads Unbound
|
||||
for every row: the column is where a claim would appear, not a state a
|
||||
reader can act on today. -->
|
||||
<TableCell><Badge variant="idle">Unbound</Badge></TableCell>
|
||||
<!-- An unidentified capture is never dispatched. -->
|
||||
<TableCell>
|
||||
<Badge :variant="identity.identified ? 'ok' : 'warn'" class="max-w-40">
|
||||
<span class="truncate">{{ identity.label }}</span>
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell class="font-mono">{{ props.capture.content_type || "—" }}</TableCell>
|
||||
<TableCell class="text-right">
|
||||
<ChevronRight class="size-4 text-fg-subtle" />
|
||||
|
||||
@@ -53,7 +53,7 @@ const webhookHint = "Point a webhook at /webhooks/capture/<source> and it will s
|
||||
<TableRow>
|
||||
<TableHead>Source</TableHead>
|
||||
<TableHead>Received</TableHead>
|
||||
<TableHead>Binding</TableHead>
|
||||
<TableHead>Event type</TableHead>
|
||||
<TableHead>Content type</TableHead>
|
||||
<TableHead class="w-10"><span class="sr-only">Payload</span></TableHead>
|
||||
</TableRow>
|
||||
|
||||
@@ -6,6 +6,8 @@ import { useRoute, useRouter } from "vue-router";
|
||||
import CaptureDetail from "./CaptureDetail.vue";
|
||||
import CaptureStatus from "./CaptureStatus.vue";
|
||||
import CapturesCard from "./CapturesCard.vue";
|
||||
import EventTypesCard from "./EventTypesCard.vue";
|
||||
import { loadEventTypes } from "./event-type-state";
|
||||
import { load, selectById, selectNewest, selected, useCaptures } from "./state";
|
||||
|
||||
/**
|
||||
@@ -66,7 +68,7 @@ onMounted(async () => {
|
||||
}
|
||||
window.addEventListener("resize", measure);
|
||||
|
||||
await load();
|
||||
await Promise.all([load(), loadEventTypes()]);
|
||||
// The URL names a selection before the window is read, so the restore waits
|
||||
// for the list; an id it no longer holds falls back to the newest capture,
|
||||
// which is what a page opened with nothing named starts on too.
|
||||
@@ -100,4 +102,7 @@ watch(selected, (capture) => {
|
||||
</div>
|
||||
<CaptureDetail :max-height="paneCap" />
|
||||
</div>
|
||||
<div class="mt-4">
|
||||
<EventTypesCard />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,79 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import RuleEditor from "./RuleEditor.vue";
|
||||
import { closeDraft, draft, saveDraft, saveError, saving } from "./event-type-state";
|
||||
|
||||
/**
|
||||
* One event-type editing session: naming a proposed group, creating a type
|
||||
* from a pasted example, or editing a type's name and rule. A refusal (an
|
||||
* overlapping rule, a taken name) is shown beside the Save button.
|
||||
*/
|
||||
const title = computed(() => {
|
||||
switch (draft.value?.mode) {
|
||||
case "proposal":
|
||||
return "Name event type";
|
||||
case "paste":
|
||||
return "Event type from payload";
|
||||
default:
|
||||
return "Edit event type";
|
||||
}
|
||||
});
|
||||
|
||||
function onOpenChange(open: boolean) {
|
||||
if (!open) closeDraft();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="draft !== null" @update:open="onOpenChange">
|
||||
<DialogContent v-if="draft" class="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ title }}</DialogTitle>
|
||||
<DialogDescription>Events on {{ draft.source || "the source" }} that match no type are never dispatched.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label for="event-type-source">Source</Label>
|
||||
<Input id="event-type-source" v-model="draft.source" class="font-mono" :disabled="draft.mode !== 'paste'" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label for="event-type-name">Name</Label>
|
||||
<Input id="event-type-name" v-model="draft.name" placeholder="pull_request.opened" />
|
||||
</div>
|
||||
|
||||
<template v-if="draft.mode === 'paste'">
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label for="event-type-headers">Headers</Label>
|
||||
<Textarea id="event-type-headers" v-model="draft.headersText" class="min-h-20 font-mono text-xs" placeholder="X-GitHub-Event: pull_request" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label for="event-type-body">Payload</Label>
|
||||
<Textarea id="event-type-body" v-model="draft.body" class="min-h-40 font-mono text-xs" placeholder="{ }" />
|
||||
</div>
|
||||
</template>
|
||||
<RuleEditor v-else v-model="draft.rule" />
|
||||
</div>
|
||||
|
||||
<Alert v-if="saveError" variant="destructive">
|
||||
<AlertDescription>{{ saveError }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="closeDraft">Cancel</Button>
|
||||
<Button :disabled="saving || !draft.name.trim() || !draft.source.trim()" @click="saveDraft">
|
||||
<Spinner v-if="saving" />
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,120 @@
|
||||
<script setup lang="ts">
|
||||
import { ClipboardPaste, Pencil, Tag, Trash2, TriangleAlert } from "@lucide/vue";
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardAction, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import EventTypeDialog from "./EventTypeDialog.vue";
|
||||
import {
|
||||
confirmDelete,
|
||||
editEventType,
|
||||
eventTypes,
|
||||
eventTypesEnabled,
|
||||
eventTypesError,
|
||||
nameProposal,
|
||||
pasteExample,
|
||||
pendingDelete,
|
||||
proposals,
|
||||
} from "./event-type-state";
|
||||
import { ruleSummary } from "./event-types";
|
||||
|
||||
/**
|
||||
* Proposed event types (groups of unidentified captures sharing a structure)
|
||||
* and the named ones. Naming a proposal or pasting an example payload creates
|
||||
* a type; a later event matching it is identified as it on arrival.
|
||||
*/
|
||||
function fieldCount(schema: Record<string, string> | null | undefined): number {
|
||||
return schema ? Object.keys(schema).length : 0;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card v-if="eventTypesEnabled">
|
||||
<CardHeader>
|
||||
<CardTitle>Event types</CardTitle>
|
||||
<CardAction>
|
||||
<Button variant="outline" size="sm" @click="pasteExample()"><ClipboardPaste /> From payload</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<Alert v-if="eventTypesError" variant="destructive">
|
||||
<TriangleAlert />
|
||||
<AlertTitle>Event types</AlertTitle>
|
||||
<AlertDescription>{{ eventTypesError }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Table v-if="proposals.length">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Proposed · source</TableHead>
|
||||
<TableHead class="w-20 text-right">Events</TableHead>
|
||||
<TableHead class="w-20 text-right">Fields</TableHead>
|
||||
<TableHead>Rule</TableHead>
|
||||
<TableHead class="w-24"><span class="sr-only">Name</span></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="p in proposals" :key="p.source + p.key">
|
||||
<TableCell class="font-mono">{{ p.source || "(unknown)" }}</TableCell>
|
||||
<TableCell class="text-right tabular-nums">{{ p.count }}</TableCell>
|
||||
<TableCell class="text-right tabular-nums">{{ fieldCount(p.schema) }}</TableCell>
|
||||
<TableCell class="font-mono text-xs"><span class="block max-w-96 truncate" :title="ruleSummary(p.rule)">{{ ruleSummary(p.rule) }}</span></TableCell>
|
||||
<TableCell class="text-right">
|
||||
<Button variant="outline" size="sm" @click="nameProposal(p)"><Tag /> Name</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<Table v-if="eventTypes.length">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Source</TableHead>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Rule</TableHead>
|
||||
<TableHead class="w-20"><span class="sr-only">Actions</span></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="t in eventTypes" :key="t.id">
|
||||
<TableCell class="font-mono">{{ t.source }}</TableCell>
|
||||
<TableCell>{{ t.name }}</TableCell>
|
||||
<TableCell class="font-mono text-xs"><span class="block max-w-96 truncate" :title="ruleSummary(t.rule)">{{ ruleSummary(t.rule) }}</span></TableCell>
|
||||
<TableCell class="text-right whitespace-nowrap">
|
||||
<Button variant="ghost" size="icon-sm" :aria-label="`Edit ${t.name}`" @click="editEventType(t)"><Pencil /></Button>
|
||||
<Button variant="ghost" size="icon-sm" :aria-label="`Delete ${t.name}`" @click="pendingDelete = t"><Trash2 /></Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<p v-if="!proposals.length && !eventTypes.length" class="text-sm text-fg-muted">No event types or proposals.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<EventTypeDialog />
|
||||
<AlertDialog :open="pendingDelete !== null" @update:open="(open) => { if (!open) pendingDelete = null; }">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete this event type?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Events matching "{{ pendingDelete?.name }}" will arrive unidentified and will not dispatch.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" @click="confirmDelete">Delete</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,72 @@
|
||||
<script setup lang="ts">
|
||||
import { Plus, X } from "@lucide/vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import type { PayloadCondition, Rule } from "./event-types";
|
||||
|
||||
/**
|
||||
* A match rule's conditions, edited in place: header equalities, then payload
|
||||
* conditions. Every condition must hold for an event to match.
|
||||
*/
|
||||
const rule = defineModel<Rule>({ required: true });
|
||||
|
||||
function headers() {
|
||||
return (rule.value.headers ||= []);
|
||||
}
|
||||
|
||||
function payload() {
|
||||
return (rule.value.payload ||= []);
|
||||
}
|
||||
|
||||
function asOp(value: unknown): PayloadCondition["op"] {
|
||||
return value === "present" ? "present" : "equals";
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label>Headers</Label>
|
||||
<div v-for="(h, i) in rule.headers || []" :key="`h${i}`" class="flex items-center gap-2">
|
||||
<Input v-model="h.name" class="font-mono" aria-label="Header name" placeholder="X-GitHub-Event" />
|
||||
<span class="text-fg-subtle">=</span>
|
||||
<Input v-model="h.value" class="font-mono" aria-label="Header value" />
|
||||
<Button variant="ghost" size="icon-sm" aria-label="Remove header condition" @click="headers().splice(i, 1)">
|
||||
<X />
|
||||
</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" class="w-fit" @click="headers().push({ name: '', value: '' })">
|
||||
<Plus /> Header
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label>Payload</Label>
|
||||
<div v-for="(p, i) in rule.payload || []" :key="`p${i}`" class="flex items-center gap-2">
|
||||
<Input v-model="p.path" class="font-mono" aria-label="Payload path" placeholder="action" />
|
||||
<Select :model-value="p.op" @update:model-value="(value) => (p.op = asOp(value))">
|
||||
<SelectTrigger size="sm" class="w-28 shrink-0" aria-label="Condition">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value="equals">equals</SelectItem>
|
||||
<SelectItem value="present">present</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Input v-if="p.op === 'equals'" v-model="p.value" class="font-mono" aria-label="Payload value" />
|
||||
<span v-else class="w-full" />
|
||||
<Button variant="ghost" size="icon-sm" aria-label="Remove payload condition" @click="payload().splice(i, 1)">
|
||||
<X />
|
||||
</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" class="w-fit" @click="payload().push({ path: '', op: 'equals', value: '' })">
|
||||
<Plus /> Payload condition
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,131 @@
|
||||
import { ref } from "vue";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
import { captures } from "./state";
|
||||
import { cleanRule, parseHeaderLines, type EventType, type Proposal, type Rule } from "./event-types";
|
||||
|
||||
/**
|
||||
* The inspector's event types: the named ones, and the groups of unidentified
|
||||
* captures proposed as types. The server groups and infers; this module holds
|
||||
* the read and one editing session at a time.
|
||||
*/
|
||||
|
||||
interface EventTypesResponse {
|
||||
enabled?: boolean;
|
||||
event_types?: EventType[];
|
||||
proposals?: Proposal[];
|
||||
}
|
||||
|
||||
export const eventTypes = ref<EventType[]>([]);
|
||||
export const proposals = ref<Proposal[]>([]);
|
||||
export const eventTypesEnabled = ref(true);
|
||||
export const eventTypesError = ref<string | null>(null);
|
||||
|
||||
/** The editor's modes: naming a proposal, pasting an example, editing a type. */
|
||||
export type DraftMode = "proposal" | "paste" | "edit";
|
||||
|
||||
export interface Draft {
|
||||
mode: DraftMode;
|
||||
id: string | null;
|
||||
source: string;
|
||||
name: string;
|
||||
rule: Rule;
|
||||
headersText: string;
|
||||
body: string;
|
||||
exampleHeaders: Record<string, string>;
|
||||
}
|
||||
|
||||
export const draft = ref<Draft | null>(null);
|
||||
export const saving = ref(false);
|
||||
export const saveError = ref<string | null>(null);
|
||||
|
||||
export async function loadEventTypes(): Promise<void> {
|
||||
try {
|
||||
const res = await api.eventTypes<EventTypesResponse>();
|
||||
eventTypesEnabled.value = res.enabled !== false;
|
||||
eventTypes.value = res.event_types || [];
|
||||
proposals.value = res.proposals || [];
|
||||
eventTypesError.value = null;
|
||||
} catch (err) {
|
||||
eventTypesError.value = (err as Error).message || String(err);
|
||||
}
|
||||
}
|
||||
|
||||
function copyRule(rule: Rule): Rule {
|
||||
return {
|
||||
headers: (rule.headers || []).map((h) => ({ ...h })),
|
||||
payload: (rule.payload || []).map((p) => ({ ...p })),
|
||||
};
|
||||
}
|
||||
|
||||
function open(next: Draft): void {
|
||||
saveError.value = null;
|
||||
draft.value = next;
|
||||
}
|
||||
|
||||
export function nameProposal(p: Proposal): void {
|
||||
const sample = captures.value.find((c) => String(c.id) === p.sample_id);
|
||||
open({
|
||||
mode: "proposal",
|
||||
id: null,
|
||||
source: p.source,
|
||||
name: "",
|
||||
rule: copyRule(p.rule),
|
||||
headersText: "",
|
||||
body: sample?.body || "",
|
||||
exampleHeaders: p.headers || {},
|
||||
});
|
||||
}
|
||||
|
||||
export function pasteExample(source = ""): void {
|
||||
open({ mode: "paste", id: null, source, name: "", rule: { headers: [], payload: [] }, headersText: "", body: "", exampleHeaders: {} });
|
||||
}
|
||||
|
||||
export function editEventType(t: EventType): void {
|
||||
open({ mode: "edit", id: t.id, source: t.source, name: t.name, rule: copyRule(t.rule), headersText: "", body: "", exampleHeaders: {} });
|
||||
}
|
||||
|
||||
export function closeDraft(): void {
|
||||
draft.value = null;
|
||||
}
|
||||
|
||||
export async function saveDraft(): Promise<void> {
|
||||
const d = draft.value;
|
||||
if (!d) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
if (d.mode === "edit" && d.id) {
|
||||
await api.eventTypeUpdate(d.id, { name: d.name, rule: cleanRule(d.rule) });
|
||||
} else {
|
||||
const headers = d.mode === "paste" ? parseHeaderLines(d.headersText) : d.exampleHeaders;
|
||||
await api.eventTypeCreate({
|
||||
source: d.source,
|
||||
name: d.name,
|
||||
// A pasted example's rule is inferred by the server from what was pasted.
|
||||
rule: d.mode === "paste" ? undefined : cleanRule(d.rule),
|
||||
example: { headers, body: d.body },
|
||||
});
|
||||
}
|
||||
draft.value = null;
|
||||
await loadEventTypes();
|
||||
} catch (err) {
|
||||
saveError.value = (err as Error).message || String(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The type awaiting a delete confirmation: its events become unidentified. */
|
||||
export const pendingDelete = ref<EventType | null>(null);
|
||||
|
||||
export async function confirmDelete(): Promise<void> {
|
||||
const t = pendingDelete.value;
|
||||
pendingDelete.value = null;
|
||||
if (!t) return;
|
||||
try {
|
||||
await api.eventTypeDelete(t.id);
|
||||
await loadEventTypes();
|
||||
} catch (err) {
|
||||
eventTypesError.value = (err as Error).message || String(err);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Event types as the inspector reads them (docs/prds/event-automation.md,
|
||||
* "Event types"). Pure: no Vue, so the rules here are tested without a DOM.
|
||||
*/
|
||||
|
||||
export interface HeaderCondition {
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface PayloadCondition {
|
||||
path: string;
|
||||
op: "equals" | "present";
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export interface Rule {
|
||||
headers: HeaderCondition[] | null;
|
||||
payload: PayloadCondition[] | null;
|
||||
}
|
||||
|
||||
export interface EventType {
|
||||
id: string;
|
||||
source: string;
|
||||
name: string;
|
||||
rule: Rule;
|
||||
schema?: Record<string, string> | null;
|
||||
}
|
||||
|
||||
export interface Proposal {
|
||||
source: string;
|
||||
key: string;
|
||||
schema: Record<string, string> | null;
|
||||
headers: Record<string, string> | null;
|
||||
count: number;
|
||||
sample_id: string;
|
||||
rule: Rule;
|
||||
}
|
||||
|
||||
/** parseHeaderLines reads pasted "Name: value" lines; anything else is skipped. */
|
||||
export function parseHeaderLines(text: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const line of text.split("\n")) {
|
||||
const at = line.indexOf(":");
|
||||
if (at <= 0) continue;
|
||||
const name = line.slice(0, at).trim();
|
||||
if (name) out[name] = line.slice(at + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** captureIdentity names what a capture was identified as when it arrived. */
|
||||
export function captureIdentity(
|
||||
capture: { id: unknown; event_type?: string },
|
||||
types: EventType[],
|
||||
): { label: string; identified: boolean } {
|
||||
if (!capture.event_type) return { label: "Unidentified", identified: false };
|
||||
const found = types.find((t) => t.id === capture.event_type);
|
||||
return { label: found ? found.name : "Deleted type", identified: true };
|
||||
}
|
||||
|
||||
/** ruleSummary renders a rule as one line of its conditions. */
|
||||
export function ruleSummary(rule: Rule): string {
|
||||
const parts = [
|
||||
...(rule.headers || []).map((h) => `${h.name} = ${h.value}`),
|
||||
...(rule.payload || []).map((p) => (p.op === "present" ? `${p.path} present` : `${p.path} = ${p.value ?? ""}`)),
|
||||
];
|
||||
return parts.length ? parts.join(" · ") : "any event";
|
||||
}
|
||||
|
||||
/** cleanRule drops the editor's blank rows, and a present condition's value. */
|
||||
export function cleanRule(rule: Rule): Rule {
|
||||
return {
|
||||
headers: (rule.headers || []).filter((h) => h.name.trim() !== "").map((h) => ({ name: h.name.trim(), value: h.value })),
|
||||
payload: (rule.payload || [])
|
||||
.filter((p) => p.path.trim() !== "")
|
||||
.map((p) => (p.op === "present" ? { path: p.path.trim(), op: p.op } : { path: p.path.trim(), op: p.op, value: p.value ?? "" })),
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { ref } from "vue";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
import { useLiveResource } from "@/stores/live-updates";
|
||||
import { loadEventTypes } from "./event-type-state";
|
||||
|
||||
/**
|
||||
* The event inspector's shared state.
|
||||
@@ -25,6 +26,8 @@ export interface Capture {
|
||||
headers?: string;
|
||||
body?: string;
|
||||
authenticated?: boolean;
|
||||
/** The event type it was identified as on arrival; empty is unidentified. */
|
||||
event_type?: string;
|
||||
}
|
||||
|
||||
interface CapturesResponse {
|
||||
@@ -92,5 +95,8 @@ export function selectNewest(): void {
|
||||
* The initial read belongs to the page, which has to await it before it can
|
||||
* restore a selection from the address bar. */
|
||||
export function useCaptures(): void {
|
||||
useLiveResource("captures", () => void load());
|
||||
useLiveResource("captures", () => {
|
||||
void load();
|
||||
void loadEventTypes();
|
||||
});
|
||||
}
|
||||
@@ -157,6 +157,11 @@ export const api = {
|
||||
updateInstall: <T = unknown>(snapshot: unknown) =>
|
||||
request<T>("/api/chat/update/install", { method: "POST", body: { snapshot }, timeoutMs: 15 * 60_000 }),
|
||||
captures: <T = unknown>(limit?: number) => request<T>("/api/captures" + qs({ limit })),
|
||||
eventTypes: <T = unknown>() => request<T>("/api/event-types"),
|
||||
eventTypeCreate: <T = unknown>(eventType: Payload) => request<T>("/api/event-types", { method: "POST", body: eventType }),
|
||||
eventTypeUpdate: <T = unknown>(id: string, eventType: Payload) =>
|
||||
request<T>(`/api/event-types/${encodeURIComponent(id)}`, { method: "PUT", body: eventType }),
|
||||
eventTypeDelete: (id: string) => request<void>(`/api/event-types/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
|
||||
mappings: <T = unknown>() => request<T>("/api/mappings"),
|
||||
mappingCreate: <T = unknown>(mapping: Payload) => request<T>("/api/mappings", { method: "POST", body: mapping }),
|
||||
mappingUpdate: <T = unknown>(id: string, mapping: Payload) =>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const { captureIdentity, cleanRule, parseHeaderLines, ruleSummary } = await import("../src/captures/event-types.ts");
|
||||
|
||||
test("pasted header lines become a name-to-value map", () => {
|
||||
assert.deepEqual(parseHeaderLines("X-GitHub-Event: pull_request\n\nContent-Type: application/json; charset=utf-8\nnot a header"), {
|
||||
"X-GitHub-Event": "pull_request",
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
});
|
||||
assert.deepEqual(parseHeaderLines(""), {});
|
||||
});
|
||||
|
||||
test("a capture reads as its type's name, as unidentified, or as a type since deleted", () => {
|
||||
const types = [{ id: "et1", source: "gh", name: "push", rule: { headers: [], payload: [] } }];
|
||||
assert.deepEqual(captureIdentity({ id: 1, event_type: "et1" }, types), { label: "push", identified: true });
|
||||
assert.deepEqual(captureIdentity({ id: 2, event_type: "" }, types), { label: "Unidentified", identified: false });
|
||||
assert.deepEqual(captureIdentity({ id: 3 }, types), { label: "Unidentified", identified: false });
|
||||
assert.deepEqual(captureIdentity({ id: 4, event_type: "gone" }, types), { label: "Deleted type", identified: true });
|
||||
});
|
||||
|
||||
test("a rule reads as its conditions joined", () => {
|
||||
assert.equal(
|
||||
ruleSummary({
|
||||
headers: [{ name: "x-github-event", value: "push" }],
|
||||
payload: [
|
||||
{ path: "action", op: "equals", value: "opened" },
|
||||
{ path: "sender", op: "present" },
|
||||
],
|
||||
}),
|
||||
"x-github-event = push · action = opened · sender present",
|
||||
);
|
||||
assert.equal(ruleSummary({ headers: [], payload: [] }), "any event");
|
||||
assert.equal(ruleSummary({ headers: null, payload: null }), "any event");
|
||||
});
|
||||
|
||||
test("blank editor rows are dropped before a rule is saved", () => {
|
||||
assert.deepEqual(
|
||||
cleanRule({
|
||||
headers: [{ name: " ", value: "x" }, { name: "X-A", value: "1" }],
|
||||
payload: [
|
||||
{ path: "", op: "present" },
|
||||
{ path: "a", op: "present", value: "stale" },
|
||||
{ path: "b", op: "equals", value: "2" },
|
||||
],
|
||||
}),
|
||||
{
|
||||
headers: [{ name: "X-A", value: "1" }],
|
||||
payload: [
|
||||
{ path: "a", op: "present" },
|
||||
{ path: "b", op: "equals", value: "2" },
|
||||
],
|
||||
},
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user