# JavaScript SDK

The SDK is a thin, typed client for the API. It sends the same requests you would send with `fetch`, returns the same JSON objects, turns error responses into exceptions, and retries rate-limited calls for you.

## Install

```bash
npm install @qelka/sdk
```

The package has no runtime dependencies: it uses the platform's `fetch` and Web Crypto. It runs on Node.js 20 and later, Deno, Bun and Cloudflare Workers, and it ships TypeScript types for every request, response, error and webhook event.

Use it on your server only. The client needs your secret API key, and a key shipped in browser or mobile code can be read and spent by anyone. See [Authentication](/docs/authentication).

## Create a client

```javascript
import { Client } from '@qelka/sdk'

const client = new Client({ apiKey: process.env.API_KEY })
```

| Option | Default | Description |
|---|---|---|
| `apiKey` | required | Your `sk_live_` or `sk_test_` key. The constructor throws if it is missing. |
| `baseUrl` | `https://api.qelka.com/v1` | API root, without a trailing slash. |
| `maxRetries` | `2` | How many times a `429`, `502` or `503` response is retried. `0` turns retries off. |
| `timeoutMs` | `30000` | Time limit of each attempt, in milliseconds, including reading the response. |
| `fetch` | the global `fetch` | A custom `fetch` function, for a proxy or for tests. |

Create one client and reuse it. Pass an `sk_test_` key in development and CI, and an `sk_live_` key in production: nothing else changes. See [Test mode](/docs/test-mode).

## Methods

| Method | Endpoint | Returns |
|---|---|---|
| `client.phone.validate({ phone })` | [POST /phone](/docs/api-reference/phone) | A `phone` result |
| `client.email.verify({ email })` | [POST /email](/docs/api-reference/email) | An `email` result |
| `client.ip.lookup({ ip })` | [POST /ip](/docs/api-reference/ip) | An `ip` result |
| `client.batch(items)` | [POST /batch](/docs/api-reference/batch) | A `list` with `data` and `credits_used` |
| `client.bulk.create({ csv, type, column })` | [POST /bulk](/docs/api-reference/bulk) | A `bulk_job` |
| `client.bulk.get(id)` | [GET /bulk/{id}](/docs/api-reference/bulk) | A `bulk_job` |
| `client.account.get()` | [GET /account](/docs/api-reference/account) | The `account` object |

Each method takes the request fields of its endpoint: `country`, `level` and `fresh` for phone numbers, `mode` and `fresh` for emails, `country`, `level` and `mode` for bulk jobs. Results use the field names of the API, in `snake_case`, so the reference pages describe them exactly. Every method also accepts an optional last argument, `{ signal }`, to cancel the request with an `AbortSignal`.

## Check a phone number, an email and an IP

```javascript
const phone = await client.phone.validate({ phone: '(415) 555-0123', country: 'US' })
if (phone.valid) console.log(phone.e164)

const email = await client.email.verify({ email: 'jane@example.com', mode: 'fast' })
console.log(email.status, email.reason, email.did_you_mean)

const ip = await client.ip.lookup({ ip: '8.8.8.8' })
console.log(ip.country?.code, ip.flags.datacenter, ip.risk.level)
```

## Run a batch

`client.batch()` takes the array of items directly:

```javascript
const { data, credits_used } = await client.batch([
  { type: 'email', email: 'jane@example.com' },
  { type: 'phone', phone: '+14155550123', level: 'live' },
  { type: 'ip', ip: '8.8.8.8' },
])

for (const entry of data) {
  if (entry.object === 'error') console.warn(entry.index, entry.error.type)
}
console.log(`${credits_used} credits`)
```

An item that fails comes back as an error object in `data`; it does not throw. Only a failure of the whole request throws.

## Run a bulk job

`csv` is the content of the file, as a string or a `Blob`:

