# Blocks, Repeaters & JSON Fields

> Structured object fields (inline fields vs componentRef), typed list fields (primitives, objects, nested lists, and discriminated variants), nesting depth limits, and json fields.

OvertCMS supports structured and repeatable content through three composite field types: `object`, `list`, and `json`.

---

## Nesting Depth Limits & Cycle Guards

To keep schemas predictable for editors, clients, and LLM agents, OvertCMS enforces strict structural limits at schema save time:

| Schema Context | Maximum Nesting Depth | Error Code |
| --- | --- | --- |
| Post Type (`object` / `list` nesting, including resolved `componentRef`) | **4** | `max_nesting_depth_exceeded` |
| Reusable Component (`object` / `list` nesting, including nested `componentRef`) | **2** | `max_nesting_depth_exceeded` |
| `<cms-block>` inside `rich_html` (runtime recursion) | **4** | `max_nesting_depth_exceeded` |

- **Circular component references** (e.g., Component A references Component B which references Component A, even through `rich_html.allowedComponents`) are rejected with `circular_component_ref`.
- **Diamond reuse** (A → B, A → C, B → D, C → D) is explicitly **allowed** as long as there is no cycle and depth stays within the limit.

---

## `object`

Use `object` to group related fields under a single JSON object (such as `seo`, `address`, or `cta`). An `object` field must define **either** inline `constraints.fields` **or** a `constraints.componentRef`—never both (`ambiguous_object_schema`) and never neither (`empty_object_schema`).

### Constraints

| Constraint Key | Type | Description |
| --- | --- | --- |
| `fields` | `FieldDefinition[]` | Inline child field definitions (each with its own type, constraints, `requiredOn`, `defaultValue`, and `aiWritable`). |
| `componentRef` | `string` | Slug of an existing reusable `Component` in the same site. Inherits the component's `fields`, `instruction`, and `aiWritable` flag. |

### Behavior

- Unknown keys inside an `object` payload fail with `unknown_field`.
- Prototype-pollution keys (`__proto__`, `constructor`, `prototype`) are rejected at every nesting depth with `forbidden_key`.
- When `componentRef` points to a component with `aiWritable: false`, API key and MCP actors receive `component_not_ai_writable` on write or clear.
- Child `defaultValue` rules apply automatically when a child key is omitted or `null`.

### Inline `object` Example

```json
{
  "key": "seo",
  "label": "SEO Metadata",
  "type": "object",
  "instruction": "Customize search engine metadata when it differs from the article title.",
  "constraints": {
    "fields": [
      {
        "key": "metaTitle",
        "label": "Meta Title",
        "type": "string",
        "constraints": { "maxLength": 60, "trim": true }
      },
      {
        "key": "metaDescription",
        "label": "Meta Description",
        "type": "text",
        "constraints": { "maxLength": 160, "disallowHtml": true, "trim": true }
      },
      {
        "key": "noIndex",
        "label": "No-Index",
        "type": "boolean",
        "defaultValue": false
      }
    ]
  }
}
```

### Component-Backed `object` Example

```json
{
  "key": "primaryCta",
  "label": "Primary CTA",
  "type": "object",
  "constraints": {
    "componentRef": "cta-button"
  }
}
```

---

## `list`

Use `list` for ordered arrays of homogeneous items—or heterogeneous page-builder blocks via discriminated union `variants[]`.

### Top-Level `list` Constraints

| Constraint Key | Type | Default | Description |
| --- | --- | --- | --- |
| `of` | `ListItemSpec` | Required | Defines the schema of each array element. |
| `minItems` | `integer` | — | Minimum array length (`>= 0`). Fails with `min_items`. |
| `maxItems` | `integer` | — | Maximum array length (`>= minItems`). Fails with `max_items`. |
| `uniqueItems` | `boolean` | `false` | Rejects duplicate normalized items (compared by canonical JSON encoding) with `duplicate_list_item`. |

<Note>
  If a `list` field has `required: true` and `minItems` is not set, an empty array `[]` fails validation with `required` when enforced (`requiredOn`).
</Note>

### `ListItemSpec` (`constraints.of`) Shapes

`constraints.of` supports five mutually clean shapes:

1. **Primitive / Media / Reference list:** Set `of.type` (e.g., `"string"`, `"number"`, `"url"`, `"image"`, `"reference"`) plus optional `of.constraints`.
2. **Inline object list:** Set `of.fields` (optionally with `of.type: "object"`).
3. **Reusable component list:** Set `of.componentRef` (optionally with `of.type: "object"`).
4. **Nested list (e.g., 2D matrix):** Set `of.type: "list"` and `of.constraints.of` (subject to the max depth 4 limit).
5. **Typed discriminated union (`variants[]`):** Set `of.variants[]`, where every element is an object containing a `"type"` discriminator matching one declared variant.

