# Text & Rich Text Fields

> Complete specification for string, text, slug, and rich_html fields including length units, formats, RE2 regex safety, 301 redirects, <cms-block> components, and bodyPatches.

OvertCMS provides four text-oriented field types: `string` (single-line), `text` (multi-line plain text), `slug` (URL identifier), and `rich_html` (canonical semantic HTML5 with embedded components and surgical patching).

---

## `string`

Use `string` for single-line text values such as titles, author names, SKUs, email addresses, and CSS colors.

### Normalization

- All C0 (`0x00`–`0x1F`), DEL (`0x7F`), and C1 (`0x80`–`0x9F`) control characters—including newlines and tabs—are stripped automatically.
- If `constraints.trim` is `true`, leading and trailing whitespace is trimmed before emptiness, length, format, and pattern checks run.

### Constraints

| Constraint Key | Type | Default | Description |
| --- | --- | --- | --- |
| `minLength` | `integer` | — | Minimum length (`>= 0`). Fails with `min_length`. |
| `maxLength` | `integer` | — | Maximum length (`>= minLength`). Fails with `max_length`. |
| `lengthUnit` | `"graphemes"` \| `"utf16"` | `"graphemes"` | `"graphemes"` counts Unicode UAX #29 extended grapheme clusters (so `"👨‍👩‍👧‍👦"` counts as 1); `"utf16"` counts UTF-16 code units (matching JavaScript `.length`). |
| `format` | `"plain"` \| `"email"` \| `"color"` | `"plain"` | Built-in semantic format validator. |
| `pattern` | `string` | — | Bounded Go RE2 regular expression. Fails with `pattern_mismatch`. |
| `trim` | `boolean` | `false` | Strips leading and trailing whitespace before validation. |

#### Built-in `format` Rules

- **`"plain"` (default):** Any string matching length and `pattern` constraints.
- **`"email"`:** Must contain no whitespace, parse cleanly via RFC 5322 (`mail.ParseAddress`) as a bare address (`addr.Address == s`), have a dot-separated domain with valid non-hyphen-bounded labels, and end in a TLD of at least 2 characters. Fails with `invalid_email`.
- **`"color"`:** Accepts CSS hex (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), `rgb()`/`rgba()` (either all 0–255 numeric channels or all 0–100% channels, optional alpha in `0–1` or `0–100%`), and `hsl()`/`hsla()` (hue `0–360` with optional `deg`, saturation `0–100%`, lightness `0–100%`, optional alpha). Fails with `invalid_color`.

#### RE2 Regex Safety Guard (`pattern`)

To guarantee linear-time validation and prevent compile-time ReDoS attacks, `constraints.pattern` is validated at both schema creation and runtime:

- Maximum length: **256 bytes**.
- Uses Go's RE2 syntax (no backreferences or lookarounds).
- **No nested bounded quantifiers** (e.g., `(a{10}){10}` is rejected).
- No single quantifier count above **1,000**, and combined quantifier expansion across the pattern must not exceed **1,000**.

### Schema & Payload Examples

```json
{
  "key": "contactEmail",
  "label": "Contact Email",
  "type": "string",
  "required": true,
  "requiredOn": "publish",
  "filterable": true,
  "unique": true,
  "constraints": {
    "format": "email",
    "maxLength": 160,
    "lengthUnit": "graphemes",
    "trim": true
  }
}
```

- **Valid:** `"editor@acme.example.dev"` (or `"  editor@acme.example.dev  "` which trims to `"editor@acme.example.dev"`)
- **Invalid:** `"not-an-email"` (`invalid_email`), `"a@localhost"` (`invalid_email` — missing dot/TLD), `12345` (`invalid_type`)

---

## `text`

Use `text` for multi-line plain text such as excerpts, meta descriptions, bios, or plain-text notes.

### Normalization

- Converts `\r\n` and `\r` line endings to `\n`.
- Strips C0/DEL/C1 control characters **except** `\n` and `\t`, which are preserved.
- Trims leading/trailing whitespace if `constraints.trim` is `true`.

### Constraints

