@billionsend/node 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +277 -2
- package/dist/index.cjs +1720 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +16959 -0
- package/dist/index.d.ts +16959 -0
- package/dist/index.js +1698 -0
- package/dist/index.js.map +1 -0
- package/package.json +75 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-17)
|
|
4
|
+
|
|
5
|
+
- First version of the BillionSend SDK for Node.js and TypeScript: every operation of the BillionSend API, grouped by resource and named after each operation's `operationId`, with request and response types generated from the OpenAPI document.
|
|
6
|
+
- Results as `{ data, error, headers }`; methods never throw.
|
|
7
|
+
- Errors as classes: `ValidationError`, `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `RateLimitError` (with `retryAfter`), `APIError`, `APIConnectionError` and `APITimeoutError`, all `BillionSendError`s with `statusCode`, `name`, `message` and `requestId` (the answer's `x-request-id`). The iterators throw the same instances.
|
|
8
|
+
- The sending operations always carry an `Idempotency-Key`: the caller's, or a new one per call that its retries reuse.
|
|
9
|
+
- Retries for 429, 5xx, timeouts, network failures and `409 concurrent_idempotent_requests`, on requests safe to repeat; `retry-after` honoured, exponential backoff otherwise; per-attempt timeouts; injectable `fetch`.
|
|
10
|
+
- List query parameters go comma-separated in one key, as the document declares them.
|
|
11
|
+
- `listAll` / `searchAll` async iterators over cursor-paginated lists.
|
|
12
|
+
- Inbox event streams (server-sent events) as async iterators of typed events, resuming with `Last-Event-ID` after a dropped connection; `stream.gap` handed out once per position; one inbox's stream ends after its `inbox.deleted` or `inbox.expired`.
|
|
13
|
+
- `verifyWebhook` checks a webhook delivery's signature and timestamp and returns the parsed event.
|
|
14
|
+
- ES module and CommonJS builds with types for both; no runtime dependencies; Node.js 18 or later.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BillionSend
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,278 @@
|
|
|
1
|
-
#
|
|
1
|
+
# BillionSend Node.js SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The official Node.js and TypeScript client for the [BillionSend](https://billionsend.com) email API: send email, run inboxes for people and agents, stream inbox events, verify webhooks, and manage domains, contacts and broadcasts.
|
|
4
|
+
|
|
5
|
+
- Every API operation, typed from the BillionSend OpenAPI document.
|
|
6
|
+
- Results as `{ data, error, headers }`: methods never throw. Errors are classes you can tell apart with `instanceof`.
|
|
7
|
+
- Safe sends: every send carries an `Idempotency-Key`, so retries after a timeout never send twice.
|
|
8
|
+
- Async iterators for every list and for live inbox events, with automatic resume.
|
|
9
|
+
- ES modules and CommonJS, with types for both. No runtime dependencies. Node.js 18 or later (any runtime with `fetch` works).
|
|
10
|
+
|
|
11
|
+
Documentation: [billionsend.com/docs](https://billionsend.com/docs) · SDK guide: [billionsend.com/docs/sdks/node](https://billionsend.com/docs/sdks/node) · Source: [github.com/billionsend/billionsend-node](https://github.com/billionsend/billionsend-node)
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @billionsend/node
|
|
17
|
+
# or: pnpm add @billionsend/node / yarn add @billionsend/node
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Authentication
|
|
21
|
+
|
|
22
|
+
Create an API key on the dashboard (it starts with `bs_`) and pass it to the client, or set `BILLIONSEND_API_KEY`:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { BillionSend } from "@billionsend/node";
|
|
26
|
+
|
|
27
|
+
const bs = new BillionSend("bs_..."); // or: new BillionSend() with BILLIONSEND_API_KEY set
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
CommonJS works the same way: `const { BillionSend } = require("@billionsend/node");`. A key restricted to one inbox is what an agent should hold; see [API keys](https://billionsend.com/docs/api-keys).
|
|
31
|
+
|
|
32
|
+
## Send an email
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
const { data, error } = await bs.emails.send({
|
|
36
|
+
from: "Acme <hello@acme.dev>",
|
|
37
|
+
to: ["ana@example.com"],
|
|
38
|
+
subject: "Welcome to Acme",
|
|
39
|
+
html: "<p>Glad you are here.</p>",
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
if (error) {
|
|
43
|
+
console.error(error.statusCode, error.name, error.message, error.requestId);
|
|
44
|
+
} else {
|
|
45
|
+
console.log("queued", data.id);
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**Idempotency.** The sending operations (`emails.send`, `emails.batch`, `emails.receiving.reply` / `forward`, `inboxes.send`, `inboxes.drafts.send`, `inboxes.threads.emails.reply` / `forward`) always send an `Idempotency-Key` header. Without your own, each call gets a new random key and that call's retries reuse it, so a retry after a timeout cannot send twice. Pass your own key to make a send safe across calls and processes too; a repeat with the same key and payload returns the first result:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
await bs.emails.send(message, { idempotencyKey: `welcome/${user.id}` });
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**Retries.** Failures worth retrying are retried up to `maxRetries` times (default 2): `429`, `5xx`, timeouts and network errors, and the `409 concurrent_idempotent_requests` the API answers while the first attempt with the same key is still running. Only requests safe to repeat are retried: `GET`, `PUT`, `DELETE` and the sending operations above. The client waits as `retry-after` asks, or backs off exponentially (0.5 s, 1 s, 2 s … up to 8 s, with jitter); a `retry-after` over a minute is not waited for, and the error comes back instead.
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
const bs = new BillionSend({ apiKey: "bs_...", maxRetries: 4 });
|
|
59
|
+
await bs.emails.send(message, { maxRetries: 0 }); // per call
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Errors
|
|
63
|
+
|
|
64
|
+
Every method resolves to one of:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
{ data: T, error: null, headers }
|
|
68
|
+
{ data: null, error: BillionSendError, headers }
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`error` is an instance of a class for its kind, all subclasses of `BillionSendError` (itself an `Error`):
|
|
72
|
+
|
|
73
|
+
| Class | When |
|
|
74
|
+
| --- | --- |
|
|
75
|
+
| `ValidationError` | `400`, `422`: the request is invalid |
|
|
76
|
+
| `AuthenticationError` | `401`, or no API key configured (`name: "missing_api_key"`, no request made) |
|
|
77
|
+
| `PermissionDeniedError` | `403`: the key, its scope, your role or your plan does not allow it |
|
|
78
|
+
| `NotFoundError` | `404` |
|
|
79
|
+
| `ConflictError` | `409`, such as an idempotency key reused with a different payload |
|
|
80
|
+
| `RateLimitError` | `429`; `retryAfter` holds the server's hint in seconds |
|
|
81
|
+
| `APIError` | `5xx` |
|
|
82
|
+
| `APIConnectionError` | no answer: DNS, connection or TLS failure (`statusCode` is `null`) |
|
|
83
|
+
| `APITimeoutError` | the request timed out (a subclass of `APIConnectionError`) |
|
|
84
|
+
|
|
85
|
+
Each carries `statusCode`, `name` (the API's error name, such as `validation_error`; `application_error` when the API sent none), `message` and `requestId`, the answer's `x-request-id`: the same id the request has on the dashboard's Logs page, so quote it when you ask about a request.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { NotFoundError, RateLimitError } from "@billionsend/node";
|
|
89
|
+
|
|
90
|
+
const { data, error } = await bs.emails.get(id);
|
|
91
|
+
if (error instanceof NotFoundError) return null;
|
|
92
|
+
if (error instanceof RateLimitError) console.log("retry in", error.retryAfter, "s");
|
|
93
|
+
else if (error) throw error;
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The iterators (`listAll`, `searchAll`, event streams) cannot return a result per item, so they throw the same error instances.
|
|
97
|
+
|
|
98
|
+
## Pagination
|
|
99
|
+
|
|
100
|
+
List methods take the API's cursor parameters (`limit`, `after`, `before`) and return one page. Every cursor list also has an async iterator that fetches pages as you go:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
for await (const contact of bs.contacts.listAll({ limit: 100 })) {
|
|
104
|
+
console.log(contact.email);
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Thread search has `searchAll`. Starting with `before` walks backward. `paginate(fetchPage)` builds the same iterator over any page fetcher.
|
|
109
|
+
|
|
110
|
+
## An agent's inbox: wait, read, reply
|
|
111
|
+
|
|
112
|
+
An agent holds a key restricted to its inbox, waits for new mail on the live event stream, reads it, and replies in the thread:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
const inboxId = "support@acme.dev"; // an inbox id or its address
|
|
116
|
+
|
|
117
|
+
const opened = await bs.inboxes.events.streamInbox(inboxId, { types: "inbox.email.received" });
|
|
118
|
+
if (opened.error) throw opened.error;
|
|
119
|
+
|
|
120
|
+
for await (const item of opened.data) {
|
|
121
|
+
if (item.event === "stream.gap") {
|
|
122
|
+
// Resumed from too far back: events may be missing. Re-read the threads.
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const { thread_id, email_id } = item.data.data;
|
|
126
|
+
if (!thread_id || !email_id) continue;
|
|
127
|
+
|
|
128
|
+
const email = await bs.inboxes.threads.emails.get(inboxId, thread_id, email_id);
|
|
129
|
+
if (email.error) throw email.error;
|
|
130
|
+
|
|
131
|
+
const answer = await draftAnswer(email.data.subject, email.data.text); // your model
|
|
132
|
+
const sent = await bs.inboxes.threads.emails.reply(
|
|
133
|
+
inboxId,
|
|
134
|
+
thread_id,
|
|
135
|
+
email_id,
|
|
136
|
+
{ text: answer },
|
|
137
|
+
{ idempotencyKey: `reply/${email_id}` }, // a replayed event cannot reply twice
|
|
138
|
+
);
|
|
139
|
+
if (sent.error) throw sent.error;
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Waiting for a sign-in code sent to the inbox:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
const { data: code } = await bs.inboxes.codes.latest("support@acme.dev", { from: "example.com", wait: 30 });
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Live events
|
|
150
|
+
|
|
151
|
+
`bs.inboxes.events.stream()` streams every inbox event of the team (it needs a team-wide key); `bs.inboxes.events.streamInbox(inbox)` streams one inbox. Both resolve once the stream is open (or with the error that refused it) and give an async iterator of typed events:
|
|
152
|
+
|
|
153
|
+
- `InboxStreamEvent`: `{ id, event, data }`, where `event` is the webhook event name (`inbox.email.received`, `inbox.thread.created`, `inbox.draft.sent`, `email.received`, …) and `data` is `{ type, created_at, inbox_id, data }`, the webhook payload's metadata with the ids to read next (`thread_id`, `email_id`, `draft_id`).
|
|
154
|
+
- `StreamGapEvent`: `{ id: null, event: "stream.gap", data: { reason } }` when the stream resumed from further back than the server keeps (24 hours): events may be missing, so read the lists again. One stream hands it out once per position.
|
|
155
|
+
|
|
156
|
+
When the connection drops (the server also closes every stream about every ten minutes), the stream reconnects with `Last-Event-ID` and replays what it missed before the live events. It gives up after `maxReconnects` failures in a row (default 5) with an `APIConnectionError`; a refusal a retry cannot fix (a revoked key) is thrown as its own class. One inbox's stream ends after that inbox's `inbox.deleted` or `inbox.expired`.
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
const opened = await bs.inboxes.events.stream({ types: "inbox.email.received,inbox.thread.created" }, {
|
|
160
|
+
lastEventId: saved, // resume where a previous run stopped
|
|
161
|
+
});
|
|
162
|
+
if (opened.error) throw opened.error;
|
|
163
|
+
for await (const item of opened.data) {
|
|
164
|
+
saved = opened.data.lastEventId;
|
|
165
|
+
// break, or opened.data.close(), ends the stream
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Verify webhooks
|
|
170
|
+
|
|
171
|
+
Every webhook delivery is signed with the endpoint's `whsec_` secret (shown when you create the endpoint, and by `webhooks.rotate`). `verifyWebhook` checks the signature and the timestamp (within 5 minutes by default, so a captured delivery cannot be replayed) and returns the parsed event; anything wrong throws a `WebhookVerificationError`. Pass the body exactly as it arrived, before any JSON parsing:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import express from "express";
|
|
175
|
+
import { verifyWebhook, WebhookVerificationError } from "@billionsend/node";
|
|
176
|
+
|
|
177
|
+
const app = express();
|
|
178
|
+
|
|
179
|
+
app.post("/webhooks/billionsend", express.raw({ type: "application/json" }), async (req, res) => {
|
|
180
|
+
try {
|
|
181
|
+
const event = await verifyWebhook(req.body, req.headers, process.env.BILLIONSEND_WEBHOOK_SECRET!);
|
|
182
|
+
if (event.type === "email.bounced") {
|
|
183
|
+
// ...
|
|
184
|
+
}
|
|
185
|
+
res.sendStatus(204);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
if (error instanceof WebhookVerificationError) return res.sendStatus(400);
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
With the Fetch API (Next.js route handlers, Hono, Bun, Deno, workers) it is `await verifyWebhook(await request.text(), request.headers, secret)`. During a secret rotation a delivery carries a signature for each live secret, and either secret verifies it.
|
|
194
|
+
|
|
195
|
+
## Agent sign-up
|
|
196
|
+
|
|
197
|
+
An agent can create its own account with no API key; the answer carries the new key and inbox.
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
const signup = await new BillionSend().agent.signup({
|
|
201
|
+
human_email: "owner@acme.dev",
|
|
202
|
+
name: "Support agent",
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
if (signup.data) {
|
|
206
|
+
const agent = new BillionSend(signup.data.api_key);
|
|
207
|
+
console.log(signup.data.inbox.email_address);
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## Configuration
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
const bs = new BillionSend({
|
|
215
|
+
apiKey: "bs_...", // default: BILLIONSEND_API_KEY
|
|
216
|
+
baseUrl: "https://api.billionsend.com", // default: BILLIONSEND_BASE_URL, then this
|
|
217
|
+
timeoutMs: 60_000, // per attempt; event streams are timed only until they open
|
|
218
|
+
maxRetries: 2, // see Retries
|
|
219
|
+
fetch: customFetch, // default: the global fetch
|
|
220
|
+
headers: { "x-my-header": "value" }, // sent with every request
|
|
221
|
+
});
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Every method takes a last `options` argument with `signal`, `headers`, `timeoutMs` and `maxRetries` for that call (and `idempotencyKey` on the sending operations).
|
|
225
|
+
|
|
226
|
+
**Batches.** `emails.batch` and `contacts.batch.create` take `batchValidation: "strict" | "permissive"` (the `x-batch-validation` header).
|
|
227
|
+
|
|
228
|
+
## Resources
|
|
229
|
+
|
|
230
|
+
| Property | Covers |
|
|
231
|
+
| --- | --- |
|
|
232
|
+
| `emails` | send, batch, list, get, update, cancel, delete, insights, metrics |
|
|
233
|
+
| `emails.receiving` | received mail: list, get, delete, reply, forward, `attachments` (list, get, text) |
|
|
234
|
+
| `domains` | create, list, get, update, delete, verify |
|
|
235
|
+
| `apiKeys` | create, list, delete |
|
|
236
|
+
| `contacts` | create, list, get, update, delete, preferences link, `batch`, `topics`, `segments` |
|
|
237
|
+
| `audiences.contacts` | contacts addressed through an audience |
|
|
238
|
+
| `contactProperties`, `segments`, `topics` | create, list, get, update, delete (segment contacts under `segments.contacts`) |
|
|
239
|
+
| `broadcasts` | create, list, get, update, delete, send, duplicate, cancel |
|
|
240
|
+
| `templates` | create, list, get, update, delete, publish, duplicate |
|
|
241
|
+
| `webhooks` | create, list, get, update, delete, rotate |
|
|
242
|
+
| `suppressions` | create, list, get, delete, `batch` add / remove |
|
|
243
|
+
| `unsubscribes` | create, list, delete |
|
|
244
|
+
| `verifications` | availability, estimate, create, list, get |
|
|
245
|
+
| `usage`, `deliverability` | get |
|
|
246
|
+
| `inboxes` | create, list, get, update, delete, send, `agent`, `safety`, `labels`, `threads` (search, labels, emails, reply, forward), `quarantine`, `codes`, `drafts`, `events` |
|
|
247
|
+
| `agent` | signup, status, claimEmail |
|
|
248
|
+
|
|
249
|
+
Method names are camelCase; request and response fields keep the API's snake_case names. All request and response types are exported, named after the API's schemas (`SendEmailRequest`, `Inbox`, …).
|
|
250
|
+
|
|
251
|
+
## Development
|
|
252
|
+
|
|
253
|
+
```bash
|
|
254
|
+
pnpm install
|
|
255
|
+
pnpm typecheck && pnpm lint && pnpm test
|
|
256
|
+
pnpm build && pnpm test:smoke
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
The contract is `openapi/api.openapi.json`, a snapshot of the published OpenAPI document; its descriptions become the doc comments of the generated types. The tests run every SDK method against a local mock that validates each request and answers from that snapshot, and fail when an operation has no SDK method. When the API changes:
|
|
260
|
+
|
|
261
|
+
```bash
|
|
262
|
+
pnpm openapi:sync # or: pnpm openapi:sync --from path/to/api.openapi.json
|
|
263
|
+
pnpm generate # regenerates src/generated/openapi.ts
|
|
264
|
+
pnpm test # what fails is what the SDK has to follow
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Releasing
|
|
268
|
+
|
|
269
|
+
Publishing is manual; nothing is published on push.
|
|
270
|
+
|
|
271
|
+
1. Set `version` in `package.json`, turn the changelog's `Unreleased` heading into that version, commit, then tag and push: `git tag v0.1.0 && git push origin main v0.1.0`.
|
|
272
|
+
2. The first version only: a member of the `@billionsend` npm organization publishes from a clean checkout of the tag, with two-factor authentication: `pnpm install --frozen-lockfile && pnpm typecheck && pnpm lint && pnpm test && pnpm test:smoke && npm publish` (`prepublishOnly` builds; `publishConfig.access` is `public`).
|
|
273
|
+
3. Once the package exists: on npmjs.com, `@billionsend/node` → Settings → Trusted Publisher → GitHub Actions, repository `billionsend/billionsend-node`, workflow `release.yml`.
|
|
274
|
+
4. Every later version: Actions → `release` → Run workflow, on the version tag. The workflow refuses a branch or a tag that differs from `package.json`, runs every check, and publishes with npm Trusted Publishing (no token stored).
|
|
275
|
+
|
|
276
|
+
## License
|
|
277
|
+
|
|
278
|
+
[MIT](LICENSE)
|