# The TypeScript SDK

`@lupeno/sdk` is the official client: every path, parameter and answer typed from the published [API description](https://api.lupeno.com/openapi.json), plus helpers for pages, idempotency and webhooks. MIT-licensed; its only dependency is `openapi-fetch`.

```sh
npm install @lupeno/sdk
```

Node 20.19 or later (an ES module — `require()` works too), Deno, Bun and edge runtimes.

## Calls

```ts
import { createLupeno, unwrap } from '@lupeno/sdk';

const lupeno = createLupeno({ apiKey: process.env.LUPENO_API_KEY! });

// Each call answers { data, error, response } …
const { data, error } = await lupeno.GET('/v1/events', { params: { query: { limit: 25 } } });

// … or throws a LupenoError (status, code, requestId, retryAfter) through unwrap.
const event = unwrap(
  await lupeno.GET('/v1/events/{eventId}', { params: { path: { eventId } } }),
);
```

Paths are written as in the reference, with their parameters typed: a wrong field name or a missing path parameter is a compile error, not a `400`.

## Retries and timeouts

The client retries by itself what is safe to retry: a `429`, a `5xx`, a network failure or a timeout, for reads, `PUT`, `DELETE` and creates carrying an `Idempotency-Key` — twice by default, backing off from half a second and honouring `Retry-After` up to a minute (a longer wait comes back to you as the answer, with `LupenoError.retryAfter` in seconds). Each attempt has 30 seconds.

```ts
const lupeno = createLupeno({
  apiKey: process.env.LUPENO_API_KEY!,
  retries: 4, // 0 turns retrying off
  timeoutMs: 10_000, // null for no limit
});
```

## Documents

A document's PDF is bytes, not JSON — `downloadDocument` asks for them (the key needs `pii` as well as `read`):

```ts
import { writeFile } from 'node:fs/promises';
import { downloadDocument } from '@lupeno/sdk';

await writeFile('invoice.pdf', await downloadDocument(lupeno, documentId));
```

With the plain call, pass `parseAs: 'arrayBuffer'`.

## Every page

```ts
import { paginate } from '@lupeno/sdk';

for await (const ticket of paginate((cursor) =>
  lupeno.GET('/v1/events/{eventId}/tickets', {
    params: { path: { eventId }, query: { cursor, limit: 100 } },
  }),
)) {
  console.log(ticket.id);
}
```

## Creates

```ts
import { idempotencyKey, unwrap } from '@lupeno/sdk';

const key = idempotencyKey(); // the same key for every retry of this create
const code = unwrap(
  await lupeno.POST('/v1/events/{eventId}/discount-codes', {
    params: { path: { eventId }, header: { 'idempotency-key': key } },
    body: { code: 'SPRING26', kind: 'percent', percentBp: 1500 },
  }),
);
```

## A script, start to finish

List your events with a test key, make a discount code on the first, name a ticket's holder and admit it at the door:

```ts
import { createLupeno, idempotencyKey, paginate, unwrap } from '@lupeno/sdk';

const lupeno = createLupeno({ apiKey: process.env.LUPENO_TEST_KEY! }); // read, write, checkin

const events = unwrap(await lupeno.GET('/v1/events', {}));
const eventId = events.items[0]!.id;

unwrap(
  await lupeno.POST('/v1/events/{eventId}/discount-codes', {
    params: { path: { eventId }, header: { 'idempotency-key': idempotencyKey() } },
    body: { code: 'TEAM10', kind: 'percent', percentBp: 1000 },
  }),
);

for await (const ticket of paginate((cursor) =>
  lupeno.GET('/v1/events/{eventId}/tickets', { params: { path: { eventId }, query: { cursor } } }),
)) {
  unwrap(
    await lupeno.POST('/v1/tickets/{ticketId}/assign', {
      params: { path: { ticketId: ticket.id } },
      body: { name: 'Jana Nováková', email: 'jana@example.com' },
    }),
  );
  unwrap(
    await lupeno.POST('/v1/events/{eventId}/check-ins', {
      params: { path: { eventId } },
      body: { ticketId: ticket.id },
    }),
  );
  break;
}
```

## Webhooks

```ts
import { constructWebhookEvent } from '@lupeno/sdk';

const event = await constructWebhookEvent({
  payload: await request.text(), // the raw body
  signature: request.headers.get('Lupeno-Signature'),
  secret: process.env.LUPENO_WEBHOOK_SECRET!,
});

switch (event.type) {
  case 'order.paid':
    // event.data is typed as the Order — deduplicate on event.id
    break;
  case 'refund.completed':
    // event.data is the Refund
    break;
  default:
  // a type this SDK does not know yet: /v1 only grows
}
```

`event` is a union on `type` (`LupenoWebhookEvent`), so each branch knows its `data`; `WebhookEventOf<'order.paid'>` names one of them.

`constructWebhookEvent` throws when the signature does not match or is older than five minutes. See [Webhooks](https://lupeno.com/developers/guides/webhooks).

## Versions

The SDK's version follows the API description's. `/v1` only grows, so a newer SDK never breaks code written for an older one — see [Versioning](https://lupeno.com/developers/guides/versioning).
