TypeScript library
The briefkasten package: briefkasten(), connect(), .on(), the event type, options and errors.
npm install briefkasten
npm install @briefkasten/adapter-github @briefkasten/adapter-linear # as neededbriefkasten(options)
Webhook handling inside your app. Returns an App.
import { briefkasten } from "briefkasten";
import { github } from "@briefkasten/adapter-github";
const hooks = briefkasten({
sources: { github: github({ secret: process.env.GITHUB_WEBHOOK_SECRET }) },
});| Option | Type | |
|---|---|---|
sources | Record<string, Source> | The sources, by name. A source comes from an adapter: github({ secret }). |
maxBodyBytes | number | Larger deliveries are refused with 413. Default 1 MiB. |
retry | { attempts, backoffMs } | How often a failing handler runs again. Default 5 attempts, from 1 s. |
store | EventStore | Where events are kept for replay. Default: in memory, the last 1000. |
log | (line) => void | Where the app's log lines go. Default: console.warn. |
App
| Member | |
|---|---|
on(pattern, handler) | Run handler for every event that matches. See patterns. |
fetch(request) | A fetch handler: (Request) => Promise<Response>. Mount it in Hono, Next.js, a Worker. |
node | A Node handler: (req, res) => void. Mount it in Express or node:http. |
replay(id) | Run the handlers for a kept event again. |
idle() | Wait until every event received so far has run its handlers. |
close() | Stop: running handlers see their signal aborted, and no retry starts. |
connect(options)
Receive events from a gateway, hosted or self-hosted, over a WebSocket your app opens. Returns an Inbox.
import { connect } from "briefkasten";
const inbox = connect({
url: "https://briefkasten.example",
token: process.env.BRIEFKASTEN_TOKEN,
});| Option | Type | |
|---|---|---|
url | string | The gateway, e.g. https://briefkasten.example. |
token | string | A subscriber token (bk_sub_…). |
filters | string[] | Only these addresses travel over the wire. |
since | string | Start after this event id. Default: where the last connection stopped. |
onEvent | (event) => void | Called after every handled event, e.g. to store its id. |
signal | AbortSignal | Closes the connection when aborted. |
project | string | Only this project's events. Default: every project the token reads. |
transport | "auto" | "websocket" | "sse" | Default auto: a WebSocket, SSE when none opens. |
The client knows no adapters, so event.body is untyped unless you name the sources' event tables:
import type { GithubEvents } from "@briefkasten/adapter-github";
const inbox = connect<{ github: GithubEvents }>({ url, token });Inbox
| Member | |
|---|---|
on(pattern, handler) | Run handler for every event that matches. |
on("error", handler) | Connection and handler errors. |
close() | Close the connection; waits for running handlers. |
Patterns
on() takes a glob over source:event, or over the full address project:adapter:source:target:event. * matches one part, ** any number.
hooks.on("github:push", handler);
hooks.on("github:pull_request.*", handler);
hooks.on(["sentry:issue.created", "linear:issue"], handler);Handlers
hooks.on("github:pull_request.opened", async (event, context) => {
context.log(`#${event.body.number} opened in ${event.target}`);
});A handler gets the event and a context with log, an AbortSignal (signal) and the adapter's actions where it has any. A handler that throws runs again with backoff.
BriefkastenEvent
| Field | Type | |
|---|---|---|
id | string | Stable and time-ordered. |
tenant | string | Whose event it is. |
project | string | The project of the source. |
adapter | string | e.g. github. |
source | string | The source's name. |
target | string | What it is about: acme/shop, a Linear team. |
event | string | e.g. pull_request.opened. |
at | string | ISO 8601, when it was received. |
body | typed per event | The adapter's parsed payload. |
test | true? | Set on test events. |
With an adapter's source, event.body is typed by the event name: inside hooks.on("github:pull_request.opened", …) it is GitHub's pull request payload.
send(options)
Posts a webhook to a hook URL, signed with the source's secret the way the provider signs: a real delivery that goes through verification. Each adapter builds its provider's deliveries, typed, from its samples and the fields you give:
import { send } from "briefkasten";
import { github } from "@briefkasten/adapter-github";
await send({
url: hookUrl,
secret,
delivery: github.events.pullRequest.opened({ repo: "acme/shop", number: 42, title: "Fix login" }),
});| Option | Type | |
|---|---|---|
url | string | The source's hook URL. |
secret | string | The source's secret. |
delivery | WebhookDelivery | An adapter's builder's delivery; withValues(delivery, { "pull_request.draft": true }) sets any value. |
It answers { id, status, ok, body }. The builders take repo, number, title and author, where the provider has them; randomFields() makes random ones for simulated traffic.
Errors
Everything throws a BriefkastenError with a code from the error list and the HTTP status: unauthorized for a wrong token, rate_limited, and so on. A client says its errors to its error handlers (to the console when it has none).
import { BriefkastenError } from "briefkasten";
try {
await inbox.close();
} catch (error) {
if (error instanceof BriefkastenError && error.code === "unauthorized") rotateToken();
}