@flowmails/flowmails-sdk 0.1.1 → 0.2.1

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: public preview (v0.1.x)** — published from the Flowmails monorepo. Wire format and surface can still change in v0.x; pin the minor version (`~0.1`) in production.
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,38 @@ const result = await fm.send({
31
31
  console.log(result); // { id: "msg_8421", status: "queued" }
32
32
  ```
33
33
 
34
+ ## A send the relay refused
35
+
36
+ `send()` answers `201` for a message the relay **refused** — the row
37
+ exists, the mail does not. The result carries the reason, so a failure
38
+ is never silent:
39
+
40
+ ```ts
41
+ const result = await fm.send({ … });
42
+ if (result.status === "failed") {
43
+ console.error(result.error); // "send_failed" — always present
44
+ console.error(result.sendFeedback); // the relay's own reason, when it gave one
45
+ }
46
+ ```
47
+
48
+ `result.error` is never `null` on a failed send: *"failed with no
49
+ reason"* is not a state the wire can be in.
50
+
51
+ ## Is my domain able to send?
52
+
53
+ ```ts
54
+ const me = await fm.me();
55
+ if (me.sending && !me.sending.canSend) {
56
+ console.warn(me.sending.state); // "not_onboarded" | "unconfigured" | "unknown" | …
57
+ }
58
+ ```
59
+
60
+ `me.sending` is the platform's own verdict, read from the same document
61
+ the dashboard reads — `null` when it cannot be known (no bound domain,
62
+ or the platform could not be read). Read it together with `state`:
63
+ `canSend: false` with `state: "unknown"` means *"we have not looked"*,
64
+ not *"this domain cannot send"*.
65
+
34
66
  ## About Flowmails
35
67
 
36
68
  [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.
@@ -46,7 +78,7 @@ The SDK throws typed errors:
46
78
  | Class | HTTP status | Retryable |
47
79
  |----------------------|-------------|-----------|
48
80
  | `AuthenticationError`| 401 | no |
49
- | `ValidationError` | 400 / 422 | no |
81
+ | `ValidationError` | 400 / 404 / 409 / 422 | no |
50
82
  | `RateLimitError` | 429 | yes (client backs off) |
51
83
  | `UpstreamError` | 5xx / 408 | yes |
52
84
  | `FlowmailsError` | other | no |
@@ -69,11 +101,74 @@ try {
69
101
  }
70
102
  ```
71
103
 
72
- ## Limitations (v0.1)
104
+ ## Idempotent sends
105
+
106
+ Give a send an `idempotencyKey` and a retry becomes free: the same key
107
+ under the same account and the same request returns the **original**
108
+ result and does not send a second message.
109
+
110
+ ```ts
111
+ await fm.send({ from, to, subject, text, idempotencyKey: "order-42" });
112
+ ```
113
+
114
+ The key is scoped to the account, not globally. Reusing one key for a
115
+ *different* payload is a client bug and is refused with
116
+ `idempotency_key_conflict` (a `ValidationError`) rather than answered
117
+ with the first result.
118
+
119
+ ## Send quota
120
+
121
+ Sends are capped per account and per domain, per hour and per day. A
122
+ refusal is a `RateLimitError` carrying the facts you need to back off:
123
+
124
+ ```ts
125
+ catch (err) {
126
+ if (err instanceof RateLimitError && err.code === "rate_limit_exceeded") {
127
+ console.log(err.remaining, err.limit, err.resetAt); // ISO-8601
128
+ }
129
+ }
130
+ ```
131
+
132
+ The same numbers travel in the `X-Flowmails-RateLimit-Remaining` and
133
+ `X-Flowmails-RateLimit-Reset` response headers. The SDK does **not**
134
+ retry a quota refusal for you — the window is an hour, so a retry
135
+ inside it cannot succeed.
136
+
137
+ ## The read half
138
+
139
+ Sending is one half of the SDK; the other is **reading** — and it
140
+ talks to a different origin (the platform worker, not the SDK
141
+ backend), so a self-hosted install sets `platformURL` too.
142
+
143
+ ```ts
144
+ // Check the credential without sending anything.
145
+ const me = await fm.me(); // { userId, domain, scopes[], sending }
146
+
147
+ // Tail the inbound log with a cursor (an event id, never a timestamp).
148
+ const page = await fm.events.list({ after: lastEventId });
149
+
150
+ // Search the mailbox history — addressing, subject and a preview.
151
+ const hits = await fm.messages.search(domainId, { q: "invoice" });
152
+
153
+ // Read the conversation a message belongs to.
154
+ const thread = await fm.threads.get(threadId);
155
+
156
+ // Wait for a message without holding a request open.
157
+ const wait = await fm.waits.create({ address: "billing@yourdomain.com" });
158
+ const status = await fm.waits.get(wait.waitId); // pending → resolved | expired
159
+
160
+ // Create a mailbox — one local part, idempotent.
161
+ await fm.addresses.create(domainId, "billing");
162
+ ```
163
+
164
+ The body is **fetched**, never pushed: an event carries the routing
165
+ facts and the subject line, and `fm.messages.get(messageId)` is the
166
+ ask. The SDK never hands you a message you did not ask for.
167
+
168
+ ## Limitations (v0.2)
73
169
 
74
- - `send` is the only endpoint. Reads (`lists`, `threads`) and webhook delivery come in v0.2.
75
- - No per-key rate-limit response (`X-Flowmails-RateLimit-Remaining`) headers yet — any 429 you see is the platform's safety floor.
76
170
  - Custom domain (HTTP/HTTPS) attachment hosting is not configurable by SDK callers; the SDK backend always sends via R2.
171
+ - 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.
77
172
 
78
173
  ## License
79
174
 
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,16 +71,31 @@ 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.
84
+ *
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.
70
89
  *
71
- * Returns `{ id, status: "queued" }` on success; throws one of
90
+ * Returns `{ id, status, messageId }` on success; throws one of
72
91
  * `AuthenticationError` / `ValidationError` / `RateLimitError` /
73
92
  * `UpstreamError` on failure (all subclasses of `FlowmailsError`).
93
+ *
94
+ * **A send the relay refused is not a throw.** The backend answers
95
+ * `201` with `status: "failed"`, and the result carries the
96
+ * reason: `error` is the typed slug and `sendFeedback` is the
97
+ * relay's own words. Check `result.error` before treating a `201`
98
+ * as "sent".
74
99
  */
75
100
  async send(opts) {
76
101
  const body = {
@@ -78,6 +103,10 @@ var Flowmails = class {
78
103
  fromName: opts.fromName,
79
104
  to: Array.isArray(opts.to) ? opts.to : [opts.to],
80
105
  replyTo: opts.replyTo,
106
+ // The SDK backend resolves this to the three `threading`
107
+ // fields. The caller names the **parent**, never the headers —
108
+ // hand-deriving `References` is how threads fork.
109
+ replyToMessageId: opts.replyToMessageId,
81
110
  subject: opts.subject,
82
111
  text: opts.text,
83
112
  html: opts.html,
@@ -85,34 +114,281 @@ var Flowmails = class {
85
114
  filename: a.filename,
86
115
  content: a.content instanceof Uint8Array ? bytesToBase64(a.content) : a.content,
87
116
  mimeType: a.mimeType
88
- }))
117
+ })),
118
+ // The idempotency key travels under the same name on the wire.
119
+ // It is deliberately **not** renamed: the backend's body is
120
+ // camelCase already, and a rename here would be one more place
121
+ // for the two sides to disagree.
122
+ idempotencyKey: opts.idempotencyKey
89
123
  };
