schema

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package schema is the typed model of a Norcube CMS site configuration: the root config, its collections, blocks, inputs and storages, and the field definitions they are made of. It parses the merged document the loader assembles (see package load) and offers the helpers every consumer needs: array item shapes, condition evaluation, select options.

The model mirrors the editor's schema module field for field. A knob the editor reads has a place here; a key it does not read lands in Field.Extra so a validator can report it.

Index

Constants

View Source
const (
	TypeText        = "text"
	TypeParagraph   = "paragraph"
	TypeRichText    = "richtext"
	TypeNumber      = "number"
	TypeBoolean     = "boolean"
	TypeDate        = "date"
	TypeColor       = "color"
	TypeRange       = "range"
	TypeMultiChoice = "multichoice"
	TypeLink        = "link"
	TypeImage       = "image"
	TypeFile        = "file"
	TypeReference   = "reference"
	TypeSelect      = "select"
	TypeGroup       = "group"
	TypeArray       = "array"

	// Legacy spellings.
	TypeURL      = "url"      // link
	TypeMarkdown = "markdown" // richtext
	TypeHTML     = "html"     // richtext
	TypeObject   = "object"   // group
	TypeBlocks   = "blocks"   // array of named components
)

Field types the editor renders. The three legacy spellings are the names fields carried before a rename and are still accepted in content written against them.

View Source
const (
	// ArrayItemTypeKey is the default discriminator of a multi-shape
	// array item; a field's `idKey` overrides it.
	ArrayItemTypeKey = "_type"
	// BlockComponentKey discriminates items of a legacy `blocks` field.
	BlockComponentKey = "_component"
	// CollectionKey stamps a file with the collection that owns it.
	CollectionKey = "_collection"
	// IDKey is the page-level identity the editor writes inline.
	IDKey = "_id"
	// RefKey marks a mapping that stands for a block or input.
	RefKey = "$ref"
	// BlockRefKey is the annotation the loader stamps on a resolved `$ref`.
	BlockRefKey = "_blockRef"
)

Keys with a fixed meaning inside content files.

View Source
const (
	LocaleFromPath        = "path"
	LocaleFromNone        = "none"
	LocaleFromFieldPrefix = "field:"

	ReferenceByPath        = "path"
	ReferenceByFieldPrefix = "field:"

	RedirectsFormatNetlify = "netlify"
	RedirectsFormatVercel  = "vercel"

	ExtraKeysShow  = "show"
	ExtraKeysHide  = "hide"
	ExtraKeysStrip = "strip"

	AreaContent = "content"
	AreaSite    = "site"

	WhenHiddenKeep = "keep"
	WhenHiddenDrop = "drop"

	DefaultCollection = "pages"
	CurrentVersion    = 1
)

Values of `localeFrom`, `by` and `redirects.format`.

View Source
const (
	OpEq       = "eq"
	OpNeq      = "neq"
	OpIn       = "in"
	OpNotIn    = "notIn"
	OpTruthy   = "truthy"
	OpFalsy    = "falsy"
	OpEmpty    = "empty"
	OpNonEmpty = "nonEmpty"
	OpGt       = "gt"
	OpLt       = "lt"
	OpMatches  = "matches"
)

Condition operators.

View Source
const (
	CustomValidatorRegex      = "regex"
	CustomValidatorExpression = "expression"
)

Built-in custom validator types.

View Source
const (
	StorageTypeRepo = "repo"

	StorageModeReadOnly  = "read-only"
	StorageModeReadWrite = "read-write"

	StorageNamingOriginal = ""
	StorageNamingSlug     = "slug"
	StorageNamingSlugHash = "slug+hash"
	StorageNamingUUID     = "uuid"

	StorageInlineRef = "ref"
	StorageInlineSVG = "svg"

	StorageDedupHash = "hash"
)

Storage knob values.

Variables

KnownOps lists the condition operators.

KnownTypes lists every field type this module understands, legacy spellings included.

View Source
var SupportedVersions = map[int]bool{1: true}

SupportedVersions lists the schema-language versions this module reads.

Functions

func ArrayIDKey

func ArrayIDKey(f Field) string

ArrayIDKey is the discriminator key the array's items carry.

func Canonical

func Canonical(t string) string

Canonical maps a legacy spelling to the current type name and returns any other name unchanged.

func Eval

func Eval(c Condition, s Scope) bool

Eval evaluates a condition against the scope.

func IsArray

func IsArray(t string) bool

IsArray reports whether a field type holds a list of items.

func IsEmptyValue

func IsEmptyValue(v any) bool

IsEmptyValue is the condition evaluator's notion of empty: nil, an empty string, an empty list. Whitespace is not empty.

func IsGroup

func IsGroup(t string) bool

IsGroup reports whether a field type nests fields.

func IsMultiShape

func IsMultiShape(f Field) bool