```javascript
import { readFile, writeFile } from 'node:fs/promises'
import { Client } from '@qelka/sdk'

const client = new Client({ apiKey: process.env.API_KEY })
const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))

const csv = await readFile('contacts.csv', 'utf8')
let job = await client.bulk.create({ csv, type: 'email', column: 'email' })

while (job.status === 'queued' || job.status === 'processing') {
  await sleep(15000)
  job = await client.bulk.get(job.id)
}

if (job.status === 'completed') {
  const result = await fetch(job.download_url)
  await writeFile('contacts-checked.csv', await result.text())
}
```

Instead of polling, you can let the `bulk.completed` [webhook](/docs/webhooks) tell you when the job is done.

## Read the account

```javascript
const account = await client.account.get()
console.log(account.plan.id, account.credits.balance, account.key.mode)
```

## Read the response headers

The plain methods return the result only. When you also need the request id, the rate limit headers or your balance, call the same method through `client.withResponse`:

```javascript
const { data, response } = await client.withResponse.email.verify({ email: 'jane@example.com' })
console.log(data.status)
console.log(response.requestId, response.creditsRemaining)
console.log(response.rateLimit.remaining, response.rateLimit.reset)
```

`client.lastResponse` holds the same information for the last call the client made.

## Handle errors

When the API answers with an error, the SDK throws an `ApiError`:

| Property | Description |
|---|---|
| `type` | The error type, such as `insufficient_credits`. See [Errors](/docs/errors). |
| `status` | The HTTP status, such as `402`. |
| `message` | The human-readable message from the API. |
| `docs` | The link to the documentation of the error type. |
| `requestId` | The `X-Request-Id` of the failed request. Include it when you contact support. |
| `retryAfter` | Seconds to wait before retrying, from the `Retry-After` header, or `null`. |
| `body` | The raw response body. |

When the API cannot be reached at all, the SDK throws an `ApiConnectionError`, and an `ApiTimeoutError` when an attempt takes longer than `timeoutMs`.

```javascript
import { ApiConnectionError, ApiError, Client } from '@qelka/sdk'

const client = new Client({ apiKey: process.env.API_KEY })

export async function verifyOrNull(email) {
  try {
    return await client.email.verify({ email })
  } catch (error) {
    if (error instanceof ApiConnectionError) return null
    if (!(error instanceof ApiError)) throw error
    if (error.type === 'insufficient_credits') {
      console.error('Out of credits', error.requestId)
      return null
    }
    if (error.type === 'invalid_request') {
      console.warn(`Rejected input: ${error.message}`)
      return null
    }
    throw error
  }
}
```

A result with a negative answer is not an error: an undeliverable address or an invalid phone number comes back as a normal result with its status.

## Automatic retries

Responses with the status `429`, `502` or `503` are retried up to `maxRetries` times. The SDK waits for the `Retry-After` delay when the API sends one, up to 60 seconds, and otherwise backs off exponentially with jitter, from about half a second up to 8 seconds. When the retries run out, it throws the last `ApiError`. Other errors are thrown at once: retrying them would fail the same way.

Retries never cost extra: failed calls are not billed.

## Verify webhooks

`verifyWebhook(rawBody, signatureHeader, secret)` checks the `X-Signature` header of a webhook request against the raw body and your signing secret. It returns a promise of `true` or `false`, and rejects signatures older than 5 minutes. `parseWebhookEvent(rawBody)` then parses the body into a typed event, and throws a `WebhookPayloadError` if it is not a valid event.

```javascript
import { parseWebhookEvent, verifyWebhook } from '@qelka/sdk'

export async function handleWebhook(rawBody, signatureHeader) {
  const valid = await verifyWebhook(rawBody, signatureHeader, process.env.WEBHOOK_SECRET)
  if (!valid) return { status: 400 }
  const event = parseWebhookEvent(rawBody)
  console.log(event.type, event.id)
  return { status: 204 }
}
```

Pass the body exactly as received, before any JSON parsing. [Webhooks](/docs/webhooks) has a complete Express example and the signature format.

## Other languages

The API is plain HTTPS and JSON, so any HTTP client works. The reference pages show curl and `fetch` for every endpoint, and the public OpenAPI 3.1 document at `https://api.qelka.com/v1/openapi.json` can generate a client in many languages.