90
- return this.request("/api/v1/messages", body);
124
+ return this.request(this.baseURL, "POST", "/api/v1/messages", {
125
+ body
126
+ });
127
+ }
128
+ /**
129
+ * The connection check — who the credential is.
130
+ *
131
+ * `flowmails test` (the CLI's documented first command) and every
132
+ * "is my setup right?" question end here. It verifies the key,
133
+ * names the account, names the bound domain and reports the
134
+ * scopes — and it sends nothing, so running it can never mail
135
+ * somebody by accident.
136
+ *
137
+ * It also answers the question the 2026-10-31 audit (P0-1) found
138
+ * missing: **may this domain actually send?** — `info.sending`
139
+ * carries the platform's own verdict, read from the same document
140
+ * the dashboard reads.
141
+ *
142
+ * ```ts
143
+ * const me = await fm.me();
144
+ * if (me.sending && !me.sending.canSend) {
145
+ * // me.sending.state says why: "not_onboarded", "unknown", …
146
+ * }
147
+ * ```
148
+ *
149
+ * @throws {AuthenticationError} when the key is missing, malformed
150
+ * or revoked.
151
+ */
152
+ async me() {
153
+ return this.request(this.baseURL, "GET", "/api/v1/me");
154
+ }
155
+ /**
156
+ * The account's receive worker, and the version of it.
157
+ *
158
+ * The receive worker does the actual receiving and sending, and it
159
+ * is versioned: `1.4.0` brought the route tables, `1.5.1` the
160
+ * Message-ID lookup, `1.6.0` the event reporting that fills the
161
+ * log this SDK reads. An agent whose worker is older than the
162
+ * platform expects sees an empty event log and has no way to tell
163
+ * "no mail yet" from "my worker cannot report".
164
+ *
165
+ * ```ts
166
+ * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });
167
+ * const worker = await fm.workerVersion();
168
+ * if (!worker.version || worker.version < "1.6.0") { … }
169
+ * ```
170
+ *
171
+ * @throws {AuthenticationError} when the key is missing, malformed
172
+ * or revoked.
173
+ */
174
+ async workerVersion() {
175
+ return this.request(this.baseURL, "GET", "/api/v1/worker-version");
91
176
  }
