@flowmails/flowmails-sdk 0.1.0 → 0.2.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The official JavaScript / TypeScript SDK for the **Flowmails SDK backend** (`https://sdk.flowmails.net`).
4
4
 
5
- > **Status: private (v0.1)** — this package is published from the Flowmails monorepo but the workspace is currently private. Wire format and surface can change in v0.x.
5
+ > **Status: public preview (v0.2.x)** — published from the Flowmails monorepo. Wire format and surface can still change in v0.x; pin the minor version (`~0.2`) in production.
6
6
 
7
7
  ## Install
8
8
 
@@ -31,6 +31,10 @@ const result = await fm.send({
31
31
  console.log(result); // { id: "msg_8421", status: "queued" }
32
32
  ```
33
33
 
34
+ ## About Flowmails
35
+
36
+ [Flowmails](https://flowmails.net) is a Cloudflare-native email platform: custom-domain mail (inbox, outbox, and routing rules) that lives in your own D1, with a REST API and webhooks on top. The dashboard, docs, and blog live at **<https://flowmails.net>** — sign up there to mint an API key and bind a domain before using this SDK.
37
+
34
38
  ## API keys
35
39
 
36
40
  API keys are minted in the Flowmails dashboard at `Settings → API Keys`. Each key is pinned to one of your registered domains — the SDK backend rejects `send(...)` calls where the `from` address doesn't land on the key-bound domain.
@@ -42,7 +46,7 @@ The SDK throws typed errors:
42
46
  | Class | HTTP status | Retryable |
43
47
  |----------------------|-------------|-----------|
44
48
  | `AuthenticationError`| 401 | no |
45
- | `ValidationError` | 400 / 422 | no |
49
+ | `ValidationError` | 400 / 404 / 409 / 422 | no |
46
50
  | `RateLimitError` | 429 | yes (client backs off) |
47
51
  | `UpstreamError` | 5xx / 408 | yes |
48
52
  | `FlowmailsError` | other | no |
@@ -65,12 +69,75 @@ try {
65
69
  }
66
70
  ```
67
71
 
68
- ## Limitations (v0.1)
72
+ ## Idempotent sends
73
+
74
+ Give a send an `idempotencyKey` and a retry becomes free: the same key
75
+ under the same account and the same request returns the **original**
76
+ result and does not send a second message.
77
+
78
+ ```ts
79
+ await fm.send({ from, to, subject, text, idempotencyKey: "order-42" });
80
+ ```
81
+
82
+ The key is scoped to the account, not globally. Reusing one key for a
83
+ *different* payload is a client bug and is refused with
84
+ `idempotency_key_conflict` (a `ValidationError`) rather than answered
85
+ with the first result.
86
+
87
+ ## Send quota
88
+
89
+ Sends are capped per account and per domain, per hour and per day. A
90
+ refusal is a `RateLimitError` carrying the facts you need to back off:
91
+
92
+ ```ts
93
+ catch (err) {
94
+ if (err instanceof RateLimitError && err.code === "rate_limit_exceeded") {
95
+ console.log(err.remaining, err.limit, err.resetAt); // ISO-8601
96
+ }
97
+ }
98
+ ```
99
+
100
+ The same numbers travel in the `X-Flowmails-RateLimit-Remaining` and
101
+ `X-Flowmails-RateLimit-Reset` response headers. The SDK does **not**
102
+ retry a quota refusal for you — the window is an hour, so a retry
103
+ inside it cannot succeed.
104
+
105
+ ## The read half
106
+
107
+ Sending is one half of the SDK; the other is **reading** — and it
108
+ talks to a different origin (the platform worker, not the SDK
109
+ backend), so a self-hosted install sets `platformURL` too.
110
+
111
+ ```ts
112
+ // Check the credential without sending anything.
113
+ const me = await fm.me(); // { accountId, domain, scopes[] }
114
+
115
+ // Tail the inbound log with a cursor (an event id, never a timestamp).
116
+ const page = await fm.events.list({ after: lastEventId });
117
+
118
+ // Search the mailbox history — addressing, subject and a preview.
119
+ const hits = await fm.messages.search(domainId, { q: "invoice" });
120
+
121
+ // Read the conversation a message belongs to.
122
+ const thread = await fm.threads.get(threadId);
123
+
124
+ // Wait for a message without holding a request open.
125
+ const wait = await fm.waits.create({ address: "billing@yourdomain.com" });
126
+ const status = await fm.waits.get(wait.waitId); // pending → resolved | expired
127
+
128
+ // Create a mailbox — one local part, idempotent.
129
+ await fm.addresses.create(domainId, "billing");
130
+ ```
131
+
132
+ The body is **fetched**, never pushed: an event carries the routing
133
+ facts and the subject line, and `fm.messages.get(messageId)` is the
134
+ ask. The SDK never hands you a message you did not ask for.
135
+
136
+ ## Limitations (v0.2)
69
137
 
70
- - `send` is the only endpoint. Reads (`lists`, `threads`) and webhook delivery come in v0.2.
71
- - No per-key rate-limit response (`X-Flowmails-RateLimit-Remaining`) headers yet — any 429 you see is the platform's safety floor.
72
138
  - Custom domain (HTTP/HTTPS) attachment hosting is not configurable by SDK callers; the SDK backend always sends via R2.
139
+ - The webhook delivery-status events (`message.delivered` / `message.bounced`) do not exist yet — and neither does bounce detection. The receive worker has no DSN ingestion, so a send's status is `sent` (the relay accepted it) or `failed` (the relay rejected it) and nothing more. The vocabulary holds `delivered` / `bounced` / `complained` / `delayed`, but nothing writes them.
73
140
 
74
141
  ## License
75
142
 
76
- UNLICENSED (private monorepo).
143
+ MIT © 2026 Flowmails. See [`LICENSE`](./LICENSE).
package/dist/index.cjs CHANGED
@@ -31,9 +31,18 @@ var ValidationError = class extends FlowmailsError {
31
31
  }
32
32
  };
33
33
  var RateLimitError = class extends FlowmailsError {
34
- constructor(code = "rate_limited", status = 429) {
34
+ /** The limit that was hit, when the server named one. */
35
+ limit;
36
+ /** The sends left in the window, when the server named one. */
37
+ remaining;
38
+ /** ISO-8601 instant the window rolls over, when the server named one. */
39
+ resetAt;
40
+ constructor(code = "rate_limited", status = 429, facts) {
35
41
  super(code, `Rate limited: ${code}`, status);
36
42
  this.name = "RateLimitError";
43
+ this.limit = facts?.limit;
44
+ this.remaining = facts?.remaining;
45
+ this.resetAt = facts?.resetAt;
37
46
  }
38
47
  };
39
48
  var UpstreamError = class extends FlowmailsError {
@@ -49,6 +58,7 @@ var UpstreamError = class extends FlowmailsError {
49
58
  var Flowmails = class {
50
59
  apiKey;
51
60
  baseURL;
61
+ platformURL;
52
62
  fetchFn;
53
63
  maxRetries;
54
64
  requestId;
@@ -61,14 +71,23 @@ var Flowmails = class {
61
71
  /\/+$/,
62
72
  ""
63
73
  );
64
- this.fetchFn = opts.fetch ?? globalThis.fetch;
74
+ this.platformURL = (opts.platformURL ?? "https://flowmails.net").replace(
75
+ /\/+$/,
76
+ ""
77
+ );
78
+ this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
65
79
  this.maxRetries = opts.maxRetries ?? 2;
66
80
  this.requestId = opts.requestId;
67
81
  }
68
82
  /**
69
- * Send mail through the SDK backend. The only v0.1 endpoint.
83
+ * Send mail through the SDK backend.
70
84
  *
71
- * Returns `{ id, status: "queued" }` on success; throws one of
85
+ * Pass `replyToMessageId` to answer a message in thread — the SDK
86
+ * backend resolves the parent and derives the `In-Reply-To` /
87
+ * `References` headers and the thread anchor, so the recipient's
88
+ * client threads it with the original conversation.
89
+ *
90
+ * Returns `{ id, status, messageId }` on success; throws one of
72
91
  * `AuthenticationError` / `ValidationError` / `RateLimitError` /
73
92
  * `UpstreamError` on failure (all subclasses of `FlowmailsError`).
74
93
  */
@@ -78,6 +97,10 @@ var Flowmails = class {
78
97
  fromName: opts.fromName,
79
98
  to: Array.isArray(opts.to) ? opts.to : [opts.to],
80
99
  replyTo: opts.replyTo,
100
+ // The SDK backend resolves this to the three `threading`
101
+ // fields. The caller names the **parent**, never the headers —
102
+ // hand-deriving `References` is how threads fork.
103
+ replyToMessageId: opts.replyToMessageId,
81
104
  subject: opts.subject,
82
105
  text: opts.text,
83
106
  html: opts.html,
@@ -85,34 +108,247 @@ var Flowmails = class {
85
108
  filename: a.filename,
86
109
  content: a.content instanceof Uint8Array ? bytesToBase64(a.content) : a.content,
87
110
  mimeType: a.mimeType
88
- }))
111
+ })),
112
+ // The idempotency key travels under the same name on the wire.
113
+ // It is deliberately **not** renamed: the backend's body is
114
+ // camelCase already, and a rename here would be one more place
115
+ // for the two sides to disagree.
116
+ idempotencyKey: opts.idempotencyKey
89
117
  };
