> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloak.chat/llms.txt
> Use this file to discover all available pages before exploring further.

# Cards and embeds

> Types, helpers, errors and caps for the encrypted card lane.

Everything on this page belongs to `client.sendCard()`, the end-to-end encrypted embed lane. For how and when to use it, see [rich cards](https://docs.cloak.chat/guides/rich-cards.md). The plaintext lane has its own [webhooks reference](https://docs.cloak.chat/api-reference/webhooks.md).

```ts theme={null}
import {
  CloakEmbedError,
  CloakComponentError,
  CLOAK_MEDIA_ORIGIN,
  isCloakMediaUrl,
  assertCardMessage,
  assertComponents,
  assertModal,
  encodeBotEmbed,
  encodeCardEnvelope,
  parseCardEnvelope,
  embedFallbackText,
  MAX_EMBED_JSON,
} from '@cloak-software/bot-sdk';
import type {
  BotEmbed,
  BotEmbedField,
  CardMessage,
  CardEdit,
  MessageCard,
  EphemeralMessage,
  ActionRow,
  Button,
  StringSelect,
  SelectOption,
  ModalDefinition,
  ModalInput,
  CloakEmbedErrorReason,
  CloakComponentErrorReason,
} from '@cloak-software/bot-sdk';
```

## sendCard

```ts theme={null}
client.sendCard(serverId: string, channelId: string, card: CardMessage): Promise<void>
client.guild(serverId).sendCard(channelId: string, card: CardMessage): Promise<void>
```

Requires `message_send`. The card is encrypted with the same conversation key and epoch as `card.content` and rides the ordinary message frame.

The returned promise rejects with `CloakEmbedError` when the card is invalid, or `CloakComponentError` when its rows are, before anything is sent and before the connection cursor moves. It does **not** reject on a server-side denial: sending is fire-and-forget, and denials arrive on the `sendRejected` event.

## editCard

```ts theme={null}
client.editCard(
  serverId: string,
  channelId: string,
  messageId: string,
  card: CardEdit,
  opts: { createdAt: Date; pinned?: boolean; groupId?: string; threadId?: string; postId?: string },
): Promise<void>

msg.editCard(card: CardEdit): Promise<void>
```

Replaces a message's card, embed and component rows together, and re-encrypts its text in the same edit. Author-only server-side, like `edit()`. `CardEdit` is `Pick<CardMessage, 'content' | 'embed' | 'components'>`: the same three fields, without the routing keys, which the edit takes from the message.

`opts.createdAt` is required because the edit addresses the row by its send time. A received `Message` carries it, which is why `msg.editCard(card)` is the convenient form. `opts.pinned` should mirror the message's current pin state (`false` when unknown). `threadId` and `postId` are mutually exclusive.

The text and the card are encrypted from one context, so pass the message's current `content` to leave the text as it was. Pass `components: []` to strip the rows after a decision. The replacement arrives on [`messageUpdate`](https://docs.cloak.chat/api-reference/events#messageupdate) as `card`. A server that predates cards ignores the card slot and edits only the text.

Rejects locally with a plain `Error` when `createdAt` is missing, with `CloakEmbedError` or `CloakComponentError` on an invalid card, and with [`CloakActionError`](https://docs.cloak.chat/api-reference/errors#cloakactionerror) on a server deny. See [Buttons and selects](https://docs.cloak.chat/guides/components.md#retire-the-controls).

## CardMessage

The payload passed to `sendCard()`.

**content** `string` *required*

Genuine human-readable text, non-blank. It is what search indexes, what push notifications and channel previews are built from, what a reply quoting this card renders, and what any surface not wired to the card renderer shows. The SDK never synthesizes it. `embedFallbackText()` derives one line if you want it.

**embed** `BotEmbed`

Exactly one embed. Clients render one card per message. Required unless `components` is present: a components-only card is a message with rows under its text and no embed at all.

**components** `ActionRow[]`

Up to 5 rows of buttons and string selects rendered under the card. Their presence is what selects the [v2 envelope](#the-two-envelopes). Validated by `assertComponents()`. Clicks arrive on the [`interaction`](https://docs.cloak.chat/api-reference/events#interaction) event. See [Buttons and selects](https://docs.cloak.chat/guides/components.md).

**groupId** `string`

The channel's group, when it is not already cached from an inbound frame.

**threadId** `string`

Post the card into a thread of `channelId`, the thread's parent. Mutually exclusive with `postId`.

**postId** `string`

Post the card into a forum post of `channelId`, the parent forum channel. Mutually exclusive with `threadId`. See [Forums](https://docs.cloak.chat/guides/forums.md).

**mentions** `MentionTarget[]`

Who to notify. These targets ride the wire in plaintext, exactly as on `send()`, because the server routes notification fanout without decrypting anything.

**replyTo** `ReplyTarget`

Make the card a true reply. It renders the quote header and fires a "replied to you" notification. A received `Message` satisfies `ReplyTarget` structurally, so `replyTo: msg` works.

**unencrypted** `never`

Declared as `never` on purpose. This lane is end-to-end encrypted, so a webhook-shaped payload is a compile error here. `assertCardMessage()` re-checks it at runtime and points you at `sendEmbed()`.

**username** `never`

Declared as `never`. Per-post personas are a webhook-lane feature. A card posts under the bot's own identity.

**avatar\_url** `never`

Declared as `never`, for the same reason as `username`.

## BotEmbed

Field names are wire names, in `snake_case`. Do not camelCase them.

**type** `'rich'`

Stamped by the SDK. Setting it to anything else is rejected.

**title** `string`

Up to 256 characters.

**description** `string`

Up to 2048 characters. Plain text, not markdown: v1 renders it literally.

**url** `string`

Click-through target for the card. A link slot: any `http(s)` URL up to 2048 characters, and nothing is fetched for it at render, so the Cloak-hosted rule does not apply.

**color** `number | string`

A decimal integer in `0..0xffffff` (for example `0x22c55e`) or a `#rrggbb` string. Exactly six hex digits, no shorthand and no alpha. Anything else is rejected.

**timestamp** `string`

ISO-8601, up to 64 characters. Rendered in the footer.

**author** `\{ name?: string; url?: string; icon_url?: string \}`

`name` up to 256. `url` is a link slot. `icon_url` is a media slot and must be Cloak-hosted.

**provider** `\{ name?: string; url?: string \}`

`name` up to 256. `url` is a link slot. There is no `provider.icon` on this lane, and passing one is rejected.

**thumbnail** `\{ url: string \}`

A media slot. Must be Cloak-hosted.

**image** `\{ url: string \}`

A media slot. Must be Cloak-hosted.

**footer** `\{ text?: string; icon_url?: string \}`

`text` up to 256. `icon_url` is a media slot and must be Cloak-hosted.

**fields** `BotEmbedField[]`

Up to 8 rows, in a three-column grid. `inline: false` takes a full row. See the warning below about older mobile builds.

> [!WARNING]
>
> `fields` render on desktop and mobile from the client release that ships with SDK 0.4.0. A mobile build older than that drops the rows silently, with no error anywhere, so until your server's members have updated, keep anything a reader must see in `description`.

There is no index signature. Unknown keys are rejected, because the renderer drops them while they still count against the payload budget. `video` is rejected by name.

## Components

The rows a card may carry under its embed. Every type here is pure data: no client state, no I/O.

### ActionRow

```ts theme={null}
interface ActionRow {
  type: 'row';
  components: Component[];  // up to 5 buttons, or exactly one select
}

type Component = Button | StringSelect;
```

A row holding a select holds nothing else. An empty row is refused.

### Button

**type** `'button'` *required*

**style** `ButtonStyle` *required*

`'primary'`, `'secondary'`, `'success'`, `'danger'`, or `'link'`.

**label** `string` *required*

1 to 80 characters.

**customId** `string`

1 to 100 characters. Required for every style but `'link'`, where it must be absent. What the `interaction` handler switches on. Opaque to everyone but the bot, and readable by every member holding the conversation key.

**url** `string`

`'link'` style only: an absolute `https` URL, up to 2048 characters. The client opens it through its trusted-link path and the click never reaches the bot. Nothing is fetched for it at render.

**emoji** `string`

Exactly one unicode emoji, rendered ahead of the label. `isSingleEmoji()` is the check.

**disabled** `boolean`

### StringSelect

**type** `'select'` *required*

**customId** `string` *required*

1 to 100 characters.

**placeholder** `string`

Up to 150 characters.

**minValues** `number`

1 to 25, default 1. Never above `maxValues`.

**maxValues** `number`

1 to 25, default 1. Never above the option count.

**disabled** `boolean`

**options** `SelectOption[]` *required*

1 to 25 options with unique `value`s.

### SelectOption

**label** `string` *required*

1 to 100 characters.

**value** `string` *required*

1 to 100 characters, unique within the select. What arrives in `Interaction.values`.

**description** `string`

Up to 100 characters.

**emoji** `string`

Exactly one unicode emoji.

**default** `boolean`

### ModalDefinition

What `Interaction.showModal()` opens. It travels only on the response lane, never inside a card. See [Modals](https://docs.cloak.chat/guides/modals.md).

**title** `string` *required*

1 to 45 characters.

**customId** `string` *required*

1 to 100 characters. Comes back as the modal interaction's `customId`.

**inputs** `ModalInput[]` *required*

1 to 5 inputs with unique `customId`s.

### ModalInput

**customId** `string` *required*

1 to 100 characters. The key in `Interaction.fields`.

**label** `string` *required*

1 to 45 characters.

**style** `'short' | 'paragraph'` *required*

**placeholder** `string`

Up to 100 characters.

**required** `boolean`

Default `true`.

**minLength** `number`

0 to 4000, never above `maxLength`.

**maxLength** `number`

1 to 4000.

**value** `string`

Pre-filled text, up to 4000 characters.

### EphemeralMessage

What `Interaction.ephemeral()` shows the clicker alone.

```ts theme={null}
interface EphemeralMessage {
  content: string;          // up to 2000 characters; may be empty when an embed or rows carry the point
  embed?: BotEmbed;
  components?: ActionRow[];
}
```

Never stored anywhere. It must carry something to show: an empty `content` with no embed and no rows is refused with `reason: 'empty'`. Rows inside it are clickable, and their clicks carry the original message id plus a `parentId` naming the interaction that produced the reply.

### MessageCard

The parsed card a received message carries on [`Message.card`](https://docs.cloak.chat/api-reference/types#message), and the `card` field on [`messageUpdate`](https://docs.cloak.chat/api-reference/events#messageupdate).

```ts theme={null}
interface MessageCard {
  embeds: BotEmbed[];
  components: ActionRow[];
}
```

Every embed that survived the read-side validator, plus the component rows. A v1 card yields one embed and no rows. A v2 card yields either or both. The same caps and the same media rule are enforced on read as on write, and a card that fails them is `null` on the message, never a partial card.

## The two envelopes

The plaintext inside the encrypted card slot has two shapes, and the SDK picks between them by whether the card carries rows.

| | v1 | v2 |
| - | - | - |
| Shape | A JSON **array**: `[{ ...embed, type: 'rich' }]` | A JSON **object**: `{ v: 2, embeds: [embed], components: [row, ...] }` |
| Emitted when | The card has no `components` | The card has at least one row |
| `embeds` | Always one | May be empty, for a components-only card |
| A client from before 0.4.0 | Renders it unchanged | Drops the whole card and shows only the message's text `content` |

The rule exists so that a component-free card keeps working on every client that ever rendered one. It also means a card with rows degrades to its `content` on an older client, with no embed and no buttons, which is one more reason `content` must be genuine text.

`encodeCardEnvelope({ embed?, components? })` makes the pick and is what `sendCard()`, `createForumPost()`, and `editCard()` call. `parseCardEnvelope(plain)` is the read side: it accepts both shapes and returns a `MessageCard` or `null`, never throwing. Both are exported for raw-frame authors.

## BotEmbedField

**name** `string` *required*

Non-empty, up to 128 characters.

**value** `string` *required*

Non-empty, up to 512 characters.

**inline** `boolean`

`true` renders the row side by side. `false` is equivalent to omitting it: the renderer keeps only a literal `true`.

## Media rules

Four slots are fetched with no user action and must have origin exactly `https://media.cloak.chat`:

| Slot | Kind |
| - | - |
| `image.url` | Media, Cloak-hosted only |
| `thumbnail.url` | Media, Cloak-hosted only |
| `author.icon_url` | Media, Cloak-hosted only |
| `footer.icon_url` | Media, Cloak-hosted only |
| `url` | Link, any `http(s)` |
| `author.url` | Link, any `http(s)` |
| `provider.url` | Link, any `http(s)` |

This is not configurable. See [rich cards](https://docs.cloak.chat/guides/rich-cards.md#media-must-be-cloak-hosted) for why.

## Helpers

### embedFallbackText

```ts theme={null}
embedFallbackText(embed: BotEmbed): string
```

Returns the `title`, else the first non-blank line of the `description`, else the embed `url`, capped at `MAX_FALLBACK_TEXT` (256). It never concatenates title and description.

Throws `CloakEmbedError` with `reason: 'content'` when the embed carries none of the three. An image-only card must be given real text, because blank content is invisible to search, notifications, previews and quoting.

### isCloakMediaUrl

```ts theme={null}
isCloakMediaUrl(raw: unknown): boolean
```

`true` only when `raw` is a string that parses as a URL, carries no userinfo, and whose origin is exactly `CLOAK_MEDIA_ORIGIN`. Comparison is exact string equality on the origin, which pins scheme, host and port together.

### assertCardMessage

```ts theme={null}
assertCardMessage(card: CardMessage): void
```

The runtime half of the `CardMessage` type. `sendCard()` calls it for you. Call it yourself to validate a card built from untrusted input before you queue a send. It throws on the first problem it finds, in a deliberate order: rows (when present), then shape, then `content`, then unknown keys, then caps, then the media rule, then link schemes, then "nothing renderable". A components-only card is refused for a bad row, never for a missing embed.

### assertComponents

```ts theme={null}
assertComponents(rows: unknown): asserts rows is ActionRow[]
```

The runtime half of `ActionRow[]`. Throws `CloakComponentError` on the first violation of any cap in the [Components](#components) section. `sendCard()`, `createForumPost()`, `editCard()`, and `Interaction.ephemeral()` call it for you. Everything it accepts renders: it is a strict refinement of the client parser, which drops a card whole on a violation.

### assertModal

```ts theme={null}
assertModal(def: unknown): asserts def is ModalDefinition
```

The runtime half of `ModalDefinition`. `Interaction.showModal()` calls it before anything is encrypted.

### parseComponents

```ts theme={null}
parseComponents(raw: unknown): ActionRow[] | null
```

The read side of `assertComponents()`: the validated rows, or `null` on any violation. Never throws.

### encodeCardEnvelope

```ts theme={null}
encodeCardEnvelope(parts: { embed?: BotEmbed; components?: ActionRow[] }): string
```

Serializes a validated card to the plaintext the wire carries, picking [v1 or v2](#the-two-envelopes) by whether rows are present, and enforces `MAX_EMBED_JSON`. Validate first; this only serializes and caps.

### parseCardEnvelope

```ts theme={null}
parseCardEnvelope(plain: string): MessageCard | null
```

Parses a decrypted card plaintext of either shape into a `MessageCard`, or `null` on any violation. Strict caps on both shapes. Never throws.

### encodeEphemeral

```ts theme={null}
encodeEphemeral(e: EphemeralMessage): string
```

Validates and serializes an ephemeral reply. `Interaction.ephemeral()` calls it for you.

### encodeBotEmbed

```ts theme={null}
encodeBotEmbed(embed: BotEmbed): string
```

Serializes one validated embed to the JSON array the wire carries, stamping `type: 'rich'`. Enforces `MAX_EMBED_JSON` on the UTF-8 byte length and throws `reason: 'cap'` when over. `sendCard()` calls it for you. Use it directly only to size a card before sending.

## CloakEmbedError

Thrown locally, before anything reaches the wire. It is the only place a bot author can be told the card is wrong: the server cannot read the payload, and the renderer strips bad input silently by design.

**name** `string`

Always `'CloakEmbedError'`.

**reason** `CloakEmbedErrorReason`

Why the embed was refused. See the table below.

**field** `string | undefined`

The exact offending path, for example `'embed.image.url'` or `'embed.fields[3].value'`. Absent when the whole payload is at fault.

**message** `string`

A remedy-carrying explanation, prefixed with `[cloak-sdk] sendCard:`.

### CloakEmbedErrorReason

| Reason | Meaning |
| - | - |
| `'shape'` | Wrong type, an unknown key, a field that does not exist on this lane, or a webhook-shaped payload |
| `'content'` | `content` missing, non-string, or blank |
| `'cap'` | Over one of the mirrored renderer caps, or over `MAX_EMBED_JSON` |
| `'media-host'` | A media slot whose URL is not Cloak-hosted |
| `'empty'` | Nothing renderable left, so the client would draw no card at all |
| `'wire-cap'` | The ciphertext exceeded `MAX_EMBED_WIRE` |

## CloakComponentError

Thrown locally when a component row, a modal definition, or an ephemeral reply's rows are refused, before anything reaches the wire. The same reasoning as `CloakEmbedError`: the server cannot read the envelope, and the client parser drops a bad card silently, so this is the only place you can be told.

**name** `string`

Always `'CloakComponentError'`.

**reason** `CloakComponentErrorReason`

`'shape'` for a wrong type, an unknown key, a missing required key, or a duplicate id. `'cap'` for a value over one of the pinned caps.

**field** `string | undefined`

The offending path, for example `'components[1].components[0].label'` or `'modal.inputs[2].customId'`.

**message** `string`

A remedy-carrying explanation, prefixed with `[cloak-sdk]`.

## Constants

Every cap mirrors a client renderer constant. Where the renderer truncates or strips a value, `sendCard()` rejects it.

| Constant | Value | Applies to |
| - | - | - |
| `CLOAK_MEDIA_ORIGIN` | `'https://media.cloak.chat'` | The one allowed media origin |
| `MAX_EMBED_JSON` | `8192` | Serialized embed JSON, in UTF-8 bytes |
| `MAX_EMBED_WIRE` | `12288` | The encrypted embed string on the wire |
| `MAX_EMBED_TITLE` | `256` | `title` |
| `MAX_EMBED_DESCRIPTION` | `2048` | `description` |
| `MAX_EMBED_FIELDS` | `8` | Rows in `fields` |
| `MAX_EMBED_FIELD_NAME` | `128` | `fields[].name` |
| `MAX_EMBED_FIELD_VALUE` | `512` | `fields[].value` |
| `MAX_EMBED_FOOTER` | `256` | `footer.text` |
| `MAX_EMBED_NAME` | `256` | `author.name` and `provider.name` |
| `MAX_EMBED_TIMESTAMP` | `64` | `timestamp` |
| `MAX_EMBED_URL` | `2048` | Every URL slot, link or media |
| `MAX_EMBED_URLS` | `8` | Total URLs across all slots. A conforming embed has seven slots, so this never binds |
| `MAX_FALLBACK_TEXT` | `256` | The output of `embedFallbackText()` |

`MAX_EMBED_JSON` sits below the server's own 16 KiB sidecar cap on the ciphertext, because base64 expands by roughly four thirds. `MAX_EMBED_WIRE` is reachable only by a payload that already failed `MAX_EMBED_JSON`. Both exist so an oversize card is a local synchronous throw rather than a `sendRejected` event with code `-11` arriving later. `MAX_EMBED_JSON` applies to the whole envelope, embed and rows together.

### Component constants

| Constant | Value | Applies to |
| - | - | - |
| `MAX_ACTION_ROWS` | `5` | Rows per card |
| `MAX_BUTTONS_PER_ROW` | `5` | Buttons per row |
| `MAX_BUTTON_LABEL` | `80` | `Button.label` |
| `MAX_BUTTON_URL` | `2048` | `Button.url` |
| `MAX_CUSTOM_ID` | `100` | Every `customId`: button, select, modal, and modal input |
| `MAX_SELECT_PLACEHOLDER` | `150` | `StringSelect.placeholder` |
| `MAX_SELECT_OPTIONS` | `25` | Options per select, and the ceiling on `minValues` and `maxValues` |
| `MAX_SELECT_OPTION_TEXT` | `100` | `SelectOption.label` and `SelectOption.value` |
| `MAX_SELECT_OPTION_DESCRIPTION` | `100` | `SelectOption.description` |
| `MAX_MODAL_TEXT` | `45` | `ModalDefinition.title` and `ModalInput.label` |
| `MAX_MODAL_INPUTS` | `5` | Inputs per modal |
| `MAX_MODAL_PLACEHOLDER` | `100` | `ModalInput.placeholder` |
| `MAX_MODAL_VALUE` | `4000` | `ModalInput.value`, `minLength`, and `maxLength` |
| `MAX_EPHEMERAL_CONTENT` | `2000` | `EphemeralMessage.content` |

## Next

> [card] [Rich cards](https://docs.cloak.chat/guides/rich-cards.md)
>
> The guide: lane choice, media rules, and a complete bot.

> [card] [Buttons and selects](https://docs.cloak.chat/guides/components.md)
>
> Rows, clicks, the three answers, and `editCard()` in practice.

> [card] [Errors](https://docs.cloak.chat/api-reference/errors.md)
>
> Every error class the SDK raises.

> [card] [Client](https://docs.cloak.chat/api-reference/client.md)
>
> Constructor options and the full method surface.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.