# TypeScript SDK

> Use the official Sendable TypeScript SDK with session-scoped and account-scoped API keys.

Source: https://wav1.recrav.com/docs/quickstart/nodejs/sdk

## Installation [#installation]

```bash
npm install @sendable-dev/sdk
```

## Create a Client [#create-a-client]

The SDK uses one `Sendable` client with resource namespaces like `messages`, `sessions`, and `webhooks`.

```ts
import { Sendable } from '@sendable-dev/sdk'

export const sendable = new Sendable({
  apiKey: process.env.SENDABLE_API_KEY!,
  apiKeyScope: 'session',
  baseUrl: process.env.SENDABLE_API_URL,
  webhookSecret: process.env.SENDABLE_WEBHOOK_SECRET,
})
```

### Configuration [#configuration]

| Option            | Required | Description                                                                                                                                                       |
| ----------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`          | Yes      | Your Sendable API key                                                                                                                                             |
| `apiKeyScope`     | No       | `'session'` or `'account'`; recommended so the SDK can fail fast on invalid operations                                                                            |
| `baseUrl`         | No       | API base URL, defaults to `https://api.sendable.dev`                                                                                                              |
| `webhookSecret`   | No       | `whsec_...` signing secret used by `webhooks` verification helpers                                                                                                |
| `fetch`           | No       | Custom fetch implementation                                                                                                                                       |
| `headers`         | No       | Default headers added to every request                                                                                                                            |
| `maxRetries`      | No       | Retries for `429`, `503` and network errors. Defaults to 2 for `GET`/`HEAD` and 0 for other methods; setting it applies to every method (see [Retries](#retries)) |
| `maxRetryDelayMs` | No       | Longest `Retry-After` the SDK waits for before retrying, default `30000`. Longer waits throw instead                                                              |

## Session-Scoped Usage [#session-scoped-usage]

Use a session-scoped API key for messages, contacts, groups, session runtime operations, and webhooks.

### Send a Message [#send-a-message]

```ts
const result = await sendable.messages.send({
  chatId: '6281234567890@s.whatsapp.net',
  text: { content: 'Hello from Sendable' },
})

console.log(result.messageId, result.status)
```

### Mention Contacts In a Group [#mention-contacts-in-a-group]

```ts
await sendable.messages.send({
  chatId: '120363427458591243@g.us',
  text: { content: 'asd @6285176702468' },
  mentions: ['6285176702468@s.whatsapp.net'],
})
```

### Format WhatsApp Text [#format-whatsapp-text]

Use the SDK formatter helpers to build `text.content` strings without changing the send API:

```ts
import { Sendable, waText } from '@sendable-dev/sdk'

const content = waText()
  .bold('Release update')
  .newline()
  .quote('Deployment completed')
  .newline()
  .bulletedList(['API healthy', 'Workers healthy'])
  .build()

await sendable.messages.send({
  chatId: '6281234567890@s.whatsapp.net',
  text: { content },
})
```

### Send a Message Asynchronously [#send-a-message-asynchronously]

Add `async: true` to queue the send. The call returns right away with a `runId` instead of a `messageId`. Use `idempotencyKey` so a retried request doesn't send the same message twice. It works for sync sends too, and a retry with the same key within 24 hours returns the first response.

```ts
const queued = await sendable.messages.send(
  {
    chatId: '6281234567890@s.whatsapp.net',
    text: { content: 'Queued message' },
    async: true,
  },
  {
    idempotencyKey: 'order-123-notify',
  },
)

const delivery = await sendable.messages.getDeliveryStatus(queued.runId!)
```

Both modes return `{ messageId, runId, status }`. Sync sends fill `messageId` with status `PENDING`. Async sends fill `runId` with status `QUEUED` and return HTTP 202.

`sendable.messages.sendAsync()` and `POST /v1/message/send-async` still work but are deprecated.

### List Messages [#list-messages]

```ts
const messages = await sendable.messages.list({
  chatId: '6281234567890@s.whatsapp.net',
  limit: 25,
})
```

### Decrypt Media Locally [#decrypt-media-locally]

Use the standalone SDK utility when you already have a WhatsApp media `url` and `mediaKey`. This runs in Node/Bun and does not proxy decrypted bytes through the Sendable API.

```ts
import { Sendable, decryptWhatsAppMedia } from '@sendable-dev/sdk'

const message = await sendable.messages.get('wamid.HBgLN...')

if (!message.image?.url || !message.image.key) {
  throw new Error('Message does not include decryptable image metadata')
}

const media = await decryptWhatsAppMedia({
  url: message.image.url,
  mediaKey: message.image.key,
  mediaType: 'image',
  mimeType: message.image.mimetype,
  messageId: message.id,
})

await Bun.write(media.fileName, media.data)
```

### Decrypt Webhook Media [#decrypt-webhook-media]

If you store Sendable webhook events, you can pass the full event or `event.data` directly into the SDK wrapper without manually mapping `url` and `mediaKey`.

```ts
import { decryptWebhookMedia } from '@sendable-dev/sdk'

const media = await decryptWebhookMedia(event)
await Bun.write(media.fileName, media.data)
```

### Session Runtime Actions [#session-runtime-actions]

```ts
const status = await sendable.sessions.status()
await sendable.sessions.start()
await sendable.sessions.restart()
await sendable.sessions.end()
```

### Contacts, Groups, and Webhooks [#contacts-groups-and-webhooks]

```ts
const contacts = await sendable.contacts.list({ limit: 20 })
const groups = await sendable.groups.list({ limit: 20 })
const webhooks = await sendable.webhooks.list({ page: 1, limit: 25 })
```

### Other Resources [#other-resources]

Every API area has a client on `sendable`:

| Client                           | Covers                                                                                |
| -------------------------------- | ------------------------------------------------------------------------------------- |
| `messages`, `media`              | send, edit, delete, star, read, history, media upload                                 |
| `chats`                          | chat list, notes, tags, archive, pin, mute, clear, delete, disappearing timer         |
| `contacts`, `presence`           | contact lookups, profile pictures, devices, presence                                  |
| `groups`, `communities`          | create, participants, settings, invites, join requests, pictures, linked groups       |
| `account`                        | profile, privacy, blocklist, account caps, app-state resync                           |
| `labels`, `business`             | Business labels, business profile, catalog, orders, quick replies                     |
| `status`, `newsletters`, `calls` | statuses, channels, call log, call links                                              |
| `events`                         | `GET /v1/events` replay feed                                                          |
| `webhooks`                       | create, update, delete, rotate secret, delivery logs, retries, signature verification |

```typescript
await sendable.groups.addParticipants('120363025000000000@g.us', ['6281234567890'])
await sendable.account.updatePrivacy({ lastSeen: 'contacts', readReceipts: 'none' })
const { data } = await sendable.events.list({ type: 'group.join-request' })
const logs = await sendable.webhooks.listLogs(webhookId, { limit: 10 })
```

## Account-Scoped Usage [#account-scoped-usage]

Use an account-scoped API key for account-level session management.

```ts
import { Sendable } from '@sendable-dev/sdk'

const accountClient = new Sendable({
  apiKey: process.env.SENDABLE_ACCOUNT_API_KEY!,
  apiKeyScope: 'account',
  baseUrl: process.env.SENDABLE_API_URL,
})

const sessions = await accountClient.sessions.list()

const created = await accountClient.sessions.create({
  state: 'ID',
  name: 'Primary session',
})
```

You can also fetch, update, and delete sessions:

```ts
const session = await accountClient.sessions.get(created.id)

await accountClient.sessions.update(created.id, {
  name: 'Production session',
  isActive: true,
})

await accountClient.sessions.delete(created.id)
```

## Webhook Verification [#webhook-verification]

If you pass `webhookSecret` into the client, you can verify and parse signed webhooks with the SDK:

```ts
import express from 'express'
import { sendable } from './sendable'

const app = express()

app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  const payload = req.body.toString()

  try {
    const event = await sendable.webhooks.verifyAndParse(payload, req.headers)
    console.log(event.type, event.data)
    return res.json({ received: true })
  } catch {
    return res.status(401).json({ error: 'Invalid signature' })
  }
})
```

## Error Handling [#error-handling]

The SDK throws typed errors you can branch on:

```ts
import {
  SendableApiError,
  SendableInsufficientScopeError,
  SendableRateLimitError,
  SendableScopeError,
} from '@sendable-dev/sdk'

try {
  await sendable.messages.send({
    chatId: '6281234567890@s.whatsapp.net',
    text: { content: 'Hello' },
  })
} catch (error) {
  if (error instanceof SendableInsufficientScopeError) {
    // The key's permissions lack error.requiredPermission, e.g. 'message:write'
    console.error('API key is missing', error.requiredPermission)
  } else if (error instanceof SendableScopeError) {
    console.error('Wrong API key scope for this operation')
  } else if (error instanceof SendableRateLimitError) {
    // error.retryAfterMs from Retry-After; error.rateLimit from RateLimit-* headers
    console.error('Slow down, retry in', error.retryAfterMs, 'ms')
  } else if (error instanceof SendableApiError) {
    console.error(error.status, error.message, error.body)
  } else {
    throw error
  }
}
```

### Retries [#retries]

Retries are opt-in for anything that could have side effects:

* `GET` and `HEAD` requests retry up to 2 times by default on `429`, `503` and network errors.
* With `maxRetries` set (on the client or per call), the SDK waits for `Retry-After` when the server sends it, otherwise it backs off exponentially with jitter (0.5 s, 1 s, 2 s, ... up to 8 s).
* `messages.send` retries `429`, `503`, network errors and `409` (same request still running). It sends an `Idempotency-Key` on every attempt, generated once per call when you do not pass `idempotencyKey`, so a retry never sends the message twice.
* Other `POST` and `PATCH` calls retry only on `429`, because the server rejects those before doing anything.

```ts
const sendable = new Sendable({
  apiKey: process.env.SENDABLE_API_KEY!,
  apiKeyScope: 'session',
  maxRetries: 3,
})

// Safe to retry: the SDK adds an Idempotency-Key for you.
await sendable.messages.send({
  chatId: '6281234567890@s.whatsapp.net',
  text: { content: 'Your order has shipped' },
})
```

## Next Steps [#next-steps]

* See [Node.js Quick Start](/docs/quickstart/nodejs) for the minimal setup flow
* See [Express Integration](/docs/quickstart/nodejs/express) for a full server example
* See [API Reference](/docs/api-reference) for endpoint-level details