90
- return this.request("/api/v1/messages", body);
118
+ return this.request(this.baseURL, "POST", "/api/v1/messages", {
119
+ body
120
+ });
121
+ }
122
+ /**
123
+ * The connection check — who the credential is.
124
+ *
125
+ * `flowmails test` (the CLI's documented first command) and every
126
+ * "is my setup right?" question end here. It verifies the key,
127
+ * names the account, names the bound domain and reports the
128
+ * scopes — and it sends nothing, so running it can never mail
129
+ * somebody by accident.
130
+ *
131
+ * @throws {AuthenticationError} when the key is missing, malformed
132
+ * or revoked.
133
+ */
134
+ async me() {
135
+ return this.request(this.baseURL, "GET", "/api/v1/me");
91
136
  }
92
137
  /**
93
- * Private: low-level request helper with retry+backoff+error
94
- * mapping. SDK callers must use the typed `send()` method
95
- * instead — this exists so future public methods can share the
96
- * same retry budget / error class mapping without re-implementing.
138
+ * The event log — the listen half of the surface, read with a
139
+ * cursor.
140
+ *
141
+ * ```ts
142
+ * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });
143
+ * let after: string | undefined;
144
+ * for (;;) {
145
+ * const page = await fm.events.list({ after, subject: "invoice" });
146
+ * for (const event of page.events) { … }
147
+ * after = page.nextCursor ?? after;
148
+ * }
149
+ * ```
150
+ */
151
+ events = {
152
+ list: async (opts = {}) => {
153
+ const query = {
154
+ after: opts.after,
155
+ limit: opts.limit,
156
+ recipient: opts.recipient,
157
+ sender: opts.sender,
158
+ subject: opts.subject
159
+ };
160
+ return this.request(
161
+ this.platformURL,
162
+ "GET",
163
+ "/api/agent/events",
164
+ { query }
165
+ );
166
+ }
167
+ };
168
+ /**
169
+ * Read one message by its SMTP `Message-ID` — the id the event
170
+ * carried.
171
+ *
172
+ * The event log deliberately hands over routing facts and a
173
+ * subject and never a body (§4.2), so the content is an explicit
174
+ * ask. This is that ask.
175
+ */
176
+ messages = {
177
+ get: async (messageId, opts = {}) => {
178
+ if (!messageId) {
179
+ throw new ValidationError("message_id_required", "messageId is required");
180
+ }
181
+ return this.request(
182
+ this.platformURL,
183
+ "GET",
184
+ `/api/agent/messages/${encodeURIComponent(messageId)}`,
185
+ { query: { domainId: opts.domainId } }
186
+ );
187
+ },
188
+ /**
189
+ * Poll a **sent** message's delivery state.
190
+ *
191
+ * `id` is the value {@link send} returned as `id` (or the SMTP
192
+ * `Message-ID`). Returns the worker's lifecycle state so an agent
193
+ * can tell `sent` from `failed` (the two the worker writes)
194
+ * instead of assuming success.
195
+ */
196
+ status: async (id) => {
197
+ if (!id) {
198
+ throw new ValidationError("message_id_required", "id is required");
199
+ }
200
+ return this.request(
201
+ this.baseURL,
202
+ "GET",
203
+ `/api/v1/messages/${encodeURIComponent(id)}`
204
+ );
205
+ },
206
+ /**
207
+ * Look back through the mailbox.
208
+ *
209
+ * The event log is the primary listen path; this is the history
210
+ * path. A hit carries addressing, the subject and a preview — the
211
+ * body is a separate, explicit ask.
212
+ */
213
+ search: async (domainId, opts) => {
214
+ if (!domainId) {
215
+ throw new ValidationError("domain_id_required", "domainId is required");
216
+ }
217
+ if (!opts?.q || opts.q.trim().length < 2) {
218
+ throw new ValidationError(
219
+ "query_too_short",
220
+ "q must be at least 2 characters"
221
+ );
222
+ }
223
+ return this.request(
224
+ this.platformURL,
225
+ "GET",
226
+ "/api/agent/emails/search",
227
+ {
228
+ query: {
229
+ q: opts.q,
230
+ domainId,
231
+ limit: opts.limit,
232
+ field: opts.field,
233
+ type: opts.type
234
+ }
235
+ }
236
+ );
237
+ }
238
+ };
239
+ /**
240
+ * The conversation a message belongs to.
241
+ *
242
+ * The core listen/reply loop can store the message ids itself;
243
+ * this is for the agent that wants the platform to reconstruct the
244
+ * chain. The chain is read from the **conversation root's** SMTP
245
+ * `Message-ID`, which is exactly what `email.threadId` holds.
97
246
  */