| Constraint Key | Type | Default | Description |
| --- | --- | --- | --- |
| `minLength` | `integer` | — | Minimum length (`>= 0`). |
| `maxLength` | `integer` | — | Maximum length (`>= minLength`). |
| `lengthUnit` | `"graphemes"` \| `"utf16"` | `"graphemes"` | Grapheme cluster or UTF-16 code unit count. |
| `pattern` | `string` | — | Bounded RE2 regex (same 256-byte / 1,000-quantifier limits). |
| `trim` | `boolean` | `false` | Trims leading/trailing whitespace before validation. |
| `maxLines` | `integer` | — | Maximum number of lines (`>= 1`, counted as `count("\n") + 1`). Fails with `max_lines`. |
| `disallowHtml` | `boolean` | `false` | Runs an HTML5 tokenizer; rejects any start tag, end tag, self-closing tag, or HTML comment with `html_not_allowed`. |

### Schema & Payload Examples

```json
{
  "key": "summary",
  "label": "Article Summary",
  "type": "text",
  "required": true,
  "requiredOn": "publish",
  "constraints": {
    "minLength": 20,
    "maxLength": 300,
    "maxLines": 3,
    "disallowHtml": true,
    "trim": true
  }
}
```

- **Valid:** `"First line summary.\nSecond line with key takeaway."`
- **Invalid:** `"<p>No HTML allowed</p>"` (`html_not_allowed`), `"Line 1\nLine 2\nLine 3\nLine 4"` (`max_lines`)

---

## `slug`

Use `slug` for the canonical URL identifier of an entry. A field key literally named `"slug"` is **only permitted** when `type` is `"slug"`.

### Constraints

| Constraint Key | Type | Default | Description |
| --- | --- | --- | --- |
| `minLength` | `integer` | — | Minimum slug length. |
| `maxLength` | `integer` | — | Maximum slug length (system fallback cap is 255 characters when no `slug` field exists). |
| `lengthUnit` | `"graphemes"` \| `"utf16"` | `"graphemes"` | Length unit. |
| `pattern` | `string` | `^[a-z0-9]+(?:-[a-z0-9]+)*$` | Custom RE2 regex overriding the default lowercase kebab-case pattern. Fails with `invalid_slug` (default) or `pattern_mismatch` (custom). |
| `trim` | `boolean` | `false` | Trims whitespace before validation. |

### Auto-Derivation, Uniqueness, and Automatic 301 Redirects

1. **Auto-derivation:** If `slug` is omitted on create and the post type defines `slugSourceField` (e.g., `"title"`), OvertCMS automatically generates a kebab-case slug from that field.
2. **Conflict guard:** If you supply both a top-level `slug` property and `data.<slugFieldKey>` with different non-empty values, the request fails with `422 slug_mismatch`.
3. **Locale-scoped uniqueness:** Slugs are unique per `(site, postType, locale)` across non-trashed entries (`409 slug_already_exists`).
4. **Dual-snapshot pinning:** When you `PATCH` the slug of an already-`published` entry, the new slug is stored in `draftData` while `entry.slug` and `entry.publicUrl` remain pinned to the live published URL so production links never break mid-edit.
5. **Automatic 301 redirects on republish:** When you publish a previously published entry whose slug changed (and the post type has a `urlTemplate`), OvertCMS atomically records a `301` redirect from the old public path to the new public path, collapses any existing redirect chains pointing to the old path directly to the new path, and removes any stale redirect whose `fromPath` now matches the newly claimed path. Redirects are exposed at `GET /delivery/v1/redirects`.

### Schema & Payload Examples

```json
{
  "key": "slug",
  "label": "URL Slug",
  "type": "slug",
  "required": true,
  "requiredOn": "draft",
  "filterable": true,
  "sortable": true,
  "constraints": {
    "minLength": 3,
    "maxLength": 120,
    "trim": true
  }
}
```

- **Valid:** `"getting-started-with-overtcms-2"`
- **Invalid:** `"Hello_World"` (`invalid_slug`), `"leading-hyphen-"` (`invalid_slug`)

---

## `rich_html`

`rich_html` is OvertCMS's primary rich-content format. Every write is parsed with a full WHATWG HTML5 fragment parser (`golang.org/x/net/html`), validated against a strict semantic allowlist, checked for XSS and LLM placeholder links, and serialized back to canonical HTML5.

### Constraints