92
177
  /**
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.
178
+ * The event log — the listen half of the surface, read with a
179
+ * cursor.
180
+ *
181
+ * ```ts
182
+ * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });
183
+ * let after: string | undefined;
184
+ * for (;;) {
185
+ * const page = await fm.events.list({ after, subject: "invoice" });
186
+ * for (const event of page.events) { … }
187
+ * after = page.nextCursor ?? after;
188
+ * }
189
+ * ```
190
+ */
191
+ events = {
192
+ list: async (opts = {}) => {
193
+ const query = {
194
+ after: opts.after,
195
+ limit: opts.limit,
196
+ recipient: opts.recipient,
197
+ sender: opts.sender,
198
+ subject: opts.subject
199
+ };
200
+ return this.request(
201
+ this.platformURL,
202
+ "GET",
203
+ "/api/agent/events",
204
+ { query }
205
+ );
206
+ }
207
+ };
208
+ /**
209
+ * Read one message by its SMTP `Message-ID` — the id the event
210
+ * carried.
211
+ *
212
+ * The event log deliberately hands over routing facts and a
213
+ * subject and never a body (§4.2), so the content is an explicit
214
+ * ask. This is that ask.
215
+ */
216
+ messages = {
217
+ get: async (messageId, opts = {}) => {
218
+ if (!messageId) {
219
+ throw new ValidationError("message_id_required", "messageId is required");
220
+ }
221
+ return this.request(
222
+ this.platformURL,
223
+ "GET",
224
+ `/api/agent/messages/${encodeURIComponent(messageId)}`,
225
+ { query: { domainId: opts.domainId } }
226
+ );
227
+ },
228
+ /**
229
+ * Poll a **sent** message's delivery state.
230
+ *
231
+ * `id` is the value {@link send} returned as `id` (or the SMTP
232
+ * `Message-ID`). Returns the worker's lifecycle state so an agent
233
+ * can tell `sent` from `failed` (the two the worker writes)
234
+ * instead of assuming success.
235
+ */
236
+ status: async (id) => {
237
+ if (!id) {
238
+ throw new ValidationError("message_id_required", "id is required");
239
+ }
240
+ return this.request(
241
+ this.baseURL,
242
+ "GET",
243
+ `/api/v1/messages/${encodeURIComponent(id)}`
244
+ );
245
+ },
246
+ /**
247
+ * Look back through the mailbox.
248
+ *
249
+ * The event log is the primary listen path; this is the history
250
+ * path. A hit carries addressing, the subject and a preview — the
251
+ * body is a separate, explicit ask.
252
+ */
253
+ search: async (domainId, opts) => {
254
+ if (!domainId) {
255
+ throw new ValidationError("domain_id_required", "domainId is required");
256
+ }
257
+ if (!opts?.q || opts.q.trim().length < 2) {
258
+ throw new ValidationError(
259
+ "query_too_short",
260
+ "q must be at least 2 characters"
261
+ );
262
+ }
263
+ return this.request(
264
+ this.platformURL,
265
+ "GET",
266
+ "/api/agent/emails/search",
267
+ {
268
+ query: {
269
+ q: opts.q,
270
+ domainId,
271
+ limit: opts.limit,
272
+ field: opts.field,
273
+ type: opts.type
274
+ }
275
+ }
276
+ );
277
+ }
278
+ };
279
+ /**
280
+ * The conversation a message belongs to.
281
+ *
282
+ * The core listen/reply loop can store the message ids itself;
283
+ * this is for the agent that wants the platform to reconstruct the
284
+ * chain. The chain is read from the **conversation root's** SMTP
285
+ * `Message-ID`, which is exactly what `email.threadId` holds.
286
+ */
287
+ threads = {
288
+ get: async (threadId, opts = {}) => {
289
+ if (!threadId) {
290
+ throw new ValidationError("thread_id_required", "threadId is required");
291
+ }
292
+ return this.request(
293
+ this.platformURL,
294
+ "GET",
295
+ `/api/agent/threads/${encodeURIComponent(threadId)}`,
296
+ { query: { domainId: opts.domainId } }
297
+ );
298
+ }
299
+ };
300
+ /**
301
+ * The durable wait — the one thing an agent cannot build for
302
+ * itself.
303
+ *
304
+ * A suspended HTTP request dies on the edge long before a
305
+ * verification mail arrives (minutes to hours later), so the wait
306
+ * is a row on the platform and the agent polls it. `create()`
307
+ * answers **immediately**; it does not block.
308
+ */
309
+ waits = {
310
+ create: async (opts) => {
311
+ return this.request(
312
+ this.platformURL,
313
+ "POST",
314
+ "/api/agent/waits",
315
+ { body: opts }
316
+ );
317
+ },
318
+ get: async (waitId) => {
319
+ if (!waitId) {
320
+ throw new ValidationError("wait_id_required", "waitId is required");
321
+ }
322
+ return this.request(
323
+ this.platformURL,
324
+ "GET",
325
+ `/api/agent/waits/${encodeURIComponent(waitId)}`
326
+ );
327
+ }
328
+ };
329
+ /**
330
+ * The addresses (mailboxes) the key's account owns, and the one
331
+ * narrow write the agent surface has: create a single one.
332
+ */
333
+ addresses = {
334
+ listDomains: async () => {
335
+ const result = await this.request(
336
+ this.platformURL,
337
+ "GET",
338
+ "/api/agent/domains"
339
+ );
340
+ return result.domains;
341
+ },
342
+ list: async (domainId) => {
343
+ if (!domainId) {
344
+ throw new ValidationError("domain_id_required", "domainId is required");
345
+ }
346
+ const result = await this.request(
347
+ this.platformURL,
348
+ "GET",
349
+ `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`
350
+ );
351
+ return result;
352
+ },
353
+ create: async (domainId, localPart) => {
354
+ if (!domainId) {
355
+ throw new ValidationError("domain_id_required", "domainId is required");
356
+ }
357
+ return this.request(
358
+ this.platformURL,
359
+ "POST",
360
+ `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,
361
+ { body: { localPart } }
362
+ );
363
+ }
364
+ };
365
+ /**
366
+ * Private: the one request path, with retry + backoff + error
367
+ * mapping shared by every public method.
368
+ *
369
+ * `origin` is explicit because the surface spans two deployments:
370
+ * the SDK backend (`baseURL`) for sending, the platform
371
+ * (`platformURL`) for reading and waiting. `method` is explicit
372
+ * because the listen endpoints are GETs — the v0.1 helper was
373
+ * POST-only, which is why reading used to mean hand-rolling HTTP.
97
374
  */
98
- async request(path, body) {
99
- const url = `${this.baseURL}${path}`;
375
+ async request(origin, method, path, opts = {}) {
376
+ const url = buildUrl(origin, path, opts.query);
100
377
  const headers = {
101
- Authorization: `Bearer ${this.apiKey}`,
102
- "Content-Type": "application/json"
378
+ Authorization: `Bearer ${this.apiKey}`
103
379
  };
380
+ if (method === "POST") headers["Content-Type"] = "application/json";
104
381
  if (this.requestId) headers["X-Flowmails-Request-Id"] = this.requestId;
105
382
  let lastError = null;
106
383
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
107
384
  let res;
108
385
  try {
109
386
  res = await this.fetchFn(url, {
110
- method: "POST",
387
+ method,
111
388
  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.
389
+ ...method === "POST" ? { body: JSON.stringify(opts.body) } : {},
390
+ // 15s matches the platform's upstream timeout — we want our
391
+ // error to be "request timed out" rather than a generic 502.
116
392
  signal: AbortSignal.timeout(15e3)
117
393
  });
118
394
  } catch (err) {
@@ -135,10 +411,19 @@ var Flowmails = class {
135
411
  }
136
412
  const code = payload.error ?? "request_failed";
137
413
  if (res.status === 401) throw new AuthenticationError(code, res.status);
138
- if (res.status === 400 || res.status === 422) {
414
+ if (res.status === 400 || res.status === 404 || res.status === 422 || res.status === 409) {
139
415
  throw new ValidationError(code, payload.detail, res.status);
140
416
  }
141
- if (res.status === 429) throw new RateLimitError(code, res.status);
417
+ if (res.status === 429) {
418
+ const facts = readQuotaFacts(res, payload);
419
+ if (code === "idempotency_key_in_progress") {
420
+ lastError = new RateLimitError(code, res.status, facts);
421
+ if (attempt >= this.maxRetries) throw lastError;
422
+ await sleep(backoffMs(attempt));
423
+ continue;
424
+ }
425
+ throw new RateLimitError(code, res.status, facts);
426
+ }
142
427
  if (res.status >= 500 || res.status === 408) {
143
428
  lastError = new UpstreamError(code, payload.detail, res.status);
144
429
  if (attempt >= this.maxRetries) throw lastError;
@@ -150,6 +435,39 @@ var Flowmails = class {
150
435
  throw lastError ?? new FlowmailsError("unknown", "Unknown failure", 0);
151
436
  }
152
437
  };
438
+ function readQuotaFacts(res, payload) {
439
+ const limit = typeof payload.limit === "number" ? payload.limit : void 0;
440
+ let remaining = typeof payload.remaining === "number" ? payload.remaining : void 0;
441
+ let resetAt = typeof payload.resetAt === "string" ? payload.resetAt : void 0;
442
+ const headerRemaining = res.headers?.get?.(
443
+ "X-Flowmails-RateLimit-Remaining"
444
+ );
445
+ if (remaining === void 0 && headerRemaining) {
446
+ const parsed = Number(headerRemaining);
447
+ if (Number.isFinite(parsed)) remaining = parsed;
448
+ }
449
+ const headerReset = res.headers?.get?.("X-Flowmails-RateLimit-Reset");
450
+ if (resetAt === void 0 && headerReset) {
451
+ const parsed = Number(headerReset);
452
+ if (Number.isFinite(parsed)) {
453
+ resetAt = new Date(parsed * 1e3).toISOString();
454
+ }
455
+ }
456
+ if (limit === void 0 && remaining === void 0 && resetAt === void 0) {
457
+ return void 0;
458
+ }
459
+ return { limit, remaining, resetAt };
460
+ }
461
+ function buildUrl(origin, path, query) {
462
+ const url = new URL(`${origin}${path}`);
463
+ if (query) {
464
+ for (const [key, value] of Object.entries(query)) {
465
+ if (value === void 0 || value === null || value === "") continue;
466
+ url.searchParams.set(key, String(value));
467
+ }
468
+ }
469
+ return url.toString();
470
+ }
153
471
  function bytesToBase64(bytes) {
154
472
  let bin = "";
155
473
  for (let i = 0; i < bytes.length; i++) {