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

# TypeScript SDK

> @cufea/sdk: typed requests, automatic idempotency keys, typed errors and webhook verification.

`@cufea/sdk` is a thin TypeScript client for the Cufea API: typed requests and answers,
automatic idempotency keys, typed errors, timeouts, safe retries and webhook signature
verification. ESM, zero runtime dependencies, global `fetch` and Web Crypto: Node 20+,
browsers and edge runtimes. Its types are generated from the same OpenAPI document as the
[API reference](https://docs.cufea.com/en/api-reference/introduction.md), so they follow the server.

> [!NOTE]
>
> The package is not published to npm yet. Until it is, call the API directly as in the
> [quickstart](https://docs.cufea.com/en/quickstart.md).

## Quickstart

The same flow as the [quickstart](https://docs.cufea.com/en/quickstart.md), against the sandbox:

```ts theme={null}
import { Cufea, CufeaError } from "@cufea/sdk";

const cufea = new Cufea({ apiKey: process.env.CUFEA_KEY!, baseUrl: "https://api.cufea.com" });

await cufea.tenant.get(); // { tenant_id, stage: "sandbox", dian_environment: "test" }

// A webhook endpoint. `secret` is shown once: keep it for verification.
const endpoint = await cufea.webhookEndpoints.create({
  url: "https://hooks.example.com/cufea",
  event_types: [], // every type
});

// Create and send an invoice.
const invoice = await cufea.invoices.create(
  {
    customer: {
      organization_type: "1",
      id_type: "31",
      id_number: "800197268",
      check_digit: "4",
      registration_name: "Acme S.A.S.",
      tax_scheme: "01",
      fiscal_responsibilities: ["O-13"],
      address: {
        line: "Cra 7 # 1-10",
        city_code: "11001",
        city_name: "Bogota, D.C.",
        department_code: "11",
        department_name: "Bogota",
      },
    },
    lines: [{ description: "Service", quantity: "1", unit_price: "100000", taxes: [{ scheme: "01", percent: "19" }] }],
    payment: { form: "1", method_code: "10" },
    reference: "ORDER-1001",
    send: true,
  },
  { idempotencyKey: "order-1001" },
);
// invoice.document_id === "SBX1", invoice.state === "prepared", invoice.send === "queued"

// Follow the status (or wait for the webhook).
const final = await cufea.invoices.waitForFinalState(invoice.document_id);
// final.state === "accepted", final.dian_status_code === "00"
```

`method_code` takes a code of the DIAN list MediosPago-2.1; any other code is a `422` (see
[Payments](https://docs.cufea.com/en/guides/payments.md)). The SDK exports the list, generated from the contract, as
`PAYMENT_MEANS_CODES` (type `PaymentMeansCode`), e.g. to validate input or fill a picker.

## Resources

| Method | Route |
| - | - |
| `cufea.health()` | `GET /v1/health` |
| `cufea.tenant.get()`, `.configuration()` | `GET /v1/tenant`, `GET /v1/tenant/configuration` |
| `cufea.tenant.uploadCertificate(stage, { p12_base64, password })`, `.certificate(stage)` | `PUT`/`GET /v1/tenant/certificate/{stage}`: the .p12 signing certificate |
| `cufea.tenant.testSet()`, `.promotion({ copyFromTest })`, `.promote({ copy_from_test })` | `GET /v1/tenant/test-set`, `GET /v1/tenant/promotion`, `POST /v1/tenant/promote` |
| `cufea.webhookEndpoints.create(body)`, `.list()`, `.delete(id)` | `/v1/tenant/webhooks` |
| `cufea.invoices.create(body)`, `.get(id)`, `.send(id)`, `.refresh(id)` | `/v1/invoices` |
| `cufea.invoices.listAll(filters)` | `GET /v1/invoices`, following the cursor (`for await`) |
| `cufea.invoices.xml(id)`, `.attachedDocument(id)` | the signed XML, the AttachedDocument XML (strings) |
| `cufea.invoices.pdf(id)`, `.emailContent(id)`, `.sendEmail(id, { email, pdf_base64? })` | the PDF (`Uint8Array`), the buyer email's subject and ZIP, send it now (production only) |
| `cufea.invoices.waitForFinalState(id, { intervalMs, timeoutMs })` | polls `get` until `accepted` or `rejected` |
| `cufea.notes.create(body)`, `.get(kind, id)`, `.send(kind, id)`, `.xml(kind, id)`, `.pdf(kind, id)`, `.emailContent(kind, id)`, `.sendEmail(kind, id, body)` | `/v1/notes` (`kind`: `credit` or `debit`) |
| `cufea.events.list(invoiceId)`, `.create(invoiceId, body)`, `.get(invoiceId, eventId)`, `.send(...)`, `.refresh(invoiceId)` | RADIAN events, `/v1/invoices/{id}/events` |
| `cufea.documents.find({ kind, reference })` | `GET /v1/documents`: is there a document with my `reference`? |

Every method takes a last `options` argument with `signal` (an `AbortSignal`) and `timeoutMs`;
the routes that honour `Idempotency-Key` also take `idempotencyKey`. Request and answer types
are exported by schema name (`InvoiceCreate`, `InvoiceRecord`, `WebhookEvent`...).

Tenant setup for the test and production stages (issuer, numbering ranges, certificates, API
keys) is not wrapped yet: the sandbox needs none of it.

## Idempotency

`invoices.create`, `invoices.send`, `notes.create`, `notes.send`, `events.create` and
`webhookEndpoints.create` always send an `Idempotency-Key`: a random UUID per call unless you
pass `idempotencyKey`. Pass your own (an order id, say) to make a retry from *your* side safe
too. See [Idempotency](https://docs.cufea.com/en/idempotency.md).

## Errors

Every error answer becomes a `CufeaError` with the fields of its problem document (see
[Errors](https://docs.cufea.com/en/errors.md)):

```ts theme={null}
try {
  await cufea.invoices.get("SBX999");
} catch (error) {
  if (error instanceof CufeaError) {
    error.status;    // 404
    error.code;      // "document_not_found": stable, branch on it
    error.requestId; // quote it when asking for help
    error.errors;    // the offending fields of a 422 validation_error
  }
}
```

An answer that is not `problem+json` (a proxy's HTML page, say) still gives a `CufeaError`,
with `code: "http_error"`. No HTTP answer at all is a `CufeaConnectionError`, and no answer
within `timeoutMs` is a `CufeaTimeoutError`.

## Timeouts and retries

```ts theme={null}
new Cufea({ apiKey, baseUrl, timeoutMs: 30_000, maxRetries: 2, retryDelayMs: 500 });
```

`timeoutMs` bounds each attempt. A network error, a timeout, a `429` or a `5xx` is retried up
to `maxRetries` times with exponential backoff and jitter (honouring a `Retry-After` of up to
30 s), but only when retrying cannot apply a request twice: `GET`, `PUT` and `DELETE`, and the
POSTs that carry an `Idempotency-Key`. Any other `4xx` is never retried.

## Webhooks

```ts theme={null}
import { webhooks } from "@cufea/sdk";

// rawBody: the exact bytes received (string, Uint8Array or ArrayBuffer), before JSON parsing.
const ok = await webhooks.verify(secret, rawBody, request.headers["x-cufea-signature"]);
if (!ok) return reply(401);
```

`verify` follows the server's rules exactly (see [Webhooks](https://docs.cufea.com/en/webhooks.md)): it refuses a `t`
more than 300 s from your clock either way, accepts the request when any `v1` entry matches,
ignores unknown keys and compares in constant time. A malformed or missing header is `false`,
never an exception. `webhooks.sign(secret, body, t)` makes a header for your receiver's tests.


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