| Constraint Key | Type | Default | Description |
| --- | --- | --- | --- |
| `minWords` | `integer` | — | Minimum Unicode-aware word count (counts CJK ideographs/Hiragana/Katakana individually; excludes `<cms-block>` and `<iframe>`). Fails with `min_words`. |
| `maxWords` | `integer` | — | Maximum Unicode-aware word count. Fails with `max_words`. |
| `maxBytes` | `integer` | — | Maximum UTF-8 byte length of the serialized canonical HTML (`>= 1`). Fails with `max_bytes`. |
| `allowedBlocks` | `string[]` | All semantic blocks | Restricts allowed block tags. Supports shorthand aliases: `"heading"`/`"headings"` (`h1`–`h6`), `"list"`/`"lists"` (`ul`, `ol`, `li`), `"code_block"`/`"codeblock"` (`pre`). Automatically enables structural children (e.g., `table` enables `caption`, `thead`, `tbody`, `tfoot`, `tr`, `th`, `td`; `figure` enables `figcaption`; `blockquote` enables `footer`). Fails with `disallowed_html_block`. |
| `allowedMarks` | `string[]` | All inline marks | Restricts inline formatting tags (`strong`, `em`, `u`, `s`, `mark`, `sup`, `sub`, `code`, `a`, `time`). Note: `<code>` inside `<pre>` is treated as a code block, not an inline mark. Fails with `disallowed_html_mark`. |
| `allowedComponents` | `string[]` | `[]` (none) | List of reusable component slugs allowed inside `<cms-block>` elements. |
| `disallowH1` | `boolean` | `false` | Rejects `<h1>` elements with `disallowed_h1` (recommended when the page title renders as `<h1>`). |
| `allowInlineMedia` | `boolean` | `true` | Permits `<img>`, `<audio>`, `<video>`, and `<source>`. When `false`, fails with `inline_media_not_allowed`. |
| `allowEmbeds` | `boolean` | `false` | Permits `<iframe>` elements with HTTPS `src` matching the embed host allowlist. When `false`, fails with `embeds_not_allowed`. |
| `allowChecklists` | `boolean` | `false` | Permits `data-checklist` on `<ul>` and `data-checked="true"\|"false"` on `<li>`. |
| `strictness` | `"strict"` \| `"sanitize"` | `"strict"` | `"strict"` rejects disallowed tags, attributes, comments, or unsafe URLs with `422`; `"sanitize"` strips them and returns structured `warnings`. |

### Semantic HTML5 Allowlist & Security Defenses

- **Permitted block elements:** `p`, `h1`–`h6`, `blockquote`, `footer` (only inside `blockquote`), `hr`, `pre`, `ul`, `ol`, `li`, `table`, `caption`, `thead`, `tbody`, `tfoot`, `tr`, `th`, `td`, `figure`, `img`, `figcaption`, `audio`, `video`, `source` (only inside `audio` or `video`), `iframe`.
- **Permitted inline elements:** `strong`, `em`, `u`, `s`, `mark`, `sup`, `sub`, `code`, `a`, `br`, `time`.
- **Permitted attributes:**
  - `code` (inside `pre` only): `class` matching `^language-[a-zA-Z0-9_+-]+$`
  - `ul`: `data-checklist` (when `allowChecklists: true`, value `""`, `"true"`, or `"false"`)
  - `ol`: `start` (integer)
  - `li`: `data-checked` (when `allowChecklists: true`, `"true"` or `"false"`)
  - `th`: `colspan`, `rowspan` (positive integer), `scope` (`row`, `col`, `rowgroup`, `colgroup`)
  - `td`: `colspan`, `rowspan` (positive integer)
  - `img`: `src`, `alt`, `title`, `width`, `height` (positive integer), `data-asset-id`
  - `audio`: `controls`
  - `video`: `controls`, `poster`
  - `source`: `src`, `type`
  - `iframe`: `src` (required HTTPS on allowlisted host), `title`, `width`, `height`, `allowfullscreen` — must have empty body (`iframe_non_empty_body`)
  - `a`: `href` (`http`, `https`, `mailto`, `tel`, root-relative `/...`, or non-bare `#anchor`), `title`, `rel`
  - `time`: `datetime`
- **Strictly forbidden:** All `on*` event handlers, inline `style`, foreign namespaces (SVG, MathML), and dangerous tags (`script`, `style`, `form`, `input`, `textarea`, `button`, `object`, `embed`, `svg`, `math`). In `sanitize` mode, subtrees of executable/form/container tags (`script`, `style`, `svg`, `math`, `noscript`, `template`, `iframe`, etc.) are dropped completely; benign unknown tags (like `<div>` or `<span>`) are unwrapped to preserve text.
- **Default `<iframe>` embed host allowlist:** `youtube.com`, `www.youtube.com`, `youtu.be`, `player.vimeo.com`, `open.spotify.com`, `www.loom.com`, `codepen.io`, `datawrapper.dwcdn.net`. Embed URLs must use `https://` and must not contain userinfo.
- **Inline media tracking & sideloading:** An `<img>` with `data-asset-id` is verified against the site's Media Library and its `src` is canonicalized to the verified asset's URL on save. External `http://`/`https://` `<img>` URLs without `data-asset-id` are automatically SSRF-checked and sideloaded into the Media Library.