#### 1. Primitive, Media, or Reference List

```json
{
  "key": "gallery",
  "label": "Photo Gallery",
  "type": "list",
  "constraints": {
    "minItems": 1,
    "maxItems": 12,
    "of": {
      "type": "image",
      "constraints": {
        "requireAlt": true,
        "minWidth": 800
      }
    }
  }
}
```

Lists of primitive scalars (`string`, `number`, `boolean`) can also set `filterable: true` on the list field—OvertCMS indexes each element in `entry_field_index` so `filter[keywords][eq]=golang` matches any entry containing `"golang"`.

#### 2. Inline Object or Component List

```json
{
  "key": "faqs",
  "label": "FAQ Items",
  "type": "list",
  "constraints": {
    "maxItems": 20,
    "of": {
      "fields": [
        {
          "key": "question",
          "label": "Question",
          "type": "string",
          "required": true,
          "requiredOn": "publish",
          "constraints": { "maxLength": 160 }
        },
        {
          "key": "answer",
          "label": "Answer",
          "type": "text",
          "required": true,
          "requiredOn": "publish"
        }
      ]
    }
  }
}
```

Or reuse a component across post types:

```json
{
  "key": "testimonials",
  "label": "Testimonials",
  "type": "list",
  "constraints": {
    "of": {
      "componentRef": "testimonial-card"
    }
  }
}
```

#### 3. Discriminated Union (`variants[]`)

Each `ListVariant` declares a unique slug `type` (`^[a-z][a-z0-9_-]{0,63}$`), optional `label` and `instruction` (max 2,000 chars), and **either** `componentRef` **or** inline `fields[]`:

```json
{
  "key": "sections",
  "label": "Landing Page Sections",
  "type": "list",
  "constraints": {
    "minItems": 1,
    "maxItems": 15,
    "of": {
      "variants": [
        {
          "type": "hero",
          "label": "Hero Banner",
          "instruction": "Place at the top of the page.",
          "componentRef": "hero-banner"
        },
        {
          "type": "feature_grid",
          "label": "Feature Grid",
          "fields": [
            {
              "key": "heading",
              "label": "Heading",
              "type": "string",
              "required": true,
              "requiredOn": "publish"
            },
            {
              "key": "columns",
              "label": "Columns",
              "type": "number",
              "defaultValue": 3,
              "constraints": { "integer": true, "min": 2, "max": 4 }
            }
          ]
        }
      ]
    }
  }
}
```

**Valid entry payload for `sections`:**

```json
{
  "sections": [
    {
      "type": "hero",
      "headline": "Ship Content Safely with Agents",
      "ctaUrl": "/docs/quickstart"
    },
    {
      "type": "feature_grid",
      "heading": "Built for Production",
      "columns": 3
    }
  ]
}
```

- Missing or empty `"type"` on a variant item fails with `missing_variant_type`.
- An undeclared `"type"` fails with `invalid_variant_type` and returns `constraint.allowedValues`.
- Unknown fields on a variant item fail with `unknown_field` (the `"type"` discriminator itself is preserved automatically).

---

## `json`

Use `json` for arbitrary valid JSON payloads (such as chart specifications, theme tokens, or third-party integration metadata) where a fixed field graph is impractical.

### Constraints

| Constraint Key | Type | Description |
| --- | --- | --- |
| `maxBytes` | `integer` | Maximum UTF-8 byte length of the serialized JSON value (`>= 1`). Fails with `max_bytes`. |
| `jsonSchema` | `object` | Optional JSON Schema object stored with the field contract and surfaced to agents and the Admin UI. Must be a valid JSON object at schema save time (`invalid_json_schema`). |

### Validation Behavior

- Accepts any valid JSON value (object, array, string, number, boolean).
- Rejects non-JSON numeric values (`NaN`, `Infinity`) with `invalid_json`.
- Rejects prototype-pollution keys (`__proto__`, `constructor`, `prototype`) at **any** nesting depth with `forbidden_key`.
- Enforces `maxBytes` against the marshaled JSON byte length (`max_bytes`).

```json
{
  "key": "chartConfig",
  "label": "Chart Configuration",
  "type": "json",
  "instruction": "Provide a Chart.js-compatible configuration object under 16 KiB.",
  "constraints": {
    "maxBytes": 16384,
    "jsonSchema": {
      "type": "object",
      "required": ["chartType", "series"],
      "properties": {
        "chartType": { "type": "string", "enum": ["line", "bar", "area"] },
        "series": { "type": "array" }
      }
    }
  }
}
```
