[SEND][ACK]

@sendack/client

Sendack's TypeScript client: plain ESM on fetch, types in index.d.ts, no dependencies and no build step, so it runs as it is in Node 18+, Deno, Bun, browsers and Workers. It speaks Sendack's Connect API with binary protobuf (crates/proto-server/proto/sendack/v1/api.proto), encoding its few messages by hand.

import { Sendack, SendackError, text, json, jsonBytes } from "@sendack/client";

// token: a string, or a function called before each call and connection (passed `refresh`, true after the server
// said `unauthenticated`); omit it for an open server
const sendack = new Sendack("https://sendack.lunaor.com", { token: () => getAccessToken() });

await sendack.publish("chat.42", "m1", jsonBytes({ text: "hi" })); // { version: "26874658802", duplicate: false, pos: "26874658802.0" }
await sendack.publish("chat.42", "m1", jsonBytes({ text: "hi" })); // { …, duplicate: true }: nothing new delivered

const history = await sendack.read("chat.42");                          // [{ pos, id, data, publisher }] from the beginning
const recent = await sendack.read("chat.42", { latest: true, limit: 50 }); // the newest 50, oldest first

// live: from a position (or from now), resuming by itself, no gap and no repeat
const live = sendack.subscribe("chat.42", { after: recent.at(-1)?.pos });
for await (const ev of live) console.log(ev.pos, json(ev.data));
live.close();

Data is a Uint8Array (publish takes bytes or a string); text(data), json(data), utf8(s) and jsonBytes(v) convert. Every failure is a SendackError with Connect's code, the human-readable message, retryAfterS and the refusal's wwwAuthenticate header (undefined unless sent) (invalid_argument, permission_denied, unauthenticated, already_exists for an id published with other data, …).

Live subscriptions

subscribe(topic, { after }) returns an async iterable. await live.ready gives the hello position (where it's live from) once iterating has connected; live.position is always the last position seen. On unavailable, a dropped connection, or an expired token (unauthenticated, when the token is a function) it reconnects from position with jittered backoff (minDelayMs 250 to maxDelayMs 30000; onError sees each). A connection that goes silent for idleMs (default 60000: twice the server's 25 s keep-alive on a quiet topic; any frame counts, a keep-alive included, and time in your loop body does not) is given up on and resumed from position the same way, so a half-dead TCP connection cannot stall it. Other errors end the iteration by throwing. close() (or an aborted signal, or break) ends it; reconnect() resumes straight away.

Durable subscriptions

await sendack.createSubscription("billing", "orders", { ackDeadlineS: 30, maxAttempts: 5, deadLetter: "orders.dead" });
const msgs = await sendack.pull("billing", { max: 10 }); // [{ pos, id, data, publisher, attempt }], each leased
await sendack.ack("billing", msgs.map((m) => m.pos));
await sendack.nack("billing", [pos]);  // hand it out again
await sendack.seek("billing", pos);    // start again after pos

And createWebhook(name, topic, url) → the secret (answered once).

Managing them

await sendack.listSubscriptions({ topic: "orders" }); // [{ name, topic, cursor, leasedUpto, outstanding, … }]
await sendack.getSubscription("billing");             // …, outstanding, consumers: [{ subject, clientId, leases, oldestLeaseUs }] (null from the list)
await sendack.deleteSubscription("billing");          // with its leases

await sendack.listWebhooks();                         // never their secrets
await sendack.getWebhook("crm");                      // …, subscription, last: { atMs, pos, ok, detail }
const { value: { secret } } = await sendack.rotateWebhookSecret("crm"); // the old one signs beside it for 24 h; held for a nod: { status: "approval_pending", ... }
await sendack.deleteWebhook("crm");

Event paging, delivery history and redelivery

const page = await sendack.events("chat.42", { after: "", limit: 100 }); // { events, nextAfter }: oldest first; nextAfter is null on a short page (the end, as of now)
for await (const ev of sendack.allEvents("chat.42", { limit: 100 })) {}  // pages until the end, then stops: it never waits for new events (use subscribe for that)

const { deliveries, nextBefore } = await sendack.webhookDeliveries("crm", { limit: 20 }); // newest first; pass nextBefore as `before` for older
// each: { seq, pos, id, atMs, ok, status ("503" or "timeout", "dns", …), latencyMs, attempt, nextRetryMs, redelivery, host }
const again = await sendack.webhookRedeliver("crm", deliveries[0].pos);                  // the attempt it made

webhookRedeliver is limited to 10 a minute per webhook: beyond that it throws a SendackError with code resource_exhausted, and retryAfterS when the server sent a Retry-After.

Notifications

const key = await sendack.notifyKey();                     // for pushManager.subscribe({ applicationServerKey })
await sendack.subscribePush(pushSubscription.toJSON());    // the token's person's browser
await sendack.unsubscribePush(pushSubscription.endpoint);
await sendack.setPreferences({ push: true, quiet: { from: "22:00", to: "07:00", tz: "Europe/London" }, email: null });
await sendack.getPreferences();
await sendack.notifyRules("chat.42");                      // { topic, enabled, recipients, push, email }: push/email say what this server can carry
await sendack.setNotifyRules("chat.42", true);             // { status: "done", value: { topic, enabled, changed } }, or approval_pending for a person's nod; off when there is none is not_found

Org audit

const { audit, nextBefore } = await sendack.orgAudit("acme", { before, limit: 20 }); // newest first; owners and staff only (403 for a member)
// each: { id, who, action, tenant, target, atMs, requestId }
for await (const rec of sendack.allOrgAudit("acme")) {}  // pages to the oldest, then stops (no polling)

Tests

node --test in this directory runs the unit tests (a fake HTTP server; no Sendack server needed).

Proof

node prove_sdk.mjs http://127.0.0.1:18195 against a running sendack-proto serve (open, or with SENDACK_TOKEN): publish and duplicates, reads, a live subscription through a connection dropped mid-frame, an expired token and a reconnect() with no gap or repeat, and a pull/ack/nack/seek round.