### Placeholder-Link Guard

To stop AI agents from shipping broken links, OvertCMS **always rejects** placeholder `<a href>` values (even in `sanitize` mode, except inside `<pre><code>` code blocks) with error code `placeholder_link_detected`:

- Empty string or bare `#`
- Literal tokens: `url`, `tbd`, `todo`, `link`, `placeholder`, `#todo`, `#tbd`, `#placeholder`, `[insert link]`, `[link]`, `[url]`, `[insert url]`, `insert link`, `your-url`, `http://...`, `https://...`
- Any value wrapped in `[...]` or containing `{{` / `}}`
- Any URL whose host is `example.com`, `example.org`, `example.net`, `.example`, or contains `placeholder`

### Embedded Components (`<cms-block>`)

Embed reusable components inside `rich_html` using an empty `<cms-block>` element with `type` and JSON-encoded `data-props`:

```html
<p>Before installing, review the production checklist:</p>
<cms-block type="callout" data-props='{"tone":"warning","body":"Back up your database before running migrations."}'></cms-block>
```

Rules enforced on every `<cms-block>`:
- Only `type` and `data-props` attributes are allowed (`disallowed_html_attribute`).
- Must contain **no child elements or non-whitespace text** (`cms_block_non_empty_body`).
- `type` must be listed in the field's `constraints.allowedComponents` (`cms_block_not_allowed`) and exist in the site's components (`cms_block_unknown_component`).
- If the component has `aiWritable: false`, API key / MCP actors receive `component_not_ai_writable`.
- `data-props` must decode to a single JSON object (no trailing tokens, no prototype-pollution keys) and is validated strictly against the component's own `FieldDefinition[]` schema—including nested references, media assets, and recursive `<cms-block>` elements up to **max nesting depth 4** (`max_nesting_depth_exceeded`).
- Normalized props are re-serialized deterministically into canonical JSON.

### Surgical Edits with `bodyPatches`

When updating large `rich_html` fields via `PATCH` (REST or `cms_update_entry`), send `bodyPatches` instead of re-transmitting the entire HTML document. Patches run sequentially against the existing field value, then pass the full result through `CanonicalizeHTML`.

Supported `op` values:

| `op` | Required Properties | Behavior |
| --- | --- | --- |
| `replace_exact` | `oldHtml`, `newHtml` | Replaces `oldHtml` with `newHtml`. |
| `append_after` | `anchorHtml`, `insertHtml` | Inserts `insertHtml` immediately after `anchorHtml`. |
| `prepend_before` | `anchorHtml`, `insertHtml` | Inserts `insertHtml` immediately before `anchorHtml`. |

Every patch enforces an **exact single-match guard**:
- Empty target/anchor returns `patch_target_required`.
- `0` matches returns `patch_target_not_found`.
- `> 1` matches returns `patch_target_ambiguous` so the caller can supply a more specific HTML snippet.

```json
{
  "expectedVersion": 4,
  "bodyPatches": {
    "body": [
      {
        "op": "replace_exact",
        "oldHtml": "<p>OvertCMS supports 15 field types.</p>",
        "newHtml": "<p>OvertCMS supports <strong>19 canonical field types</strong>.</p>"
      },
      {
        "op": "append_after",
        "anchorHtml": "<h2>Next Steps</h2>",
        "insertHtml": "<p>Read the <a href=\"/docs/mcp\">MCP Server guide</a>.</p>"
      }
    ]
  }
}
```

### Derived HTML Projections

On the Delivery Plane, pass `?include=plainText,wordCount,headings,readingTime` to compute read-only projections for every `rich_html` field without storing duplicate columns:

- `plainText` — normalized plain text (excluding `<cms-block>` and `<iframe>`)
- `wordCount` — Unicode + CJK-aware word count
- `readingTime` — estimated minutes at 225 words/minute (`ceil(wordCount / 225)`)
- `headings` — ordered array of `{ level, id, text }` with diacritic-stripped, deduplicated slug IDs (`id`, `id-2`, …)