IsMultiShape reports whether the array accepts more than one shape.

func IsStringLike

func IsStringLike(t string) bool

IsStringLike reports whether values of the type are strings.

func KnownKnobs

func KnownKnobs(t string) map[string]bool

KnownKnobs returns the keys a field of type t may carry.

func OptionValues

func OptionValues(opts []SelectOption) []string

OptionValues returns the option values in order.

func PresenceOp

func PresenceOp(op string) bool

PresenceOp reports whether the operator only asks whether a value is there, so a path that resolves to nothing is a legitimate answer.

func PrimitiveBucket

func PrimitiveBucket(t string) string

PrimitiveBucket is the value type a primitive field type produces: "string", "number", "boolean", or "" for groups and arrays.

func ResolvePath

func ResolvePath(path string, s Scope) (any, bool)

ResolvePath reads a condition path (`key`, `$parent.key`, `$root.a.b`, `$item.k`, dotted descents, numeric array indexes) against the scope. The second result is false when any segment is missing.

func Truthy

func Truthy(v any) bool

Truthy mirrors JavaScript truthiness for the values YAML produces.

Types

type Block

type Block struct {
	Key         string
	Label       string
	Description string
	Fields      []Field
	Preview     *Preview
	Raw         map[string]any
}

Block is a reusable group of fields.

type Collection

type Collection struct {
	Key             string
	Label           string
	Description     string
	Path            string
	Match           string
	HasBody         bool
	ExtraKeysPolicy string
	Area            string
	Preview         *Preview
	PreviewPath     string
	LocaleFrom      string
	SchemaVersion   *int
	Fields          []Field
	Raw             map[string]any
}

Collection is one content type.

type Computed

type Computed struct {
	From      string
	Transform string
	Mode      string
}

Computed derives a field's value from another field.

type Condition

type Condition struct {
	Field string
	Op    string
	Value any

	All []Condition
	Any []Condition
	Not *Condition
}

Condition is a `visibleIf` tree: a leaf (Field, Op, Value) or one of All, Any, Not.

func (Condition) IsLeaf

func (c Condition) IsLeaf() bool

IsLeaf reports whether the condition compares one field.

type Config

type Config struct {
	SchemaVersion  int
	SiteURL        string
	PagesDir       string
	PublicDir      string
	DefaultStorage string
	InputsFromGlob []string
	// Storages in declared order.
	Storages   []Storage
	Preview    PreviewSite
	Redirects  Redirects
	KnownPaths []string
	Variables  Variables
	// Collections keyed by name; CollectionKeys keeps the declared order.
	Collections    map[string]Collection
	CollectionKeys []string
	// Blocks and Inputs keyed by name.
	Blocks    map[string]Block
	BlockKeys []string
	Inputs    map[string]Field
	InputKeys []string
	// Raw is the merged document the config was parsed from.
	Raw map[string]any
}

Config is a site's whole configuration after merging and `$ref` resolution.

func Parse

func Parse(doc map[string]any) (*Config, error)

Parse reads a merged configuration document (the shape the loader produces and the editor receives: a map with `collections`, `blocks`, `inputs`, `storages`, `preview` and the root keys) into a Config.

Parse is lenient: a malformed knob is kept in Field.Extra or ignored, never fatal, because the validators report malformed knobs with a file and a path. The only error is a document that is not a mapping.

func (*Config) DefaultStorageConfig

func (c *Config) DefaultStorageConfig() (Storage, bool)

DefaultStorageConfig returns the storage a field without `storage` uses: the declared default, else the first declared.

func (*Config) ReferenceKeys

func (c *Config) ReferenceKeys() []string

ReferenceKeys lists the field names any reference field looks entries up by (`by: field:<k>`), sorted.

func (*Config) ResolveStorage

func (c *Config) ResolveStorage(name string) (Storage, bool)

ResolveStorage returns the storage a field uses: the named one, or the default when the name is empty.

func (*Config) Storage

func (c *Config) Storage(name string) (Storage, bool)

Storage returns the named storage.

func (*Config) StorageNames

func (c *Config) StorageNames() []string

StorageNames lists the declared storages in order.

type CustomValidator

type CustomValidator struct {
	Type    string
	Message string
	Params  map[string]any
}

CustomValidator is one `customValidators` entry; Params holds every key but `type` and `message`.

type Entry

type Entry struct {
	Name  string
	Field Field
}

Entry is one allowed shape of an array field, with the name items carry in their discriminator.

func ItemEntries

func ItemEntries(f Field) []Entry

ItemEntries lists an array field's shapes. The name is the entry's `name`, else its `key`, else a synthetic `__entry_<i>` that no item can match (the validator reports those).

func ResolveItemEntry

func ResolveItemEntry(f Field, item any) *Entry

