DNF90 服务端与启动器完整源码(含 GM 工具功能增强)

服务端(Go):
- GM 塞背包/带属性装备发放:在线角色推送 op14 增量物品行,背包实时刷新,无需回角色选择界面
- GM 改金币/改等级:去掉在线拒绝,落库后推送 op14 钱包/op37 等级状态,在线实时刷新
- 等级端点统一切换到新版 GMSetCharacterLevel(自带在线刷新)
- 无限/锁死疲劳模式 + 燃烧疲劳:每房间消耗 2 点、打怪与通关经验双倍
- 燃烧疲劳开关时给所有在线角色推送系统提示(op12 mode 0)
- 深渊史诗掉率:GM 全局倍率 + 城镇增益药剂窗口倍率,真实接入掉落结算

启动器(Python/JS):
- 标题栏自绘、窗口 1204x717、禁止拖拽改大小、仅最小化/关闭
- GM 工具:疲劳与燃烧、深渊史诗掉率、拍卖行上架(单一定价对齐)
- 拍卖行上架前端对齐服务端单一价格语义,修复 400 报错
This commit is contained in:
hanfuit committed 2026-11-04 14:31:55 +08:00
commit 645b64fe21
4388 files changed
+1405457

No files matched your search

@@ -0,0 +1,282 @@
package admincmd
import (
"context"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"fmt"
"strings"
"sync"
"time"
)
var (
ErrApprovalNotFound = errors.New("admin approval not found")
ErrApprovalNotPending = errors.New("admin approval is not pending")
ErrApprovalNotApproved = errors.New("admin approval is not approved")
ErrApprovalSelfApprove = errors.New("admin approval requires different approver")
ErrApprovalConfirmation = errors.New("admin approval confirmation is invalid")
)
const (
ApprovalPending = "pending"
ApprovalApproved = "approved"
ApprovalRejected = "rejected"
ApprovalExecuted = "executed"
)
type ApprovalPolicy struct {
CommandPolicy Policy
RequireDifferentApprover bool
RequireConfirmation bool
}
type ApprovalDecision struct {
Approver string `json:"approver"`
Reason string `json:"reason,omitempty"`
Confirmation string `json:"confirmation,omitempty"`
}
type ApprovalRequest struct {
ID string `json:"id"`
Command Command `json:"command"`
Status string `json:"status"`
Approver string `json:"approver,omitempty"`
DecisionReason string `json:"decision_reason,omitempty"`
RequestedAt time.Time `json:"requested_at"`
DecidedAt time.Time `json:"decided_at,omitempty"`
ExecutedAt time.Time `json:"executed_at,omitempty"`
Receipt *Receipt `json:"receipt,omitempty"`
}
type ApprovalStore struct {
mu sync.Mutex
now func() time.Time
policy ApprovalPolicy
requests map[string]ApprovalRequest
}
func DangerousApprovalPolicy() ApprovalPolicy {
return ApprovalPolicy{
CommandPolicy: Policy{
RequireActor: true,
RequireTarget: true,
RequireReason: true,
RequireIdempotencyKey: true,
RequireConfirmation: false,
},
RequireDifferentApprover: true,
RequireConfirmation: true,
}
}
func NewApprovalStore(policy ApprovalPolicy, now func() time.Time) *ApprovalStore {
if now == nil {
now = func() time.Time { return time.Now().UTC() }
}
if policy.CommandPolicy == (Policy{}) {
policy = DangerousApprovalPolicy()
}
return &ApprovalStore{
now: now,
policy: policy,
requests: make(map[string]ApprovalRequest),
}
}
func (s *ApprovalStore) Submit(ctx context.Context, command Command) (ApprovalRequest, error) {
if err := ctxErr(ctx); err != nil {
return ApprovalRequest{}, err
}
if s == nil {
return ApprovalRequest{}, ErrApprovalNotFound
}
command = Normalize(command)
if err := Validate(command, s.policy.CommandPolicy); err != nil {
return ApprovalRequest{}, err
}
id, err := approvalID(command)
if err != nil {
return ApprovalRequest{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
if current, ok := s.requests[id]; ok {
return cloneApprovalRequest(current), nil
}
request := ApprovalRequest{
ID: id,
Command: command,
Status: ApprovalPending,
RequestedAt: s.now().UTC(),
}
s.requests[id] = request
return cloneApprovalRequest(request), nil
}
func (s *ApprovalStore) Approve(ctx context.Context, id string, decision ApprovalDecision) (ApprovalRequest, error) {
return s.decide(ctx, id, decision, ApprovalApproved)
}
func (s *ApprovalStore) Reject(ctx context.Context, id string, decision ApprovalDecision) (ApprovalRequest, error) {
return s.decide(ctx, id, decision, ApprovalRejected)
}
func (s *ApprovalStore) ExecuteApproved(ctx context.Context, id string) (Receipt, error) {
if err := ctxErr(ctx); err != nil {
return Receipt{}, err
}
if s == nil {
return Receipt{}, ErrApprovalNotFound
}
id = strings.TrimSpace(id)
s.mu.Lock()
defer s.mu.Unlock()
request, ok := s.requests[id]
if !ok {
return Receipt{}, ErrApprovalNotFound
}
if request.Status == ApprovalExecuted && request.Receipt != nil {
return *request.Receipt, nil
}
if request.Status != ApprovalApproved {
return Receipt{}, ErrApprovalNotApproved
}
if err := Validate(request.Command, DangerousPolicy()); err != nil {
return Receipt{}, err
}
receipt, err := NewReceipt(request.Command, ApprovalExecuted, s.now().UTC())
if err != nil {
return Receipt{}, err
}
request.Status = ApprovalExecuted
request.ExecutedAt = receipt.CreatedAt
request.Receipt = &receipt
s.requests[id] = request
return receipt, nil
}
func (s *ApprovalStore) Get(id string) (ApprovalRequest, bool) {
if s == nil {
return ApprovalRequest{}, false
}
id = strings.TrimSpace(id)
s.mu.Lock()
defer s.mu.Unlock()
request, ok := s.requests[id]
return cloneApprovalRequest(request), ok
}
func (s *ApprovalStore) List() []ApprovalRequest {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
out := make([]ApprovalRequest, 0, len(s.requests))
for _, request := range s.requests {
out = append(out, cloneApprovalRequest(request))
}
return out
}
func (s *ApprovalStore) decide(ctx context.Context, id string, decision ApprovalDecision, status string) (ApprovalRequest, error) {
if err := ctxErr(ctx); err != nil {
return ApprovalRequest{}, err
}
if s == nil {
return ApprovalRequest{}, ErrApprovalNotFound
}
id = strings.TrimSpace(id)
decision.Approver = strings.TrimSpace(decision.Approver)
decision.Reason = strings.TrimSpace(decision.Reason)
decision.Confirmation = strings.TrimSpace(decision.Confirmation)
if decision.Approver == "" {
return ApprovalRequest{}, ErrMissingActor
}
s.mu.Lock()
defer s.mu.Unlock()
request, ok := s.requests[id]
if !ok {
return ApprovalRequest{}, ErrApprovalNotFound
}
if request.Status != ApprovalPending {
return ApprovalRequest{}, ErrApprovalNotPending
}
if s.policy.RequireDifferentApprover && strings.EqualFold(decision.Approver, strings.TrimSpace(request.Command.Actor)) {
return ApprovalRequest{}, ErrApprovalSelfApprove
}
if status == ApprovalApproved && s.policy.RequireConfirmation && !confirmMatches(request.Command.Operation, decision.Confirmation) {
return ApprovalRequest{}, fmt.Errorf("%w: expected %s", ErrApprovalConfirmation, request.Command.Operation)
}
request.Status = status
request.Approver = decision.Approver
request.DecisionReason = decision.Reason
request.DecidedAt = s.now().UTC()
if status == ApprovalApproved {
request.Command.Confirmation = request.Command.Operation
}
s.requests[id] = request
return cloneApprovalRequest(request), nil
}
func confirmMatches(operation string, confirmation string) bool {
expected := strings.ToLower(strings.TrimSpace(operation))
got := strings.ToLower(strings.TrimSpace(confirmation))
if expected == "" || got == "" || len(expected) != len(got) {
return false
}
return subtle.ConstantTimeCompare([]byte(expected), []byte(got)) == 1
}
func approvalID(command Command) (string, error) {
hash, err := ParamsHash(command.Params)
if err != nil {
return "", err
}
seed := strings.Join([]string{
command.Operation,
command.Scope,
command.Environment,
command.ShardID,
command.Target,
command.Actor,
command.IdempotencyKey,
hash,
}, "|")
sum := sha256.Sum256([]byte(seed))
return "approval-" + hex.EncodeToString(sum[:12]), nil
}
func ApprovalID(command Command) (string, error) {
return approvalID(Normalize(command))
}
func cloneApprovalRequest(request ApprovalRequest) ApprovalRequest {
request.Command.Params = cloneParams(request.Command.Params)
if request.Receipt != nil {
receipt := *request.Receipt
request.Receipt = &receipt
}
return request
}
func cloneParams(params map[string]any) map[string]any {
if len(params) == 0 {
return nil
}
out := make(map[string]any, len(params))
for key, value := range params {
out[key] = value
}
return out
}
func ctxErr(ctx context.Context) error {
if ctx == nil {
return nil
}
return ctx.Err()
}
@@ -0,0 +1,182 @@
package admincmd
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"time"
)
var (
ErrMissingOperation = errors.New("admin command operation is required")
ErrMissingActor = errors.New("admin command actor is required")
ErrMissingTarget = errors.New("admin command target is required")
ErrMissingReason = errors.New("admin command reason is required")
ErrMissingIdempotencyKey = errors.New("admin command idempotency key is required")
ErrMissingConfirmation = errors.New("admin command confirmation is required")
)
type Command struct {
Operation string `json:"operation"`
Scope string `json:"scope,omitempty"`
Environment string `json:"environment,omitempty"`
ShardID string `json:"shard_id,omitempty"`
Target string `json:"target,omitempty"`
Actor string `json:"actor"`
Reason string `json:"reason,omitempty"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
Confirmation string `json:"confirmation,omitempty"`
OfflineSafe bool `json:"offline_safe,omitempty"`
Params map[string]any `json:"params,omitempty"`
}
type Policy struct {
RequireActor bool
RequireTarget bool
RequireReason bool
RequireIdempotencyKey bool
RequireConfirmation bool
}
type Receipt struct {
ID string `json:"id"`
Operation string `json:"operation"`
Scope string `json:"scope,omitempty"`
Environment string `json:"environment,omitempty"`
ShardID string `json:"shard_id,omitempty"`
Target string `json:"target,omitempty"`
Actor string `json:"actor,omitempty"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
ParamsHash string `json:"params_hash,omitempty"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
func DangerousPolicy() Policy {
return Policy{
RequireActor: true,
RequireTarget: true,
RequireReason: true,
RequireIdempotencyKey: true,
RequireConfirmation: true,
}
}
func Validate(command Command, policy Policy) error {
command = Normalize(command)
if command.Operation == "" {
return ErrMissingOperation
}
if policy.RequireActor && command.Actor == "" {
return ErrMissingActor
}
if policy.RequireTarget && command.Target == "" {
return ErrMissingTarget
}
if policy.RequireReason && command.Reason == "" {
return ErrMissingReason
}
if policy.RequireIdempotencyKey && command.IdempotencyKey == "" {
return ErrMissingIdempotencyKey
}
if policy.RequireConfirmation && command.Confirmation == "" {
return ErrMissingConfirmation
}
return nil
}
func Normalize(command Command) Command {
command.Operation = strings.TrimSpace(command.Operation)
command.Scope = strings.Trim(strings.ToLower(strings.TrimSpace(command.Scope)), ":")
command.Environment = strings.TrimSpace(command.Environment)
command.ShardID = strings.TrimSpace(command.ShardID)
command.Target = strings.TrimSpace(command.Target)
command.Actor = strings.TrimSpace(command.Actor)
command.Reason = strings.TrimSpace(command.Reason)
command.IdempotencyKey = strings.TrimSpace(command.IdempotencyKey)
command.Confirmation = strings.TrimSpace(command.Confirmation)
return command
}
func ParamsHash(params map[string]any) (string, error) {
if len(params) == 0 {
return "", nil
}
payload, err := json.Marshal(canonicalParams(params))
if err != nil {
return "", err
}
sum := sha256.Sum256(payload)
return hex.EncodeToString(sum[:]), nil
}
func canonicalParams(params map[string]any) map[string]any {
out := make(map[string]any, len(params))
type paramPair struct {
key string
value any
}
pairs := make([]paramPair, 0, len(params))
for key, value := range params {
normalized := strings.TrimSpace(key)
if normalized == "" {
continue
}
pairs = append(pairs, paramPair{key: normalized, value: value})
}
sort.Slice(pairs, func(i, j int) bool { return pairs[i].key < pairs[j].key })
for _, pair := range pairs {
out[pair.key] = canonicalParamValue(pair.value)
}
return out
}
func canonicalParamValue(value any) any {
switch typed := value.(type) {
case map[string]any:
return canonicalParams(typed)
case []any:
out := make([]any, len(typed))
for i, item := range typed {
out[i] = canonicalParamValue(item)
}
return out
default:
return value
}
}
func NewReceipt(command Command, status string, now time.Time) (Receipt, error) {
command = Normalize(command)
if command.Operation == "" {
return Receipt{}, ErrMissingOperation
}
if now.IsZero() {
now = time.Now().UTC()
} else {
now = now.UTC()
}
paramsHash, err := ParamsHash(command.Params)
if err != nil {
return Receipt{}, err
}
idSeed := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s", command.Operation, command.Scope, command.Environment, command.ShardID, command.Target, command.IdempotencyKey, paramsHash)
sum := sha256.Sum256([]byte(idSeed))
return Receipt{
ID: hex.EncodeToString(sum[:16]),
Operation: command.Operation,
Scope: command.Scope,
Environment: command.Environment,
ShardID: command.ShardID,
Target: command.Target,
Actor: command.Actor,
IdempotencyKey: command.IdempotencyKey,
ParamsHash: paramsHash,
Status: strings.TrimSpace(status),
CreatedAt: now,
}, nil
}
@@ -0,0 +1,465 @@
package admincmd
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
)
var (
ErrTemplateNotFound = errors.New("admin command template not found")
ErrInvalidTemplate = errors.New("admin command template is invalid")
ErrInvalidParam = errors.New("admin command template param is invalid")
)
const (
ParamString = "string"
ParamInt = "int"
ParamBool = "bool"
ParamNumber = "number"
)
type ParamSpec struct {
Name string `json:"name"`
Type string `json:"type,omitempty"`
Required bool `json:"required,omitempty"`
Allowed []string `json:"allowed,omitempty"`
Description string `json:"description,omitempty"`
}
type Template struct {
Name string `json:"name"`
Operation string `json:"operation"`
Scope string `json:"scope,omitempty"`
Target string `json:"target,omitempty"`
ShardID string `json:"shard_id,omitempty"`
OfflineSafe bool `json:"offline_safe,omitempty"`
Dangerous bool `json:"dangerous,omitempty"`
Description string `json:"description,omitempty"`
Params []ParamSpec `json:"params,omitempty"`
}
type TemplateRegistry struct {
templates map[string]Template
}
func NewTemplateRegistry(templates ...Template) (*TemplateRegistry, error) {
registry := &TemplateRegistry{templates: make(map[string]Template, len(templates))}
for _, template := range templates {
if err := registry.Register(template); err != nil {
return nil, err
}
}
return registry, nil
}
func LoadTemplateRegistry(data []byte) (*TemplateRegistry, error) {
var doc struct {
Templates []Template `json:"templates"`
}
if err := json.Unmarshal(data, &doc); err != nil {
return nil, err
}
return NewTemplateRegistry(doc.Templates...)
}
func (r *TemplateRegistry) Register(template Template) error {
if r == nil {
return ErrTemplateNotFound
}
template = normalizeTemplate(template)
if err := validateTemplate(template); err != nil {
return err
}
if r.templates == nil {
r.templates = make(map[string]Template)
}
if _, exists := r.templates[template.Name]; exists {
return fmt.Errorf("%w: duplicate template %s", ErrInvalidTemplate, template.Name)
}
r.templates[template.Name] = cloneTemplate(template)
return nil
}
func (r *TemplateRegistry) Get(name string) (Template, bool) {
if r == nil {
return Template{}, false
}
name = normalizeTemplateID(name)
template, ok := r.templates[name]
return cloneTemplate(template), ok
}
func (r *TemplateRegistry) List() []Template {
if r == nil {
return nil
}
out := make([]Template, 0, len(r.templates))
for _, template := range r.templates {
out = append(out, cloneTemplate(template))
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
func (r *TemplateRegistry) Build(name string, command Command, params map[string]any) (Command, error) {
template, ok := r.Get(name)
if !ok {
return Command{}, fmt.Errorf("%w: %s", ErrTemplateNotFound, strings.TrimSpace(name))
}
return template.Build(command, params)
}
func (t Template) Build(command Command, params map[string]any) (Command, error) {
t = normalizeTemplate(t)
if err := validateTemplate(t); err != nil {
return Command{}, err
}
normalizedParams, err := normTemplateParams(t, params)
if err != nil {
return Command{}, err
}
command = Normalize(command)
command.Operation = t.Operation
command.Scope = firstTemplateString(t.Scope, command.Scope)
command.Target = firstTemplateString(t.Target, command.Target)
command.ShardID = firstTemplateString(t.ShardID, command.ShardID)
command.OfflineSafe = command.OfflineSafe || t.OfflineSafe
command.Params = normalizedParams
if t.Dangerous && command.Confirmation == "" {
command.Confirmation = t.Operation
}
return command, nil
}
func DefaultTemplates() []Template {
return []Template{
{
Name: "profile_repair",
Operation: "profile.repair",
Scope: "logic",
Target: "player",
Dangerous: true,
Description: "Profile check or targeted field repair",
Params: []ParamSpec{
{Name: "account_id", Type: ParamString, Required: true},
{Name: "field", Type: ParamString, Required: true},
{Name: "mode", Type: ParamString, Required: true, Allowed: []string{"check", "repair"}},
},
},
{
Name: "mail_publish",
Operation: "notice.publish",
Scope: "logic",
Target: "notice",
Dangerous: true,
Description: "Notice, mail, or operation announcement publish",
Params: []ParamSpec{
{Name: "notice_id", Type: ParamString, Required: true},
{Name: "shard_id", Type: ParamString},
{Name: "audience", Type: ParamString, Required: true, Allowed: []string{"account", "shard", "all"}},
},
},
{
Name: "redeem_code_put",
Operation: "redeem.code.put",
Scope: "redeem",
Target: "code",
Dangerous: true,
Description: "Create or update a redeem code definition",
Params: []ParamSpec{
{Name: "code", Type: ParamString, Required: true},
{Name: "reward_ref", Type: ParamString, Required: true},
{Name: "campaign", Type: ParamString},
{Name: "max_uses", Type: ParamInt},
{Name: "per_account_limit", Type: ParamInt},
},
},
{
Name: "redeem_claim_repair",
Operation: "redeem.claim.repair",
Scope: "redeem",
Target: "account",
Dangerous: true,
Description: "Manual redeem claim repair or compensation",
Params: []ParamSpec{
{Name: "code", Type: ParamString, Required: true},
{Name: "account_id", Type: ParamString, Required: true},
{Name: "idempotency_key", Type: ParamString, Required: true},
},
},
{
Name: "payment_replay",
Operation: "commerce.fulfillment.replay",
Scope: "commerce",
Target: "order",
Dangerous: true,
Description: "Payment fulfillment compensation or receipt replay",
Params: []ParamSpec{
{Name: "order_id", Type: ParamString, Required: true},
{Name: "channel", Type: ParamString, Required: true},
},
},
{
Name: "shard_drain",
Operation: "servergroup.shard.operation",
Scope: "servergroup",
Target: "shard",
Dangerous: true,
Description: "Open, drain, or close a shard",
Params: []ParamSpec{
{Name: "shard_id", Type: ParamString, Required: true},
{Name: "state", Type: ParamString, Required: true, Allowed: []string{"open", "draining", "closed"}},
{Name: "next_version", Type: ParamString, Required: true},
},
},
{
Name: "servergroup_merge",
Operation: "servergroup.merge.workflow",
Scope: "servergroup",
Target: "merge",
Dangerous: true,
Description: "区服合服 dry-run、执行或回滚工作流",
Params: []ParamSpec{
{Name: "merge_id", Type: ParamString, Required: true},
{Name: "main_shard_id", Type: ParamString, Required: true},
{Name: "shards", Type: ParamString, Required: true, Description: "逗号分隔的区服 ID 列表"},
{Name: "mode", Type: ParamString, Required: true, Allowed: []string{"dry_run", "apply", "rollback_dry_run", "rollback"}},
{Name: "check_features", Type: ParamString, Description: "逗号分隔的检查 feature"},
{Name: "block_features", Type: ParamString, Description: "逗号分隔的冻结 feature"},
{Name: "next_version", Type: ParamString},
{Name: "archive_id", Type: ParamString},
{Name: "rollback_archive_id", Type: ParamString, Description: "回滚时引用的 apply 归档 ID"},
{Name: "restore_version", Type: ParamString},
{Name: "allow_version_mismatch", Type: ParamBool},
},
},
}
}
func normalizeTemplate(template Template) Template {
template.Name = normalizeTemplateID(template.Name)
template.Operation = strings.TrimSpace(template.Operation)
template.Scope = strings.Trim(strings.ToLower(strings.TrimSpace(template.Scope)), ":")
template.Target = strings.TrimSpace(template.Target)
template.ShardID = strings.TrimSpace(template.ShardID)
template.Description = strings.TrimSpace(template.Description)
out := make([]ParamSpec, 0, len(template.Params))
for _, param := range template.Params {
param.Name = normalizeTemplateID(param.Name)
param.Type = normalizeParamType(param.Type)
param.Description = strings.TrimSpace(param.Description)
param.Allowed = normAllowedValues(param.Allowed)
out = append(out, param)
}
template.Params = out
return template
}
func validateTemplate(template Template) error {
if template.Name == "" || template.Operation == "" {
return fmt.Errorf("%w: name and operation are required", ErrInvalidTemplate)
}
seen := make(map[string]struct{}, len(template.Params))
for _, param := range template.Params {
if param.Name == "" {
return fmt.Errorf("%w: param name is required", ErrInvalidTemplate)
}
if _, exists := seen[param.Name]; exists {
return fmt.Errorf("%w: duplicate param %s", ErrInvalidTemplate, param.Name)
}
seen[param.Name] = struct{}{}
switch param.Type {
case "", ParamString, ParamInt, ParamBool, ParamNumber:
default:
return fmt.Errorf("%w: unsupported param type %s", ErrInvalidTemplate, param.Type)
}
}
return nil
}
func normTemplateParams(template Template, params map[string]any) (map[string]any, error) {
params = normalizeParamMap(params)
out := make(map[string]any, len(params))
specs := make(map[string]ParamSpec, len(template.Params))
for _, spec := range template.Params {
specs[spec.Name] = spec
value, ok := params[spec.Name]
if !ok {
if spec.Required {
return nil, fmt.Errorf("%w: %s is required", ErrInvalidParam, spec.Name)
}
continue
}
normalized, err := normalizeParamValue(spec, value)
if err != nil {
return nil, err
}
out[spec.Name] = normalized
}
for name := range params {
if _, ok := specs[name]; !ok {
return nil, fmt.Errorf("%w: unexpected param %s", ErrInvalidParam, name)
}
}
return out, nil
}
func normalizeParamValue(spec ParamSpec, value any) (any, error) {
switch spec.Type {
case "", ParamString:
raw, ok := value.(string)
if !ok {
return nil, fmt.Errorf("%w: %s must be string", ErrInvalidParam, spec.Name)
}
text := strings.TrimSpace(raw)
if err := validateAllowedValue(spec, text); err != nil {
return nil, err
}
return text, nil
case ParamInt:
parsed, err := parseTemplateInt(value)
if err != nil {
return nil, fmt.Errorf("%w: %s must be int", ErrInvalidParam, spec.Name)
}
return parsed, nil
case ParamBool:
parsed, err := parseTemplateBool(value)
if err != nil {
return nil, fmt.Errorf("%w: %s must be bool", ErrInvalidParam, spec.Name)
}
return parsed, nil
case ParamNumber:
parsed, err := parseTemplateNumber(value)
if err != nil {
return nil, fmt.Errorf("%w: %s must be number", ErrInvalidParam, spec.Name)
}
return parsed, nil
default:
return nil, fmt.Errorf("%w: unsupported param type %s", ErrInvalidTemplate, spec.Type)
}
}
func validateAllowedValue(spec ParamSpec, value string) error {
if len(spec.Allowed) == 0 {
return nil
}
for _, allowed := range spec.Allowed {
if value == allowed {
return nil
}
}
return fmt.Errorf("%w: %s must be one of %s", ErrInvalidParam, spec.Name, strings.Join(spec.Allowed, ","))
}
func parseTemplateInt(value any) (int64, error) {
switch v := value.(type) {
case int:
return int64(v), nil
case int64:
return v, nil
case float64:
if v != float64(int64(v)) {
return 0, ErrInvalidParam
}
return int64(v), nil
case json.Number:
return v.Int64()
case string:
return strconv.ParseInt(strings.TrimSpace(v), 10, 64)
default:
return 0, ErrInvalidParam
}
}
func parseTemplateBool(value any) (bool, error) {
switch v := value.(type) {
case bool:
return v, nil
case string:
return strconv.ParseBool(strings.TrimSpace(v))
default:
return false, ErrInvalidParam
}
}
func parseTemplateNumber(value any) (float64, error) {
switch v := value.(type) {
case int:
return float64(v), nil
case int64:
return float64(v), nil
case float64:
return v, nil
case json.Number:
return v.Float64()
case string:
return strconv.ParseFloat(strings.TrimSpace(v), 64)
default:
return 0, ErrInvalidParam
}
}
func normalizeParamMap(params map[string]any) map[string]any {
out := make(map[string]any, len(params))
for key, value := range params {
key = normalizeTemplateID(key)
if key != "" {
out[key] = value
}
}
return out
}
func normalizeTemplateID(value string) string {
return strings.Trim(strings.ToLower(strings.TrimSpace(value)), ":")
}
func normalizeParamType(value string) string {
value = strings.ToLower(strings.TrimSpace(value))
if value == "" {
return ParamString
}
return value
}
func normAllowedValues(values []string) []string {
if len(values) == 0 {
return nil
}
out := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
if value == "" {
continue
}
if _, ok := seen[value]; ok {
continue
}
seen[value] = struct{}{}
out = append(out, value)
}
return out
}
func cloneTemplate(template Template) Template {
template.Params = append([]ParamSpec(nil), template.Params...)
for idx := range template.Params {
template.Params[idx].Allowed = append([]string(nil), template.Params[idx].Allowed...)
}
return template
}
func firstTemplateString(values ...string) string {
for _, value := range values {
value = strings.TrimSpace(value)
if value != "" {
return value
}
}
return ""
}