# `Layr8.Message`
[🔗](https://github.com/layr8/elixir_sdk/blob/main/lib/layr8/message.ex#L17)

A DIDComm v2 message.

## Fields

- `id` — unique message identifier (UUID v4)
- `type` — DIDComm message type URI
- `from` — sender DID
- `to` — list of recipient DIDs
- `thread_id` — correlates messages in a thread (`thid`)
- `parent_thread_id` — links to a parent thread (`pthid`)
- `body` — message payload (arbitrary map)
- `attachments` — list of `Layr8.Attachment` structs (DIDComm v2 attachments)
- `context` — inbound-only metadata from the cloud-node

## Wire Format (outbound)

    {
      "id": "...",
      "type": "...",
      "from": "...",
      "to": [...],
      "thid": "...",
      "pthid": "...",
      "body": {...},
      "attachments": [...]
    }

## Wire Format (inbound, from cloud-node)

    {
      "context": {"recipient": "...", "authorized": true, "sender_credentials": [...]},
      "plaintext": {"id": "...", "type": "...", "from": "...", "to": [...], "body": {...}, "thid": "...", "pthid": "..."}
    }

# `t`

```elixir
@type t() :: %Layr8.Message{
  attachments: [Layr8.Attachment.t()],
  body: map() | nil,
  context: Layr8.Message.Context.t() | nil,
  from: String.t(),
  id: String.t(),
  parent_thread_id: String.t(),
  thread_id: String.t(),
  to: [String.t()],
  type: String.t()
}
```

# `generate_id`

```elixir
@spec generate_id() :: String.t()
```

Generate a new unique message ID (UUID v4).

# `marshal`

```elixir
@spec marshal(t()) :: map()
```

Serializes a `Layr8.Message` into a DIDComm JSON envelope map.

The result is suitable for encoding with `Jason.encode!/1`.

## Example

    msg = %Layr8.Message{id: "abc", type: "...", from: "did:ex:alice", to: ["did:ex:bob"], body: %{text: "hi"}}
    Layr8.Message.marshal(msg)
    # => %{"id" => "abc", "type" => "...", "from" => "did:ex:alice", "to" => ["did:ex:bob"], "body" => %{text: "hi"}}

# `parse`

```elixir
@spec parse(map() | String.t()) :: {:ok, t()} | {:error, term()}
```

Parses an inbound cloud-node message envelope (with context + plaintext) into a `Layr8.Message`.

Accepts a map (already JSON-decoded) or a JSON string.

## Example

    envelope = %{
      "context" => %{"recipient" => "did:ex:bob", "authorized" => true, "sender_credentials" => []},
      "plaintext" => %{"id" => "abc", "type" => "...", "from" => "did:ex:alice", "to" => ["did:ex:bob"], "body" => %{}}
    }
    Layr8.Message.parse(envelope)

---

*Consult [api-reference.md](api-reference.md) for complete listing*