ResolveItemEntry picks the shape of one item: by discriminator for mappings, by value type for primitives, the lone shape for single-shape arrays. A mapping without a discriminator falls back to the first group shape, as the editor does. Returns nil when nothing fits.

type Field

type Field struct {
	Key         string
	Type        string
	Label       string
	Description string
	// Name is the discriminator of an array item shape when it differs
	// from Key.
	Name string
	// BlockRef is the block or input a `$ref` resolved from.
	BlockRef string

	Required        bool
	RequiredMessage string
	Nullable        bool
	Hidden          bool
	VisibleIf       *Condition
	WhenHidden      string
	Computed        *Computed
	Custom          []CustomValidator
	// Default is the declared default; HasDefault distinguishes an
	// explicit null from no default.
	Default    any
	HasDefault bool
	// Variables is false when the field opts out of the placeholder
	// paster; nil when unset.
	Variables *bool

	// text, paragraph, richtext, link
	Regex             string
	RegexMessage      string
	MinLength         *int
	MinLengthMessage  string
	MaxLength         *int
	MaxLengthMessage  string
	RecommendedLength *RecommendedLength
	Rows              *int
	// richtext and color
	Format string
	// richtext
	RichTextOptions map[string]any

	// number, range, multichoice
	Min  *float64
	Max  *float64
	Step *float64

	// select, multichoice
	Options           []SelectOption
	Widget            string
	Searchable        bool
	SearchPlaceholder string

	// image, file
	Accept  string
	MaxSize int64
	Storage string
	Dir     string
	LockDir bool

	// reference
	Collection string
	By         string
	Multiple   bool

	// group
	Fields  []Field
	Preview *Preview
	Inline  bool

	// array
	Items           []Field
	IDKey           string
	MinItems        *int
	MinItemsMessage string
	MaxItems        *int
	MaxItemsMessage string
	UniqueOn        string
	UniqueOnMessage string
	// Components backs the legacy `blocks` type.
	Components []string

	// Extra holds keys the editor does not read for this field type.
	Extra map[string]any
	// Raw is the field as parsed, for consumers that need a knob this
	// model does not name.
	Raw map[string]any
}

Field is one field definition. Every type-specific knob has a place; a nil pointer or zero value means the knob is absent.

func ItemFields

func ItemFields(c *Config, f Field, item map[string]any) []Field

ItemFields returns the fields of the shape one array item has, or nil for a primitive shape or an item no shape fits. Legacy `blocks` fields look the component up in the config's blocks.

func ParseField

func ParseField(m map[string]any) Field

ParseField reads one field definition.

func ParseFields

func ParseFields(v any) []Field

ParseFields reads a `fields` or `items` list.

type Preview

type Preview struct {
	Title       []Resolver
	Description []Resolver
	Image       []Resolver
	Badges      [][]Resolver
}

Preview says how an entry renders as a summary row.

type PreviewSite

type PreviewSite struct {
	DefaultLocale       string
	Locales             []string
	PrefixDefaultLocale bool
}

PreviewSite holds the site-level i18n facts of the `preview` block.

type RecommendedLength

type RecommendedLength struct {
	From *int
	To   *int
}

RecommendedLength is the soft length window of a text field.

type Redirects

type Redirects struct {
	File   string
	Format string
}

Redirects says where URL changes are recorded.

func (Redirects) Enabled

func (r Redirects) Enabled() bool

Enabled reports whether the site declares a redirects file in a format this module can write.

type Resolver

type Resolver struct {
	Key     string
	Literal string
}

Resolver is one entry of a preview slot: a field key or a literal.

type Scope

type Scope struct {
	Self    map[string]any
	Parents []map[string]any
	Root    map[string]any
	Item    map[string]any
}

Scope is what a condition path can reach: the current group's values, the chain of parents up to the root, and the nearest array item.

func RootScope

func RootScope(frontmatter map[string]any) Scope

RootScope is the scope at the top of a document.

func (Scope) Child

func (s Scope) Child(child map[string]any) Scope

Child is the scope after descending into a group.

func (Scope) ItemScope

func (s Scope) ItemScope(item map[string]any) Scope

ItemScope is the scope after entering an array item.

type SelectOption

type SelectOption struct {
	Value       string
	Label       string
	Description string
}

SelectOption is one option of a select or multichoice field.

func ParseOptions

func ParseOptions(v any) []SelectOption

ParseOptions normalises a select's options (strings or {value, label, description} maps) to SelectOption.

type Storage

type Storage struct {
	Name      string
	Type      string
	Mode      string
	Accept    string
	Naming    string
	Inline    string
	Dedup     string
	MaxSize   int64
	Path      string
	PublicURL string
	Raw       map[string]any
}

Storage is one upload destination.

type Variables

type Variables struct {
	File  string
	Field string
}

Variables points at the site's `{{placeholder}}` document.

Jump to

Keyboard shortcuts

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