# JavaScript/TypeScript SDK

A small, zero-dependency client with full TypeScript types. Works in Node 18+, Deno, Bun and edge runtimes. **Server-side only.**

## Install

The package is being prepared for npm. Until then, download the single file into your project:

```bash
curl -o tryoncloud.mjs https://www.tryoncloud.com/sdk/tryoncloud.mjs
```

> **Tip:** Plain `fetch` works just as well. The SDK only saves you the form building, error parsing and header reading. See [Generate a try-on](/docs/generate).

## Usage

```js
import { readFile, writeFile } from "node:fs/promises"
import { TryOnCloud, TryOnCloudError } from "./tryoncloud.mjs"

const client = new TryOnCloud() // reads TRYONCLOUD_API_KEY

try {
  const result = await client.generate({
    garment: { url: "https://cdn.yourstore.com/shirt.jpg" },
    person: { data: await readFile("person.jpg"), filename: "person.jpg" },
    customerId: "shopper_123",          // optional, your own end-user id
    idempotencyKey: crypto.randomUUID(), // optional, a retry is never charged twice
  })
  await writeFile("result.png", result.image)
  console.log("free credit?", result.creditWasFree, "request", result.requestId)
} catch (e) {
  if (e instanceof TryOnCloudError && e.code === "NO_CREDITS") {
    console.log("Out of credits, top up in the dashboard")
  } else if (e instanceof TryOnCloudError && e.code === "KEY_LIMIT_REACHED") {
    console.log("This key used its monthly limit", e.details) // { used, limit }
  } else throw e
}
```

## API

| Method | Returns | Endpoint |
|---|---|---|
| `new TryOnCloud({ apiKey?, baseUrl?, timeoutMs? })` | client | |
| `generate({ garment, person, mock?, customerId?, idempotencyKey? })` | `{ image, contentType, resultId, creditWasFree, mock, requestId }` | `POST /generate` |
| `createGeneration({ garment, person, mock?, customerId?, metadata?, webhookUrl?, idempotencyKey? })` | the job (`status: "queued"`) | `POST /generations` |
| `getGeneration(id)` | the job | `GET /generations/:id` |
| `waitForGeneration(id, { intervalMs?, timeoutMs? })` | the finished job (polls) | `GET /generations/:id` |
| `createBatch({ items, webhookUrl?, mock? })` | the batch | `POST /batches` |
| `getBatch(id)` | the batch with every item | `GET /batches/:id` |
| `cancelBatch(id)` | the batch, with `cancelled_now` and `refunded_credits` | `DELETE /batches/:id` |
| `getResult(resultId)` | the image bytes | `GET /results/:id` |
| `deleteResult(resultId)` | nothing | `DELETE /results/:id` |
| `deleteCustomer(customerId)` | `{ results_deleted, records_cleared, webhook_events_deleted }` | `DELETE /customers/:id` |
| `credits()` | `{ credits_remaining, purchased_remaining, purchased_total, free_remaining, spends_from }` | `GET /credits` |
| `TryOnCloud.verifyWebhook(rawBody, headers, secret)` | `true` or `false` | |

Image inputs:

- `{ url }`: a public https image URL (garment, or the person in `createGeneration`)
- `{ base64 }`: a base64 string
- `{ data, filename? }`: a `Blob`, `ArrayBuffer`, `Uint8Array` or Node `Buffer`

Errors are thrown as `TryOnCloudError`, with `status`, `code` (see [Errors](/docs/errors)), `requestId`, `details` (extra fields such as `used` and `limit`) and `retryAfter` on `429`.

## Async jobs and batches

```js
// One async try-on, result fetched when ready
const job = await client.createGeneration({ garment, person, customerId: "shopper_123" })
const done = await client.waitForGeneration(job.id) // or receive a webhook instead
if (done.status === "completed") await writeFile("look.png", await client.getResult(done.result_id))

// A catalogue batch, notified by webhook
const batch = await client.createBatch({
  items: skus.map((s) => ({ garment_url: s.imageUrl, person_url: modelUrl, customer_id: s.sku })),
  webhookUrl: "https://example.com/hooks/tryoncloud",
})
```

See [Async jobs, batches and webhooks](/docs/async) for limits and events.

## Verify webhooks

Pass the raw request body, the headers and your signing secret (**API Keys > Webhooks**):

```js
// Next.js route handler
export async function POST(request) {
  const raw = await request.text()
  if (!(await TryOnCloud.verifyWebhook(raw, request.headers, process.env.TRYONCLOUD_WEBHOOK_SECRET))) {
    return new Response("bad signature", { status: 401 })
  }
  const { event, data } = JSON.parse(raw)
  // event: generation.completed | generation.failed | batch.completed | webhook.test
  return new Response("ok")
}
```

Deliveries older than 5 minutes are rejected, so a captured delivery cannot be replayed.

## Test mode

```js
const preview = await client.generate({ garment, person, mock: true }) // free, returns the person image
const testJob = await client.createGeneration({ garment, person, mock: true }) // free, completes without a render
```
