chore: import upstream snapshot with attribution
CI / license-header (push) Has been skipped
CI / e2e-dry-run (push) Has been skipped
CI / fast-gate (push) Failing after 0s
Test PR Label Logic / test-pr-labels (push) Failing after 1s
Skill Format Check / check-format (push) Failing after 2s
CI / security (push) Failing after 5s
CI / unit-test (push) Has been skipped
CI / lint (push) Has been skipped
CI / script-test (push) Has been skipped
CI / deterministic-gate (push) Has been skipped
CI / coverage (push) Has been skipped
CI / results (push) Has been cancelled
CI / deadcode (push) Has been cancelled
CI / e2e-live (push) Has been cancelled
CI / license-header (push) Has been skipped
CI / e2e-dry-run (push) Has been skipped
CI / fast-gate (push) Failing after 0s
Test PR Label Logic / test-pr-labels (push) Failing after 1s
Skill Format Check / check-format (push) Failing after 2s
CI / security (push) Failing after 5s
CI / unit-test (push) Has been skipped
CI / lint (push) Has been skipped
CI / script-test (push) Has been skipped
CI / deterministic-gate (push) Has been skipped
CI / coverage (push) Has been skipped
CI / results (push) Has been cancelled
CI / deadcode (push) Has been cancelled
CI / e2e-live (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,257 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/internal/affordance"
|
||||
"github.com/larksuite/cli/internal/apicatalog"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/meta"
|
||||
)
|
||||
|
||||
// Convert renders a meta.Field as a JSON-Schema Property. meta owns the value
|
||||
// normalization (canonical type, literal coercion, enum ordering); this adds
|
||||
// only the JSON-Schema-specific shape: the "file" binary format, numeric
|
||||
// bounds, nested object/array properties, and the array-items fallback.
|
||||
func Convert(f meta.Field) Property {
|
||||
var p Property
|
||||
|
||||
p.Type = f.CanonicalType()
|
||||
if f.Type == "file" {
|
||||
p.Format = "binary"
|
||||
}
|
||||
p.Description = normalizeDesc(f.Description)
|
||||
p.Default = f.CoercedDefault()
|
||||
p.Example = f.CoercedExample()
|
||||
p.Minimum = f.MinBound()
|
||||
p.Maximum = f.MaxBound()
|
||||
p.Enum, p.EnumDescriptions = enumSchema(f.EnumOptions())
|
||||
|
||||
if children := f.Children(); len(children) > 0 {
|
||||
props, required := propsOf(children), requiredOf(children)
|
||||
if p.Type == "array" {
|
||||
// meta_data quirk: array element schema is wrapped in "properties".
|
||||
p.Items = &Property{Type: "object", Properties: props, Required: required}
|
||||
} else {
|
||||
if p.Type == "" {
|
||||
p.Type = "object" // infer
|
||||
}
|
||||
p.Properties = props
|
||||
p.Required = required
|
||||
}
|
||||
}
|
||||
|
||||
// Every array needs an items schema to be valid for consumers that require
|
||||
// one, even when meta_data describes no element shape.
|
||||
if p.Type == "array" && p.Items == nil {
|
||||
p.Items = &Property{}
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
var (
|
||||
sepRunRe = regexp.MustCompile(`[;;]{2,}`)
|
||||
spaceRunRe = regexp.MustCompile(`[ \t]{2,}`)
|
||||
)
|
||||
|
||||
// normalizeDesc de-crufts a meta_data description for the envelope — strips
|
||||
// markdown emphasis and collapses doubled separators/spaces — but keeps content
|
||||
// (links, newlines, sentences); the compact flag-help has its own stricter pass.
|
||||
func normalizeDesc(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
s = strings.ReplaceAll(s, "**", "")
|
||||
s = sepRunRe.ReplaceAllString(s, "; ")
|
||||
s = spaceRunRe.ReplaceAllString(s, " ")
|
||||
return strings.TrimRight(s, " ;;。.,,、\n")
|
||||
}
|
||||
|
||||
// enumSchema splits coerced enum options into the parallel enum / enumDescriptions
|
||||
// arrays for the envelope. enumDescriptions is nil unless at least one value
|
||||
// carries a description (so the bare-enum form stays values-only), keeping the
|
||||
// two arrays index-aligned for AI consumers.
|
||||
func enumSchema(opts []meta.EnumOption) (values []interface{}, descriptions []string) {
|
||||
if len(opts) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
values = make([]interface{}, len(opts))
|
||||
descs := make([]string, len(opts))
|
||||
hasDesc := false
|
||||
for i, o := range opts {
|
||||
values[i] = o.Value
|
||||
descs[i] = o.Description
|
||||
if o.Description != "" {
|
||||
hasDesc = true
|
||||
}
|
||||
}
|
||||
if hasDesc {
|
||||
descriptions = descs
|
||||
}
|
||||
return values, descriptions
|
||||
}
|
||||
|
||||
// propsOf renders fields as an ordered JSON-Schema property map. meta's field
|
||||
// accessors return fields sorted by name, so the property order is alphabetical.
|
||||
func propsOf(fields []meta.Field) *OrderedProps {
|
||||
op := &OrderedProps{}
|
||||
for _, f := range fields {
|
||||
op.Set(f.Name, Convert(f))
|
||||
}
|
||||
return op
|
||||
}
|
||||
|
||||
// paramPropsOf is propsOf for the params section: each property also carries
|
||||
// its CLI flag (--kebab-name).
|
||||
func paramPropsOf(fields []meta.Field) *OrderedProps {
|
||||
op := &OrderedProps{}
|
||||
for _, f := range fields {
|
||||
p := Convert(f)
|
||||
p.Flag = "--" + f.FlagName()
|
||||
op.Set(f.Name, p)
|
||||
}
|
||||
return op
|
||||
}
|
||||
|
||||
// requiredOf returns the alphabetized names of the required fields.
|
||||
func requiredOf(fields []meta.Field) []string {
|
||||
var required []string
|
||||
for _, f := range fields {
|
||||
if f.Required {
|
||||
required = append(required, f.Name)
|
||||
}
|
||||
}
|
||||
sort.Strings(required)
|
||||
return required
|
||||
}
|
||||
|
||||
// buildInputSchema produces the inputSchema sections — params (path+query →
|
||||
// --params), data (non-file body → --data), file (file body → --file) — plus a
|
||||
// `yes` confirmation gate for high-risk-write methods.
|
||||
func buildInputSchema(m meta.Method) *InputSchema {
|
||||
is := &InputSchema{
|
||||
Type: "object",
|
||||
Required: []string{}, // never nil — stable envelope shape
|
||||
Properties: &OrderedProps{},
|
||||
}
|
||||
|
||||
addInputObject(is, "params", "", m.Params(), true, "")
|
||||
addInputObject(is, "data", "", m.Data(), false, "--data")
|
||||
addInputObject(is, "file", "Binary file uploads. Each property is a file field with format:binary; CLI maps each to --file <key>=<path>.", m.Files(), false, "--file")
|
||||
|
||||
if m.Risk == core.RiskHighRiskWrite {
|
||||
falseVal := false
|
||||
is.Properties.Set("yes", Property{
|
||||
Type: "boolean",
|
||||
Flag: "--yes",
|
||||
Default: falseVal,
|
||||
Description: "CLI confirmation gate. Must be true to execute; lark-cli rejects with confirmation_required if absent or false. Pass --yes only after the user has explicitly confirmed; not sent to the backend.",
|
||||
})
|
||||
}
|
||||
|
||||
sort.Strings(is.Required)
|
||||
return is
|
||||
}
|
||||
|
||||
// addInputObject adds one section (params/data/file) when it has fields, marking
|
||||
// the section required at top level when any field is. asFlags tags each property
|
||||
// with its --flag (params only); carrier names the section's flag (--data/--file).
|
||||
func addInputObject(is *InputSchema, name, description string, fields []meta.Field, asFlags bool, carrier string) {
|
||||
if len(fields) == 0 {
|
||||
return
|
||||
}
|
||||
props := propsOf(fields)
|
||||
if asFlags {
|
||||
props = paramPropsOf(fields)
|
||||
}
|
||||
req := requiredOf(fields)
|
||||
is.Properties.Set(name, Property{
|
||||
Type: "object",
|
||||
Description: description,
|
||||
Carrier: carrier,
|
||||
Required: req,
|
||||
Properties: props,
|
||||
})
|
||||
if len(req) > 0 {
|
||||
is.Required = append(is.Required, name)
|
||||
}
|
||||
}
|
||||
|
||||
// buildOutputSchema produces the outputSchema from the response-body fields.
|
||||
func buildOutputSchema(m meta.Method) *OutputSchema {
|
||||
return &OutputSchema{Type: "object", Properties: propsOf(m.Response())}
|
||||
}
|
||||
|
||||
// buildMeta produces the _meta extension namespace.
|
||||
func buildMeta(m meta.Method) *Meta {
|
||||
out := &Meta{
|
||||
EnvelopeVersion: "1.0",
|
||||
RequiredScopes: []string{}, // never nil for stable JSON
|
||||
Scopes: m.Scopes,
|
||||
AccessTokens: m.Identities(),
|
||||
Danger: m.Danger,
|
||||
}
|
||||
if a, ok := m.ParsedAffordance(); ok {
|
||||
out.Affordance = &a
|
||||
}
|
||||
if len(m.RequiredScopes) > 0 {
|
||||
out.RequiredScopes = m.RequiredScopes
|
||||
}
|
||||
if m.Risk != "" {
|
||||
out.Risk = m.Risk
|
||||
} else {
|
||||
out.Risk = core.RiskRead
|
||||
}
|
||||
if m.DocURL != "" {
|
||||
out.DocURL = m.DocURL
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// EnvelopeOf renders the MCP envelope for one method ref — the ref-based entry
|
||||
// callers use, since apicatalog.MethodRef is the metadata navigation currency.
|
||||
func EnvelopeOf(ref apicatalog.MethodRef) Envelope {
|
||||
m := ref.Method
|
||||
// The affordance overlay lives in the CLI, not the metadata; look it up
|
||||
// lazily here (it takes precedence over any affordance the metadata carries).
|
||||
if raw, ok := affordance.For(ref.Service.Name, m.ID); ok {
|
||||
m.Affordance = raw
|
||||
}
|
||||
return assemble(ref.Service.Name, ref.ResourcePath, m)
|
||||
}
|
||||
|
||||
// Envelopes renders the given method refs into envelopes, sorted by name. The
|
||||
// caller supplies the refs (from apicatalog navigation), so this package owns
|
||||
// only rendering — never metadata source selection or traversal.
|
||||
func Envelopes(refs []apicatalog.MethodRef) []Envelope {
|
||||
var out []Envelope
|
||||
for _, ref := range refs {
|
||||
out = append(out, EnvelopeOf(ref))
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
|
||||
// assemble builds the envelope from a method's navigation context. The method
|
||||
// name comes from m.Name, injected by the typed accessors.
|
||||
func assemble(serviceName string, resourcePath []string, m meta.Method) Envelope {
|
||||
name := serviceName
|
||||
for _, r := range resourcePath {
|
||||
name += " " + r
|
||||
}
|
||||
name += " " + m.Name
|
||||
|
||||
return Envelope{
|
||||
Name: name,
|
||||
Description: normalizeDesc(m.Description),
|
||||
InputSchema: buildInputSchema(m),
|
||||
OutputSchema: buildOutputSchema(m),
|
||||
Meta: buildMeta(m),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/larksuite/cli/internal/affordance"
|
||||
"github.com/larksuite/cli/internal/apicatalog"
|
||||
"github.com/larksuite/cli/internal/meta"
|
||||
"github.com/larksuite/cli/internal/registry"
|
||||
)
|
||||
|
||||
// TestMain isolates registry-backed tests from any host ~/.lark-cli cache so
|
||||
// the suite gives the same answer on every machine. Without this, a stale
|
||||
// local remote_meta.json could surface methods that aren't in the embedded
|
||||
// snapshot (or alter their data) depending on the contributor's environment.
|
||||
//
|
||||
// Note: os.Exit skips deferred functions, so cleanup is done explicitly
|
||||
// after m.Run before exiting.
|
||||
func TestMain(m *testing.M) {
|
||||
dir, err := os.MkdirTemp("", "schema-test-cfg-*")
|
||||
if err != nil {
|
||||
// Surface the failure rather than silently running against the host
|
||||
// cache — that defeats the whole purpose of this isolation.
|
||||
println("schema test setup: MkdirTemp failed:", err.Error())
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
|
||||
os.Setenv("LARKSUITE_CLI_REMOTE_META", "off") // never touch network
|
||||
code := m.Run()
|
||||
os.RemoveAll(dir)
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func TestConvertProperty_BasicTypes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input map[string]interface{}
|
||||
wantType string
|
||||
}{
|
||||
{"string", map[string]interface{}{"type": "string"}, "string"},
|
||||
{"integer", map[string]interface{}{"type": "integer"}, "integer"},
|
||||
{"boolean", map[string]interface{}{"type": "boolean"}, "boolean"},
|
||||
{"number", map[string]interface{}{"type": "number"}, "number"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := convertProperty(tt.input, "")
|
||||
if got.Type != tt.wantType {
|
||||
t.Errorf("Type = %q, want %q", got.Type, tt.wantType)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_FileBinary(t *testing.T) {
|
||||
input := map[string]interface{}{"type": "file", "description": "upload"}
|
||||
got := convertProperty(input, "")
|
||||
if got.Type != "string" {
|
||||
t.Errorf("Type = %q, want \"string\"", got.Type)
|
||||
}
|
||||
if got.Format != "binary" {
|
||||
t.Errorf("Format = %q, want \"binary\"", got.Format)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_OptionsToEnum(t *testing.T) {
|
||||
input := map[string]interface{}{
|
||||
"type": "string",
|
||||
"options": []interface{}{
|
||||
map[string]interface{}{"value": "banana"},
|
||||
map[string]interface{}{"value": "apple"},
|
||||
map[string]interface{}{"value": "banana"}, // duplicate
|
||||
},
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
// string enums preserve source order (deduped), matching the `enum`
|
||||
// branch. Numeric/boolean enums would still be sorted by value.
|
||||
want := []interface{}{"banana", "apple"}
|
||||
if !reflect.DeepEqual(got.Enum, want) {
|
||||
t.Errorf("Enum = %v, want %v", got.Enum, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_EnumPassThrough(t *testing.T) {
|
||||
input := map[string]interface{}{
|
||||
"type": "string",
|
||||
"enum": []interface{}{"x", "y"},
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
want := []interface{}{"x", "y"} // pass through, no sort
|
||||
if !reflect.DeepEqual(got.Enum, want) {
|
||||
t.Errorf("Enum = %v, want %v", got.Enum, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_EnumIntegerCoerce(t *testing.T) {
|
||||
input := map[string]interface{}{
|
||||
"type": "integer",
|
||||
"options": []interface{}{
|
||||
map[string]interface{}{"value": "10"},
|
||||
map[string]interface{}{"value": "1"},
|
||||
map[string]interface{}{"value": "2"},
|
||||
},
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
want := []interface{}{int64(1), int64(2), int64(10)} // typed + numerically sorted
|
||||
if !reflect.DeepEqual(got.Enum, want) {
|
||||
t.Errorf("Enum = %v, want %v", got.Enum, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_ListTypeFallback(t *testing.T) {
|
||||
input := map[string]interface{}{
|
||||
"type": "list",
|
||||
"description": "ids",
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
if got.Type != "array" {
|
||||
t.Errorf("Type = %q, want %q", got.Type, "array")
|
||||
}
|
||||
if got.Items == nil {
|
||||
t.Fatalf("Items = nil, want non-nil (any-schema fallback)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_MinMaxParsing(t *testing.T) {
|
||||
input := map[string]interface{}{"type": "integer", "min": "10", "max": "50"}
|
||||
got := convertProperty(input, "")
|
||||
if got.Minimum == nil || *got.Minimum != 10.0 {
|
||||
t.Errorf("Minimum = %v, want 10", got.Minimum)
|
||||
}
|
||||
if got.Maximum == nil || *got.Maximum != 50.0 {
|
||||
t.Errorf("Maximum = %v, want 50", got.Maximum)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_MinMaxInvalid(t *testing.T) {
|
||||
input := map[string]interface{}{"type": "integer", "min": "not_a_number"}
|
||||
got := convertProperty(input, "")
|
||||
if got.Minimum != nil {
|
||||
t.Errorf("Minimum = %v, want nil for unparseable min", got.Minimum)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_ArrayWithProperties(t *testing.T) {
|
||||
// meta_data quirk: array element schema is in "properties" not "items"
|
||||
input := map[string]interface{}{
|
||||
"type": "array",
|
||||
"properties": map[string]interface{}{
|
||||
"id": map[string]interface{}{"type": "string"},
|
||||
"name": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
if got.Type != "array" {
|
||||
t.Fatalf("Type = %q, want \"array\"", got.Type)
|
||||
}
|
||||
if got.Items == nil {
|
||||
t.Fatal("Items is nil, want non-nil")
|
||||
}
|
||||
if got.Items.Type != "object" {
|
||||
t.Errorf("Items.Type = %q, want \"object\"", got.Items.Type)
|
||||
}
|
||||
if got.Items.Properties == nil || len(got.Items.Properties.Map) != 2 {
|
||||
t.Errorf("Items.Properties did not contain both id and name")
|
||||
}
|
||||
if got.Properties != nil {
|
||||
t.Error("array Property must not have top-level Properties after unfold")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_ObjectWithProperties(t *testing.T) {
|
||||
input := map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"x": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
if got.Type != "object" {
|
||||
t.Errorf("Type = %q, want \"object\"", got.Type)
|
||||
}
|
||||
if got.Properties == nil || got.Properties.Map["x"].Type != "string" {
|
||||
t.Errorf("nested Properties not preserved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_InferObjectFromProperties(t *testing.T) {
|
||||
input := map[string]interface{}{
|
||||
"properties": map[string]interface{}{
|
||||
"y": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
if got.Type != "object" {
|
||||
t.Errorf("Type = %q, want \"object\" (inferred)", got.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_DropsRefAndAnnotations(t *testing.T) {
|
||||
input := map[string]interface{}{
|
||||
"type": "string",
|
||||
"ref": "operator",
|
||||
"annotations": []interface{}{"readOnly"},
|
||||
"enumName": "FooEnum",
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
// 这些字段直接被丢弃;Property 结构里也没存这些字段,断言只有 type 设置即可
|
||||
if got.Type != "string" {
|
||||
t.Errorf("Type = %q", got.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertProperty_DescriptionDefaultExample(t *testing.T) {
|
||||
input := map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "hello\nworld",
|
||||
"default": "",
|
||||
"example": "ex",
|
||||
}
|
||||
got := convertProperty(input, "")
|
||||
if got.Description != "hello\nworld" {
|
||||
t.Errorf("Description not preserved verbatim")
|
||||
}
|
||||
if got.Default != "" {
|
||||
t.Errorf("Default = %v, want empty string (preserved)", got.Default)
|
||||
}
|
||||
if got.Example != "ex" {
|
||||
t.Errorf("Example = %v, want \"ex\"", got.Example)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildInputSchema_ReactionsList(t *testing.T) {
|
||||
method := loadMethodFromRegistry(t, "im", []string{"reactions"}, "list")
|
||||
|
||||
is := buildInputSchema(method)
|
||||
|
||||
if is.Type != "object" {
|
||||
t.Errorf("Type = %q, want \"object\"", is.Type)
|
||||
}
|
||||
// top-level required: ["params"] because message_id is a required path param
|
||||
if !reflect.DeepEqual(is.Required, []string{"params"}) {
|
||||
t.Errorf("Required = %v, want [params]", is.Required)
|
||||
}
|
||||
// top-level properties only contains "params" (no body fields, no high-risk-write)
|
||||
if !reflect.DeepEqual(is.Properties.Order, []string{"params"}) {
|
||||
t.Errorf("top-level properties order = %v, want [params]", is.Properties.Order)
|
||||
}
|
||||
// params sub-object: required + property order
|
||||
params := is.Properties.Map["params"]
|
||||
if params.Type != "object" {
|
||||
t.Errorf("params.Type = %q, want \"object\"", params.Type)
|
||||
}
|
||||
if !reflect.DeepEqual(params.Required, []string{"message_id"}) {
|
||||
t.Errorf("params.Required = %v, want [message_id]", params.Required)
|
||||
}
|
||||
if want := []string{"message_id", "page_size", "page_token", "reaction_type", "user_id_type"}; !reflect.DeepEqual(params.Properties.Order, want) {
|
||||
t.Errorf("params.properties order = %v, want %v (alphabetical)", params.Properties.Order, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildInputSchema_ImagesCreate_FileAndBody(t *testing.T) {
|
||||
method := loadMethodFromRegistry(t, "im", []string{"images"}, "create")
|
||||
|
||||
is := buildInputSchema(method)
|
||||
|
||||
// top-level required: ["data", "file"] — image_type body required + image file required
|
||||
if !reflect.DeepEqual(is.Required, []string{"data", "file"}) {
|
||||
t.Errorf("Required = %v, want [data, file]", is.Required)
|
||||
}
|
||||
// top-level properties: data (for non-file body) + file (for binary upload)
|
||||
if !reflect.DeepEqual(is.Properties.Order, []string{"data", "file"}) {
|
||||
t.Errorf("top-level properties order = %v, want [data, file]", is.Properties.Order)
|
||||
}
|
||||
// data sub-object carries only non-file body fields (image_type)
|
||||
data := is.Properties.Map["data"]
|
||||
if !reflect.DeepEqual(data.Required, []string{"image_type"}) {
|
||||
t.Errorf("data.Required = %v, want [image_type]", data.Required)
|
||||
}
|
||||
if !reflect.DeepEqual(data.Properties.Order, []string{"image_type"}) {
|
||||
t.Errorf("data.properties order = %v, want [image_type]", data.Properties.Order)
|
||||
}
|
||||
if it := data.Properties.Map["image_type"]; !reflect.DeepEqual(it.Enum, []interface{}{"message", "avatar"}) {
|
||||
t.Errorf("image_type unexpected: %+v", it)
|
||||
}
|
||||
if _, isFile := data.Properties.Map["image"]; isFile {
|
||||
t.Errorf("image (file field) should NOT appear in data sub-object")
|
||||
}
|
||||
|
||||
// file sub-object carries the binary upload field
|
||||
file := is.Properties.Map["file"]
|
||||
if file.Type != "object" {
|
||||
t.Errorf("file.Type = %q, want \"object\"", file.Type)
|
||||
}
|
||||
if !reflect.DeepEqual(file.Required, []string{"image"}) {
|
||||
t.Errorf("file.Required = %v, want [image]", file.Required)
|
||||
}
|
||||
if !reflect.DeepEqual(file.Properties.Order, []string{"image"}) {
|
||||
t.Errorf("file.properties order = %v, want [image]", file.Properties.Order)
|
||||
}
|
||||
img := file.Properties.Map["image"]
|
||||
if img.Type != "string" {
|
||||
t.Errorf("image.Type = %q, want \"string\"", img.Type)
|
||||
}
|
||||
if img.Format != "binary" {
|
||||
t.Errorf("image.Format = %q, want \"binary\"", img.Format)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildInputSchema_HighRiskWriteInjectsYes(t *testing.T) {
|
||||
// Synthesized method to avoid registry-overlay variance (remote cache may
|
||||
// strip `risk` field); buildInputSchema only cares about the method map.
|
||||
method := map[string]interface{}{
|
||||
"risk": "high-risk-write",
|
||||
"parameters": map[string]interface{}{
|
||||
"message_id": map[string]interface{}{
|
||||
"type": "string",
|
||||
"location": "path",
|
||||
"required": true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
is := buildInputSchema(meta.FromMap(method))
|
||||
|
||||
// yes lives at inputSchema.properties.yes (sibling of params/data)
|
||||
yes, ok := is.Properties.Map["yes"]
|
||||
if !ok {
|
||||
t.Fatal("expected top-level `yes` property in high-risk-write envelope, not found")
|
||||
}
|
||||
if yes.Type != "boolean" {
|
||||
t.Errorf("yes.Type = %q, want \"boolean\"", yes.Type)
|
||||
}
|
||||
if v, _ := yes.Default.(bool); v != false {
|
||||
t.Errorf("yes.Default = %v, want false", yes.Default)
|
||||
}
|
||||
// yes must NOT be in top-level required
|
||||
for _, r := range is.Required {
|
||||
if r == "yes" {
|
||||
t.Errorf("`yes` should not appear in top-level required")
|
||||
}
|
||||
}
|
||||
// yes is appended to properties.Order
|
||||
last := is.Properties.Order[len(is.Properties.Order)-1]
|
||||
if last != "yes" {
|
||||
t.Errorf("`yes` should be last in properties.Order, got: %v", is.Properties.Order)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildInputSchema_NoYesForReadRisk(t *testing.T) {
|
||||
method := loadMethodFromRegistry(t, "im", []string{"reactions"}, "list")
|
||||
|
||||
is := buildInputSchema(method)
|
||||
if _, ok := is.Properties.Map["yes"]; ok {
|
||||
t.Errorf("`yes` must not be injected for risk=read")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildOutputSchema_ReactionsList(t *testing.T) {
|
||||
method := loadMethodFromRegistry(t, "im", []string{"reactions"}, "list")
|
||||
|
||||
os := buildOutputSchema(method)
|
||||
|
||||
if os.Type != "object" {
|
||||
t.Errorf("Type = %q, want \"object\"", os.Type)
|
||||
}
|
||||
// Top-level response: has_more, page_token, items
|
||||
if _, ok := os.Properties.Map["items"]; !ok {
|
||||
t.Fatal("items not found in outputSchema")
|
||||
}
|
||||
items := os.Properties.Map["items"]
|
||||
if items.Type != "array" {
|
||||
t.Errorf("items.Type = %q, want \"array\"", items.Type)
|
||||
}
|
||||
if items.Items == nil {
|
||||
t.Fatal("items.Items is nil (array unfold failed)")
|
||||
}
|
||||
if items.Items.Type != "object" {
|
||||
t.Errorf("items.Items.Type = %q, want \"object\"", items.Items.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMeta_FullFields(t *testing.T) {
|
||||
// Synthesized method to avoid runtime variance from remote-cache overlay
|
||||
// (which strips `risk` from merged services). All other field semantics
|
||||
// match the real im.images.create entry in meta_data.json.
|
||||
method := map[string]interface{}{
|
||||
"risk": "write",
|
||||
"danger": true,
|
||||
"scopes": []interface{}{
|
||||
"im:resource:upload",
|
||||
"im:resource",
|
||||
},
|
||||
"accessTokens": []interface{}{"tenant"},
|
||||
"docUrl": "https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/image/create",
|
||||
}
|
||||
m := buildMeta(meta.FromMap(method))
|
||||
|
||||
if m.EnvelopeVersion != "1.0" {
|
||||
t.Errorf("EnvelopeVersion = %q", m.EnvelopeVersion)
|
||||
}
|
||||
if m.Risk != "write" {
|
||||
t.Errorf("Risk = %q, want \"write\"", m.Risk)
|
||||
}
|
||||
if !m.Danger {
|
||||
t.Errorf("Danger = false, want true")
|
||||
}
|
||||
if !reflect.DeepEqual(m.AccessTokens, []string{"bot"}) {
|
||||
t.Errorf("AccessTokens = %v, want [bot]", m.AccessTokens)
|
||||
}
|
||||
if m.DocURL == "" {
|
||||
t.Errorf("DocURL should be present for im.images.create")
|
||||
}
|
||||
if !reflect.DeepEqual(m.Scopes, []string{"im:resource:upload", "im:resource"}) {
|
||||
t.Errorf("Scopes = %v, want [im:resource:upload, im:resource] (meta_data natural order)", m.Scopes)
|
||||
}
|
||||
if m.RequiredScopes == nil {
|
||||
t.Errorf("RequiredScopes should be empty slice, not nil")
|
||||
}
|
||||
if len(m.RequiredScopes) != 0 {
|
||||
t.Errorf("RequiredScopes should be empty for this method, got %v", m.RequiredScopes)
|
||||
}
|
||||
if m.Affordance != nil {
|
||||
t.Errorf("Affordance must be nil when method has no affordance field, got %+v", m.Affordance)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMeta_MissingRiskDefaultsToRead(t *testing.T) {
|
||||
method := map[string]interface{}{
|
||||
"scopes": []interface{}{"x"},
|
||||
"accessTokens": []interface{}{"user"},
|
||||
// no risk field
|
||||
}
|
||||
m := buildMeta(meta.FromMap(method))
|
||||
if m.Risk != "read" {
|
||||
t.Errorf("Risk = %q, want \"read\" (default for missing risk)", m.Risk)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMeta_RequiredScopesPresent(t *testing.T) {
|
||||
method := loadMethodFromRegistry(t, "mail", []string{"user_mailbox", "messages"}, "get")
|
||||
m := buildMeta(method)
|
||||
if len(m.RequiredScopes) == 0 {
|
||||
t.Errorf("RequiredScopes should be non-empty for mail.user_mailbox.messages.get")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvert_EnumDescriptions(t *testing.T) {
|
||||
// options carrying descriptions -> enum + parallel enumDescriptions
|
||||
withDesc := Convert(meta.Field{Type: "string", Options: []meta.Option{
|
||||
{Value: "open_id", Description: "A"},
|
||||
{Value: "user_id", Description: "B"},
|
||||
}})
|
||||
if !reflect.DeepEqual(withDesc.Enum, []interface{}{"open_id", "user_id"}) {
|
||||
t.Errorf("Enum = %v", withDesc.Enum)
|
||||
}
|
||||
if !reflect.DeepEqual(withDesc.EnumDescriptions, []string{"A", "B"}) {
|
||||
t.Errorf("EnumDescriptions = %v, want [A B] aligned with enum", withDesc.EnumDescriptions)
|
||||
}
|
||||
|
||||
// bare enum form (no descriptions) -> enumDescriptions omitted (nil)
|
||||
bare := Convert(meta.Field{Type: "string", Enum: []any{"x", "y"}})
|
||||
if !reflect.DeepEqual(bare.Enum, []interface{}{"x", "y"}) {
|
||||
t.Errorf("bare Enum = %v", bare.Enum)
|
||||
}
|
||||
if bare.EnumDescriptions != nil {
|
||||
t.Errorf("bare enum must have nil EnumDescriptions, got %v", bare.EnumDescriptions)
|
||||
}
|
||||
|
||||
// enum + options both present -> enumDescriptions backfilled, aligned, "" where absent
|
||||
both := Convert(meta.Field{Type: "string", Enum: []any{"1", "2", "3"}, Options: []meta.Option{
|
||||
{Value: "1", Description: "from"},
|
||||
{Value: "2", Description: "to"},
|
||||
}})
|
||||
if !reflect.DeepEqual(both.Enum, []interface{}{"1", "2", "3"}) {
|
||||
t.Errorf("both Enum = %v", both.Enum)
|
||||
}
|
||||
if !reflect.DeepEqual(both.EnumDescriptions, []string{"from", "to", ""}) {
|
||||
t.Errorf("both EnumDescriptions = %v, want [from to \"\"] aligned with enum", both.EnumDescriptions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMeta_AffordanceFromMethod(t *testing.T) {
|
||||
method := map[string]interface{}{
|
||||
"scopes": []interface{}{"x"},
|
||||
"accessTokens": []interface{}{"user"},
|
||||
"risk": "read",
|
||||
"affordance": map[string]interface{}{
|
||||
"use_when": []interface{}{"trigger"},
|
||||
},
|
||||
}
|
||||
m := buildMeta(meta.FromMap(method))
|
||||
if m.Affordance == nil {
|
||||
t.Fatal("Affordance should be populated from method[\"affordance\"]")
|
||||
}
|
||||
if len(m.Affordance.UseWhen) != 1 || m.Affordance.UseWhen[0] != "trigger" {
|
||||
t.Errorf("UseWhen = %v", m.Affordance.UseWhen)
|
||||
}
|
||||
}
|
||||
|
||||
// EnvelopeOf injects affordance from the CLI overlay (looked up lazily by
|
||||
// service + method id), so a method whose metadata carries none still gets
|
||||
// guidance in its envelope when an overlay entry exists.
|
||||
func TestEnvelopeOf_AffordanceFromOverlay(t *testing.T) {
|
||||
// The overlay source is the top-level affordance/ tree, injected at startup;
|
||||
// inject a fixture so this unit test does not depend on the shipped content.
|
||||
// Reset afterwards (this binary installs no source by default) for isolation.
|
||||
t.Cleanup(func() { affordance.SetSource(nil) })
|
||||
affordance.SetSource(fstest.MapFS{"approval.md": &fstest.MapFile{Data: []byte(
|
||||
"# approval\n> skill: lark-approval\n\n## instances get\n查询某审批实例的状态与进度。\n\n### Examples\n\n**按 code 查询**\n```bash\nlark-cli approval instances get --instance-code \"x\"\n```\n")}})
|
||||
env := synthEnvelope("approval", []string{"instances"}, meta.Method{ID: "instances.get", Name: "get"})
|
||||
if env.Meta == nil || env.Meta.Affordance == nil {
|
||||
t.Fatal("expected affordance from the approval overlay, got none")
|
||||
}
|
||||
if len(env.Meta.Affordance.UseWhen) == 0 || len(env.Meta.Affordance.Examples) == 0 {
|
||||
t.Errorf("overlay affordance missing use_when/examples: %+v", env.Meta.Affordance)
|
||||
}
|
||||
|
||||
// A method id with no overlay entry carries no affordance.
|
||||
bare := synthEnvelope("approval", []string{"instances"}, meta.Method{ID: "instances.no_such_method", Name: "x"})
|
||||
if bare.Meta != nil && bare.Meta.Affordance != nil {
|
||||
t.Errorf("method without overlay should have no affordance, got %+v", bare.Meta.Affordance)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMeta_MissingDocURLOmitted(t *testing.T) {
|
||||
method := map[string]interface{}{
|
||||
"scopes": []interface{}{"x"},
|
||||
"accessTokens": []interface{}{"user"},
|
||||
"risk": "read",
|
||||
// no docUrl
|
||||
}
|
||||
m := buildMeta(meta.FromMap(method))
|
||||
if m.DocURL != "" {
|
||||
t.Errorf("DocURL = %q, want empty (will be omitempty)", m.DocURL)
|
||||
}
|
||||
// Verify JSON serialization omits doc_url
|
||||
b, _ := json.Marshal(m)
|
||||
if strings.Contains(string(b), "doc_url") {
|
||||
t.Errorf("doc_url should be omitted from JSON, got: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildOutputSchema_EmptyResponseBody(t *testing.T) {
|
||||
// 装配器对空 responseBody 应生成 properties = {} (不 nil)
|
||||
method := map[string]interface{}{}
|
||||
os := buildOutputSchema(meta.FromMap(method))
|
||||
if os.Type != "object" {
|
||||
t.Errorf("Type = %q, want \"object\"", os.Type)
|
||||
}
|
||||
if os.Properties == nil {
|
||||
t.Fatal("Properties is nil, want empty OrderedProps")
|
||||
}
|
||||
if len(os.Properties.Order) != 0 {
|
||||
t.Errorf("Properties.Order should be empty, got %v", os.Properties.Order)
|
||||
}
|
||||
}
|
||||
|
||||
// synthEnvelope renders an envelope for a synthetic (service, resourcePath, method)
|
||||
// via the public ref entry, so these unit tests build the same MethodRef the
|
||||
// command layer feeds Envelope.
|
||||
func synthEnvelope(serviceName string, resourcePath []string, m meta.Method) Envelope {
|
||||
return EnvelopeOf(apicatalog.MethodRef{Service: meta.Service{Name: serviceName}, ResourcePath: resourcePath, Method: m})
|
||||
}
|
||||
|
||||
func TestAssembleEnvelope_ReactionsList_FullStructure(t *testing.T) {
|
||||
method := loadMethodFromRegistry(t, "im", []string{"reactions"}, "list")
|
||||
env := synthEnvelope("im", []string{"reactions"}, method)
|
||||
|
||||
if env.Name != "im reactions list" {
|
||||
t.Errorf("Name = %q, want \"im reactions list\"", env.Name)
|
||||
}
|
||||
if env.Description == "" {
|
||||
t.Errorf("Description should not be empty for im.reactions.list")
|
||||
}
|
||||
if env.InputSchema == nil || env.OutputSchema == nil || env.Meta == nil {
|
||||
t.Fatal("InputSchema/OutputSchema/Meta must all be non-nil")
|
||||
}
|
||||
if env.Meta.EnvelopeVersion != "1.0" {
|
||||
t.Errorf("Meta.EnvelopeVersion = %q", env.Meta.EnvelopeVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleEnvelope_NestedResource_NameJoinedWithSpaces(t *testing.T) {
|
||||
// im.chat.members.create — resource path is one element "chat.members" with
|
||||
// an internal dot. Substituted from plan's `bots` because remote-cache
|
||||
// overlay strips `bots` from the loaded method map on this environment;
|
||||
// the assertion is about name joining, not method specifics.
|
||||
method := loadMethodFromRegistry(t, "im", []string{"chat.members"}, "create")
|
||||
env := synthEnvelope("im", []string{"chat.members"}, method)
|
||||
// chat.members resourcePath stays as one element in the slice with a dot;
|
||||
// name should split it to "im chat.members create" — we keep the dot as-is
|
||||
// inside the resource segment to round-trip with completion logic.
|
||||
if env.Name != "im chat.members create" {
|
||||
t.Errorf("Name = %q, want \"im chat.members create\"", env.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleEnvelope_JSONIsStable(t *testing.T) {
|
||||
// Assemble twice; JSON output must be byte-identical (determinism).
|
||||
method := loadMethodFromRegistry(t, "im", []string{"reactions"}, "list")
|
||||
a := synthEnvelope("im", []string{"reactions"}, method)
|
||||
b := synthEnvelope("im", []string{"reactions"}, method)
|
||||
ja, _ := json.MarshalIndent(a, "", " ")
|
||||
jb, _ := json.MarshalIndent(b, "", " ")
|
||||
if string(ja) != string(jb) {
|
||||
t.Errorf("envelope assembly is non-deterministic:\nfirst:\n%s\nsecond:\n%s", ja, jb)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleService_Im(t *testing.T) {
|
||||
svc, _ := registry.ServiceTyped("im")
|
||||
envs := Envelopes(apicatalog.ServiceMethods(svc, nil))
|
||||
if len(envs) == 0 {
|
||||
t.Fatal("expected non-empty envelopes for service im")
|
||||
}
|
||||
// Every envelope.Name starts with "im "
|
||||
for _, e := range envs {
|
||||
if !strings.HasPrefix(e.Name, "im ") {
|
||||
t.Errorf("envelope name %q does not start with \"im \"", e.Name)
|
||||
}
|
||||
}
|
||||
// Sorted by name
|
||||
for i := 1; i < len(envs); i++ {
|
||||
if envs[i-1].Name > envs[i].Name {
|
||||
t.Errorf("envelopes not sorted by name at idx %d: %q > %q", i, envs[i-1].Name, envs[i].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleService_FilterByAccessToken(t *testing.T) {
|
||||
svc, _ := registry.ServiceTyped("im")
|
||||
// Filter to bot-only (--as bot, which corresponds to "tenant")
|
||||
envs := Envelopes(apicatalog.ServiceMethods(svc, func(m meta.Method) bool {
|
||||
for _, t := range m.AccessTokens {
|
||||
if t == "tenant" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}))
|
||||
// Every envelope's _meta.access_tokens must contain "bot"
|
||||
for _, e := range envs {
|
||||
found := false
|
||||
for _, t := range e.Meta.AccessTokens {
|
||||
if t == "bot" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("envelope %q does not declare bot access", e.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleAll_AtLeast193(t *testing.T) {
|
||||
envs := Envelopes(registry.EmbeddedCatalog().WalkMethods(nil))
|
||||
// Envelope assembly is overlay-independent: it walks the embedded
|
||||
// meta_data.json directly, so the count is stable across machines.
|
||||
if len(envs) < 193 {
|
||||
t.Errorf("envelope count = %d, expected >= 193", len(envs))
|
||||
}
|
||||
// Spot check: im reactions list should be present
|
||||
found := false
|
||||
for _, e := range envs {
|
||||
if e.Name == "im reactions list" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("im reactions list not found in AssembleAll output")
|
||||
}
|
||||
}
|
||||
|
||||
// loadMethodFromRegistry is a test helper that pulls one method from the real
|
||||
// embedded meta_data.json via the registry's typed accessor, with Name set.
|
||||
func loadMethodFromRegistry(t *testing.T, service string, resourcePath []string, methodName string) meta.Method {
|
||||
t.Helper()
|
||||
svc, ok := registry.ServiceTyped(service)
|
||||
if !ok {
|
||||
t.Fatalf("service %q not found in registry", service)
|
||||
}
|
||||
resKey := strings.Join(resourcePath, ".")
|
||||
res, ok := svc.Resources[resKey]
|
||||
if !ok {
|
||||
t.Fatalf("resource %q.%s not found", service, resKey)
|
||||
}
|
||||
m, ok := res.Methods[methodName]
|
||||
if !ok {
|
||||
t.Fatalf("method %q.%s.%s not found", service, resKey, methodName)
|
||||
}
|
||||
m.Name = methodName
|
||||
return m
|
||||
}
|
||||
|
||||
// convertProperty is a test helper: it decodes a single field-spec map into a
|
||||
// meta.Field and renders its Property (the conversion the assembler does).
|
||||
func convertProperty(fieldMap map[string]interface{}, _ string) Property {
|
||||
b, _ := json.Marshal(fieldMap)
|
||||
var f meta.Field
|
||||
_ = json.Unmarshal(b, &f)
|
||||
return Convert(f)
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
)
|
||||
|
||||
var validJSONSchemaTypes = map[string]bool{
|
||||
"string": true,
|
||||
"integer": true,
|
||||
"number": true,
|
||||
"boolean": true,
|
||||
"array": true,
|
||||
"object": true,
|
||||
}
|
||||
|
||||
var validAccessTokens = map[string]bool{
|
||||
"user": true,
|
||||
"bot": true,
|
||||
}
|
||||
|
||||
// lintEnvelope runs L1-L3 checks and returns a list of errors. Empty slice
|
||||
// means the envelope is compliant.
|
||||
func lintEnvelope(env Envelope) []error {
|
||||
var errs []error
|
||||
|
||||
// ---- L1: structural ----
|
||||
if env.Name == "" {
|
||||
errs = append(errs, errors.New("L1: name must not be empty"))
|
||||
}
|
||||
if env.InputSchema == nil {
|
||||
errs = append(errs, errors.New("L1: inputSchema must not be nil"))
|
||||
} else {
|
||||
if env.InputSchema.Type != "object" {
|
||||
errs = append(errs, fmt.Errorf("L1: inputSchema.type = %q, want \"object\"", env.InputSchema.Type))
|
||||
}
|
||||
if env.InputSchema.Properties == nil {
|
||||
errs = append(errs, errors.New("L1: inputSchema.properties must not be nil"))
|
||||
}
|
||||
}
|
||||
if env.OutputSchema == nil {
|
||||
errs = append(errs, errors.New("L1: outputSchema must not be nil"))
|
||||
} else {
|
||||
if env.OutputSchema.Type != "object" {
|
||||
errs = append(errs, fmt.Errorf("L1: outputSchema.type = %q, want \"object\"", env.OutputSchema.Type))
|
||||
}
|
||||
}
|
||||
if env.Meta == nil {
|
||||
errs = append(errs, errors.New("L1: _meta must not be nil"))
|
||||
// Cannot continue meta-dependent checks
|
||||
return errs
|
||||
}
|
||||
if env.Meta.EnvelopeVersion != "1.0" {
|
||||
errs = append(errs, fmt.Errorf("L1: _meta.envelope_version = %q, want \"1.0\"", env.Meta.EnvelopeVersion))
|
||||
}
|
||||
|
||||
// L1: validate every Property type recursively
|
||||
if env.InputSchema != nil && env.InputSchema.Properties != nil {
|
||||
validatePropertyTypes(env.InputSchema.Properties, &errs)
|
||||
}
|
||||
if env.OutputSchema != nil && env.OutputSchema.Properties != nil {
|
||||
validatePropertyTypes(env.OutputSchema.Properties, &errs)
|
||||
}
|
||||
|
||||
// ---- L2: type-level consistency ----
|
||||
if env.InputSchema != nil && env.InputSchema.Properties != nil {
|
||||
// Walk the whole property tree so format/min-max checks reach leaf
|
||||
// fields nested under the params/data wrapper.
|
||||
walkForL2(env.InputSchema.Properties, &errs)
|
||||
// Top-level required keys must exist in top-level properties.
|
||||
for _, r := range env.InputSchema.Required {
|
||||
if _, ok := env.InputSchema.Properties.Map[r]; !ok {
|
||||
errs = append(errs, fmt.Errorf("L2: required key %q not found in properties", r))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- L3: cross-field self-consistency ----
|
||||
dangerExpected := env.Meta.Risk == core.RiskWrite || env.Meta.Risk == core.RiskHighRiskWrite
|
||||
if env.Meta.Danger != dangerExpected {
|
||||
errs = append(errs, fmt.Errorf("L3: _meta.danger=%v inconsistent with risk=%q", env.Meta.Danger, env.Meta.Risk))
|
||||
}
|
||||
|
||||
// `yes` lives at inputSchema.properties.yes (sibling of params/data),
|
||||
// injected only for risk == RiskHighRiskWrite.
|
||||
hasYes := false
|
||||
if env.InputSchema != nil && env.InputSchema.Properties != nil {
|
||||
_, hasYes = env.InputSchema.Properties.Map["yes"]
|
||||
}
|
||||
wantYes := env.Meta.Risk == core.RiskHighRiskWrite
|
||||
if hasYes != wantYes {
|
||||
errs = append(errs, fmt.Errorf("L3: inputSchema `yes` property=%v inconsistent with risk=%q", hasYes, env.Meta.Risk))
|
||||
}
|
||||
|
||||
if len(env.Meta.AccessTokens) == 0 {
|
||||
errs = append(errs, errors.New("L3: _meta.access_tokens must not be empty"))
|
||||
}
|
||||
for _, t := range env.Meta.AccessTokens {
|
||||
if !validAccessTokens[t] {
|
||||
errs = append(errs, fmt.Errorf("L3: _meta.access_tokens contains invalid value %q (allowed: user, bot)", t))
|
||||
}
|
||||
}
|
||||
|
||||
return errs
|
||||
}
|
||||
|
||||
// walkForL2 recursively applies per-field L2 checks (format:binary on
|
||||
// non-string; minimum>=maximum) plus the sub-object required-exists invariant.
|
||||
// Required only matters on object-typed Properties (e.g. the params / data
|
||||
// wrappers); leaf scalars ignore it.
|
||||
func walkForL2(props *OrderedProps, errs *[]error) {
|
||||
if props == nil {
|
||||
return
|
||||
}
|
||||
for _, k := range props.Order {
|
||||
p := props.Map[k]
|
||||
if p.Format == "binary" && p.Type != "string" {
|
||||
*errs = append(*errs, fmt.Errorf("L2: field %q has format: binary but type = %q (want string)", k, p.Type))
|
||||
}
|
||||
if p.Minimum != nil && p.Maximum != nil && *p.Minimum >= *p.Maximum {
|
||||
*errs = append(*errs, fmt.Errorf("L2: field %q minimum (%v) >= maximum (%v)", k, *p.Minimum, *p.Maximum))
|
||||
}
|
||||
if n := len(p.EnumDescriptions); n > 0 && n != len(p.Enum) {
|
||||
*errs = append(*errs, fmt.Errorf("L2: field %q enumDescriptions length (%d) != enum length (%d)", k, n, len(p.Enum)))
|
||||
}
|
||||
if len(p.Required) > 0 && p.Properties != nil {
|
||||
for _, r := range p.Required {
|
||||
if _, ok := p.Properties.Map[r]; !ok {
|
||||
*errs = append(*errs, fmt.Errorf("L2: required key %q in %q not found in its properties", r, k))
|
||||
}
|
||||
}
|
||||
}
|
||||
if p.Properties != nil {
|
||||
walkForL2(p.Properties, errs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// validatePropertyTypes walks an OrderedProps tree and asserts:
|
||||
// - every Property.Type is in validJSONSchemaTypes (or empty for nested objects with only properties)
|
||||
// - array Properties have Items
|
||||
//
|
||||
// Errors are appended to *errs.
|
||||
func validatePropertyTypes(props *OrderedProps, errs *[]error) {
|
||||
if props == nil {
|
||||
return
|
||||
}
|
||||
for _, k := range props.Order {
|
||||
p := props.Map[k]
|
||||
if p.Type != "" && !validJSONSchemaTypes[p.Type] {
|
||||
*errs = append(*errs, fmt.Errorf("L1: property %q has invalid type %q", k, p.Type))
|
||||
}
|
||||
if p.Type == "array" && p.Items == nil {
|
||||
*errs = append(*errs, fmt.Errorf("L1: array property %q missing items", k))
|
||||
}
|
||||
if p.Properties != nil {
|
||||
validatePropertyTypes(p.Properties, errs)
|
||||
}
|
||||
// Validate the array-element schema itself, not only its child
|
||||
// properties — a primitive element with an invalid type (e.g.
|
||||
// `items.type = "list"`) would otherwise slip past lint.
|
||||
if p.Items != nil {
|
||||
validateItemSchema(k, p.Items, errs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// validateItemSchema checks a single array element schema for invalid types,
|
||||
// then recurses into any further nested properties/items.
|
||||
func validateItemSchema(parentKey string, item *Property, errs *[]error) {
|
||||
if item.Type != "" && !validJSONSchemaTypes[item.Type] {
|
||||
*errs = append(*errs, fmt.Errorf("L1: array property %q items has invalid type %q", parentKey, item.Type))
|
||||
}
|
||||
if item.Type == "array" && item.Items == nil {
|
||||
*errs = append(*errs, fmt.Errorf("L1: array property %q items (nested array) missing items", parentKey))
|
||||
}
|
||||
if item.Properties != nil {
|
||||
validatePropertyTypes(item.Properties, errs)
|
||||
}
|
||||
if item.Items != nil {
|
||||
validateItemSchema(parentKey, item.Items, errs)
|
||||
}
|
||||
}
|
||||
|
||||
// coverageBaseline is the per-metric warn threshold for L4 coverage checks.
|
||||
// If the measured rate drops below the baseline, t.Logf emits a warning but
|
||||
// does NOT fail the test. Adjust these constants upward as meta_data quality
|
||||
// improves over time.
|
||||
var coverageBaseline = map[string]float64{
|
||||
"description": 0.99,
|
||||
"scopes": 1.00,
|
||||
"doc_url": 0.98,
|
||||
"risk": 0.96,
|
||||
}
|
||||
|
||||
// measureCoverage returns the non-empty rate for each tracked metric.
|
||||
func measureCoverage(envs []Envelope) map[string]float64 {
|
||||
if len(envs) == 0 {
|
||||
return map[string]float64{
|
||||
"description": 0,
|
||||
"scopes": 0,
|
||||
"doc_url": 0,
|
||||
"risk": 0,
|
||||
}
|
||||
}
|
||||
total := float64(len(envs))
|
||||
var descNonEmpty, scopesNonEmpty, docURLNonEmpty, riskNonEmpty float64
|
||||
for _, e := range envs {
|
||||
if e.Description != "" {
|
||||
descNonEmpty++
|
||||
}
|
||||
if e.Meta == nil {
|
||||
continue
|
||||
}
|
||||
if len(e.Meta.Scopes) > 0 {
|
||||
scopesNonEmpty++
|
||||
}
|
||||
if e.Meta.DocURL != "" {
|
||||
docURLNonEmpty++
|
||||
}
|
||||
if e.Meta.Risk != "" {
|
||||
riskNonEmpty++
|
||||
}
|
||||
}
|
||||
return map[string]float64{
|
||||
"description": descNonEmpty / total,
|
||||
"scopes": scopesNonEmpty / total,
|
||||
"doc_url": docURLNonEmpty / total,
|
||||
"risk": riskNonEmpty / total,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/apicatalog"
|
||||
"github.com/larksuite/cli/internal/registry"
|
||||
)
|
||||
|
||||
// validEnvelope builds a baseline valid envelope used as a starting point in
|
||||
// negative tests below.
|
||||
func validEnvelope() Envelope {
|
||||
props := &OrderedProps{Map: map[string]Property{}}
|
||||
return Envelope{
|
||||
Name: "x y z",
|
||||
Description: "ok",
|
||||
InputSchema: &InputSchema{
|
||||
Type: "object",
|
||||
Properties: props,
|
||||
},
|
||||
OutputSchema: &OutputSchema{
|
||||
Type: "object",
|
||||
Properties: &OrderedProps{Map: map[string]Property{}},
|
||||
},
|
||||
Meta: &Meta{
|
||||
EnvelopeVersion: "1.0",
|
||||
AccessTokens: []string{"user"},
|
||||
Risk: "read",
|
||||
Danger: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintEnvelope_Valid(t *testing.T) {
|
||||
env := validEnvelope()
|
||||
errs := lintEnvelope(env)
|
||||
if len(errs) != 0 {
|
||||
t.Errorf("expected no errors, got: %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintEnvelope_L1_StructuralChecks(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Envelope)
|
||||
wantSub string
|
||||
}{
|
||||
{
|
||||
name: "empty name",
|
||||
mutate: func(e *Envelope) { e.Name = "" },
|
||||
wantSub: "name",
|
||||
},
|
||||
{
|
||||
name: "nil InputSchema",
|
||||
mutate: func(e *Envelope) { e.InputSchema = nil },
|
||||
wantSub: "inputSchema",
|
||||
},
|
||||
{
|
||||
name: "inputSchema type not object",
|
||||
mutate: func(e *Envelope) { e.InputSchema.Type = "string" },
|
||||
wantSub: "inputSchema.type",
|
||||
},
|
||||
{
|
||||
name: "nil OutputSchema",
|
||||
mutate: func(e *Envelope) { e.OutputSchema = nil },
|
||||
wantSub: "outputSchema",
|
||||
},
|
||||
{
|
||||
name: "nil Meta",
|
||||
mutate: func(e *Envelope) { e.Meta = nil },
|
||||
wantSub: "_meta",
|
||||
},
|
||||
{
|
||||
name: "wrong envelope version",
|
||||
mutate: func(e *Envelope) { e.Meta.EnvelopeVersion = "0.9" },
|
||||
wantSub: "envelope_version",
|
||||
},
|
||||
{
|
||||
name: "invalid property type",
|
||||
mutate: func(e *Envelope) {
|
||||
e.InputSchema.Properties.Order = []string{"x"}
|
||||
e.InputSchema.Properties.Map["x"] = Property{Type: "unknown_type"}
|
||||
},
|
||||
wantSub: "invalid type",
|
||||
},
|
||||
{
|
||||
name: "array missing items",
|
||||
mutate: func(e *Envelope) {
|
||||
e.InputSchema.Properties.Order = []string{"x"}
|
||||
e.InputSchema.Properties.Map["x"] = Property{Type: "array"} // no Items
|
||||
},
|
||||
wantSub: "items",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
env := validEnvelope()
|
||||
tt.mutate(&env)
|
||||
errs := lintEnvelope(env)
|
||||
if len(errs) == 0 {
|
||||
t.Fatalf("expected lint error, got none")
|
||||
}
|
||||
found := false
|
||||
for _, e := range errs {
|
||||
if strings.Contains(e.Error(), tt.wantSub) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("expected error containing %q, got: %v", tt.wantSub, errs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintEnvelope_L2_TypeChecks(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Envelope)
|
||||
wantSub string
|
||||
}{
|
||||
{
|
||||
name: "format binary on non-string",
|
||||
mutate: func(e *Envelope) {
|
||||
e.InputSchema.Properties.Order = []string{"f"}
|
||||
e.InputSchema.Properties.Map["f"] = Property{Type: "integer", Format: "binary"}
|
||||
},
|
||||
wantSub: "format: binary",
|
||||
},
|
||||
{
|
||||
name: "required key not in properties",
|
||||
mutate: func(e *Envelope) {
|
||||
e.InputSchema.Required = []string{"nonexistent"}
|
||||
},
|
||||
wantSub: "required",
|
||||
},
|
||||
{
|
||||
name: "minimum >= maximum",
|
||||
mutate: func(e *Envelope) {
|
||||
min, max := 50.0, 10.0
|
||||
e.InputSchema.Properties.Order = []string{"n"}
|
||||
e.InputSchema.Properties.Map["n"] = Property{Type: "integer", Minimum: &min, Maximum: &max}
|
||||
},
|
||||
wantSub: "minimum",
|
||||
},
|
||||
{
|
||||
name: "enumDescriptions length must match enum",
|
||||
mutate: func(e *Envelope) {
|
||||
e.InputSchema.Properties.Order = []string{"k"}
|
||||
e.InputSchema.Properties.Map["k"] = Property{
|
||||
Type: "string",
|
||||
Enum: []interface{}{"a", "b", "c"},
|
||||
EnumDescriptions: []string{"only one"}, // misaligned with 3 enum values
|
||||
}
|
||||
},
|
||||
wantSub: "enumDescriptions",
|
||||
},
|
||||
{
|
||||
// Regression guard: walkForL2 must recurse into the params/data
|
||||
// sub-objects introduced by the 4-bucket inputSchema, not only the
|
||||
// top-level Properties map.
|
||||
name: "format binary on non-string inside params sub-object",
|
||||
mutate: func(e *Envelope) {
|
||||
e.InputSchema.Properties.Order = []string{"params"}
|
||||
e.InputSchema.Properties.Map["params"] = Property{
|
||||
Type: "object",
|
||||
Properties: &OrderedProps{
|
||||
Order: []string{"id"},
|
||||
Map: map[string]Property{
|
||||
"id": {Type: "integer", Format: "binary"}, // wrong: binary on integer
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
wantSub: "format: binary",
|
||||
},
|
||||
{
|
||||
name: "sub-object required references missing property",
|
||||
mutate: func(e *Envelope) {
|
||||
e.InputSchema.Properties.Order = []string{"data"}
|
||||
e.InputSchema.Properties.Map["data"] = Property{
|
||||
Type: "object",
|
||||
Required: []string{"ghost"}, // not in properties below
|
||||
Properties: &OrderedProps{
|
||||
Order: []string{"real"},
|
||||
Map: map[string]Property{"real": {Type: "string"}},
|
||||
},
|
||||
}
|
||||
},
|
||||
wantSub: "ghost",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
env := validEnvelope()
|
||||
tt.mutate(&env)
|
||||
errs := lintEnvelope(env)
|
||||
if len(errs) == 0 {
|
||||
t.Fatalf("expected lint error, got none")
|
||||
}
|
||||
found := false
|
||||
for _, e := range errs {
|
||||
if strings.Contains(e.Error(), tt.wantSub) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("expected error containing %q, got: %v", tt.wantSub, errs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintEnvelope_L3_CrossFieldChecks(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Envelope)
|
||||
wantSub string
|
||||
}{
|
||||
{
|
||||
name: "danger true but risk read",
|
||||
mutate: func(e *Envelope) {
|
||||
e.Meta.Danger = true
|
||||
e.Meta.Risk = "read"
|
||||
},
|
||||
wantSub: "danger",
|
||||
},
|
||||
{
|
||||
name: "high-risk-write without yes",
|
||||
mutate: func(e *Envelope) {
|
||||
e.Meta.Risk = "high-risk-write"
|
||||
e.Meta.Danger = true
|
||||
// no yes injection
|
||||
},
|
||||
wantSub: "yes",
|
||||
},
|
||||
{
|
||||
name: "yes injected but risk not high-risk-write",
|
||||
mutate: func(e *Envelope) {
|
||||
e.InputSchema.Properties.Order = []string{"yes"}
|
||||
e.InputSchema.Properties.Map["yes"] = Property{Type: "boolean"}
|
||||
},
|
||||
wantSub: "yes",
|
||||
},
|
||||
{
|
||||
name: "empty access_tokens",
|
||||
mutate: func(e *Envelope) {
|
||||
e.Meta.AccessTokens = []string{}
|
||||
},
|
||||
wantSub: "access_tokens",
|
||||
},
|
||||
{
|
||||
name: "invalid access_token value",
|
||||
mutate: func(e *Envelope) {
|
||||
e.Meta.AccessTokens = []string{"admin"}
|
||||
},
|
||||
wantSub: "access_tokens",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
env := validEnvelope()
|
||||
tt.mutate(&env)
|
||||
errs := lintEnvelope(env)
|
||||
if len(errs) == 0 {
|
||||
t.Fatalf("expected lint error, got none")
|
||||
}
|
||||
found := false
|
||||
for _, e := range errs {
|
||||
if strings.Contains(e.Error(), tt.wantSub) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("expected error containing %q, got: %v", tt.wantSub, errs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMeasureCoverage_Counts(t *testing.T) {
|
||||
envs := []Envelope{
|
||||
{Description: "ok", Meta: &Meta{Scopes: []string{"s"}, Risk: "read", DocURL: "http://x"}},
|
||||
{Description: "", Meta: &Meta{Scopes: []string{}, Risk: "", DocURL: ""}},
|
||||
{Description: "ok2", Meta: &Meta{Scopes: []string{"s"}, Risk: "write", DocURL: "http://y"}},
|
||||
}
|
||||
c := measureCoverage(envs)
|
||||
// 2/3 have non-empty description = ~0.667
|
||||
if c["description"] < 0.66 || c["description"] > 0.67 {
|
||||
t.Errorf("description coverage = %v, want ~0.667", c["description"])
|
||||
}
|
||||
// 2/3 have non-empty scopes
|
||||
if c["scopes"] < 0.66 || c["scopes"] > 0.67 {
|
||||
t.Errorf("scopes coverage = %v, want ~0.667", c["scopes"])
|
||||
}
|
||||
// 2/3 have doc_url
|
||||
if c["doc_url"] < 0.66 || c["doc_url"] > 0.67 {
|
||||
t.Errorf("doc_url coverage = %v, want ~0.667", c["doc_url"])
|
||||
}
|
||||
// 2/3 have non-empty risk (but our builder always fills risk with "read" default — this test uses raw envs)
|
||||
if c["risk"] < 0.66 || c["risk"] > 0.67 {
|
||||
t.Errorf("risk coverage = %v, want ~0.667", c["risk"])
|
||||
}
|
||||
}
|
||||
|
||||
// isKnownDataInconsistency returns true for lint errors that originate from
|
||||
// real meta_data quality issues we still have to ship around in PR-1. With
|
||||
// Task 17b the assembler walks embedded data only, so overlay-induced
|
||||
// inconsistencies (risk-stripping) no longer appear; only the true embedded
|
||||
// meta_data data-quality patterns remain.
|
||||
//
|
||||
// As meta_data quality improves this filter should be tightened/removed so
|
||||
// TestAllEnvelopesPass becomes a hard gate again.
|
||||
func isKnownDataInconsistency(msg string) bool {
|
||||
switch {
|
||||
case strings.Contains(msg, `L3: _meta.danger=false inconsistent with risk="write"`):
|
||||
// Embedded meta_data has ~7 envelopes (e.g. attendance.user_tasks.query,
|
||||
// drive.user.subscription, mail.user_mailbox.event.subscribe) where
|
||||
// `risk="write"` but `danger` is missing (defaults to false). Needs a
|
||||
// meta_data fix to set danger=true on these write methods.
|
||||
return true
|
||||
case strings.Contains(msg, `L3: _meta.danger=true inconsistent with risk="read"`):
|
||||
// Embedded meta_data has ~9 envelopes (e.g. calendar.events.search_event,
|
||||
// drive.metas.batch_query, mail.user_mailbox.templates.create) where
|
||||
// `danger=true` but `risk` is missing (defaults to "read"). Needs a
|
||||
// meta_data fix to set the proper risk level on these methods.
|
||||
return true
|
||||
case strings.Contains(msg, "L2: field") && strings.Contains(msg, "minimum") && strings.Contains(msg, "maximum"):
|
||||
// meta_data sets min == max on some fields (e.g.
|
||||
// mail.user_mailbox.event.subscribe.event_type), which the lint reads
|
||||
// as min >= max. Real fix is in meta_data.
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestAllEnvelopesPass(t *testing.T) {
|
||||
failCount := 0
|
||||
knownWarnings := 0
|
||||
knownEnvelopes := map[string]bool{}
|
||||
// Use embedded data only so the gate is deterministic across machines
|
||||
// (matches Task 17b: envelope assembly is overlay-independent).
|
||||
for _, svc := range registry.EmbeddedServicesTyped() {
|
||||
envs := Envelopes(apicatalog.ServiceMethods(svc, nil))
|
||||
for _, env := range envs {
|
||||
errs := lintEnvelope(env)
|
||||
if len(errs) == 0 {
|
||||
continue
|
||||
}
|
||||
var realErrs []error
|
||||
for _, e := range errs {
|
||||
if isKnownDataInconsistency(e.Error()) {
|
||||
t.Logf("env %s skipped: known data-level inconsistency: %v", env.Name, e)
|
||||
knownWarnings++
|
||||
knownEnvelopes[env.Name] = true
|
||||
continue
|
||||
}
|
||||
realErrs = append(realErrs, e)
|
||||
}
|
||||
if len(realErrs) > 0 {
|
||||
for _, e := range realErrs {
|
||||
t.Errorf("%s: %v", env.Name, e)
|
||||
}
|
||||
failCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Logf("L1-L3 known data-level inconsistencies: %d warnings across %d envelopes (danger/risk mismatch + min==max)", knownWarnings, len(knownEnvelopes))
|
||||
if failCount > 0 {
|
||||
t.Fatalf("%d envelopes failed L1-L3 lint with non-data-level errors", failCount)
|
||||
}
|
||||
|
||||
// L4 coverage report (warn-only via t.Logf)
|
||||
all := Envelopes(registry.EmbeddedCatalog().WalkMethods(nil))
|
||||
c := measureCoverage(all)
|
||||
for metric, rate := range c {
|
||||
baseline := coverageBaseline[metric]
|
||||
if rate < baseline {
|
||||
t.Logf("L4 coverage warn: %s = %.1f%% (baseline: %.1f%%)", metric, rate*100, baseline*100)
|
||||
} else {
|
||||
t.Logf("L4 coverage ok: %s = %.1f%% (baseline: %.1f%%)", metric, rate*100, baseline*100)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/larksuite/cli/internal/meta"
|
||||
)
|
||||
|
||||
// Envelope is the MCP Tool spec contract for a single API method command.
|
||||
//
|
||||
// The REST route (httpMethod/path) is deliberately NOT exposed: every
|
||||
// schema-resolvable method already has a typed command, so the raw path would
|
||||
// only tempt an agent toward the `api` escape hatch.
|
||||
type Envelope struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema *InputSchema `json:"inputSchema"`
|
||||
OutputSchema *OutputSchema `json:"outputSchema"`
|
||||
Meta *Meta `json:"_meta"`
|
||||
}
|
||||
|
||||
// InputSchema is JSON Schema Draft 2020-12 flattened.
|
||||
//
|
||||
// Required is intentionally rendered (no omitempty) so the envelope shape
|
||||
// stays stable for AI consumers — an empty []string means "no required
|
||||
// fields" rather than "schema is missing the field".
|
||||
type InputSchema struct {
|
||||
Type string `json:"type"`
|
||||
Required []string `json:"required"`
|
||||
Properties *OrderedProps `json:"properties"`
|
||||
}
|
||||
|
||||
// OutputSchema wraps responseBody into a JSON Schema object.
|
||||
type OutputSchema struct {
|
||||
Type string `json:"type"`
|
||||
Properties *OrderedProps `json:"properties"`
|
||||
}
|
||||
|
||||
// Property is one field's JSON Schema shape, recursive.
|
||||
//
|
||||
// Required is used when Property describes a nested object (e.g. the
|
||||
// "params" / "data" sub-objects inside inputSchema): it lists which keys
|
||||
// inside that object's Properties are mandatory. Leaf fields ignore it.
|
||||
type Property struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
// Flag is the typed CLI flag a params property maps to (e.g. "--folder-id");
|
||||
// absent on body/file fields, which travel via the section's Carrier.
|
||||
Flag string `json:"flag,omitempty"`
|
||||
// Carrier names the flag a whole inputSchema section travels on ("--data" /
|
||||
// "--file"); empty on the params section, whose properties carry their Flag.
|
||||
Carrier string `json:"carrier,omitempty"`
|
||||
Enum []interface{} `json:"enum,omitempty"`
|
||||
// EnumDescriptions, when present, is parallel to Enum: the human meaning of
|
||||
// each allowed value, in the same order. Omitted when no value carries a
|
||||
// description. This is the widely-recognized JSON-Schema extension (VS Code,
|
||||
// OpenAPI tooling) that lets an AI consumer learn what each enum value means
|
||||
// without a second lookup.
|
||||
EnumDescriptions []string `json:"enumDescriptions,omitempty"`
|
||||
Default interface{} `json:"default,omitempty"`
|
||||
Example interface{} `json:"example,omitempty"`
|
||||
Minimum *float64 `json:"minimum,omitempty"`
|
||||
Maximum *float64 `json:"maximum,omitempty"`
|
||||
Format string `json:"format,omitempty"`
|
||||
Required []string `json:"required,omitempty"`
|
||||
Properties *OrderedProps `json:"properties,omitempty"`
|
||||
Items *Property `json:"items,omitempty"`
|
||||
}
|
||||
|
||||
// Meta is the Lark-specific extension namespace.
|
||||
type Meta struct {
|
||||
EnvelopeVersion string `json:"envelope_version"`
|
||||
Scopes []string `json:"scopes"`
|
||||
RequiredScopes []string `json:"required_scopes"`
|
||||
AccessTokens []string `json:"access_tokens"`
|
||||
Danger bool `json:"danger"`
|
||||
Risk string `json:"risk"`
|
||||
DocURL string `json:"doc_url,omitempty"`
|
||||
Affordance *meta.Affordance `json:"affordance,omitempty"`
|
||||
}
|
||||
|
||||
// OrderedProps is map[string]Property with preserved key order on MarshalJSON.
|
||||
// It is used wherever JSON output must reflect meta_data.json's natural field
|
||||
// order rather than Go's default alphabetical map encoding.
|
||||
type OrderedProps struct {
|
||||
Order []string
|
||||
Map map[string]Property
|
||||
}
|
||||
|
||||
// Set adds or replaces a property, recording first-seen keys in Order so JSON
|
||||
// output preserves insertion order. Re-setting an existing key updates its
|
||||
// value without reordering. Centralizing mutation here keeps Order and Map from
|
||||
// drifting out of sync.
|
||||
func (o *OrderedProps) Set(key string, p Property) {
|
||||
if o.Map == nil {
|
||||
o.Map = make(map[string]Property)
|
||||
}
|
||||
if _, exists := o.Map[key]; !exists {
|
||||
o.Order = append(o.Order, key)
|
||||
}
|
||||
o.Map[key] = p
|
||||
}
|
||||
|
||||
// MarshalJSON emits keys in Order, not alphabetical. If Order is empty but
|
||||
// Map has entries, fall back to alphabetical key order over Map so callers
|
||||
// that only populated Map (no explicit ordering) still see their fields.
|
||||
func (o *OrderedProps) MarshalJSON() ([]byte, error) {
|
||||
if o == nil || (len(o.Order) == 0 && len(o.Map) == 0) {
|
||||
return []byte("{}"), nil
|
||||
}
|
||||
keys := o.Order
|
||||
if len(keys) == 0 {
|
||||
keys = make([]string, 0, len(o.Map))
|
||||
for k := range o.Map {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte('{')
|
||||
for i, k := range keys {
|
||||
if i > 0 {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
keyJSON, err := json.Marshal(k)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal key %q: %w", k, err)
|
||||
}
|
||||
buf.Write(keyJSON)
|
||||
buf.WriteByte(':')
|
||||
valJSON, err := json.Marshal(o.Map[k])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal value for %q: %w", k, err)
|
||||
}
|
||||
buf.Write(valJSON)
|
||||
}
|
||||
buf.WriteByte('}')
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON parses an object preserving key order via json.Decoder.Token().
|
||||
// Used for round-tripping in tests (and future golden update flows).
|
||||
func (o *OrderedProps) UnmarshalJSON(data []byte) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if delim, ok := tok.(json.Delim); !ok || delim != '{' {
|
||||
return fmt.Errorf("expected object, got %v", tok)
|
||||
}
|
||||
o.Order = nil
|
||||
o.Map = make(map[string]Property)
|
||||
for dec.More() {
|
||||
keyTok, err := dec.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, ok := keyTok.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected string key, got %v", keyTok)
|
||||
}
|
||||
var prop Property
|
||||
if err := dec.Decode(&prop); err != nil {
|
||||
return err
|
||||
}
|
||||
o.Order = append(o.Order, key)
|
||||
o.Map[key] = prop
|
||||
}
|
||||
if _, err := dec.Token(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOrderedProps_Set(t *testing.T) {
|
||||
op := &OrderedProps{}
|
||||
op.Set("b", Property{Type: "string"})
|
||||
op.Set("a", Property{Type: "integer"})
|
||||
op.Set("b", Property{Type: "boolean"}) // re-set: updates value, keeps position
|
||||
|
||||
wantOrder := []string{"b", "a"}
|
||||
if len(op.Order) != len(wantOrder) || op.Order[0] != "b" || op.Order[1] != "a" {
|
||||
t.Errorf("Order = %v, want %v (insertion order, no duplicate on re-set)", op.Order, wantOrder)
|
||||
}
|
||||
if op.Map["b"].Type != "boolean" {
|
||||
t.Errorf("re-set value = %q, want boolean", op.Map["b"].Type)
|
||||
}
|
||||
}
|
||||
|
||||
// OrderedProps 在测试里验证:MarshalJSON 按 Order 切片顺序输出 key,跳过 Go map 默认字母序。
|
||||
func TestOrderedProps_MarshalJSON_PreservesOrder(t *testing.T) {
|
||||
op := &OrderedProps{
|
||||
Order: []string{"z_first", "a_second", "m_third"},
|
||||
Map: map[string]Property{
|
||||
"z_first": {Type: "string"},
|
||||
"a_second": {Type: "integer"},
|
||||
"m_third": {Type: "boolean"},
|
||||
},
|
||||
}
|
||||
b, err := json.Marshal(op)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal failed: %v", err)
|
||||
}
|
||||
got := string(b)
|
||||
want := `{"z_first":{"type":"string"},"a_second":{"type":"integer"},"m_third":{"type":"boolean"}}`
|
||||
if got != want {
|
||||
t.Errorf("OrderedProps key order not preserved:\ngot: %s\nwant: %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderedProps_MarshalJSON_Empty(t *testing.T) {
|
||||
op := &OrderedProps{Order: nil, Map: nil}
|
||||
b, err := json.Marshal(op)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal failed: %v", err)
|
||||
}
|
||||
if string(b) != "{}" {
|
||||
t.Errorf("empty OrderedProps should marshal to {}, got: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderedProps_UnmarshalJSON_RoundTrip(t *testing.T) {
|
||||
in := []byte(`{"first":{"type":"string"},"second":{"type":"integer"}}`)
|
||||
var op OrderedProps
|
||||
if err := json.Unmarshal(in, &op); err != nil {
|
||||
t.Fatalf("Unmarshal failed: %v", err)
|
||||
}
|
||||
if len(op.Order) != 2 {
|
||||
t.Fatalf("expected 2 keys, got %d", len(op.Order))
|
||||
}
|
||||
if op.Order[0] != "first" || op.Order[1] != "second" {
|
||||
t.Errorf("unmarshal lost order: got %v", op.Order)
|
||||
}
|
||||
if op.Map["first"].Type != "string" {
|
||||
t.Errorf("first.type mismatch")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user