98
- async request(path, body) {
99
- const url = `${this.baseURL}${path}`;
247
+ threads = {
248
+ get: async (threadId, opts = {}) => {
249
+ if (!threadId) {
250
+ throw new ValidationError("thread_id_required", "threadId is required");
251
+ }
252
+ return this.request(
253
+ this.platformURL,
254
+ "GET",
255
+ `/api/agent/threads/${encodeURIComponent(threadId)}`,
256
+ { query: { domainId: opts.domainId } }
257
+ );
258
+ }
259
+ };
260
+ /**
261
+ * The durable wait — the one thing an agent cannot build for
262
+ * itself.
263
+ *
264
+ * A suspended HTTP request dies on the edge long before a
265
+ * verification mail arrives (minutes to hours later), so the wait
266
+ * is a row on the platform and the agent polls it. `create()`
267
+ * answers **immediately**; it does not block.
268
+ */
269
+ waits = {
270
+ create: async (opts) => {
271
+ return this.request(
272
+ this.platformURL,
273
+ "POST",
274
+ "/api/agent/waits",
275
+ { body: opts }
276
+ );
277
+ },
278
+ get: async (waitId) => {
279
+ if (!waitId) {
280
+ throw new ValidationError("wait_id_required", "waitId is required");
281
+ }
282
+ return this.request(
283
+ this.platformURL,
284
+ "GET",
285
+ `/api/agent/waits/${encodeURIComponent(waitId)}`
286
+ );
287
+ }
288
+ };
289
+ /**
290
+ * The addresses (mailboxes) the key's account owns, and the one
291
+ * narrow write the agent surface has: create a single one.
292
+ */
293
+ addresses = {
294
+ listDomains: async () => {
295
+ const result = await this.request(
296
+ this.platformURL,
297
+ "GET",
298
+ "/api/agent/domains"
299
+ );
300
+ return result.domains;
301
+ },
302
+ list: async (domainId) => {
303
+ if (!domainId) {
304
+ throw new ValidationError("domain_id_required", "domainId is required");
305
+ }
306
+ const result = await this.request(
307
+ this.platformURL,
308
+ "GET",
309
+ `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`
310
+ );
311
+ return result;
312
+ },
313
+ create: async (domainId, localPart) => {
314
+ if (!domainId) {
315
+ throw new ValidationError("domain_id_required", "domainId is required");
316
+ }
317
+ return this.request(
318
+ this.platformURL,
319
+ "POST",
320
+ `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,
321
+ { body: { localPart } }
322
+ );
323
+ }
324
+ };
325
+ /**
326
+ * Private: the one request path, with retry + backoff + error
327
+ * mapping shared by every public method.
328
+ *
329
+ * `origin` is explicit because the surface spans two deployments:
330
+ * the SDK backend (`baseURL`) for sending, the platform
331
+ * (`platformURL`) for reading and waiting. `method` is explicit
332
+ * because the listen endpoints are GETs — the v0.1 helper was
333
+ * POST-only, which is why reading used to mean hand-rolling HTTP.
334
+ */
335
+ async request(origin, method, path, opts = {}) {
336
+ const url = buildUrl(origin, path, opts.query);
100
337
  const headers = {
101
- Authorization: `Bearer ${this.apiKey}`,
102
- "Content-Type": "application/json"
338
+ Authorization: `Bearer ${this.apiKey}`
103
339
  };
340
+ if (method === "POST") headers["Content-Type"] = "application/json";
104
341
  if (this.requestId) headers["X-Flowmails-Request-Id"] = this.requestId;
105
342
  let lastError = null;
106
343
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
107
344
  let res;
108
345
  try {
109
346
  res = await this.fetchFn(url, {
110
- method: "POST",
347
+ method,
111
348
  headers,
112
- body: JSON.stringify(body),
113
- // 15s matches the SDK backend's upstream timeout — we want
114
- // our error to be "request timed out" rather than the
115
- // backend's generic 502.
349
+ ...method === "POST" ? { body: JSON.stringify(opts.body) } : {},
350
+ // 15s matches the platform's upstream timeout — we want our
351
+ // error to be "request timed out" rather than a generic 502.
116
352
  signal: AbortSignal.timeout(15e3)
117
353
  });
118
354
  } catch (err) {
@@ -135,10 +371,19 @@ var Flowmails = class {
135
371
  }
136
372
  const code = payload.error ?? "request_failed";
137
373
  if (res.status === 401) throw new AuthenticationError(code, res.status);
138
- if (res.status === 400 || res.status === 422) {
374
+ if (res.status === 400 || res.status === 404 || res.status === 422 || res.status === 409) {
139
375
  throw new ValidationError(code, payload.detail, res.status);
140
376
  }
141
- if (res.status === 429) throw new RateLimitError(code, res.status);
377
+ if (res.status === 429) {
378
+ const facts = readQuotaFacts(res, payload);
379
+ if (code === "idempotency_key_in_progress") {
380
+ lastError = new RateLimitError(code, res.status, facts);
381
+ if (attempt >= this.maxRetries) throw lastError;
382
+ await sleep(backoffMs(attempt));
383
+ continue;
384
+ }
385
+ throw new RateLimitError(code, res.status, facts);
386
+ }
142
387
  if (res.status >= 500 || res.status === 408) {
143
388
  lastError = new UpstreamError(code, payload.detail, res.status);
144
389
  if (attempt >= this.maxRetries) throw lastError;
@@ -150,6 +395,39 @@ var Flowmails = class {
150
395
  throw lastError ?? new FlowmailsError("unknown", "Unknown failure", 0);
151
396
  }
152
397
  };
398
+ function readQuotaFacts(res, payload) {
399
+ const limit = typeof payload.limit === "number" ? payload.limit : void 0;
400
+ let remaining = typeof payload.remaining === "number" ? payload.remaining : void 0;
401
+ let resetAt = typeof payload.resetAt === "string" ? payload.resetAt : void 0;
402
+ const headerRemaining = res.headers?.get?.(
403
+ "X-Flowmails-RateLimit-Remaining"
404
+ );
405
+ if (remaining === void 0 && headerRemaining) {
406
+ const parsed = Number(headerRemaining);
407
+ if (Number.isFinite(parsed)) remaining = parsed;
408
+ }
409
+ const headerReset = res.headers?.get?.("X-Flowmails-RateLimit-Reset");
410
+ if (resetAt === void 0 && headerReset) {
411
+ const parsed = Number(headerReset);
412
+ if (Number.isFinite(parsed)) {
413
+ resetAt = new Date(parsed * 1e3).toISOString();
414
+ }
415
+ }
416
+ if (limit === void 0 && remaining === void 0 && resetAt === void 0) {
417
+ return void 0;
418
+ }
419
+ return { limit, remaining, resetAt };
420
+ }
421
+ function buildUrl(origin, path, query) {
422
+ const url = new URL(`${origin}${path}`);
423
+ if (query) {
424
+ for (const [key, value] of Object.entries(query)) {
425
+ if (value === void 0 || value === null || value === "") continue;
426
+ url.searchParams.set(key, String(value));
427
+ }
428
+ }
429
+ return url.toString();
430
+ }
153
431
  function bytesToBase64(bytes) {
154
432
  let bin = "";
155
433
  for (let i = 0; i < bytes.length; i++) {