TypeScript SDK
Official @kestrelmq/sdk client for single and streaming CSV bulk ingestion, cursor-paginated delivery inspection, replay/cancel operations, analytics, and RFC 9457 error handling.
@kestrelmq/sdk is a zero-dependency, strictly typed ESM TypeScript client built on native fetch (DEFAULT_SDK_TIMEOUT_MS = 10_000).
Installation & Initialization
npm install @kestrelmq/sdkBoth baseUrl and apiKey are required in KestrelClientOptions (baseUrl automatically appends /v1 if omitted). When apiKey starts with kmq_live_, the client sends both Authorization: Bearer <key> and X-API-Key: <key> headers; if authenticating with an operator JWT, pass workspaceId to attach X-Workspace-Id:
import { KestrelClient } from "@kestrelmq/sdk";
export const kestrel = new KestrelClient({
baseUrl: process.env.KESTRELMQ_BASE_URL ?? "http://localhost:3000",
apiKey: process.env.KESTRELMQ_API_KEY!,
timeoutMs: 10_000, // default: 10_000ms
// workspaceId: "7c9e6679-7425-40de-944b-e07fc1f90ae7", // optional for JWT auth
});Single & Delayed Event Ingestion (events.send)
Publishes one outbound event (POST /v1/events) with optional recipient, deliverAt (string | Date for SCHEDULED delayed execution), and idempotencyKey (sent in both the Idempotency-Key header and JSON body):
const receipt = await kestrel.events.send({
event: "order.paid",
payload: {
orderId: "ord_9001",
amount: 149.99,
currency: "USD",
},
recipient: {
email: "ava@acme.io",
},
deliverAt: new Date(Date.now() + 60_000), // optional delayed execution
idempotencyKey: "order-paid-ord_9001",
});
console.log({
eventId: receipt.eventId, // UUID
idempotentReplay: receipt.idempotentReplay,
deliveryIds: receipt.deliveryIds, // readonly string[] (UUIDs)
statuses: receipt.deliveries.map((d) => d.status), // ["SCHEDULED"]
});Streaming CSV Bulk Import (events.sendBulk)
kestrel.events.sendBulk(csv, options?) streams an RFC 4180 CSV payload via multipart/form-data (POST /v1/events/bulk), accepting Blob | Buffer | Uint8Array | string | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>.
CSV Columns & Limits
- Required columns:
event_name(orevent) andpayload(serialized JSON object). - Optional columns:
recipient(JSON object),idempotency_key,deliver_at(ISO-8601 timestamp). - Guardrails: Max file size
10 MiB, max10,000rows (exceeding either returns413 Payload Too Large), persisted in transactional chunks of500rows, with up to100row-level validation errors reported inerrors.
import { createReadStream } from "node:fs";
const csvContent = [
"event_name,payload,recipient,idempotency_key,deliver_at",
'invoice.generated,"{""invoiceId"":""inv_1001"",""total"":29}","{""email"":""ops@acme.io""}",inv-1001,',
'invoice.generated,"{""invoiceId"":""inv_1002"",""total"":299}","{""email"":""cto@acme.io""}",inv-1002,2026-12-01T09:00:00Z',
].join("\n");
// Accepts string, Buffer, Blob, ReadableStream, or fs.createReadStream(...)
const result = await kestrel.events.sendBulk(csvContent, {
filename: "invoices-2026-11.csv",
timeoutMs: 30_000,
});
console.log({
totalRows: result.totalRows,
importedEvents: result.importedEvents,
createdDeliveries: result.createdDeliveries,
skippedDuplicates: result.skippedDuplicates,
failedRows: result.failedRows,
errors: result.errors, // readonly { row: number; message: string }[]
});Deliveries: List, Inspect, Replay & Cancel (deliveries.*)
Query deliveries with zero-OFFSET keyset cursor pagination (data, nextCursor, hasMore), inspect masked attempt timelines, replay FAILED deliveries, or cancel uncompleted ones:
// 1. Keyset cursor pagination filtered by status, eventName, or integrationId
const page = await kestrel.deliveries.list({
status: "FAILED",
eventName: "order.paid",
limit: 20,
});
for (const item of page.data) {
// 2. Inspect full delivery record + masked delivery_attempts history
const detail = await kestrel.deliveries.get(item.id);
const lastAttempt = detail.attempts.at(-1);
console.log(detail.status, lastAttempt?.responseStatus, lastAttempt?.durationMs);
// 3. Reset FAILED delivery to PENDING with a fresh retry budget
const replayed = await kestrel.deliveries.replay(item.id);
console.log("Re-queued:", replayed.id, replayed.jobId, replayed.status); // "PENDING"
}
// 4. Cancel a PENDING, SCHEDULED, RETRYING, or PAUSED delivery
const canceled = await kestrel.deliveries.cancel(
"9bafef5c-41d2-4e89-9a0b-3c14d78e02f1"
);
console.log(canceled.status, canceled.removedFromQueue); // "CANCELED" true| SDK Method | HTTP Endpoint | Description |
|---|---|---|
events.send(input) | POST /v1/events | Ingest a single event (PENDING or SCHEDULED via deliverAt). |
events.sendBulk(csv, opts?) | POST /v1/events/bulk | Stream RFC 4180 CSV (multipart/form-data, up to 10 MiB / 10,000 rows). |
deliveries.list(params?) | GET /v1/deliveries | Cursor-paginated list (limit, cursor, status, eventName, integrationId). |
deliveries.get(id) | GET /v1/deliveries/:id | Delivery detail with parent event, integration, routingRule, and attempts. |
deliveries.replay(id) | POST /v1/deliveries/:id/replay | Reset to PENDING and enqueue a fresh BullMQ retry job. |
deliveries.cancel(id) | POST /v1/deliveries/:id/cancel | Cancel an uncompleted delivery (PENDING, SCHEDULED, RETRYING, PAUSED). |
analytics.summary(window?) | GET /v1/analytics/summary | Workspace metrics over '24h' (default), '7d', or '30d' (60s Redis cache). |
Workspace Telemetry (analytics.summary)
Pass an optional positional AnalyticsWindow ('24h' | '7d' | '30d', defaults to '24h'):
const summary = await kestrel.analytics.summary("24h");
console.log({
window: summary.window,
totalEvents: summary.totalEvents,
totalDeliveries: summary.totalDeliveries,
successRate: summary.successRate,
avgDurationMs: summary.avgDurationMs,
p95DurationMs: summary.p95DurationMs,
failedCount: summary.deliveriesByStatus.FAILED,
pausedCount: summary.deliveriesByStatus.PAUSED,
cached: summary.cached,
});Error Handling (KestrelApiError & KestrelTimeoutError)
Non-2xx responses return RFC 9457 Problem Details (application/problem+json) and throw KestrelApiError. Client-side request timeouts throw KestrelTimeoutError:
import { KestrelApiError, KestrelTimeoutError } from "@kestrelmq/sdk";
try {
await kestrel.events.send({
event: "order.paid",
payload: { orderId: "ord_9001" }, // missing required `amount` in STRICT mode
});
} catch (err) {
if (err instanceof KestrelApiError) {
console.error({
status: err.status, // 400 (or 429 on rate limit)
type: err.type, // "https://errors.kestrelmq.dev/bad-request"
title: err.title, // "Bad Request"
detail: err.detail,
instance: err.instance, // "/v1/events"
timestamp: err.timestamp,
errors: err.errors, // readonly string[] (e.g. Ajv validation messages)
retryAfterSec: err.retryAfterSec, // parsed from Retry-After on 429
requestId: err.requestId, // X-Request-Id correlation ID
});
} else if (err instanceof KestrelTimeoutError) {
console.error(`Timed out after ${err.timeoutMs}ms calling ${err.url}`);
}
}