# @updash/mail-api

A typed TypeScript client for the [UpDash Mail API](https://api.updash.com/docs): order automotive direct mail by campaign, from Node 18+ or an edge runtime on your server (never in a browser: the key is a secret). No dependencies: it calls the global `fetch`. The types are generated from [`/openapi.json`](https://api.updash.com/openapi.json).

**Pre-release (0.1.0), and not published.** `@updash/mail-api` is not on npm, its repository is private, and the npm package named `updash` is someone else's. Plain HTTPS is the supported way in today: the REST API and the [docs](https://api.updash.com/docs) are the contract, and this package only wraps them. Ask Xcel if you want the package file.

## Install (a package file from Xcel)

```sh
npm install ./updash-mail-api-0.1.0.tgz
```

Xcel builds that file with `npm pack` in `sdk/typescript`.

The package is ESM only (`import`, not `require`) and ships its own `.d.ts` types. Get a sandbox key (`xm_test_...`) as the [Quickstart](https://api.updash.com/docs/quickstart) says: a sandbox key never prints, mails or spends.

## Quickstart: the sandbox flow

The same steps as the [Quickstart](https://api.updash.com/docs/quickstart), with `demo-motors`, the sample dealer every sandbox starts with.

```ts
import { randomUUID } from "node:crypto";
import { UpdashMail } from "@updash/mail-api";

const mail = new UpdashMail({ apiKey: process.env.XM_KEY! }); // baseUrl defaults to https://api.updash.com

// 1. Find a template and see what it prints for the dealer.
const { templates } = await mail.templates.list({ query: "birthday" }); // compact; detail: "full" adds every slot
console.log(templates.map((t) => `${t.code}: ${t.preview_url}`)); // open a preview_url in a browser
const brand = await mail.dealers.brand("demo-motors");

// 2. Create the campaign, tagged with your own order id. One Idempotency-Key per order: store it
// with the order and send it again only to retry this create.
const orderKey = randomUUID();
const { campaign } = await mail.campaigns.create(
  { dealer_id: "demo-motors", product_code: "postcard_6x9", name: "November service reminder", external_ref: "cmp_778" },
  { idempotencyKey: orderKey },
);

// 3. The audience: start an upload, PUT the CSV to the signed URL (no key), then complete it.
const csv = [
  "external_id,first_name,last_name,address1,city,state,zip,vehicle_year,vehicle_make,vehicle_model",
  "crm-1001,Maria,Lopez,412 Cedar Ln,Springfield,IL,62704,2020,Honda,Accord",
].join("\n");
const upload = await mail.campaigns.audience.start(campaign.id);
await mail.campaigns.audience.upload(upload, csv); // a string or a Blob
const { audience } = await mail.campaigns.audience.complete(campaign.id, { audience_id: upload.audience_id });
console.log(`${audience.mailable_count} of ${audience.submitted_count} mailable`);
// Or in one call: the CSV as the body, or a link Xcel fetches once.
// await mail.campaigns.audience.import(campaign.id, csv, { columnMap: { customer_id: "external_id" } });
// await mail.campaigns.audience.import(campaign.id, { source_url: "https://exports.example.com/nov.csv?sig=..." });

// 4. Creative: fill the template's copy slots. Store details you leave out (phone, signer) print from
// the dealer's profile. The gift is a dealer fact: send the dealer's real one.
const { creative } = await mail.campaigns.creative(campaign.id, {
  template_code: "postcard_6x9_birthday",
  copy: {
    note: "Happy birthday from all of us! Thank you for trusting us with your {{recipient.vehicle|vehicle}}. Your gift is on the other side: stop by any time this month.",
    gift_offer: "$50 toward any service",
    expires: "12/31/2026",
  },
});
if (!creative.preflight.ok) throw new Error(creative.preflight.issues.map((i) => `${i.code}: ${i.fix}`).join("\n"));

// 5. Proof, quote and approval. Prices: https://api.updash.com/console/pricing, signed in (quote.notes name your volume tier).
await mail.campaigns.proof(campaign.id);
const { quote } = await mail.campaigns.quote(campaign.id);
// max_spend_cents is the most the person you work for said to spend, never the quote total alone.
const budgetCents = 50_000;
const approval = await mail.campaigns.approval(campaign.id, { quote_id: quote.id, max_spend_cents: budgetCents });
// Only a person approves spend. In the sandbox, open review_url and approve; live links go by email.
if ("review_url" in approval) console.log(`Approve here: ${approval.review_url}`);
// Poll about once a minute (or use a webhook), and stop if the approver says no or the link expires.
for (;;) {
  const status = await mail.campaigns.get(campaign.id);
  if (status.campaign.status === "approved") break;
  const decision = status.latest_approval?.status;
  if (decision === "rejected" || decision === "expired") throw new Error(`The approval was ${decision}.`);
  await new Promise((r) => setTimeout(r, 60_000));
}

// 6. Submit, then (sandbox only) move the order to completed, which simulates results.
await mail.campaigns.submit(campaign.id, { approval_id: approval.approval_id }, { idempotencyKey: `submit-${campaign.id}` });
await mail.test.advance(campaign.id, { to: "completed" });

// 7. Results: totals on the first page, and every lead by your external_id, page after page.
const results = await mail.campaigns.results(campaign.id);
console.log(results.results?.responses, results.results?.matched);
for await (const lead of mail.campaigns.results(campaign.id)) {
  console.log(lead.external_id, lead.responses.map((r) => r.type_label), lead.matches.map((m) => m.kind));
}
```

## Coming from Lob

Lob sends one piece per call. The UpDash Mail API orders a **campaign**: one dealer, one product, an audience file, a creative, a quote and a person's approval ([Coming from Lob](https://api.updash.com/docs/coming-from-lob)).

```ts
const mailDate = new Date(Date.now() + 21 * 86_400_000).toISOString().slice(0, 10); // three weeks out, YYYY-MM-DD

// Lob: one postcard for one person.
//   await postcardsApi.create({ to, from: "adr_123", front: "tmpl_front", back: "tmpl_back",
//     merge_variables: { first_name: "Pat" }, send_date: mailDate, use_type: "marketing", metadata });

// UpDash: the same mailing to a list.
const { campaign } = await mail.campaigns.create({
  dealer_id: "demo-motors", // `from`: the dealer's profile prints the return address
  product_code: "postcard_6x9", // `size`
  name: "December service",
  requested_mail_date: mailDate, // `send_date`
  external_ref: "lob_cmp_123",
  metadata: { program: "service" }, // `metadata`, same limits
});
const upload = await mail.campaigns.audience.start(campaign.id);
await mail.campaigns.audience.upload(upload, recipientsCsv); // `to`: one CSV row per recipient
// A Lob-style export keeps address_line1, address_city ... ; column_map renames the rest.
await mail.campaigns.audience.complete(campaign.id, { audience_id: upload.audience_id, column_map: { id: "external_id" } });
await mail.campaigns.creative(campaign.id, { template_code: "postcard_6x9_birthday", copy: { gift_offer: "$50 toward any service" /* ... */ } }); // `front`/`back` + `merge_variables`
const { quote } = await mail.campaigns.quote(campaign.id, { mail_class: "first_class" }); // `mail_type`
```

| Lob | Here |
| --- | --- |
| `new Configuration({ username: key })`, Basic auth | `new UpdashMail({ apiKey })`, `Authorization: Bearer` |
| `postcardsApi.create(...)`, `lettersApi.create(...)` | `campaigns.create`, then `audience`, `creative`, `proof`, `quote`, `approval`, `submit` |
| `to` | Rows of the audience CSV (`campaigns.audience.upload`) |
| `from` | The dealer's profile (`dealers.profile.get`, `patch`) |
| `front`, `back`, `template_id` | `template_code`, `html` or `artwork` on `campaigns.creative` |
| `file`, a PDF URL | `artwork: { url }` on `campaigns.creative`, or `artwork.start` + `artwork.upload` |
| `merge_variables` | `copy` (same on every piece) and audience columns (`{{recipient.<column>}}`) |
| `send_date` | `requested_mail_date` on `campaigns.create` |
| `size`, `mail_type` | `product_code` on the campaign, `mail_class` on the quote |
| `idempotency_key` | `idempotencyKey` on `campaigns.create`, `submit`, `templates.save`, `dealers.import` (a UUID when left out) |
| List with `after` | `for await (const c of mail.campaigns.list())`, or `starting_after` |
| Template compile | `templates.preview(code, { copy, format: "json" })` |
| Webhook signature check | `verifyWebhook(rawBody, headers, secret)` |

A field this API does not take (Lob's `send_date`, `merge_variables`, `template_id`) is refused with 400 `invalid_request`, never ignored: the error's `field` names it and `fix` names the field to send. The types catch most of these before a request.

## Errors

Every API error is thrown as an `UpdashMailError` carrying the [error envelope](https://api.updash.com/docs/errors): `code` (stable: branch on it), `message`, `fix` (what to do next), `field`, the HTTP `status` and `requestId` (`X-Request-Id`; quote it to Xcel).

```ts
import { UpdashMailError } from "@updash/mail-api";

try {
  await mail.campaigns.submit(campaignId, { approval_id: approvalId }, { idempotencyKey: `submit-${campaignId}` });
} catch (err) {
  if (!(err instanceof UpdashMailError)) throw err;
  if (err.code === "approval_pending") console.log("Wait for the approver.");
  else console.error(`${err.status} ${err.code}: ${err.message} Fix: ${err.fix} (request ${err.requestId})`);
}
```

The SDK's own codes: `connection_error` (status 0: no answer came; `err.cause` is the network error), `invalid_response` (a success body that is not JSON), `upload_failed` (a signed-URL PUT was refused) and `http_<status>` (an answer without the envelope, such as an expired preview link's text).

## Retries and idempotency

The client retries a call only when a repeat cannot do something twice: every GET, and the POSTs that carry an `Idempotency-Key` (`campaigns.create`, `campaigns.approval`, `campaigns.submit`, `campaigns.audience.import`, `keys.create`, `templates.save`, `dealers.import`), which the API replays. It retries after a 429, a 5xx or a network error, up to `maxRetries` times (default 2), waiting the answer's `Retry-After` when it has one (a wait over 60 seconds is not retried: the error comes to you) or else about 0.5, 1, 2 ... seconds with jitter. Nothing else is retried, so a quote, an approval request or a creative is never made twice by the SDK.

```ts
import { UpdashMail } from "@updash/mail-api";

const mail = new UpdashMail({ apiKey, maxRetries: 4 });
await mail.campaigns.get(id, { maxRetries: 0, signal: AbortSignal.timeout(10_000) }); // per call
```

Without `idempotencyKey`, each call gets a new UUID, so the SDK's own retries replay instead of creating a second campaign. To retry safely after your process restarts, keep your own key with the order and pass it every time. `$response.idempotentReplayed` is `true` when the API answered from the stored result.

A retry of `campaigns.approval` with the same key emails nobody again. A new call with a new key expires the pending approval and emails the approver, so keep your own key with the approval you asked for.

## A key for each store

A key that reaches every dealer can make a key limited to one store. The secret comes back once:

```ts
const { key, id } = await mail.keys.create({ label: "Demo Motors", dealer_ids: ["demo-motors"] }, { idempotencyKey: `store-key-demo-motors-1` });
await saveSecretForStore("demo-motors", key); // null on a retry: no stored answer holds a secret

for await (const k of mail.keys.list()) console.log(k.label, k.dealer_ids, k.revoked_at);
await mail.keys.revoke(id);
```

If the first answer was lost, `key` is `null` on the retry: revoke that key and make another with a new `idempotencyKey`.

## Who was mailed

```ts
for await (const row of mail.leads.list({ external_id: "crm-1001" })) console.log(row.campaign_id, row.status, row.mailed, row.row_key);
for await (const row of mail.campaigns.leads(campaignId, { external_id: "crm-1001" })) console.log(row.row_key, row.result_status);
```

An empty list means no current audience holds that id. A rejected row is named in the audience's `reconciliation.rejected_rows`, with its `external_id`.

## Paging

`campaigns.list`, `dealers.list` and `campaigns.results` return the first page when awaited, and every item on every page with `for await`:

```ts
const page = await mail.campaigns.list({ dealer_id: "demo-motors", limit: 25 }); // one page
for await (const c of mail.campaigns.list({ status: "completed" })) console.log(c.id, c.external_ref); // all of them
for await (const p of mail.dealers.list().pages()) console.log(p.dealers.length); // page by page
```

Campaigns page by `starting_after` = `next_cursor` while `has_more`, dealers by `after` = `next_after`, and a campaign's leads by `leads_after` = `leads.next_after`. Template and profile versions page with `before` = `next_before` by hand.

## Webhooks

`verifyWebhook(rawBody, headers, secret)` checks `X-Xcel-Signature` (`t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`, keyed with the whole `whsec_` secret), rejects a `t` more than 300 seconds from now, and returns the parsed event. It throws a `WebhookVerificationError` with a `reason`: `missing_signature`, `malformed_signature`, `timestamp_out_of_tolerance`, `signature_mismatch` or `invalid_payload`. Pass the raw body exactly as received: re-serialized JSON does not match.

```ts
import express from "express";
import { verifyWebhook, WebhookVerificationError } from "@updash/mail-api";

const app = express();
app.post("/xcel/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    const event = await verifyWebhook(req.body, req.headers, process.env.XCEL_WEBHOOK_SECRET!);
    // De-duplicate on event.id, queue the work, answer quickly.
    res.status(204).end();
  } catch (err) {
    if (err instanceof WebhookVerificationError) return res.status(400).send(err.reason);
    throw err;
  }
});

// Next.js, Cloudflare Workers, Deno and other Request-based runtimes:
export async function POST(req: Request) {
  const event = await verifyWebhook(await req.text(), req.headers, process.env.XCEL_WEBHOOK_SECRET!);
  return new Response(null, { status: 204 });
}
```

- `headers` is a `Headers` object, a plain object such as Node's `req.headers`, or the header's value itself.
- `rawBody` is a string, a `Uint8Array` (a Node `Buffer` too) or an `ArrayBuffer`.
- While you [rotate the secret](https://api.updash.com/docs/webhooks#manage-your-endpoints), pass both: `verifyWebhook(body, headers, [newSecret, oldSecret])`.
- `{ toleranceSeconds, now }` change the clock check; `toleranceSeconds: Infinity` turns it off, for the [test vector](https://api.updash.com/docs/webhooks#verify-the-signature) or a stored delivery.

Register an endpoint with `mail.webhooks.create({ url, event_types })`: its `secret` is in that answer only.

## Responses

Each JSON answer is the API's body, typed, with its metadata as a non-enumerable `$response` (`status`, `requestId`, `idempotentReplayed`, `headers`; `JSON.stringify` leaves it out). Previews can answer with a file instead: `templates.preview` without `format: "json"`, `artwork.preview` without it, and the preview links (`templates.openPreview`, `artwork.openPreview`, which take the token or the whole `preview_url` and send no key) return `{ contentType, data: ArrayBuffer, $response }`.

```ts
const pdf = await mail.templates.preview("postcard_6x9_birthday", { copy, format: "pdf" });
await writeFile("preview.pdf", new Uint8Array(pdf.data));
console.log(pdf.$response.headers.get("x-xcel-preflight-ok"));
```

## Types

Every schema in `/openapi.json` is exported by name (`Campaign`, `CampaignStatus`, `DealerProfile`, `WebhookEvent`, ...; the error envelope is `ErrorEnvelope`), and each operation has `<OperationId>Query`, `<OperationId>Body` and `<OperationId>Response` types (`ListCampaignsQuery`, `CreateCampaignBody`, `CreateCampaignResponse`) and an entry in `Operations`.

- Request types follow each schema's `required`.
- Response types treat every declared field as present (the API sends `null` for an empty one), except the few the API leaves out of some answers, which are optional (a template's `html` and `created_at` exist only on your own templates).
- `DealerProfile` and `Address` serve requests and answers, so they follow `required` both ways.

## Methods

| Method | Route |
| --- | --- |
| `health()` | `GET /v1/health` (no key) |
| `products.list(query?)` | `GET /v1/products` |
| `templates.list(query?)` | `GET /v1/templates` |
| `templates.get(code, query?)` | `GET /v1/templates/{code}` |
| `templates.save(body, { idempotencyKey? })` | `POST /v1/templates` |
| `templates.versions(code, query?)` | `GET /v1/templates/{code}/versions` |
| `templates.retire(code)` | `POST /v1/templates/{code}/retire` |
| `templates.preview(code, body?)` | `POST /v1/templates/{code}/preview` |
| `templates.openPreview(tokenOrUrl, query?)` | `GET /preview/{token}` (no key) |
| `dealers.list(query?)` (pages) | `GET /v1/dealers` |
| `dealers.create(body)` | `POST /v1/dealers` |
| `dealers.import(csv, { idempotencyKey? })` | `POST /v1/dealers/import` |
| `dealers.get(id)` | `GET /v1/dealers/{id}` |
| `dealers.brand(id)` | `GET /v1/dealers/{id}/brand` |
| `dealers.logo(id, logo, { ifMatch? })` | `POST /v1/dealers/{id}/logo` |
| `dealers.assets.list(id, query?)` | `GET /v1/dealers/{id}/assets` |
| `dealers.assets.upload(id, asset, { ifMatch? })` | `POST /v1/dealers/{id}/assets` |
| `dealers.assets.get(id, assetId)` | `GET /v1/dealers/{id}/assets/{asset_id}` |
| `dealers.assets.update(id, assetId, body, { ifMatch? })` | `PATCH /v1/dealers/{id}/assets/{asset_id}` |
| `dealers.assets.delete(id, assetId, { ifMatch? })` | `DELETE /v1/dealers/{id}/assets/{asset_id}` |
| `dealers.approvers.list(id)` | `GET /v1/dealers/{id}/approvers` |
| `dealers.approvers.invite(id, { email, name? })` | `POST /v1/dealers/{id}/approvers` |
| `dealers.suppressions.add(id, source)` | `POST /v1/dealers/{id}/suppressions` |
| `dealers.suppressions.get(id)` | `GET /v1/dealers/{id}/suppressions` |
| `dealers.suppressions.clear(id, { idempotencyKey? })` | `DELETE /v1/dealers/{id}/suppressions` |
| `dealers.profile.get(id, query?)` | `GET /v1/dealers/{id}/profile` |
| `dealers.profile.replace(id, profile, { ifMatch? })` | `PUT /v1/dealers/{id}/profile` |
| `dealers.profile.patch(id, patch, { ifMatch? })` | `PATCH /v1/dealers/{id}/profile` |
| `dealers.profile.versions(id, query?)` | `GET /v1/dealers/{id}/profile/versions` |
| `campaigns.list(query?)` (pages) | `GET /v1/campaigns` |
| `campaigns.create(body, { idempotencyKey? })` | `POST /v1/campaigns` |
| `campaigns.get(id)` | `GET /v1/campaigns/{id}` |
| `campaigns.audience.import(id, source, { columnMap?, vehicleSource? })` | `POST /v1/campaigns/{id}/audience/import` (`source`: `{ source_url }`, or the CSV as a string or Blob) |
| `campaigns.audience.start(id, body?)` | `POST /v1/campaigns/{id}/audience` |
| `campaigns.audience.upload(target, csv)` | `PUT` to the signed `upload_url` (no key) |
| `campaigns.audience.complete(id, body)` | `POST /v1/campaigns/{id}/audience/complete` |
| `campaigns.audience.delete(id, audienceId)` | `DELETE /v1/campaigns/{id}/audience/{audience_id}` |
| `campaigns.creative(id, body)` | `POST /v1/campaigns/{id}/creative` |
| `campaigns.proof(id)` | `POST /v1/campaigns/{id}/proof` |
| `campaigns.validate(id, { method? })` | `GET` (or `POST`) `/v1/campaigns/{id}/validate` |
| `campaigns.quote(id, body?)` | `POST /v1/campaigns/{id}/quote` |
| `campaigns.approval(id, body, { idempotencyKey? })` | `POST /v1/campaigns/{id}/approval` |
| `campaigns.submit(id, body, { idempotencyKey? })` | `POST /v1/campaigns/{id}/submit` |
| `campaigns.results(id, query?)` (pages leads) | `GET /v1/campaigns/{id}/results` |
| `campaigns.leads(id, query?)` (pages rows) | `GET /v1/campaigns/{id}/leads` |
| `leads.list(query)` (pages rows) | `GET /v1/leads` |
| `keys.create(body, { idempotencyKey? })` | `POST /v1/keys` |
| `keys.list(query?)` (pages keys) | `GET /v1/keys` |
| `keys.revoke(id)` | `DELETE /v1/keys/{id}` |
| `artwork.start(body)` | `POST /v1/artwork` |
| `artwork.startForCampaign(id)` | `POST /v1/campaigns/{id}/creative/artwork` |
| `artwork.upload(target, file, { contentType? })` | `PUT` to the signed `upload_url` (no key) |
| `artwork.preview(body)` | `POST /v1/artwork/preview` |
| `artwork.openPreview(tokenOrUrl)` | `GET /preview/artwork/{token}` (no key) |
| `test.approve(id, body)` | `POST /v1/test/campaigns/{id}/approval` (sandbox keys) |
| `test.advance(id, body?)` | `POST /v1/test/campaigns/{id}/advance` (sandbox keys) |
| `webhooks.create(body)` | `POST /v1/webhooks` |
| `webhooks.list()` | `GET /v1/webhooks` |
| `webhooks.delete(id)` | `DELETE /v1/webhooks/{id}` |
| `webhooks.rotate(id)` | `POST /v1/webhooks/{id}/rotate-secret` |
| `webhooks.eventTypes()` | `GET /v1/webhooks/event-types` |
| `events.list(query?)` (pages events) | `GET /v1/events` |
| `webhooks.test(id)` | `POST /v1/webhooks/{id}/test` |
| `webhooks.deliveries(id, query?)` | `GET /v1/webhooks/{id}/deliveries` |
| `webhooks.replay(id, deliveryId)` | `POST /v1/webhooks/{id}/deliveries/{delivery_id}/replay` |
| `account.get()` | `GET /v1/account` |

Every method also takes `{ signal, maxRetries }`. A dealer `id` is Xcel's dealer id or your external id.

