smplkit

package module
v3.0.3 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: MIT Imports: 29 Imported by: 0

README

smplkit Go SDK

Go Reference Build Coverage License Docs

The official Go SDK for smplkit — simple application infrastructure that just works.

Installation

go get github.com/smplkit/go-sdk/v3

Requirements

  • Go 1.24+

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    smplkit "github.com/smplkit/go-sdk/v3"
)

func main() {
    ctx := context.Background()

    // API key resolved from SMPLKIT_API_KEY env var or ~/.smplkit config file.
    // Pass explicitly as the first argument to override:
    //   smplkit.NewClient("sk_api_...", "production", "my-service")
    client, err := smplkit.NewClient("", "production", "my-service")
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // ── Runtime: resolve config values ──────────────────────────────────
    // Returns the merged map for the current environment.
    values, err := client.Config().Get(ctx, "user_service")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(values["timeout"])

    // Or unmarshal directly into a typed struct.
    type ServiceConfig struct {
        Timeout int    `json:"timeout"`
        Retries int    `json:"retries"`
    }
    var cfg ServiceConfig
    if err := client.Config().GetInto(ctx, "user_service", &cfg); err != nil {
        log.Fatal(err)
    }
    fmt.Println(cfg.Timeout)

    // ── Management: CRUD operations ──────────────────────────────────────
    mgmt := client.Config().Management()

    configs, err := mgmt.List(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(len(configs))

    raw, err := mgmt.Get(ctx, "user_service")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(raw.ID)

    newConfig := mgmt.New("my_service", smplkit.WithConfigName("My Service"))
    newConfig.Items = map[string]interface{}{"timeout": 30, "retries": 3}
    if err := newConfig.Save(ctx); err != nil {
        log.Fatal(err)
    }

    if err := mgmt.Delete(ctx, "my_service"); err != nil {
        log.Fatal(err)
    }
}

Configuration

All settings are resolved from three sources, in order of precedence:

  1. Constructor arguments — highest priority, always wins.
  2. Environment variables — e.g. SMPLKIT_API_KEY, SMPLKIT_ENVIRONMENT.
  3. Configuration file (~/.smplkit) — INI-format with profile support.
  4. Defaults — built-in SDK defaults.
Configuration File

The ~/.smplkit file supports a [common] section (applied to all profiles) and named profiles:

[common]
environment = production
service = my-app

[default]
api_key = sk_api_abc123

[local]
base_domain = localhost
scheme = http
api_key = sk_api_local_xyz
environment = development
debug = true
Constructor Examples
// Use a named profile
client, err := smplkit.NewClient(smplkit.Config{Profile: "local"})

// Or configure explicitly
client, err := smplkit.NewClient(smplkit.Config{
    APIKey:      "sk_api_...",
    Environment: "production",
    Service:     "my-service",
})

For the complete configuration reference, see the Configuration Guide.

Error Handling

All SDK errors extend SmplError and support errors.Is() / errors.As():

import "errors"

config, err := client.Config().Management().Get(ctx, "nonexistent")
if err != nil {
    var notFound *smplkit.SmplNotFoundError
    if errors.As(err, &notFound) {
        fmt.Println("Not found:", notFound.Message)
    } else {
        fmt.Println("Error:", err)
    }
}
Error Cause
SmplNotFoundError HTTP 404 — resource not found
SmplConflictError HTTP 409 — conflict
SmplValidationError HTTP 422 — validation error
SmplTimeoutError Request timed out
SmplConnectionError Network connectivity issue
SmplError Any other SDK error

Feature Flags

The SDK includes a full-featured feature flags client with management API, prescriptive runtime evaluation, and real-time updates.

Management API
ctx := context.Background()
mgmt := client.Flags().Management()

// Create a flag using typed factories
flag := mgmt.NewBooleanFlag("checkout-v2", false,
    smplkit.WithFlagName("Checkout V2"),
    smplkit.WithFlagDescription("Controls rollout of the new checkout experience."),
)
if err := flag.Save(ctx); err != nil {
    log.Fatal(err)
}

// Configure environments and rules, then save again
flag.SetEnvironmentEnabled("staging", true)
flag.AddRule(smplkit.NewRule("Enable for enterprise").
    Environment("staging").
    When("user.plan", "==", "enterprise").
    Serve(true).
    Build())
if err := flag.Save(ctx); err != nil {
    log.Fatal(err)
}

// List, get, delete
allFlags, _ := mgmt.List(ctx)
fetched, _ := mgmt.Get(ctx, "checkout-v2")
_ = allFlags
_ = fetched
err := mgmt.Delete(ctx, "checkout-v2")
Runtime Evaluation
// Define typed flag handles
checkout := flags.BoolFlag("checkout-v2", false)
banner   := flags.StringFlag("banner-color", "red")
retries  := flags.NumberFlag("max-retries", 3)

// Register a context provider
flags.SetContextProvider(func(ctx context.Context) []smplkit.Context {
    return []smplkit.Context{
        smplkit.NewContext("user", "user-42", map[string]interface{}{
            "plan": "enterprise",
        }),
    }
})

// Connect to an environment
err := flags.Connect(ctx, "staging")

// Evaluate — uses provider context, caches results
isV2 := checkout.Get(ctx)            // true (rule matched)
color := banner.Get(ctx)             // "blue"

// Explicit context override
basicUser := smplkit.NewContext("user", "u-1", map[string]interface{}{"plan": "free"})
isV2 = checkout.Get(ctx, basicUser)  // false

// Change listeners
flags.OnChange(func(evt *smplkit.FlagChangeEvent) {
    fmt.Println("flag changed:", evt.Key)
})

// Cache stats
stats := flags.Stats()
fmt.Printf("hits=%d misses=%d\n", stats.CacheHits, stats.CacheMisses)

// Cleanup
flags.Disconnect(ctx)
Flag Types
Constant Value
FlagTypeBoolean "BOOLEAN"
FlagTypeString "STRING"
FlagTypeNumeric "NUMERIC"
FlagTypeJSON "JSON"

Debug Logging

Set SMPLKIT_DEBUG=1 to enable verbose diagnostic output to stderr. This is useful for troubleshooting real-time level changes, WebSocket connectivity, and SDK initialization. Debug output bypasses the managed logging framework and writes directly to stderr.

SMPLKIT_DEBUG=1 ./my-app

Accepted values: 1, true, yes (case-insensitive). Any other value (or unset) disables debug output.

Documentation

License

MIT

Documentation

Overview

Package smplkit provides a Go client for the smplkit platform.

Quick start:

client, err := smplkit.NewClient(smplkit.Config{
    APIKey:      "sk_api_...",
    Environment: "production",
    Service:     "my-service",
})
cfg, err := client.Config().Get(ctx, "my-service")
if err != nil {
    var notFound *smplkit.NotFoundError
    if errors.As(err, &notFound) {
        // handle not found
    }
    return err
}
fmt.Println(cfg.Name)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NormalizeLoggerName

func NormalizeLoggerName(name string) string

NormalizeLoggerName normalizes a logger name to the canonical dot-separated, lowercase form. For example: "myapp/database:queries" becomes "myapp.database.queries".

Types

type AccountSettings

type AccountSettings struct {
	// Raw is the full settings map. Mutations here are persisted on Save.
	Raw map[string]interface{}
	// contains filtered or unexported fields
}

AccountSettings holds per-account configuration. The wire format is an opaque JSON object; documented keys are exposed as typed accessors, and all keys (known and unknown) are preserved in Raw. Mutate via the setters and call Save(ctx) to persist.

func (*AccountSettings) EnvironmentOrder

func (s *AccountSettings) EnvironmentOrder() []string

EnvironmentOrder returns the canonical ordering of STANDARD environments. Returns nil if not set.

func (*AccountSettings) Save

func (s *AccountSettings) Save(ctx context.Context) error

Save writes the full settings object back to the server.

func (*AccountSettings) SetEnvironmentOrder

func (s *AccountSettings) SetEnvironmentOrder(order []string)

SetEnvironmentOrder sets the canonical ordering of STANDARD environments.

type AccountSettingsManagement

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

AccountSettingsManagement provides get/save for account-level settings. Obtain one via ManagementClient.AccountSettings().

func (*AccountSettingsManagement) Get

Get retrieves the current account settings.

type ApiErrorDetail

type ApiErrorDetail struct {
	Status string      `json:"status,omitempty"`
	Title  string      `json:"title,omitempty"`
	Detail string      `json:"detail,omitempty"`
	Source ErrorSource `json:"source,omitempty"`
}

ApiErrorDetail holds a single JSON:API error object as surfaced by the smplkit platform's JSON:API responses. Mirrors Python's ApiErrorDetail.

type BooleanFlagHandle

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

BooleanFlagHandle is a typed handle for a boolean flag.

func (*BooleanFlagHandle) Get

func (h *BooleanFlagHandle) Get(ctx context.Context, contexts ...Context) bool

Get evaluates the flag and returns a typed boolean value.

func (*BooleanFlagHandle) OnChange

func (h *BooleanFlagHandle) OnChange(cb func(*FlagChangeEvent))

OnChange registers a flag-specific change listener.

type ChangeListenerOption

type ChangeListenerOption func(*changeListenerConfig)

ChangeListenerOption configures an OnChange listener.

func WithConfigID

func WithConfigID(id string) ChangeListenerOption

WithConfigID restricts the listener to changes in the given config.

func WithItemKey

func WithItemKey(key string) ChangeListenerOption

WithItemKey restricts the listener to changes of the given item key.

type Client

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

Client is the top-level entry point for the smplkit SDK.

Create one with NewClient and access sub-clients via accessor methods:

client, err := smplkit.NewClient(smplkit.Config{APIKey: "sk_api_...", Environment: "production", Service: "my-service"})
cfgs, err := client.Config().Management().List(ctx)

func NewClient

func NewClient(cfg Config, opts ...ClientOption) (*Client, error)

NewClient creates a new smplkit API client.

Configuration is resolved from four layers (later layers override earlier ones):

  1. Defaults (scheme=https, baseDomain=smplkit.com)
  2. Config file (~/.smplkit) with [common] and profile sections
  3. Environment variables (SMPLKIT_API_KEY, SMPLKIT_ENVIRONMENT, etc.)
  4. Explicit Config struct fields

Use ClientOption functions to customize the timeout or HTTP client.

func (*Client) Close

func (c *Client) Close() error

Close releases all resources held by the client and its sub-clients.

func (*Client) Config

func (c *Client) Config() *ConfigClient

Config returns the sub-client for config management operations.

func (*Client) Environment

func (c *Client) Environment() string

Environment returns the resolved environment name.

func (*Client) Flags

func (c *Client) Flags() *FlagsClient

Flags returns the sub-client for flags management and runtime operations.

func (*Client) Logging

func (c *Client) Logging() *LoggingClient

Logging returns the sub-client for logging management and runtime operations.

func (*Client) Manage

func (c *Client) Manage() *ManagementClient

Manage returns the management-plane sub-client. Mirrors Python's SmplClient.manage attribute (rule 1).

The returned ManagementClient exposes eight flat namespaces:

client.Manage().Contexts()
client.Manage().ContextTypes()
client.Manage().Environments()
client.Manage().AccountSettings()
client.Manage().Config()
client.Manage().Flags()
client.Manage().Loggers()
client.Manage().LogGroups()

The same *ManagementClient is shared by the runtime sub-clients — client.Config().Management() returns the same instance as client.Manage().Config().

func (*Client) Management

func (c *Client) Management() *ManagementClient

Management returns the sub-client for app-service management operations (environments, context types, contexts, account settings).

func (*Client) Service

func (c *Client) Service() string

Service returns the resolved service name.

func (*Client) WaitUntilReady added in v3.0.2

func (c *Client) WaitUntilReady(ctx context.Context, timeout time.Duration) error

WaitUntilReady eagerly opens the live-updates WebSocket and blocks until the server has accepted the upgrade, validated the API key, and registered the subscription. After this returns, on-change listeners are guaranteed to receive every server event from this point forward — including events triggered by writes the caller fires immediately afterward.

Without this, code that constructs a Client and immediately calls a management write (Save / Delete / SetX+Save) can race the broadcast of the resulting change event and silently miss it: the SDK has not yet appeared in the server's subscriber registry when the broadcast runs, so the broadcast goes to zero subscribers.

timeout=0 uses the SDK default (5s). Context cancellation also returns. Mirrors Python's client.wait_until_ready() and TypeScript's client.waitUntilReady().

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures the Client. Pass options to NewClient.

func WithHTTPClient

func WithHTTPClient(c *http.Client) ClientOption

WithHTTPClient replaces the default HTTP client entirely. When set, the WithTimeout option is ignored because the caller controls the client.

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout sets the HTTP request timeout. The default is 30 seconds.

type Color

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

Color is a CSS hex color string. It is immutable: construct a fresh Color via NewColor or NewColorRGB to change a value. Mirrors the Python SDK's Color type (rule 8 of the cross-SDK overhaul).

The constructors validate their inputs at the SDK boundary so customer mistakes surface at the call site rather than as a server 400 later.

func MustColor

func MustColor(hex string) Color

MustColor is the panic-on-error variant of NewColor for compile-time constants. Customer code that builds colors from runtime input should always use NewColor and check the error.

func NewColor

func NewColor(hex string) (Color, error)

NewColor constructs a Color from a CSS hex string. Accepts #RGB, #RRGGBB, or #RRGGBBAA. Any other input returns a non-nil error.

func NewColorRGB

func NewColorRGB(r, g, b int) (Color, error)

NewColorRGB constructs a Color from 0–255 integer components. Each component is validated; out-of-range values produce a non-nil error.

func (Color) Hex

func (c Color) Hex() string

Hex returns the canonical (lowercase) CSS hex string.

func (Color) IsZero

func (c Color) IsZero() bool

IsZero reports whether c is the zero Color value (i.e. unset).

func (Color) String

func (c Color) String() string

String returns the canonical hex string, satisfying fmt.Stringer.

type Config

type Config struct {
	// Profile selects the INI profile from ~/.smplkit.
	// Falls back to SMPLKIT_PROFILE env var, then "default".
	Profile string

	// APIKey is the Bearer token for API authentication.
	// Falls back to SMPLKIT_API_KEY env var, then the config file.
	APIKey string

	// BaseDomain overrides the base domain for service URLs.
	// Default: "smplkit.com". Falls back to SMPLKIT_BASE_DOMAIN env var.
	BaseDomain string

	// Scheme overrides the URL scheme. Default: "https".
	// Falls back to SMPLKIT_SCHEME env var.
	Scheme string

	// Environment is the target environment (e.g. "production", "staging").
	// Falls back to SMPLKIT_ENVIRONMENT env var, then the config file.
	Environment string

	// Service is the service identifier.
	// Falls back to SMPLKIT_SERVICE env var, then the config file.
	Service string

	// Debug enables verbose debug output.
	// Falls back to SMPLKIT_DEBUG env var, then the config file.
	Debug bool

	// DisableTelemetry disables anonymous SDK usage telemetry.
	// Falls back to SMPLKIT_DISABLE_TELEMETRY env var, then the config file.
	DisableTelemetry bool
}

Config holds user-facing configuration for the smplkit SDK. Fields use Go zero values (empty string, false) to represent "unset". Resolution order: defaults -> config file -> env vars -> struct fields.

type ConfigChangeEvent

type ConfigChangeEvent struct {
	// ConfigID is the config ID that changed (e.g. "user_service").
	ConfigID string
	// ItemKey is the item key within the config that changed.
	ItemKey string
	// OldValue is the value before the change (nil if the key was new).
	OldValue interface{}
	// NewValue is the value after the change (nil if the key was removed).
	NewValue interface{}
	// Source is "websocket" for server-pushed changes or "manual" for Refresh calls.
	Source string
}

ConfigChangeEvent describes a single value change detected on refresh.

type ConfigClient

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

ConfigClient provides operations for config resources and resolved value access. Obtain one via Client.Config().

func (*ConfigClient) Get

func (c *ConfigClient) Get(ctx context.Context, id string) (*LiveConfig, error)

Get returns the resolved config values for the given ID. Get returns a LiveConfig — a live, dict-like, read-only proxy whose reads always reflect the latest resolved values for the given config ID. WebSocket updates are picked up automatically; there is no separate Subscribe step (rule 10 of the cross-SDK overhaul).

Mirrors Python's client.config.get(id) which returns a LiveConfigProxy. Customer code that wants a one-shot snapshot map should call .Value() (or use Snapshot for the verbatim snapshot shape).

func (*ConfigClient) GetBool

func (c *ConfigClient) GetBool(ctx context.Context, configID, itemKey string, defaultVal ...bool) (bool, error)

GetBool returns the resolved bool value for (configID, itemKey).

func (*ConfigClient) GetInt

func (c *ConfigClient) GetInt(ctx context.Context, configID, itemKey string, defaultVal ...int) (int, error)

GetInt returns the resolved int value for (configID, itemKey).

func (*ConfigClient) GetInto

func (c *ConfigClient) GetInto(ctx context.Context, id string, target interface{}) error

GetInto resolves the config and unmarshals it into the target struct. The target must be a pointer to a struct. Dot-notation keys (e.g. "database.host") are expanded into nested structures before unmarshaling.

func (*ConfigClient) GetString

func (c *ConfigClient) GetString(ctx context.Context, configID, itemKey string, defaultVal ...string) (string, error)

GetString returns the resolved string value for (configID, itemKey).

func (*ConfigClient) GetValue

func (c *ConfigClient) GetValue(ctx context.Context, configID string, itemKey ...string) (interface{}, error)

GetValue reads a resolved config value.

func (*ConfigClient) Management

func (c *ConfigClient) Management() *ConfigManagement

Management returns the sub-object for config CRUD operations.

Returns the same *ConfigManagement instance that client.Manage().Config() returns — runtime and management surfaces share one management object.

func (*ConfigClient) OnChange

func (c *ConfigClient) OnChange(cb func(*ConfigChangeEvent), opts ...ChangeListenerOption)

OnChange registers a listener that fires when a config value changes (on Refresh). Use WithConfigID and/or WithItemKey to scope the listener.

func (*ConfigClient) Refresh

func (c *ConfigClient) Refresh(ctx context.Context) error

Refresh re-fetches all configs and resolves current values. OnChange listeners fire for any values that changed.

func (*ConfigClient) Snapshot

func (c *ConfigClient) Snapshot(ctx context.Context, id string) (map[string]interface{}, error)

Snapshot returns a one-shot copy of the resolved values for the given config ID. Use Get to receive a live proxy that always reflects the latest values without re-fetching.

func (*ConfigClient) Subscribe deprecated

func (c *ConfigClient) Subscribe(ctx context.Context, id string) (*LiveConfig, error)

Subscribe is a deprecated alias for Get.

Deprecated: Use Get — it now returns the same LiveConfig proxy that Subscribe used to provide. The Python SDK collapsed the two methods into one for the same reason (rule 10).

type ConfigEntry

type ConfigEntry struct {
	// ID is the config identifier (e.g. "user_service").
	ID string
	// Name is the display name for the config.
	Name string
	// Description is an optional description of the config.
	Description *string
	// Parent is the parent config ID, or nil for root configs.
	Parent *string
	// Items holds the base configuration values.
	Items map[string]interface{}
	// Environments maps environment names to their value overrides.
	Environments map[string]map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Config represents a configuration resource from the smplkit platform.

func (*ConfigEntry) Delete

func (c *ConfigEntry) Delete(ctx context.Context) error

Delete removes the config from the server. Equivalent to mgmt.Config().Delete(ctx, c.ID).

func (*ConfigEntry) Remove

func (c *ConfigEntry) Remove(name, environment string)

Remove removes an item. environment="" removes from base; non-empty removes the per-env override only.

func (*ConfigEntry) Save

func (c *ConfigEntry) Save(ctx context.Context) error

Save persists the config to the server. The Config instance is updated with the server response.

func (*ConfigEntry) SetBoolean

func (c *ConfigEntry) SetBoolean(name string, value bool, environment string)

SetBoolean sets a boolean item.

func (*ConfigEntry) SetJSON

func (c *ConfigEntry) SetJSON(name string, value interface{}, environment string)

SetJSON sets a JSON item.

func (*ConfigEntry) SetNumber

func (c *ConfigEntry) SetNumber(name string, value float64, environment string)

SetNumber sets a numeric item.

func (*ConfigEntry) SetString

func (c *ConfigEntry) SetString(name, value, environment string)

SetString sets a string item. environment="" updates the base item; non-empty scopes to that environment.

func (*ConfigEntry) TypedEnvironments

func (c *ConfigEntry) TypedEnvironments() map[string]ConfigEnvironment

TypedEnvironments returns a typed, read-only view of per-environment item overrides on a ConfigEntry.

type ConfigEnvironment

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

ConfigEnvironment is the per-environment configuration on a Config. Frozen — mutate via Config.SetString / SetNumber / SetBoolean / SetJSON / Remove with an environment kwarg.

Mirrors Python's smplkit.config.models.ConfigEnvironment.

func NewConfigEnvironment

func NewConfigEnvironment(values map[string]interface{}) ConfigEnvironment

NewConfigEnvironment constructs a ConfigEnvironment. Used by the SDK when parsing server responses.

func (ConfigEnvironment) Values

func (e ConfigEnvironment) Values() map[string]interface{}

Values returns a defensive copy of the per-env value overrides.

type ConfigManagement

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

ConfigManagement provides CRUD operations for config resources. Obtain one via Client.Manage().Config() or ConfigClient.Management().

The struct owns its generated API client directly; the optional runtime back-reference is set only when ConfigManagement is wired into a runtime Client so active-record Save/Delete can refresh the runtime resolved-config cache.

func (*ConfigManagement) Delete

func (m *ConfigManagement) Delete(ctx context.Context, id string) error

Delete removes a config by its ID.

func (*ConfigManagement) Get

Get retrieves a config by its ID. Returns NotFoundError if no match.

func (*ConfigManagement) List

func (m *ConfigManagement) List(ctx context.Context) ([]*ConfigEntry, error)

List returns all configs for the account.

func (*ConfigManagement) New

func (m *ConfigManagement) New(id string, opts ...ConfigOption) *ConfigEntry

New creates an unsaved ConfigEntry with the given ID. Call Save(ctx) to persist. If name is not provided via WithConfigName, it is auto-generated from the ID.

type ConfigOption

type ConfigOption func(*ConfigEntry)

ConfigOption configures an unsaved Config returned by ConfigClient.New.

func WithConfigDescription

func WithConfigDescription(desc string) ConfigOption

WithConfigDescription sets the description for a config.

func WithConfigEnvironments

func WithConfigEnvironments(envs map[string]map[string]interface{}) ConfigOption

WithConfigEnvironments sets the environment-specific overrides for a config.

func WithConfigItems

func WithConfigItems(items map[string]interface{}) ConfigOption

WithConfigItems sets the base configuration values for a config.

func WithConfigName

func WithConfigName(name string) ConfigOption

WithConfigName sets the display name for a config.

func WithConfigParent

func WithConfigParent(parentID string) ConfigOption

WithConfigParent sets the parent config UUID for inheritance.

type ConflictError

type ConflictError struct {
	Base Error
}

ConflictError is raised when an operation conflicts with current resource state.

func (*ConflictError) Error

func (e *ConflictError) Error() string

Error implements the error interface.

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type ConnectionError

type ConnectionError struct {
	Base Error
}

ConnectionError is raised when a network request fails.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error implements the error interface.

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type Context

type Context struct {
	// Type is the context type (e.g. "user", "account").
	Type string
	// Key is the unique identifier for this entity.
	Key string
	// Name is an optional display name.
	Name string
	// Attributes holds arbitrary key-value data for rule evaluation.
	Attributes map[string]interface{}
}

Context represents a typed evaluation context entity.

Each Context identifies an entity (user, account, device, etc.) by type and key, with optional attributes that JSON Logic rules can target.

ctx := smplkit.NewContext("user", "user-123", map[string]any{
    "plan": "enterprise",
    "firstName": "Alice",
})

Identity locking note (rule 9): Python's Context locks `type` and `key` after the entity has been persisted. Go's idiom of exported struct fields makes that lock unenforceable at compile time — `ctx.Type = "X"` is always allowed by the language. Customer code that wants identity-locking semantics should treat persisted Contexts (those returned by mgmt.Contexts().Get / List) as read-only and construct fresh ones via NewContext for new entities. The compile-time-checkable equivalent in Python (TypeError on non-string args) is enforced here by the type system; the runtime "must not be empty" check is enforced by NewContext which panics on empty inputs.

func NewContext

func NewContext(contextType, key string, attrs map[string]interface{}, opts ...ContextOption) Context

NewContext creates a new evaluation context. The optional attrs map provides attributes for JSON Logic rule evaluation. Use WithName to set a display name, or WithAttr to add individual attributes.

// Using a map:
ctx := smplkit.NewContext("user", "user-123", map[string]any{"plan": "enterprise"})

// Using functional options:
ctx := smplkit.NewContext("user", "user-123", nil,
    smplkit.WithName("Alice"),
    smplkit.WithAttr("plan", "enterprise"),
)

Fail-fast validation (rule 6 of the cross-SDK overhaul): empty type or key panics with a clear message. The Python SDK raises TypeError for non-string args; in Go the type system enforces that, so we only need to enforce non-emptiness. Numeric IDs must be stringified at the SDK boundary — silent normalization weakens the contract.

func (Context) CompositeID

func (c Context) CompositeID() string

CompositeID returns the composite "type:key" identifier mirroring Python's Context.id property. Useful when calling sub-clients that accept either a composite id or separate (type, key) arguments.

type ContextEntity

type ContextEntity struct {
	// ContextType is the context type key (e.g. "user").
	ContextType string
	// Key is the entity's unique identifier within its type.
	Key string
	// Name is an optional display name.
	Name *string
	// Attributes holds arbitrary attribute data.
	Attributes map[string]interface{}
	// CreatedAt is the server creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

ContextEntity is the active-record model returned by ContextsManagement.List / Get. Mutate Attributes (or Name) and call Save(ctx) to persist; call Delete(ctx) to remove.

Mirrors Python's smplkit.Context active-record model (rule 3). The builder-style smplkit.Context (in flags_types.go) remains the canonical input type for flag evaluation; this struct is the management-side read/write model with a back-reference to its parent client.

func (*ContextEntity) CompositeID

func (ce *ContextEntity) CompositeID() string

CompositeID returns the composite "type:key" identifier.

func (*ContextEntity) Delete

func (ce *ContextEntity) Delete(ctx context.Context) error

Delete removes this context entity from the server. Equivalent to mgmt.Contexts().Delete(ctx, ce.ContextType, ce.Key).

func (*ContextEntity) Save

func (ce *ContextEntity) Save(ctx context.Context) error

Save persists the context entity to the server. The instance is updated with server-returned fields on success.

type ContextOption

type ContextOption func(*Context)

ContextOption configures a Context. Use WithName and WithAttr.

func WithAttr

func WithAttr(key string, value interface{}) ContextOption

WithAttr adds a single attribute to a Context.

func WithName

func WithName(name string) ContextOption

WithName sets the display name on a Context.

type ContextType

type ContextType struct {
	// ID is the context type identifier (e.g. "user", "account").
	ID string
	// Name is the display name.
	Name string
	// Attributes maps attribute names to their metadata dicts.
	Attributes map[string]map[string]interface{}
	// CreatedAt is the server creation timestamp (nil for unsaved instances).
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

ContextType represents a context-type resource on the smplkit platform. Mutate Attributes via AddAttribute / RemoveAttribute / UpdateAttribute, then call Save(ctx) to persist.

func (*ContextType) AddAttribute

func (ct *ContextType) AddAttribute(name string, meta ...map[string]interface{})

AddAttribute adds (or replaces) an attribute slot with the given metadata. Call Save(ctx) to persist.

func (*ContextType) RemoveAttribute

func (ct *ContextType) RemoveAttribute(name string)

RemoveAttribute removes an attribute slot. Call Save(ctx) to persist.

func (*ContextType) Save

func (ct *ContextType) Save(ctx context.Context) error

Save creates or updates the context type on the server. Creates if CreatedAt is nil, otherwise updates.

func (*ContextType) UpdateAttribute

func (ct *ContextType) UpdateAttribute(name string, meta map[string]interface{})

UpdateAttribute replaces an attribute slot's metadata. Call Save(ctx) to persist.

type ContextTypeOption

type ContextTypeOption func(*ContextType)

ContextTypeOption configures an unsaved ContextType returned by ContextTypesManagement.New.

func WithContextTypeName

func WithContextTypeName(name string) ContextTypeOption

WithContextTypeName sets the display name for a context type.

type ContextTypesManagement

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

ContextTypesManagement provides CRUD operations for context type resources. Obtain one via ManagementClient.ContextTypes().

func (*ContextTypesManagement) Delete

func (m *ContextTypesManagement) Delete(ctx context.Context, id string) error

Delete removes a context type by ID.

func (*ContextTypesManagement) Get

Get retrieves a single context type by ID.

func (*ContextTypesManagement) List

List returns all context types for the account.

func (*ContextTypesManagement) New

New returns an unsaved ContextType. Call ct.Save(ctx) to persist. If no name option is provided the ID is used as the display name.

type ContextsManagement

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

ContextsManagement provides context registration, listing, and deletion. Obtain one via ManagementClient.Contexts().

func (*ContextsManagement) Delete

func (m *ContextsManagement) Delete(ctx context.Context, parts ...string) error

Delete removes a context by its composite "type:key" id, or by separate type and key arguments.

func (*ContextsManagement) Flush

func (m *ContextsManagement) Flush(ctx context.Context) error

Flush sends any pending context observations to the server immediately.

func (*ContextsManagement) Get

func (m *ContextsManagement) Get(ctx context.Context, parts ...string) (*ContextEntity, error)

Get retrieves a single context by its composite "type:key" id, or by separate type and key arguments:

management.Contexts().Get(ctx, "user:usr_123")
management.Contexts().Get(ctx, "user", "usr_123")

func (*ContextsManagement) List

func (m *ContextsManagement) List(ctx context.Context, contextType string) ([]*ContextEntity, error)

List returns all context instances of the given context type.

func (*ContextsManagement) Register

func (m *ContextsManagement) Register(ctx context.Context, contexts []Context, opts ...ContextsRegisterOption) error

Register buffers contexts for registration with the server. By default contexts are queued for background flush; use WithContextFlush() to perform an immediate synchronous flush after queuing.

type ContextsRegisterOption

type ContextsRegisterOption func(*contextsRegisterOpts)

ContextsRegisterOption configures a Register call.

func WithContextFlush

func WithContextFlush() ContextsRegisterOption

WithContextFlush causes Register to immediately flush the buffer to the server. Without this option contexts are queued for the next background flush.

type Environment

type Environment struct {
	// ID is the environment slug (e.g. "production").
	ID string
	// Name is the display name.
	Name string
	// Color is an optional hex color string for the Console UI.
	Color *string
	// Classification controls whether this environment participates in ordering.
	Classification EnvironmentClassification
	// CreatedAt is the server creation timestamp (nil for unsaved instances).
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Environment represents a smplkit environment resource. Mutate fields and call Save(ctx) to persist.

func (*Environment) Save

func (e *Environment) Save(ctx context.Context) error

Save creates or updates the environment on the server. The instance is updated with server-returned fields on success. PUT semantics: creates if CreatedAt is nil, otherwise updates.

func (*Environment) SetTypedColor

func (e *Environment) SetTypedColor(c Color)

SetTypedColor sets the environment's display color from a typed Color. A zero Color clears the color. Call Save(ctx) to persist.

func (*Environment) TypedColor

func (e *Environment) TypedColor() Color

TypedColor returns the environment's display color as a typed Color value, or a zero Color if no color is set on this environment.

Mirrors Python's Environment.color property which returns a Color instance (rule 9). The wire transports a hex string; the SDK wraps it at the boundary. A malformed hex string on the wire returns the zero Color rather than surfacing a validation error on read.

type EnvironmentClassification

type EnvironmentClassification string

EnvironmentClassification indicates whether an environment participates in the canonical environment ordering.

STANDARD environments are the customer's deploy targets — production, staging, development, etc. They participate in AccountSettings.EnvironmentOrder and appear in the standard Console environment columns.

AD_HOC environments are transient targets (preview branches, individual developer sandboxes) that should not appear in the standard ordering.

const (
	// EnvironmentClassificationStandard marks an environment as a canonical deploy target.
	EnvironmentClassificationStandard EnvironmentClassification = "STANDARD"
	// EnvironmentClassificationAdHoc marks an environment as a transient, non-ordered target.
	EnvironmentClassificationAdHoc EnvironmentClassification = "AD_HOC"
)

type EnvironmentOption

type EnvironmentOption func(*Environment)

EnvironmentOption configures an unsaved Environment returned by EnvironmentsManagement.New.

func WithEnvironmentClassification

func WithEnvironmentClassification(c EnvironmentClassification) EnvironmentOption

WithEnvironmentClassification sets the classification (STANDARD or AD_HOC).

func WithEnvironmentColor

func WithEnvironmentColor(color string) EnvironmentOption

WithEnvironmentColor sets the display color (hex string, e.g. "#ef4444").

type EnvironmentsManagement

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

EnvironmentsManagement provides CRUD operations for environment resources. Obtain one via ManagementClient.Environments().

func (*EnvironmentsManagement) Delete

func (m *EnvironmentsManagement) Delete(ctx context.Context, id string) error

Delete removes an environment by ID.

func (*EnvironmentsManagement) Get

Get retrieves a single environment by ID.

func (*EnvironmentsManagement) List

List returns all environments for the account.

func (*EnvironmentsManagement) New

New returns an unsaved Environment. Call env.Save(ctx) to persist.

type Error

type Error struct {
	// Message is a human-readable summary of the error.
	Message string
	// StatusCode holds the HTTP status code if the error came from the API.
	StatusCode int
	// ResponseBody holds the raw response body if available.
	ResponseBody string
	// Errors holds parsed JSON:API error details when available.
	Errors []ApiErrorDetail
}

Error is the base error type for all smplkit SDK errors. The flat hierarchy mirrors the Python SDK: ConnectionError, TimeoutError, NotFoundError, ConflictError, and ValidationError are direct subtypes.

To match any SDK error use errors.As against *Error:

var e *smplkit.Error
if errors.As(err, &e) { ... }

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type ErrorDetail

type ErrorDetail = ApiErrorDetail

ErrorDetail is an alias for ApiErrorDetail kept for backward compatibility. New code should use ApiErrorDetail.

type ErrorSource

type ErrorSource struct {
	Pointer string `json:"pointer,omitempty"`
}

ErrorSource identifies the source of a JSON:API error.

type Flag

type Flag struct {
	// ID is the flag identifier (e.g. "dark-mode").
	ID string
	// Name is the display name for the flag.
	Name string
	// Type is the value type (BOOLEAN, STRING, NUMERIC, JSON).
	Type string
	// Default is the default value for the flag.
	Default interface{}
	// Values is the closed set of possible values (constrained), or nil (unconstrained).
	Values *[]FlagValue
	// Description is an optional description of the flag.
	Description *string
	// Environments maps environment names to their configuration.
	Environments map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Flag represents a flag resource from the smplkit platform.

func (*Flag) AddRule

func (f *Flag) AddRule(builtRule map[string]interface{}) error

AddRule appends a rule to the specified environment. The builtRule must include an "environment" key (use NewRule(...).Environment("env").Build()). Call Save(ctx) to persist.

func (*Flag) AddValue

func (f *Flag) AddValue(name string, value interface{}) *Flag

AddValue appends a constrained value to the flag's value set. Returns f for chaining. Mirrors Python's flag.add_value.

func (*Flag) ClearDefault

func (f *Flag) ClearDefault(environment string)

ClearDefault clears the per-environment default override on the named environment. environment must be non-empty (mirrors Python's `clear_default(*, environment)` which makes the kwarg required).

Call Flag.Save(ctx) to persist.

func (*Flag) ClearRules

func (f *Flag) ClearRules(envKey string)

ClearRules removes all rules for the specified environment. Call Save(ctx) to persist.

func (*Flag) ClearRulesAll

func (f *Flag) ClearRulesAll()

ClearRulesAll clears rules in every environment configured on this flag. Mirrors Python's clear_rules(*, environment=None) with environment=None. For a single-environment clear, use the existing ClearRules(envKey).

func (*Flag) ClearValues

func (f *Flag) ClearValues()

ClearValues sets values to nil (unconstrained). Call Save(ctx) to persist.

func (*Flag) Delete

func (f *Flag) Delete(ctx context.Context) error

Delete removes the flag from the server. Equivalent to mgmt.Flags().Delete(ctx, f.ID) — provided as a convenience on the active-record model (rule 3 of the cross-SDK overhaul).

func (*Flag) DisableRules

func (f *Flag) DisableRules(environment string)

DisableRules disables rule evaluation (kill switch). environment="" disables rules in every environment configured on this flag.

func (*Flag) EnableRules

func (f *Flag) EnableRules(environment string)

EnableRules enables rule evaluation. environment="" enables rules in every environment configured on this flag; non-empty scopes to that single environment. Mirrors Python's enable_rules(*, environment=None).

func (*Flag) RemoveValue

func (f *Flag) RemoveValue(value interface{}) *Flag

RemoveValue removes the first values entry whose Value field matches. Returns f for chaining.

func (*Flag) Save

func (f *Flag) Save(ctx context.Context) error

Save persists the flag to the server. The Flag instance is updated with the server response.

func (*Flag) SetDefault

func (f *Flag) SetDefault(value interface{}, environment string)

SetDefault sets the default served value. environment="" updates the flag-level base default; environment="production" sets the per-env default. Mirrors Python's flag.set_default(value, *, environment=None).

Call Flag.Save(ctx) to persist.

func (*Flag) SetEnvironmentDefault

func (f *Flag) SetEnvironmentDefault(envKey string, defaultVal interface{})

SetEnvironmentDefault sets the environment-specific default value. Call Save(ctx) to persist.

func (*Flag) SetEnvironmentEnabled

func (f *Flag) SetEnvironmentEnabled(envKey string, enabled bool)

SetEnvironmentEnabled sets the enabled flag for an environment. Call Save(ctx) to persist.

func (*Flag) TypedEnvironments

func (f *Flag) TypedEnvironments() map[string]FlagEnvironment

TypedEnvironments returns a typed, read-only view of per-environment configuration on a Flag. Mirrors Python's flag.environments property returning dict[str, FlagEnvironment].

The returned map is a defensive copy; mutating it has no effect on the underlying flag. Mutate the flag via SetDefault / EnableRules / DisableRules / AddRule (with environment scoping) instead.

type FlagChangeEvent

type FlagChangeEvent struct {
	// ID is the flag ID that changed.
	ID string
	// Source is "websocket" or "manual".
	Source string
	// Deleted is true when the flag was deleted server-side.
	Deleted bool
}

FlagChangeEvent describes a flag definition change.

type FlagEnvironment

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

FlagEnvironment is the per-environment configuration on a Flag. Frozen. Mutate via Flag.AddRule / Flag.EnableRules / Flag.DisableRules / Flag.SetDefault / Flag.ClearRules with environment scoping.

Mirrors Python's smplkit.flags.models.FlagEnvironment.

func NewFlagEnvironment

func NewFlagEnvironment(enabled bool, defaultValue interface{}, rules []FlagRule) FlagEnvironment

NewFlagEnvironment constructs a FlagEnvironment. Used by the SDK when parsing server responses; exposed for completeness.

func (FlagEnvironment) Default

func (e FlagEnvironment) Default() interface{}

Default returns the environment-specific default override, or nil if no override is set (in which case the flag's base default applies).

func (FlagEnvironment) Enabled

func (e FlagEnvironment) Enabled() bool

Enabled reports whether the flag is active in this environment.

func (FlagEnvironment) Rules

func (e FlagEnvironment) Rules() []FlagRule

Rules returns a defensive copy of the targeting rules.

type FlagOption

type FlagOption func(*Flag)

FlagOption configures an unsaved Flag returned by factory methods.

func WithFlagDescription

func WithFlagDescription(desc string) FlagOption

WithFlagDescription sets the description for a flag.

func WithFlagName

func WithFlagName(name string) FlagOption

WithFlagName sets the display name for a flag.

func WithFlagValues

func WithFlagValues(values []FlagValue) FlagOption

WithFlagValues sets the closed value set for a flag (constrained).

type FlagRule

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

FlagRule is a single targeting rule on a Flag. Frozen — author rules via the smplkit.Rule fluent builder and pass through Flag.AddRule.

Mirrors Python's smplkit.flags.models.FlagRule.

func NewFlagRule

func NewFlagRule(logic map[string]interface{}, value interface{}, description string) FlagRule

NewFlagRule constructs a FlagRule. Customer code typically uses the Rule fluent builder; this constructor is used by the SDK when parsing server responses and exposed for completeness.

func (FlagRule) Description

func (r FlagRule) Description() string

Description returns the human-readable label, if any.

func (FlagRule) Logic

func (r FlagRule) Logic() map[string]interface{}

Logic returns a defensive copy of the JSON Logic predicate. Empty map means "always match".

func (FlagRule) Value

func (r FlagRule) Value() interface{}

Value returns the value served when Logic evaluates truthy.

type FlagStats

type FlagStats struct {
	// CacheHits is the number of evaluations served from cache.
	CacheHits int
	// CacheMisses is the number of evaluations that required computation.
	CacheMisses int
}

FlagStats holds runtime statistics for the flags subsystem.

type FlagType

type FlagType string

FlagType represents the value type of a flag.

const (
	// FlagTypeBoolean represents a boolean flag.
	FlagTypeBoolean FlagType = "BOOLEAN"
	// FlagTypeString represents a string flag.
	FlagTypeString FlagType = "STRING"
	// FlagTypeNumeric represents a numeric flag.
	FlagTypeNumeric FlagType = "NUMERIC"
	// FlagTypeJSON represents a JSON flag.
	FlagTypeJSON FlagType = "JSON"
)

type FlagValue

type FlagValue struct {
	Name  string
	Value interface{}
}

FlagValue represents a named value in a flag's value set.

type FlagsClient

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

FlagsClient provides management and runtime operations for flag resources. Obtain one via Client.Flags().

func (*FlagsClient) BooleanFlag

func (c *FlagsClient) BooleanFlag(key string, defaultValue bool) *BooleanFlagHandle

BooleanFlag returns a typed handle for a boolean flag.

func (*FlagsClient) ConnectionStatus

func (c *FlagsClient) ConnectionStatus() string

ConnectionStatus returns the current real-time connection status.

func (*FlagsClient) Disconnect

func (c *FlagsClient) Disconnect(ctx context.Context)

Disconnect stops real-time updates and releases runtime resources.

func (*FlagsClient) Evaluate

func (c *FlagsClient) Evaluate(ctx context.Context, key string, environment string, contexts []Context) interface{}

Evaluate evaluates a flag with the given environment and contexts.

func (*FlagsClient) JsonFlag

func (c *FlagsClient) JsonFlag(key string, defaultValue map[string]interface{}) *JsonFlagHandle

JsonFlag returns a typed handle for a JSON flag.

func (*FlagsClient) Management

func (c *FlagsClient) Management() *FlagsManagement

Management returns the sub-object for flag CRUD operations.

func (*FlagsClient) NumberFlag

func (c *FlagsClient) NumberFlag(key string, defaultValue float64) *NumberFlagHandle

NumberFlag returns a typed handle for a numeric flag.

func (*FlagsClient) OnChange

func (c *FlagsClient) OnChange(cb func(*FlagChangeEvent))

OnChange registers a global change listener that fires for any flag change.

func (*FlagsClient) OnChangeKey

func (c *FlagsClient) OnChangeKey(key string, cb func(*FlagChangeEvent))

OnChangeKey registers a key-scoped change listener that fires only when the specified flag key changes.

func (*FlagsClient) Refresh

func (c *FlagsClient) Refresh(ctx context.Context) error

Refresh fetches the latest flag definitions from the server.

func (*FlagsClient) SetContextProvider

func (c *FlagsClient) SetContextProvider(fn func(ctx context.Context) []Context)

SetContextProvider registers a function that provides evaluation contexts.

func (*FlagsClient) Stats

func (c *FlagsClient) Stats() FlagStats

Stats returns runtime statistics.

func (*FlagsClient) StringFlag

func (c *FlagsClient) StringFlag(key string, defaultValue string) *StringFlagHandle

StringFlag returns a typed handle for a string flag.

type FlagsManagement

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

FlagsManagement provides CRUD operations for flag resources. Obtain one via Client.Manage().Flags() or FlagsClient.Management().

Owns its generated API client directly (no runtime-skeleton dependency); the optional runtime back-reference is set only when wired into a runtime Client so context-type CRUD (which lives on the app service) and runtime cache invalidation work via the live FlagsClient.

func (*FlagsManagement) CreateContextType

func (m *FlagsManagement) CreateContextType(ctx context.Context, id string, name string) (*ContextType, error)

CreateContextType creates a new context type.

func (*FlagsManagement) Delete

func (m *FlagsManagement) Delete(ctx context.Context, id string) error

Delete removes a flag by its ID.

func (*FlagsManagement) DeleteContextType

func (m *FlagsManagement) DeleteContextType(ctx context.Context, ctID string) error

DeleteContextType deletes a context type by its ID.

func (*FlagsManagement) Get

func (m *FlagsManagement) Get(ctx context.Context, id string) (*Flag, error)

Get retrieves a flag by its ID. Returns NotFoundError if no match.

func (*FlagsManagement) List

func (m *FlagsManagement) List(ctx context.Context) ([]*Flag, error)

List returns all flags for the account.

func (*FlagsManagement) ListContextTypes

func (m *FlagsManagement) ListContextTypes(ctx context.Context) ([]*ContextType, error)

ListContextTypes lists all context types.

func (*FlagsManagement) ListContexts

func (m *FlagsManagement) ListContexts(ctx context.Context, contextTypeKey string) ([]map[string]interface{}, error)

ListContexts lists context instances filtered by context type key.

func (*FlagsManagement) NewBooleanFlag

func (m *FlagsManagement) NewBooleanFlag(id string, defaultValue bool, opts ...FlagOption) *Flag

NewBooleanFlag creates an unsaved boolean flag. Call Save(ctx) to persist. If name is not provided via WithFlagName, it is auto-generated from the ID.

func (*FlagsManagement) NewJsonFlag

func (m *FlagsManagement) NewJsonFlag(id string, defaultValue map[string]interface{}, opts ...FlagOption) *Flag

NewJsonFlag creates an unsaved JSON flag. Call Save(ctx) to persist.

func (*FlagsManagement) NewNumberFlag

func (m *FlagsManagement) NewNumberFlag(id string, defaultValue float64, opts ...FlagOption) *Flag

NewNumberFlag creates an unsaved numeric flag. Call Save(ctx) to persist.

func (*FlagsManagement) NewStringFlag

func (m *FlagsManagement) NewStringFlag(id string, defaultValue string, opts ...FlagOption) *Flag

NewStringFlag creates an unsaved string flag. Call Save(ctx) to persist.

func (*FlagsManagement) UpdateContextType

func (m *FlagsManagement) UpdateContextType(ctx context.Context, ctID string, attributes map[string]interface{}) (*ContextType, error)

UpdateContextType updates a context type's attributes.

type FlagsRuntime

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

FlagsRuntime holds the runtime state for the flags subsystem. Access it via FlagsClient methods like BooleanFlag, Disconnect, etc.

func (*FlagsRuntime) BooleanFlag

func (rt *FlagsRuntime) BooleanFlag(key string, defaultValue bool) *BooleanFlagHandle

BooleanFlag returns a typed handle for a boolean flag.

func (*FlagsRuntime) ConnectionStatus

func (rt *FlagsRuntime) ConnectionStatus() string

ConnectionStatus returns the current real-time connection status.

func (*FlagsRuntime) Evaluate

func (rt *FlagsRuntime) Evaluate(ctx context.Context, key string, environment string, contexts []Context) interface{}

Evaluate evaluates a flag with the given environment and contexts.

func (*FlagsRuntime) FlushContexts

func (rt *FlagsRuntime) FlushContexts(ctx context.Context)

FlushContexts sends any pending context registrations to the server immediately.

func (*FlagsRuntime) JsonFlag

func (rt *FlagsRuntime) JsonFlag(key string, defaultValue map[string]interface{}) *JsonFlagHandle

JsonFlag returns a typed handle for a JSON flag.

func (*FlagsRuntime) NumberFlag

func (rt *FlagsRuntime) NumberFlag(key string, defaultValue float64) *NumberFlagHandle

NumberFlag returns a typed handle for a numeric flag.

func (*FlagsRuntime) OnChange

func (rt *FlagsRuntime) OnChange(cb func(*FlagChangeEvent))

OnChange registers a global change listener.

func (*FlagsRuntime) OnChangeKey

func (rt *FlagsRuntime) OnChangeKey(key string, cb func(*FlagChangeEvent))

OnChangeKey registers a key-scoped change listener that fires only when the specified flag key changes.

func (*FlagsRuntime) Refresh

func (rt *FlagsRuntime) Refresh(ctx context.Context) error

Refresh fetches the latest flag definitions from the server. Change listeners fire after the refresh completes.

func (*FlagsRuntime) Register

func (rt *FlagsRuntime) Register(ctx context.Context, contexts ...Context)

Register explicitly registers context(s) with the server.

func (*FlagsRuntime) SetContextProvider

func (rt *FlagsRuntime) SetContextProvider(fn func(ctx context.Context) []Context)

SetContextProvider registers a function that provides evaluation contexts.

func (*FlagsRuntime) Stats

func (rt *FlagsRuntime) Stats() FlagStats

Stats returns runtime statistics.

func (*FlagsRuntime) StringFlag

func (rt *FlagsRuntime) StringFlag(key string, defaultValue string) *StringFlagHandle

StringFlag returns a typed handle for a string flag.

type JsonFlagHandle

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

JsonFlagHandle is a typed handle for a JSON flag.

func (*JsonFlagHandle) Get

func (h *JsonFlagHandle) Get(ctx context.Context, contexts ...Context) map[string]interface{}

Get evaluates the flag and returns a typed map value.

func (*JsonFlagHandle) OnChange

func (h *JsonFlagHandle) OnChange(cb func(*FlagChangeEvent))

OnChange registers a flag-specific change listener.

type LiveConfig

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

LiveConfig is a live, dict-like, read-only proxy for a config's resolved values. Returned by ConfigClient.Get and Subscribe. Every read goes through the client's resolved-config cache, so WebSocket updates are picked up automatically — no Subscribe step is required (rule 10 of the cross-SDK overhaul).

Customer mutation paths are absent: there is no Set / Put / Delete method on LiveConfig. To mutate configs use the management surface:

client.Manage().Config().Get(ctx, id) // active-record model with Save / Delete

func (*LiveConfig) Get

func (lc *LiveConfig) Get(key string) (interface{}, bool)

Get returns a single resolved value by key. The second return is false if the key is absent. Mirrors Python's `proxy[key]` / `proxy.get(key)` dict-like access.

func (*LiveConfig) Has

func (lc *LiveConfig) Has(key string) bool

Has reports whether a resolved value exists for the given key.

func (*LiveConfig) ID

func (lc *LiveConfig) ID() string

ID returns the config ID this proxy reads from.

func (*LiveConfig) Keys

func (lc *LiveConfig) Keys() []string

Keys returns a snapshot of the resolved key set in unspecified order.

func (*LiveConfig) Len

func (lc *LiveConfig) Len() int

Len returns the number of resolved keys.

func (*LiveConfig) OnChange

func (lc *LiveConfig) OnChange(cb func(*ConfigChangeEvent))

OnChange registers a listener that fires when any item in this config changes. Mirrors Python's `proxy.on_change(fn)` listener-form sugar (rule 11 — the proxy-scoped form of OnChange).

func (*LiveConfig) OnChangeKey

func (lc *LiveConfig) OnChangeKey(key string, cb func(*ConfigChangeEvent))

OnChangeKey registers a listener that fires only when the named item in this config changes. Mirrors `proxy.on_change(item_key=...)`.

func (*LiveConfig) Value

func (lc *LiveConfig) Value() map[string]interface{}

Value returns a defensive copy of the latest resolved values.

func (*LiveConfig) ValueInto

func (lc *LiveConfig) ValueInto(target interface{}) error

ValueInto unmarshals the latest resolved values into the target struct. The target must be a pointer to a struct. Dot-notation keys (e.g. "database.host") are expanded into nested structures before unmarshaling.

type LogGroup

type LogGroup struct {
	// ID is the log group identifier.
	ID string
	// Name is the display name for the log group.
	Name string
	// Level is the base log level (nil = inherit).
	Level *LogLevel
	// Group is the parent group ID (nil = no parent).
	Group *string
	// Environments maps environment names to their configuration.
	Environments map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

LogGroup represents a log group resource from the smplkit platform.

func (*LogGroup) ClearAllEnvironmentLevels

func (g *LogGroup) ClearAllEnvironmentLevels()

ClearAllEnvironmentLevels clears all environment-specific levels. Call Save to persist.

func (*LogGroup) ClearEnvironmentLevel

func (g *LogGroup) ClearEnvironmentLevel(env string)

ClearEnvironmentLevel clears the log level for a specific environment. Call Save to persist.

func (*LogGroup) ClearLevel

func (g *LogGroup) ClearLevel()

ClearLevel clears the base log level. Call Save to persist.

func (*LogGroup) Save

func (g *LogGroup) Save(ctx context.Context) error

Save persists the log group to the server. The LogGroup instance is updated with the server response.

func (*LogGroup) SetEnvironmentLevel

func (g *LogGroup) SetEnvironmentLevel(env string, level LogLevel)

SetEnvironmentLevel sets the log level for a specific environment. Call Save to persist.

func (*LogGroup) SetLevel

func (g *LogGroup) SetLevel(level LogLevel)

SetLevel sets the base log level. Call Save to persist.

func (*LogGroup) TypedEnvironments

func (g *LogGroup) TypedEnvironments() map[string]LoggerEnvironment

TypedEnvironments returns a typed, read-only view of per-environment configuration on a LogGroup.

type LogGroupOption

type LogGroupOption func(*LogGroup)

LogGroupOption configures an unsaved LogGroup returned by LoggingClient.NewGroup.

func WithLogGroupName

func WithLogGroupName(name string) LogGroupOption

WithLogGroupName sets the display name for a log group.

func WithLogGroupParent

func WithLogGroupParent(groupID string) LogGroupOption

WithLogGroupParent sets the parent group UUID.

type LogGroupsManagement

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

LogGroupsManagement is the mgmt.log_groups namespace — CRUD against log groups. Split from the older combined LoggingManagement to keep loggers and log groups in distinct namespaces (rule 2).

Obtain one via client.Manage().LogGroups().

func (*LogGroupsManagement) Delete

func (m *LogGroupsManagement) Delete(ctx context.Context, id string) error

Delete removes a log group by ID.

func (*LogGroupsManagement) Get

Get retrieves a log group by ID.

func (*LogGroupsManagement) List

func (m *LogGroupsManagement) List(ctx context.Context) ([]*LogGroup, error)

List returns all log groups for the account.

func (*LogGroupsManagement) New

func (m *LogGroupsManagement) New(id string, opts ...LogGroupOption) *LogGroup

New returns an unsaved LogGroup with the given ID. Call group.Save(ctx) to persist.

type LogLevel

type LogLevel string

LogLevel represents a smplkit canonical log level.

const (
	LogLevelTrace  LogLevel = "TRACE"
	LogLevelDebug  LogLevel = "DEBUG"
	LogLevelInfo   LogLevel = "INFO"
	LogLevelWarn   LogLevel = "WARN"
	LogLevelError  LogLevel = "ERROR"
	LogLevelFatal  LogLevel = "FATAL"
	LogLevelSilent LogLevel = "SILENT"
)

type Logger

type Logger struct {
	// ID is the logger identifier.
	ID string
	// Name is the display name for the logger.
	Name string
	// Level is the base log level (nil = inherit).
	Level *LogLevel
	// Group is the group ID (nil = no group).
	Group *string
	// Managed indicates whether smplkit controls this logger's level.
	Managed bool
	// Sources holds source metadata.
	Sources []map[string]interface{}
	// Environments maps environment names to their configuration.
	Environments map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Logger represents a logger resource from the smplkit platform.

func (*Logger) ClearAllEnvironmentLevels

func (l *Logger) ClearAllEnvironmentLevels()

ClearAllEnvironmentLevels clears all environment-specific levels. Call Save to persist.

func (*Logger) ClearBaseLevel deprecated

func (l *Logger) ClearBaseLevel()

ClearBaseLevel clears the logger's base level.

Deprecated: Use ClearLevel("") for the unified per-env verb.

func (*Logger) ClearEnvironmentLevel

func (l *Logger) ClearEnvironmentLevel(env string)

ClearEnvironmentLevel clears the log level for a specific environment. Call Save to persist.

func (*Logger) ClearLevel

func (l *Logger) ClearLevel(environment string)

ClearLevel clears the level. environment="" clears the logger's base level (causing it to inherit from its parent); non-empty clears the per-env override. Mirrors Python's clear_level(*, environment=None).

func (*Logger) Delete

func (l *Logger) Delete(ctx context.Context) error

Delete removes the logger from the server. Equivalent to mgmt.Loggers().Delete(ctx, l.ID).

func (*Logger) Save

func (l *Logger) Save(ctx context.Context) error

Save persists the logger to the server. PUT has upsert semantics: the server creates the logger if it does not exist. The Logger instance is updated with the server response.

func (*Logger) SetBaseLevel deprecated

func (l *Logger) SetBaseLevel(level LogLevel)

SetBaseLevel sets the logger's base level (no environment scoping).

Deprecated: Use SetLevel(level, "") for the unified per-env verb that mirrors the Python SDK's set_level(level, *, environment=None).

func (*Logger) SetEnvironmentLevel

func (l *Logger) SetEnvironmentLevel(env string, level LogLevel)

SetEnvironmentLevel sets the log level for a specific environment. Call Save to persist.

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel, environment string)

SetLevel sets the level. environment="" updates the logger's base level; non-empty scopes to that environment. Mirrors Python's logger.set_level(level, *, environment=None).

func (*Logger) TypedEnvironments

func (l *Logger) TypedEnvironments() map[string]LoggerEnvironment

TypedEnvironments returns a typed, read-only view of per-environment configuration on a Logger. Each value's Level() is a *LogLevel — nil when no override is set for that environment.

type LoggerChangeEvent

type LoggerChangeEvent struct {
	// ID is the logger ID that changed.
	ID string
	// Level is the new resolved level (nil if deleted).
	Level *LogLevel
	// Source is "websocket" or "refresh".
	Source string
	// Deleted is true when the logger was deleted server-side.
	Deleted bool
}

LoggerChangeEvent describes a logger definition change.

type LoggerEnvironment

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

LoggerEnvironment is the per-environment configuration on a Logger or LogGroup — currently just an optional level override. Frozen.

Mirrors Python's smplkit.logging.models.LoggerEnvironment.

func NewLoggerEnvironment

func NewLoggerEnvironment(level *LogLevel) LoggerEnvironment

NewLoggerEnvironment constructs a LoggerEnvironment. Used by the SDK when parsing server responses.

func (LoggerEnvironment) Level

func (e LoggerEnvironment) Level() *LogLevel

Level returns the per-env level override, or nil if no override is set (in which case inheritance applies).

type LoggerOption

type LoggerOption func(*Logger)

LoggerOption configures an unsaved Logger returned by LoggingClient.New.

func WithLoggerManaged

func WithLoggerManaged(managed bool) LoggerOption

WithLoggerManaged sets whether smplkit controls this logger's level.

func WithLoggerName

func WithLoggerName(name string) LoggerOption

WithLoggerName sets the display name for a logger.

type LoggerSource

type LoggerSource struct {
	// ID is the normalized logger name (e.g. "sqlalchemy.engine").
	ID string
	// Service overrides the client's own service name.
	// Nil means use the client's service.
	Service *string
	// Environment overrides the client's own environment.
	// Nil means use the client's environment.
	Environment *string
	// ResolvedLevel is the effective log level observed in the process.
	ResolvedLevel *LogLevel
}

LoggerSource describes a logger observed in a remote service process. Used with LoggingManagement.RegisterSources to seed source discovery data (e.g. for sample-data loading or cross-service migration) without running the actual service.

func NewLoggerSource

func NewLoggerSource(id string, opts ...LoggerSourceOption) LoggerSource

NewLoggerSource creates a LoggerSource with the given logger ID and options.

type LoggerSourceOption

type LoggerSourceOption func(*LoggerSource)

LoggerSourceOption configures a LoggerSource.

func WithLoggerSourceEnvironment

func WithLoggerSourceEnvironment(env string) LoggerSourceOption

WithLoggerSourceEnvironment sets an explicit environment for the source.

func WithLoggerSourceResolvedLevel

func WithLoggerSourceResolvedLevel(level LogLevel) LoggerSourceOption

WithLoggerSourceResolvedLevel sets the effective log level for the source.

func WithLoggerSourceService

func WithLoggerSourceService(service string) LoggerSourceOption

WithLoggerSourceService sets an explicit service name for the source.

type LoggersManagement

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

LoggersManagement is the mgmt.loggers namespace — CRUD against single loggers (no log groups). Mirrors Python's mgmt.loggers (rule 2 of the cross-SDK overhaul, where loggers and log groups live in distinct flat namespaces).

Obtain one via client.Manage().Loggers().

func (*LoggersManagement) Delete

func (m *LoggersManagement) Delete(ctx context.Context, id string) error

Delete removes a logger by ID.

func (*LoggersManagement) Get

func (m *LoggersManagement) Get(ctx context.Context, id string) (*Logger, error)

Get retrieves a logger by ID. Returns NotFoundError if no match.

func (*LoggersManagement) List

func (m *LoggersManagement) List(ctx context.Context) ([]*Logger, error)

List returns all loggers for the account.

func (*LoggersManagement) New

func (m *LoggersManagement) New(id string) *Logger

New returns an unsaved Logger with the given ID. Call logger.Save(ctx) to persist. The display name defaults to id (rule 9: drop the name kwarg when name and id would normally be identical) and managed defaults to true (every customer using the management API to create a logger is doing so to manage it).

type LoggingClient

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

LoggingClient provides management and runtime operations for logging resources. Obtain one via Client.Logging().

func (*LoggingClient) Install

func (c *LoggingClient) Install(ctx context.Context) error

Install hooks the SDK into the application's logging machinery: it runs adapter discovery, fetches managed-logger definitions from the platform, applies resolved levels, and opens the live-updates WebSocket so subsequent server-side level changes propagate.

Safe to call multiple times; only the first call takes effect. There is no companion Stop() — close the parent Client instead.

Mirrors Python's client.logging.install() (rule 4 of the cross-SDK overhaul). The pre-existing Start name is retained as a deprecated shim that simply forwards to Install.

func (*LoggingClient) Management

func (c *LoggingClient) Management() *LoggingManagement

Management returns the sub-object for logger and log group CRUD operations.

func (*LoggingClient) OnChange

func (c *LoggingClient) OnChange(cb func(*LoggerChangeEvent))

OnChange registers a global change listener that fires for any logger change.

func (*LoggingClient) OnChangeKey

func (c *LoggingClient) OnChangeKey(key string, cb func(*LoggerChangeEvent))

OnChangeKey registers a key-scoped change listener.

func (*LoggingClient) RegisterAdapter

func (c *LoggingClient) RegisterAdapter(adapter adapters.LoggingAdapter)

RegisterAdapter registers a logging adapter. Must be called before Install(). At least one adapter must be registered for runtime features to function.

func (*LoggingClient) RegisterLogger

func (c *LoggingClient) RegisterLogger(name string, level LogLevel)

RegisterLogger explicitly registers a logger name for smplkit management. Call before or after Start().

func (*LoggingClient) Start deprecated

func (c *LoggingClient) Start(ctx context.Context) error

Start is a deprecated alias for Install.

Deprecated: Use Install.

type LoggingManagement

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

LoggingManagement provides CRUD operations for logger and log group resources. Obtain one via Client.Manage().Loggers() (for the canonical split surface) or LoggingClient.Management() (for the older combined surface).

Owns its generated API client directly; the runtime back-reference is set only when wired into a runtime Client.

func (*LoggingManagement) Delete

func (m *LoggingManagement) Delete(ctx context.Context, id string) error

Delete removes a logger by its ID.

func (*LoggingManagement) DeleteGroup

func (m *LoggingManagement) DeleteGroup(ctx context.Context, id string) error

DeleteGroup removes a log group by its ID.

func (*LoggingManagement) Get

func (m *LoggingManagement) Get(ctx context.Context, id string) (*Logger, error)

Get retrieves a logger by its ID.

func (*LoggingManagement) GetGroup

func (m *LoggingManagement) GetGroup(ctx context.Context, id string) (*LogGroup, error)

GetGroup retrieves a log group by its ID.

func (*LoggingManagement) List

func (m *LoggingManagement) List(ctx context.Context) ([]*Logger, error)

List returns all loggers for the account.

func (*LoggingManagement) ListGroups

func (m *LoggingManagement) ListGroups(ctx context.Context) ([]*LogGroup, error)

ListGroups returns all log groups for the account.

func (*LoggingManagement) New

func (m *LoggingManagement) New(id string, opts ...LoggerOption) *Logger

New creates an unsaved Logger with the given ID. Call Save(ctx) to persist. If name is not provided via WithLoggerName, it is auto-generated from the ID.

func (*LoggingManagement) NewGroup

func (m *LoggingManagement) NewGroup(id string, opts ...LogGroupOption) *LogGroup

NewGroup creates an unsaved LogGroup with the given ID. Call Save(ctx) to persist.

func (*LoggingManagement) RegisterSources

func (m *LoggingManagement) RegisterSources(ctx context.Context, sources []LoggerSource) error

RegisterSources registers a batch of logger sources observed in external services. This is useful for seeding source-discovery data without running the actual service process — e.g. for sample-data loading or cross-service migration.

type ManagementClient

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

ManagementClient is the management-plane sub-client. Obtain one via Client.Manage() (or via NewManagementClient for a standalone management client with zero construction side effects — no service registration, no metrics, no websocket).

The eight flat namespaces mirror the Python SDK's SmplManagementClient:

mgmt.Contexts()         // context entity CRUD
mgmt.ContextTypes()     // context-type schemas
mgmt.Environments()     // environments
mgmt.AccountSettings()  // account-level settings
mgmt.Config()           // config CRUD (was client.Config().Management())
mgmt.Flags()            // flag CRUD (was client.Flags().Management())
mgmt.Loggers()          // logger CRUD (split from the old logging mgmt)
mgmt.LogGroups()        // log-group CRUD (split from the old logging mgmt)

func NewManagementClient

func NewManagementClient(cfg ManagementConfig, opts ...ClientOption) (*ManagementClient, error)

NewManagementClient creates a new management-only smplkit client.

Construction has zero side effects: no service registration, no metrics thread, no websocket, no logger discovery, no synchronous outbound HTTP calls. Use this client for setup scripts, CI/CD jobs, admin tools, and anywhere else the goal is CRUD against the platform — not runtime instrumentation.

Mirrors Python's SmplManagementClient (rule 1 of the cross-SDK overhaul). The Go implementation owns its sub-management surfaces directly — no runtime-Client skeleton is constructed.

func (*ManagementClient) AccountSettings

func (m *ManagementClient) AccountSettings() *AccountSettingsManagement

AccountSettings returns the sub-client for account settings get/save.

func (*ManagementClient) Close

func (m *ManagementClient) Close() error

Close releases HTTP resources held by this management client. No-op for the management client returned from a runtime Client — close the runtime Client instead so its WebSocket / metrics / context flush all unwind in order. For a standalone management client built via NewManagementClient, Close has nothing to release (the underlying http.Client is owned by net/http and pooled there) but is provided for symmetry and to give customers a clean defer point.

func (*ManagementClient) Config

func (m *ManagementClient) Config() *ConfigManagement

Config returns the sub-client for config CRUD (mgmt.config). Mirrors Python's mgmt.config namespace.

func (*ManagementClient) ContextTypes

func (m *ManagementClient) ContextTypes() *ContextTypesManagement

ContextTypes returns the sub-client for context type CRUD operations.

func (*ManagementClient) Contexts

func (m *ManagementClient) Contexts() *ContextsManagement

Contexts returns the sub-client for context registration and read/delete operations.

func (*ManagementClient) Environments

func (m *ManagementClient) Environments() *EnvironmentsManagement

Environments returns the sub-client for environment CRUD operations.

func (*ManagementClient) Flags

func (m *ManagementClient) Flags() *FlagsManagement

Flags returns the sub-client for flag CRUD (mgmt.flags).

func (*ManagementClient) LogGroups

func (m *ManagementClient) LogGroups() *LogGroupsManagement

LogGroups returns the sub-client for log-group CRUD (mgmt.log_groups).

func (*ManagementClient) Loggers

func (m *ManagementClient) Loggers() *LoggersManagement

Loggers returns the sub-client for logger CRUD (mgmt.loggers). Split from the older combined LoggingManagement so loggers and log groups live in distinct namespaces.

type ManagementConfig

type ManagementConfig struct {
	// Profile selects an INI section in ~/.smplkit (defaults to "default").
	Profile string
	// APIKey authenticates with the smplkit platform.
	APIKey string
	// BaseDomain is the base domain for API requests (default "smplkit.com").
	BaseDomain string
	// Scheme is the URL scheme (default "https").
	Scheme string
	// Debug enables debug output in the SDK.
	Debug bool
}

ManagementConfig holds the construction-time configuration for a management-only client. Mirrors smplkit.Config but drops the runtime fields (Environment, Service) that don't apply to management work.

All fields are optional. When omitted, the SDK resolves them from SMPLKIT_* environment variables or the ~/.smplkit profile.

type NotFoundError

type NotFoundError struct {
	Base Error
}

NotFoundError is raised when a requested resource does not exist.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error implements the error interface.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type NumberFlagHandle

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

NumberFlagHandle is a typed handle for a numeric flag.

func (*NumberFlagHandle) Get

func (h *NumberFlagHandle) Get(ctx context.Context, contexts ...Context) float64

Get evaluates the flag and returns a typed float64 value.

func (*NumberFlagHandle) OnChange

func (h *NumberFlagHandle) OnChange(cb func(*FlagChangeEvent))

OnChange registers a flag-specific change listener.

type Rule

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

Rule is a fluent builder for JSON Logic rule dicts.

rule := smplkit.NewRule("Enable for enterprise users").
    When("user.plan", "==", "enterprise").
    Serve(true).
    Build()

func NewRule

func NewRule(description string) *Rule

NewRule creates a new rule builder with the given description.

func (*Rule) Build

func (r *Rule) Build() map[string]interface{}

Build finalizes and returns the rule as a plain map.

Python's Rule(description, *, environment="...") makes environment a required keyword arg at construction. Go has no kwargs, so the builder permits chained Environment(...) and only validates at the AddRule boundary — Flag.AddRule rejects any rule whose Build() output has no "environment" key. The validation is one frame away from the mistake, which is acceptable for the breaking-change tradeoff of keeping NewRule single-arg.

func (*Rule) Environment

func (r *Rule) Environment(envKey string) *Rule

Environment tags this rule with an environment key (required for AddRule).

func (*Rule) Serve

func (r *Rule) Serve(value interface{}) *Rule

Serve sets the value returned when this rule matches.

func (*Rule) When

func (r *Rule) When(variable, op string, value interface{}) *Rule

When adds a condition. Multiple calls are AND'd. Supported operators: ==, !=, >, <, >=, <=, in, contains.

type SmplConflictError deprecated

type SmplConflictError = ConflictError

SmplConflictError is a deprecated alias for ConflictError.

Deprecated: Use ConflictError.

type SmplConnectionError deprecated

type SmplConnectionError = ConnectionError

SmplConnectionError is a deprecated alias for ConnectionError.

Deprecated: Use ConnectionError.

type SmplError deprecated

type SmplError = Error

SmplError is a deprecated alias for Error.

Deprecated: Use Error.

type SmplNotFoundError deprecated

type SmplNotFoundError = NotFoundError

SmplNotFoundError is a deprecated alias for NotFoundError.

Deprecated: Use NotFoundError.

type SmplTimeoutError deprecated

type SmplTimeoutError = TimeoutError

SmplTimeoutError is a deprecated alias for TimeoutError.

Deprecated: Use TimeoutError.

type SmplValidationError deprecated

type SmplValidationError = ValidationError

SmplValidationError is a deprecated alias for ValidationError.

Deprecated: Use ValidationError.

type StringFlagHandle

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

StringFlagHandle is a typed handle for a string flag.

func (*StringFlagHandle) Get

func (h *StringFlagHandle) Get(ctx context.Context, contexts ...Context) string

Get evaluates the flag and returns a typed string value.

func (*StringFlagHandle) OnChange

func (h *StringFlagHandle) OnChange(cb func(*FlagChangeEvent))

OnChange registers a flag-specific change listener.

type TimeoutError

type TimeoutError struct {
	Base Error
}

TimeoutError is raised when an operation exceeds its timeout.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements the error interface.

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type ValidationError

type ValidationError struct {
	Base Error
}

ValidationError is raised when the server rejects a request due to validation errors.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

Directories

Path Synopsis
internal
debug
Package debug provides the SMPLKIT_DEBUG diagnostic facility.
Package debug provides the SMPLKIT_DEBUG diagnostic facility.
generated/app
Package app contains auto-generated types from the app OpenAPI spec.
Package app contains auto-generated types from the app OpenAPI spec.
generated/config
Package config contains auto-generated types from the config OpenAPI spec.
Package config contains auto-generated types from the config OpenAPI spec.
generated/flags
Package flags provides primitives to interact with the openapi HTTP API.
Package flags provides primitives to interact with the openapi HTTP API.
generated/logging
Package logging provides primitives to interact with the openapi HTTP API.
Package logging provides primitives to interact with the openapi HTTP API.
logging

Jump to

Keyboard shortcuts

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