@flowmails/flowmails-sdk 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Flowmails
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 ADDED
@@ -0,0 +1,76 @@
1
+ # @flowmails/flowmails-sdk
2
+
3
+ The official JavaScript / TypeScript SDK for the **Flowmails SDK backend** (`https://sdk.flowmails.net`).
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.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @flowmails/flowmails-sdk
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```ts
16
+ import { Flowmails } from "@flowmails/flowmails-sdk";
17
+
18
+ const fm = new Flowmails({
19
+ apiKey: process.env.FLOWMAILS_API_KEY!,
20
+ // baseURL: "https://sdk.flowmails.net", // default
21
+ });
22
+
23
+ const result = await fm.send({
24
+ from: "support@yourdomain.com",
25
+ to: "customer@example.com",
26
+ subject: "Order #1234 confirmed",
27
+ text: "Thanks for your order — we'll ship it tomorrow.",
28
+ // html: "<p>Thanks for your order…</p>",
29
+ });
30
+
31
+ console.log(result); // { id: "msg_8421", status: "queued" }
32
+ ```
33
+
34
+ ## API keys
35
+
36
+ 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.
37
+
38
+ ## Errors
39
+
40
+ The SDK throws typed errors:
41
+
42
+ | Class | HTTP status | Retryable |
43
+ |----------------------|-------------|-----------|
44
+ | `AuthenticationError`| 401 | no |
45
+ | `ValidationError` | 400 / 422 | no |
46
+ | `RateLimitError` | 429 | yes (client backs off) |
47
+ | `UpstreamError` | 5xx / 408 | yes |
48
+ | `FlowmailsError` | other | no |
49
+
50
+ Use `instanceof` to discriminate:
51
+
52
+ ```ts
53
+ import { RateLimitError, FlowmailsError } from "@flowmails/flowmails-sdk";
54
+
55
+ try {
56
+ await fm.send({ ... });
57
+ } catch (err) {
58
+ if (err instanceof RateLimitError) {
59
+ // backoff and retry
60
+ } else if (err instanceof FlowmailsError) {
61
+ // surface `err.code` to your logs
62
+ } else {
63
+ throw err;
64
+ }
65
+ }
66
+ ```
67
+
68
+ ## Limitations (v0.1)
69
+
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
+ - Custom domain (HTTP/HTTPS) attachment hosting is not configurable by SDK callers; the SDK backend always sends via R2.
73
+
74
+ ## License
75
+
76
+ UNLICENSED (private monorepo).
package/dist/index.cjs ADDED
@@ -0,0 +1,175 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var FlowmailsError = class extends Error {
5
+ /** Machine-readable error slug, sent back from the SDK backend. */
6
+ code;
7
+ /** HTTP status from the SDK backend response. */
8
+ status;
9
+ /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */
10
+ retryable;
11
+ constructor(code, message, status) {
12
+ super(message);
13
+ this.name = "FlowmailsError";
14
+ this.code = code;
15
+ this.status = status;
16
+ this.retryable = status >= 500 || status === 408 || status === 429;
17
+ }
18
+ };
19
+ var AuthenticationError = class extends FlowmailsError {
20
+ constructor(code = "api_key_invalid", status = 401) {
21
+ super(code, `Authentication failed: ${code}`, status);
22
+ this.name = "AuthenticationError";
23
+ }
24
+ };
25
+ var ValidationError = class extends FlowmailsError {
26
+ detail;
27
+ constructor(code, detail, status = 400) {
28
+ super(code, `Validation failed: ${code}${detail ? ` \u2014 ${detail}` : ""}`, status);
29
+ this.name = "ValidationError";
30
+ this.detail = detail;
31
+ }
32
+ };
33
+ var RateLimitError = class extends FlowmailsError {
34
+ constructor(code = "rate_limited", status = 429) {
35
+ super(code, `Rate limited: ${code}`, status);
36
+ this.name = "RateLimitError";
37
+ }
38
+ };
39
+ var UpstreamError = class extends FlowmailsError {
40
+ upstreamMessage;
41
+ constructor(code, upstreamMessage, status = 502) {
42
+ super(code, `Upstream failure: ${code}`, status);
43
+ this.name = "UpstreamError";
44
+ this.upstreamMessage = upstreamMessage;
45
+ }
46
+ };
47
+
48
+ // src/client.ts
49
+ var Flowmails = class {
50
+ apiKey;
51
+ baseURL;
52
+ fetchFn;
53
+ maxRetries;
54
+ requestId;
55
+ constructor(opts) {
56
+ if (!opts.apiKey) {
57
+ throw new Error("Flowmails: apiKey is required");
58
+ }
59
+ this.apiKey = opts.apiKey;
60
+ this.baseURL = (opts.baseURL ?? "https://sdk.flowmails.net").replace(
61
+ /\/+$/,
62
+ ""
63
+ );
64
+ this.fetchFn = opts.fetch ?? globalThis.fetch;
65
+ this.maxRetries = opts.maxRetries ?? 2;
66
+ this.requestId = opts.requestId;
67
+ }
68
+ /**
69
+ * Send mail through the SDK backend. The only v0.1 endpoint.
70
+ *
71
+ * Returns `{ id, status: "queued" }` on success; throws one of
72
+ * `AuthenticationError` / `ValidationError` / `RateLimitError` /
73
+ * `UpstreamError` on failure (all subclasses of `FlowmailsError`).
74
+ */
75
+ async send(opts) {
76
+ const body = {
77
+ from: opts.from,
78
+ fromName: opts.fromName,
79
+ to: Array.isArray(opts.to) ? opts.to : [opts.to],
80
+ replyTo: opts.replyTo,
81
+ subject: opts.subject,
82
+ text: opts.text,
83
+ html: opts.html,
84
+ attachments: opts.attachments?.map((a) => ({
85
+ filename: a.filename,
86
+ content: a.content instanceof Uint8Array ? bytesToBase64(a.content) : a.content,
87
+ mimeType: a.mimeType
88
+ }))
89
+ };
90
+ return this.request("/api/v1/messages", body);
91
+ }
92
+ /**
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.
97
+ */
98
+ async request(path, body) {
99
+ const url = `${this.baseURL}${path}`;
100
+ const headers = {
101
+ Authorization: `Bearer ${this.apiKey}`,
102
+ "Content-Type": "application/json"
103
+ };
104
+ if (this.requestId) headers["X-Flowmails-Request-Id"] = this.requestId;
105
+ let lastError = null;
106
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
107
+ let res;
108
+ try {
109
+ res = await this.fetchFn(url, {
110
+ method: "POST",
111
+ 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.
116
+ signal: AbortSignal.timeout(15e3)
117
+ });
118
+ } catch (err) {
119
+ lastError = new UpstreamError(
120
+ "network_error",
121
+ err instanceof Error ? err.message : void 0,
122
+ 0
123
+ );
124
+ if (attempt >= this.maxRetries) throw lastError;
125
+ await sleep(backoffMs(attempt));
126
+ continue;
127
+ }
128
+ if (res.ok) {
129
+ return await res.json();
130
+ }
131
+ let payload = {};
132
+ try {
133
+ payload = await res.json();
134
+ } catch {
135
+ }
136
+ const code = payload.error ?? "request_failed";
137
+ if (res.status === 401) throw new AuthenticationError(code, res.status);
138
+ if (res.status === 400 || res.status === 422) {
139
+ throw new ValidationError(code, payload.detail, res.status);
140
+ }
141
+ if (res.status === 429) throw new RateLimitError(code, res.status);
142
+ if (res.status >= 500 || res.status === 408) {
143
+ lastError = new UpstreamError(code, payload.detail, res.status);
144
+ if (attempt >= this.maxRetries) throw lastError;
145
+ await sleep(backoffMs(attempt));
146
+ continue;
147
+ }
148
+ throw new FlowmailsError(code, `Request failed: ${code}`, res.status);
149
+ }
150
+ throw lastError ?? new FlowmailsError("unknown", "Unknown failure", 0);
151
+ }
152
+ };
153
+ function bytesToBase64(bytes) {
154
+ let bin = "";
155
+ for (let i = 0; i < bytes.length; i++) {
156
+ bin += String.fromCharCode(bytes[i]);
157
+ }
158
+ return btoa(bin);
159
+ }
160
+ function backoffMs(attempt) {
161
+ const base = Math.min(250 * 2 ** attempt, 4e3);
162
+ return base + Math.floor(Math.random() * base);
163
+ }
164
+ function sleep(ms) {
165
+ return new Promise((resolve) => setTimeout(resolve, ms));
166
+ }
167
+
168
+ exports.AuthenticationError = AuthenticationError;
169
+ exports.Flowmails = Flowmails;
170
+ exports.FlowmailsError = FlowmailsError;
171
+ exports.RateLimitError = RateLimitError;
172
+ exports.UpstreamError = UpstreamError;
173
+ exports.ValidationError = ValidationError;
174
+ //# sourceMappingURL=index.cjs.map
175
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";;;AASO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA,EAE/B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,MAAA,EAAgB;AACzD,IAAA,KAAA,CAAM,OAAO,CAA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Q,MAAA,EAAQ,IAAI,MAAM,CAAA;AAC9D,QAAA,IAAI,OAAA,IAAW,IAAA,CAAK,UAAA,EAAY,MAAM,SAAA;AACtC,QAAA,MAAM,KAAA,CAAM,SAAA,CAAU,OAAO,CAAC,CAAA;AAC9B,QAAA;AAAA,MACF;AAGA,MAAA,MAAM,IAAI,cAAA,CAAe,IAAA,EAAM,mBAAmB,IAAI,CAAA,CAAA,EAAI,IAAI,MAAM,CAAA;AAAA,IACtE;AAIA,IAAA,MAAM,SAAA,IAAa,IAAI,cAAA,CAAe,SAAA,EAAW,mBAAmB,CAAC,CAAA;AAAA,EACvE;AACF;AAIA,SAAS,cAAc,KAAA,EAA2B;AAGhD,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,GAAA,IAAO,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EACrC;AACA,EAAA,OAAO,KAAK,GAAG,CAAA;AACjB;AAEA,SAAS,UAAU,OAAA,EAAyB;AAE1C,EAAA,MAAM,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,GAAM,CAAA,IAAK,SAAS,GAAK,CAAA;AAC/C,EAAA,OAAO,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,IAAI,CAAA;AAC/C;AAEA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"index.cjs","sourcesContent":["/**\n * Public error hierarchy. Mirrors the SDK backend's JSON contract\n * documented in `apps/sdk-backend/src/utils/errors.js`.\n *\n * The base `FlowmailsError` carries the raw `code` string (e.g.\n * `\"validation_failed\"`) plus the HTTP status. Subclasses add\n * richer contextual fields (validation `detail`, auth `reason`)\n * that the SDK backend actually emits.\n */\nexport class FlowmailsError extends Error {\n /** Machine-readable error slug, sent back from the SDK backend. */\n readonly code: string;\n /** HTTP status from the SDK backend response. */\n readonly status: number;\n /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */\n readonly retryable: boolean;\n\n constructor(code: string, message: string, status: number) {\n super(message);\n this.name = \"FlowmailsError\";\n this.code = code;\n this.status = status;\n this.retryable = status >= 500 || status === 408 || status === 429;\n }\n}\n\n/**\n * 401 — API key missing / invalid / revoked. NOT retryable.\n */\nexport class AuthenticationError extends FlowmailsError {\n constructor(code = \"api_key_invalid\", status = 401) {\n super(code, `Authentication failed: ${code}`, status);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * 400 / 422 — request was syntactically valid but rejected by the\n * backend. NOT retryable without code changes.\n */\nexport class ValidationError extends FlowmailsError {\n readonly detail?: string;\n constructor(code: string, detail: string | undefined, status = 400) {\n super(code, `Validation failed: ${code}${detail ? ` — ${detail}` : \"\"}`, status);\n this.name = \"ValidationError\";\n this.detail = detail;\n }\n}\n\n/**\n * 408 / 429 — request was rate-limited or timed out. Retryable.\n */\nexport class RateLimitError extends FlowmailsError {\n constructor(code = \"rate_limited\", status = 429) {\n super(code, `Rate limited: ${code}`, status);\n this.name = \"RateLimitError\";\n }\n}\n\n/**\n * 502 / 504 — the SDK backend couldn't reach the upstream\n * receive-worker, or the upstream returned a malformed response.\n * Retryable.\n */\nexport class UpstreamError extends FlowmailsError {\n readonly upstreamMessage?: string;\n constructor(code: string, upstreamMessage: string | undefined, status = 502) {\n super(code, `Upstream failure: ${code}`, status);\n this.name = \"UpstreamError\";\n this.upstreamMessage = upstreamMessage;\n }\n}\n","/**\n * Public SDK facade. The whole shape of the package is:\n *\n * new Flowmails({ apiKey: \"fm_…\" }).send({...})\n *\n * No top-level helper functions, no globals, no implicit init.\n * Construction takes an `apiKey` and an optional `baseURL`\n * (mainly for testing / private-region deployments).\n *\n * `send` is the only public method in v0.1 — there is exactly\n * one outbound endpoint (`POST /api/v1/messages`). The\n * `request<T>` helper below it carries the retry / backoff /\n * error-mapping machinery and is private; future public methods\n * (e.g. `webhooks.send`) will call `request<T>` internally so\n * the choke point stays in one place.\n *\n * The payload DTOs (`SendOptions` / `SendResult` / `SendAttachment`)\n * mirror common email-clients (Gmail API, Resend, Postmark), NOT\n * the receive-worker's wire format. `send` does the rename to\n * wire on the way out (html → content, Uint8Array → base64).\n */\nimport {\n AuthenticationError,\n FlowmailsError,\n RateLimitError,\n UpstreamError,\n ValidationError,\n} from \"./errors.js\";\n\n// ---------- Public payload types ----------\n\n/**\n * A single file attached to the outbound message.\n *\n * `filename` and `content` are required. `mimeType` defaults to\n * `application/octet-stream` if the SDK backend cannot infer it\n * from the filename (the backend forwards `mimeType` to the\n * receive-worker which sets it on the SMTP part).\n */\nexport interface SendAttachment {\n filename: string;\n content: string | Uint8Array;\n mimeType?: string;\n}\n\n/**\n * Composed send payload.\n *\n * `to` accepts a single address or an array. `subject` is required.\n * At least one of `text` / `html` must be a non-empty string.\n */\nexport interface SendOptions {\n /**\n * Sender address. MUST land on the domain the API key is bound\n * to (the SDK backend enforces this with a 422 on mismatch).\n */\n from: string;\n /** Display name for the sender; the email-worker falls back to the\n * local-part capitalised. */\n fromName?: string;\n /** One recipient or an array. */\n to: string | string[];\n /** Optional reply-to override. */\n replyTo?: string;\n /** Subject line — required, non-empty. */\n subject: string;\n /** Plain-text body. Required iff `html` is also missing. */\n text?: string;\n /** HTML body. Required iff `text` is also missing. Inline\n * `cid:` images and remote `data:` urls are auto-extracted by\n * the email-worker into R2 embeds. */\n html?: string;\n /** Attachments. */\n attachments?: SendAttachment[];\n}\n\n/**\n * Result of a successful send. Matches the marketing-copy promise\n * in `apps/web/app/routes/home.tsx`:\n *\n * { \"id\": \"msg_8421\", \"status\": \"queued\" }\n */\nexport interface SendResult {\n /** Numeric email row id (stringified for JSON safety). */\n id: string;\n /** Always `\"queued\"` for now; the SDK backend doesn't surface\n * the SMTP `delivered` / `bounced` lifecycle — that comes via\n * webhooks in a future milestone. */\n status: \"queued\";\n}\n\n// ---------- Options & class ----------\n\nexport interface FlowmailsOptions {\n /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */\n apiKey: string;\n /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */\n baseURL?: string;\n /** Inject a `fetch` implementation (Workers environments, test harnesses). */\n fetch?: typeof globalThis.fetch;\n /**\n * Number of automatic retries on transient failures (5xx, 408,\n * 429). Defaults to 2. Set to 0 to disable. The retry budget is\n * bounded; doesn't apply to 4xx validation / auth failures.\n */\n maxRetries?: number;\n /**\n * Optional request-id header for cross-stack tracing. If set,\n * every outbound request carries `X-Flowmails-Request-Id`, and\n * the SDK backend echoes it back on the response so callers can\n * correlate platform logs with their own.\n */\n requestId?: string;\n}\n\nexport class Flowmails {\n private readonly apiKey: string;\n private readonly baseURL: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly maxRetries: number;\n private readonly requestId?: string;\n\n constructor(opts: FlowmailsOptions) {\n if (!opts.apiKey) {\n throw new Error(\"Flowmails: apiKey is required\");\n }\n this.apiKey = opts.apiKey;\n this.baseURL = (opts.baseURL ?? \"https://sdk.flowmails.net\").replace(\n /\\/+$/,\n \"\",\n );\n this.fetchFn = opts.fetch ?? globalThis.fetch;\n this.maxRetries = opts.maxRetries ?? 2;\n this.requestId = opts.requestId;\n }\n\n /**\n * Send mail through the SDK backend. The only v0.1 endpoint.\n *\n * Returns `{ id, status: \"queued\" }` on success; throws one of\n * `AuthenticationError` / `ValidationError` / `RateLimitError` /\n * `UpstreamError` on failure (all subclasses of `FlowmailsError`).\n */\n async send(opts: SendOptions): Promise<SendResult> {\n // The wire-shape renames (html → content, Uint8Array → base64)\n // happen here. Keeping this logic adjacent to the type\n // definitions avoids a separate \"resource\" indirection for a\n // single endpoint — when a second endpoint ships, this is the\n // place to extract a small internal helper.\n const body = {\n from: opts.from,\n fromName: opts.fromName,\n to: Array.isArray(opts.to) ? opts.to : [opts.to],\n replyTo: opts.replyTo,\n subject: opts.subject,\n text: opts.text,\n html: opts.html,\n attachments: opts.attachments?.map((a) => ({\n filename: a.filename,\n content:\n a.content instanceof Uint8Array\n ? bytesToBase64(a.content)\n : a.content,\n mimeType: a.mimeType,\n })),\n };\n\n return this.request<SendResult>(\"/api/v1/messages\", body);\n }\n\n /**\n * Private: low-level request helper with retry+backoff+error\n * mapping. SDK callers must use the typed `send()` method\n * instead — this exists so future public methods can share the\n * same retry budget / error class mapping without re-implementing.\n */\n private async request<T>(path: string, body: unknown): Promise<T> {\n const url = `${this.baseURL}${path}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n if (this.requestId) headers[\"X-Flowmails-Request-Id\"] = this.requestId;\n\n let lastError: FlowmailsError | null = null;\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n // 15s matches the SDK backend's upstream timeout — we want\n // our error to be \"request timed out\" rather than the\n // backend's generic 502.\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n lastError = new UpstreamError(\n \"network_error\",\n err instanceof Error ? err.message : undefined,\n 0,\n );\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // 2xx — happy path. Decode and return.\n if (res.ok) {\n return (await res.json()) as T;\n }\n\n // Non-2xx — render to a typed error.\n let payload: { error?: string; detail?: string; reason?: string } = {};\n try {\n payload = (await res.json()) as typeof payload;\n } catch {\n // Body wasn't JSON; fall back to status-based error.\n }\n\n const code = payload.error ?? \"request_failed\";\n\n if (res.status === 401) throw new AuthenticationError(code, res.status);\n if (res.status === 400 || res.status === 422) {\n throw new ValidationError(code, payload.detail, res.status);\n }\n if (res.status === 429) throw new RateLimitError(code, res.status);\n if (res.status >= 500 || res.status === 408) {\n lastError = new UpstreamError(code, payload.detail, res.status);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // Anything else: not retryable, throw immediately.\n throw new FlowmailsError(code, `Request failed: ${code}`, res.status);\n }\n\n // Shouldn't reach here — last iteration always throws. Type\n // assertion keeps the compiler happy without `any`.\n throw lastError ?? new FlowmailsError(\"unknown\", \"Unknown failure\", 0);\n }\n}\n\n// ---------- Module-level helpers ----------\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Browser-safe base64 of a `Uint8Array`. Avoids pulling in a\n // Buffer polyfill in the worker / browser bundles.\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++) {\n bin += String.fromCharCode(bytes[i]);\n }\n return btoa(bin);\n}\n\nfunction backoffMs(attempt: number): number {\n // Exponential backoff with jitter, capped at 4 s. attempt 0 → 250 ms.\n const base = Math.min(250 * 2 ** attempt, 4_000);\n return base + Math.floor(Math.random() * base);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}"]}
@@ -0,0 +1,151 @@
1
+ /**
2
+ * A single file attached to the outbound message.
3
+ *
4
+ * `filename` and `content` are required. `mimeType` defaults to
5
+ * `application/octet-stream` if the SDK backend cannot infer it
6
+ * from the filename (the backend forwards `mimeType` to the
7
+ * receive-worker which sets it on the SMTP part).
8
+ */
9
+ interface SendAttachment {
10
+ filename: string;
11
+ content: string | Uint8Array;
12
+ mimeType?: string;
13
+ }
14
+ /**
15
+ * Composed send payload.
16
+ *
17
+ * `to` accepts a single address or an array. `subject` is required.
18
+ * At least one of `text` / `html` must be a non-empty string.
19
+ */
20
+ interface SendOptions {
21
+ /**
22
+ * Sender address. MUST land on the domain the API key is bound
23
+ * to (the SDK backend enforces this with a 422 on mismatch).
24
+ */
25
+ from: string;
26
+ /** Display name for the sender; the email-worker falls back to the
27
+ * local-part capitalised. */
28
+ fromName?: string;
29
+ /** One recipient or an array. */
30
+ to: string | string[];
31
+ /** Optional reply-to override. */
32
+ replyTo?: string;
33
+ /** Subject line — required, non-empty. */
34
+ subject: string;
35
+ /** Plain-text body. Required iff `html` is also missing. */
36
+ text?: string;
37
+ /** HTML body. Required iff `text` is also missing. Inline
38
+ * `cid:` images and remote `data:` urls are auto-extracted by
39
+ * the email-worker into R2 embeds. */
40
+ html?: string;
41
+ /** Attachments. */
42
+ attachments?: SendAttachment[];
43
+ }
44
+ /**
45
+ * Result of a successful send. Matches the marketing-copy promise
46
+ * in `apps/web/app/routes/home.tsx`:
47
+ *
48
+ * { "id": "msg_8421", "status": "queued" }
49
+ */
50
+ interface SendResult {
51
+ /** Numeric email row id (stringified for JSON safety). */
52
+ id: string;
53
+ /** Always `"queued"` for now; the SDK backend doesn't surface
54
+ * the SMTP `delivered` / `bounced` lifecycle — that comes via
55
+ * webhooks in a future milestone. */
56
+ status: "queued";
57
+ }
58
+ interface FlowmailsOptions {
59
+ /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */
60
+ apiKey: string;
61
+ /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */
62
+ baseURL?: string;
63
+ /** Inject a `fetch` implementation (Workers environments, test harnesses). */
64
+ fetch?: typeof globalThis.fetch;
65
+ /**
66
+ * Number of automatic retries on transient failures (5xx, 408,
67
+ * 429). Defaults to 2. Set to 0 to disable. The retry budget is
68
+ * bounded; doesn't apply to 4xx validation / auth failures.
69
+ */
70
+ maxRetries?: number;
71
+ /**
72
+ * Optional request-id header for cross-stack tracing. If set,
73
+ * every outbound request carries `X-Flowmails-Request-Id`, and
74
+ * the SDK backend echoes it back on the response so callers can
75
+ * correlate platform logs with their own.
76
+ */
77
+ requestId?: string;
78
+ }
79
+ declare class Flowmails {
80
+ private readonly apiKey;
81
+ private readonly baseURL;
82
+ private readonly fetchFn;
83
+ private readonly maxRetries;
84
+ private readonly requestId?;
85
+ constructor(opts: FlowmailsOptions);
86
+ /**
87
+ * Send mail through the SDK backend. The only v0.1 endpoint.
88
+ *
89
+ * Returns `{ id, status: "queued" }` on success; throws one of
90
+ * `AuthenticationError` / `ValidationError` / `RateLimitError` /
91
+ * `UpstreamError` on failure (all subclasses of `FlowmailsError`).
92
+ */
93
+ send(opts: SendOptions): Promise<SendResult>;
94
+ /**
95
+ * Private: low-level request helper with retry+backoff+error
96
+ * mapping. SDK callers must use the typed `send()` method
97
+ * instead — this exists so future public methods can share the
98
+ * same retry budget / error class mapping without re-implementing.
99
+ */
100
+ private request;
101
+ }
102
+
103
+ /**
104
+ * Public error hierarchy. Mirrors the SDK backend's JSON contract
105
+ * documented in `apps/sdk-backend/src/utils/errors.js`.
106
+ *
107
+ * The base `FlowmailsError` carries the raw `code` string (e.g.
108
+ * `"validation_failed"`) plus the HTTP status. Subclasses add
109
+ * richer contextual fields (validation `detail`, auth `reason`)
110
+ * that the SDK backend actually emits.
111
+ */
112
+ declare class FlowmailsError extends Error {
113
+ /** Machine-readable error slug, sent back from the SDK backend. */
114
+ readonly code: string;
115
+ /** HTTP status from the SDK backend response. */
116
+ readonly status: number;
117
+ /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */
118
+ readonly retryable: boolean;
119
+ constructor(code: string, message: string, status: number);
120
+ }
121
+ /**
122
+ * 401 — API key missing / invalid / revoked. NOT retryable.
123
+ */
124
+ declare class AuthenticationError extends FlowmailsError {
125
+ constructor(code?: string, status?: number);
126
+ }
127
+ /**
128
+ * 400 / 422 — request was syntactically valid but rejected by the
129
+ * backend. NOT retryable without code changes.
130
+ */
131
+ declare class ValidationError extends FlowmailsError {
132
+ readonly detail?: string;
133
+ constructor(code: string, detail: string | undefined, status?: number);
134
+ }
135
+ /**
136
+ * 408 / 429 — request was rate-limited or timed out. Retryable.
137
+ */
138
+ declare class RateLimitError extends FlowmailsError {
139
+ constructor(code?: string, status?: number);
140
+ }
141
+ /**
142
+ * 502 / 504 — the SDK backend couldn't reach the upstream
143
+ * receive-worker, or the upstream returned a malformed response.
144
+ * Retryable.
145
+ */
146
+ declare class UpstreamError extends FlowmailsError {
147
+ readonly upstreamMessage?: string;
148
+ constructor(code: string, upstreamMessage: string | undefined, status?: number);
149
+ }
150
+
151
+ export { AuthenticationError, Flowmails, FlowmailsError, type FlowmailsOptions, RateLimitError, type SendAttachment, type SendOptions, type SendResult, UpstreamError, ValidationError };
@@ -0,0 +1,151 @@
1
+ /**
2
+ * A single file attached to the outbound message.
3
+ *
4
+ * `filename` and `content` are required. `mimeType` defaults to
5
+ * `application/octet-stream` if the SDK backend cannot infer it
6
+ * from the filename (the backend forwards `mimeType` to the
7
+ * receive-worker which sets it on the SMTP part).
8
+ */
9
+ interface SendAttachment {
10
+ filename: string;
11
+ content: string | Uint8Array;
12
+ mimeType?: string;
13
+ }
14
+ /**
15
+ * Composed send payload.
16
+ *
17
+ * `to` accepts a single address or an array. `subject` is required.
18
+ * At least one of `text` / `html` must be a non-empty string.
19
+ */
20
+ interface SendOptions {
21
+ /**
22
+ * Sender address. MUST land on the domain the API key is bound
23
+ * to (the SDK backend enforces this with a 422 on mismatch).
24
+ */
25
+ from: string;
26
+ /** Display name for the sender; the email-worker falls back to the
27
+ * local-part capitalised. */
28
+ fromName?: string;
29
+ /** One recipient or an array. */
30
+ to: string | string[];
31
+ /** Optional reply-to override. */
32
+ replyTo?: string;
33
+ /** Subject line — required, non-empty. */
34
+ subject: string;
35
+ /** Plain-text body. Required iff `html` is also missing. */
36
+ text?: string;
37
+ /** HTML body. Required iff `text` is also missing. Inline
38
+ * `cid:` images and remote `data:` urls are auto-extracted by
39
+ * the email-worker into R2 embeds. */
40
+ html?: string;
41
+ /** Attachments. */
42
+ attachments?: SendAttachment[];
43
+ }
44
+ /**
45
+ * Result of a successful send. Matches the marketing-copy promise
46
+ * in `apps/web/app/routes/home.tsx`:
47
+ *
48
+ * { "id": "msg_8421", "status": "queued" }
49
+ */
50
+ interface SendResult {
51
+ /** Numeric email row id (stringified for JSON safety). */
52
+ id: string;
53
+ /** Always `"queued"` for now; the SDK backend doesn't surface
54
+ * the SMTP `delivered` / `bounced` lifecycle — that comes via
55
+ * webhooks in a future milestone. */
56
+ status: "queued";
57
+ }
58
+ interface FlowmailsOptions {
59
+ /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */
60
+ apiKey: string;
61
+ /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */
62
+ baseURL?: string;
63
+ /** Inject a `fetch` implementation (Workers environments, test harnesses). */
64
+ fetch?: typeof globalThis.fetch;
65
+ /**
66
+ * Number of automatic retries on transient failures (5xx, 408,
67
+ * 429). Defaults to 2. Set to 0 to disable. The retry budget is
68
+ * bounded; doesn't apply to 4xx validation / auth failures.
69
+ */
70
+ maxRetries?: number;
71
+ /**
72
+ * Optional request-id header for cross-stack tracing. If set,
73
+ * every outbound request carries `X-Flowmails-Request-Id`, and
74
+ * the SDK backend echoes it back on the response so callers can
75
+ * correlate platform logs with their own.
76
+ */
77
+ requestId?: string;
78
+ }
79
+ declare class Flowmails {
80
+ private readonly apiKey;
81
+ private readonly baseURL;
82
+ private readonly fetchFn;
83
+ private readonly maxRetries;
84
+ private readonly requestId?;
85
+ constructor(opts: FlowmailsOptions);
86
+ /**
87
+ * Send mail through the SDK backend. The only v0.1 endpoint.
88
+ *
89
+ * Returns `{ id, status: "queued" }` on success; throws one of
90
+ * `AuthenticationError` / `ValidationError` / `RateLimitError` /
91
+ * `UpstreamError` on failure (all subclasses of `FlowmailsError`).
92
+ */
93
+ send(opts: SendOptions): Promise<SendResult>;
94
+ /**
95
+ * Private: low-level request helper with retry+backoff+error
96
+ * mapping. SDK callers must use the typed `send()` method
97
+ * instead — this exists so future public methods can share the
98
+ * same retry budget / error class mapping without re-implementing.
99
+ */
100
+ private request;
101
+ }
102
+
103
+ /**
104
+ * Public error hierarchy. Mirrors the SDK backend's JSON contract
105
+ * documented in `apps/sdk-backend/src/utils/errors.js`.
106
+ *
107
+ * The base `FlowmailsError` carries the raw `code` string (e.g.
108
+ * `"validation_failed"`) plus the HTTP status. Subclasses add
109
+ * richer contextual fields (validation `detail`, auth `reason`)
110
+ * that the SDK backend actually emits.
111
+ */
112
+ declare class FlowmailsError extends Error {
113
+ /** Machine-readable error slug, sent back from the SDK backend. */
114
+ readonly code: string;
115
+ /** HTTP status from the SDK backend response. */
116
+ readonly status: number;
117
+ /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */
118
+ readonly retryable: boolean;
119
+ constructor(code: string, message: string, status: number);
120
+ }
121
+ /**
122
+ * 401 — API key missing / invalid / revoked. NOT retryable.
123
+ */
124
+ declare class AuthenticationError extends FlowmailsError {
125
+ constructor(code?: string, status?: number);
126
+ }
127
+ /**
128
+ * 400 / 422 — request was syntactically valid but rejected by the
129
+ * backend. NOT retryable without code changes.
130
+ */
131
+ declare class ValidationError extends FlowmailsError {
132
+ readonly detail?: string;
133
+ constructor(code: string, detail: string | undefined, status?: number);
134
+ }
135
+ /**
136
+ * 408 / 429 — request was rate-limited or timed out. Retryable.
137
+ */
138
+ declare class RateLimitError extends FlowmailsError {
139
+ constructor(code?: string, status?: number);
140
+ }
141
+ /**
142
+ * 502 / 504 — the SDK backend couldn't reach the upstream
143
+ * receive-worker, or the upstream returned a malformed response.
144
+ * Retryable.
145
+ */
146
+ declare class UpstreamError extends FlowmailsError {
147
+ readonly upstreamMessage?: string;
148
+ constructor(code: string, upstreamMessage: string | undefined, status?: number);
149
+ }
150
+
151
+ export { AuthenticationError, Flowmails, FlowmailsError, type FlowmailsOptions, RateLimitError, type SendAttachment, type SendOptions, type SendResult, UpstreamError, ValidationError };
package/dist/index.js ADDED
@@ -0,0 +1,168 @@
1
+ // src/errors.ts
2
+ var FlowmailsError = class extends Error {
3
+ /** Machine-readable error slug, sent back from the SDK backend. */
4
+ code;
5
+ /** HTTP status from the SDK backend response. */
6
+ status;
7
+ /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */
8
+ retryable;
9
+ constructor(code, message, status) {
10
+ super(message);
11
+ this.name = "FlowmailsError";
12
+ this.code = code;
13
+ this.status = status;
14
+ this.retryable = status >= 500 || status === 408 || status === 429;
15
+ }
16
+ };
17
+ var AuthenticationError = class extends FlowmailsError {
18
+ constructor(code = "api_key_invalid", status = 401) {
19
+ super(code, `Authentication failed: ${code}`, status);
20
+ this.name = "AuthenticationError";
21
+ }
22
+ };
23
+ var ValidationError = class extends FlowmailsError {
24
+ detail;
25
+ constructor(code, detail, status = 400) {
26
+ super(code, `Validation failed: ${code}${detail ? ` \u2014 ${detail}` : ""}`, status);
27
+ this.name = "ValidationError";
28
+ this.detail = detail;
29
+ }
30
+ };
31
+ var RateLimitError = class extends FlowmailsError {
32
+ constructor(code = "rate_limited", status = 429) {
33
+ super(code, `Rate limited: ${code}`, status);
34
+ this.name = "RateLimitError";
35
+ }
36
+ };
37
+ var UpstreamError = class extends FlowmailsError {
38
+ upstreamMessage;
39
+ constructor(code, upstreamMessage, status = 502) {
40
+ super(code, `Upstream failure: ${code}`, status);
41
+ this.name = "UpstreamError";
42
+ this.upstreamMessage = upstreamMessage;
43
+ }
44
+ };
45
+
46
+ // src/client.ts
47
+ var Flowmails = class {
48
+ apiKey;
49
+ baseURL;
50
+ fetchFn;
51
+ maxRetries;
52
+ requestId;
53
+ constructor(opts) {
54
+ if (!opts.apiKey) {
55
+ throw new Error("Flowmails: apiKey is required");
56
+ }
57
+ this.apiKey = opts.apiKey;
58
+ this.baseURL = (opts.baseURL ?? "https://sdk.flowmails.net").replace(
59
+ /\/+$/,
60
+ ""
61
+ );
62
+ this.fetchFn = opts.fetch ?? globalThis.fetch;
63
+ this.maxRetries = opts.maxRetries ?? 2;
64
+ this.requestId = opts.requestId;
65
+ }
66
+ /**
67
+ * Send mail through the SDK backend. The only v0.1 endpoint.
68
+ *
69
+ * Returns `{ id, status: "queued" }` on success; throws one of
70
+ * `AuthenticationError` / `ValidationError` / `RateLimitError` /
71
+ * `UpstreamError` on failure (all subclasses of `FlowmailsError`).
72
+ */
73
+ async send(opts) {
74
+ const body = {
75
+ from: opts.from,
76
+ fromName: opts.fromName,
77
+ to: Array.isArray(opts.to) ? opts.to : [opts.to],
78
+ replyTo: opts.replyTo,
79
+ subject: opts.subject,
80
+ text: opts.text,
81
+ html: opts.html,
82
+ attachments: opts.attachments?.map((a) => ({
83
+ filename: a.filename,
84
+ content: a.content instanceof Uint8Array ? bytesToBase64(a.content) : a.content,
85
+ mimeType: a.mimeType
86
+ }))
87
+ };
88
+ return this.request("/api/v1/messages", body);
89
+ }
90
+ /**
91
+ * Private: low-level request helper with retry+backoff+error
92
+ * mapping. SDK callers must use the typed `send()` method
93
+ * instead — this exists so future public methods can share the
94
+ * same retry budget / error class mapping without re-implementing.
95
+ */
96
+ async request(path, body) {
97
+ const url = `${this.baseURL}${path}`;
98
+ const headers = {
99
+ Authorization: `Bearer ${this.apiKey}`,
100
+ "Content-Type": "application/json"
101
+ };
102
+ if (this.requestId) headers["X-Flowmails-Request-Id"] = this.requestId;
103
+ let lastError = null;
104
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
105
+ let res;
106
+ try {
107
+ res = await this.fetchFn(url, {
108
+ method: "POST",
109
+ headers,
110
+ body: JSON.stringify(body),
111
+ // 15s matches the SDK backend's upstream timeout — we want
112
+ // our error to be "request timed out" rather than the
113
+ // backend's generic 502.
114
+ signal: AbortSignal.timeout(15e3)
115
+ });
116
+ } catch (err) {
117
+ lastError = new UpstreamError(
118
+ "network_error",
119
+ err instanceof Error ? err.message : void 0,
120
+ 0
121
+ );
122
+ if (attempt >= this.maxRetries) throw lastError;
123
+ await sleep(backoffMs(attempt));
124
+ continue;
125
+ }
126
+ if (res.ok) {
127
+ return await res.json();
128
+ }
129
+ let payload = {};
130
+ try {
131
+ payload = await res.json();
132
+ } catch {
133
+ }
134
+ const code = payload.error ?? "request_failed";
135
+ if (res.status === 401) throw new AuthenticationError(code, res.status);
136
+ if (res.status === 400 || res.status === 422) {
137
+ throw new ValidationError(code, payload.detail, res.status);
138
+ }
139
+ if (res.status === 429) throw new RateLimitError(code, res.status);
140
+ if (res.status >= 500 || res.status === 408) {
141
+ lastError = new UpstreamError(code, payload.detail, res.status);
142
+ if (attempt >= this.maxRetries) throw lastError;
143
+ await sleep(backoffMs(attempt));
144
+ continue;
145
+ }
146
+ throw new FlowmailsError(code, `Request failed: ${code}`, res.status);
147
+ }
148
+ throw lastError ?? new FlowmailsError("unknown", "Unknown failure", 0);
149
+ }
150
+ };
151
+ function bytesToBase64(bytes) {
152
+ let bin = "";
153
+ for (let i = 0; i < bytes.length; i++) {
154
+ bin += String.fromCharCode(bytes[i]);
155
+ }
156
+ return btoa(bin);
157
+ }
158
+ function backoffMs(attempt) {
159
+ const base = Math.min(250 * 2 ** attempt, 4e3);
160
+ return base + Math.floor(Math.random() * base);
161
+ }
162
+ function sleep(ms) {
163
+ return new Promise((resolve) => setTimeout(resolve, ms));
164
+ }
165
+
166
+ export { AuthenticationError, Flowmails, FlowmailsError, RateLimitError, UpstreamError, ValidationError };
167
+ //# sourceMappingURL=index.js.map
168
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";AASO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA,EAE/B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,MAAA,EAAgB;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,SAAA,GAAY,MAAA,IAAU,GAAA,IAAO,MAAA,KAAW,OAAO,MAAA,KAAW,GAAA;AAAA,EACjE;AACF;AAKO,IAAM,mBAAA,GAAN,cAAkC,cAAA,CAAe;AAAA,EACtD,WAAA,CAAY,IAAA,GAAO,iBAAA,EA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I,cAAA,CAAe,SAAA,EAAW,mBAAmB,CAAC,CAAA;AAAA,EACvE;AACF;AAIA,SAAS,cAAc,KAAA,EAA2B;AAGhD,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,GAAA,IAAO,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EACrC;AACA,EAAA,OAAO,KAAK,GAAG,CAAA;AACjB;AAEA,SAAS,UAAU,OAAA,EAAyB;AAE1C,EAAA,MAAM,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,GAAM,CAAA,IAAK,SAAS,GAAK,CAAA;AAC/C,EAAA,OAAO,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,IAAI,CAAA;AAC/C;AAEA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"index.js","sourcesContent":["/**\n * Public error hierarchy. Mirrors the SDK backend's JSON contract\n * documented in `apps/sdk-backend/src/utils/errors.js`.\n *\n * The base `FlowmailsError` carries the raw `code` string (e.g.\n * `\"validation_failed\"`) plus the HTTP status. Subclasses add\n * richer contextual fields (validation `detail`, auth `reason`)\n * that the SDK backend actually emits.\n */\nexport class FlowmailsError extends Error {\n /** Machine-readable error slug, sent back from the SDK backend. */\n readonly code: string;\n /** HTTP status from the SDK backend response. */\n readonly status: number;\n /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */\n readonly retryable: boolean;\n\n constructor(code: string, message: string, status: number) {\n super(message);\n this.name = \"FlowmailsError\";\n this.code = code;\n this.status = status;\n this.retryable = status >= 500 || status === 408 || status === 429;\n }\n}\n\n/**\n * 401 — API key missing / invalid / revoked. NOT retryable.\n */\nexport class AuthenticationError extends FlowmailsError {\n constructor(code = \"api_key_invalid\", status = 401) {\n super(code, `Authentication failed: ${code}`, status);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * 400 / 422 — request was syntactically valid but rejected by the\n * backend. NOT retryable without code changes.\n */\nexport class ValidationError extends FlowmailsError {\n readonly detail?: string;\n constructor(code: string, detail: string | undefined, status = 400) {\n super(code, `Validation failed: ${code}${detail ? ` — ${detail}` : \"\"}`, status);\n this.name = \"ValidationError\";\n this.detail = detail;\n }\n}\n\n/**\n * 408 / 429 — request was rate-limited or timed out. Retryable.\n */\nexport class RateLimitError extends FlowmailsError {\n constructor(code = \"rate_limited\", status = 429) {\n super(code, `Rate limited: ${code}`, status);\n this.name = \"RateLimitError\";\n }\n}\n\n/**\n * 502 / 504 — the SDK backend couldn't reach the upstream\n * receive-worker, or the upstream returned a malformed response.\n * Retryable.\n */\nexport class UpstreamError extends FlowmailsError {\n readonly upstreamMessage?: string;\n constructor(code: string, upstreamMessage: string | undefined, status = 502) {\n super(code, `Upstream failure: ${code}`, status);\n this.name = \"UpstreamError\";\n this.upstreamMessage = upstreamMessage;\n }\n}\n","/**\n * Public SDK facade. The whole shape of the package is:\n *\n * new Flowmails({ apiKey: \"fm_…\" }).send({...})\n *\n * No top-level helper functions, no globals, no implicit init.\n * Construction takes an `apiKey` and an optional `baseURL`\n * (mainly for testing / private-region deployments).\n *\n * `send` is the only public method in v0.1 — there is exactly\n * one outbound endpoint (`POST /api/v1/messages`). The\n * `request<T>` helper below it carries the retry / backoff /\n * error-mapping machinery and is private; future public methods\n * (e.g. `webhooks.send`) will call `request<T>` internally so\n * the choke point stays in one place.\n *\n * The payload DTOs (`SendOptions` / `SendResult` / `SendAttachment`)\n * mirror common email-clients (Gmail API, Resend, Postmark), NOT\n * the receive-worker's wire format. `send` does the rename to\n * wire on the way out (html → content, Uint8Array → base64).\n */\nimport {\n AuthenticationError,\n FlowmailsError,\n RateLimitError,\n UpstreamError,\n ValidationError,\n} from \"./errors.js\";\n\n// ---------- Public payload types ----------\n\n/**\n * A single file attached to the outbound message.\n *\n * `filename` and `content` are required. `mimeType` defaults to\n * `application/octet-stream` if the SDK backend cannot infer it\n * from the filename (the backend forwards `mimeType` to the\n * receive-worker which sets it on the SMTP part).\n */\nexport interface SendAttachment {\n filename: string;\n content: string | Uint8Array;\n mimeType?: string;\n}\n\n/**\n * Composed send payload.\n *\n * `to` accepts a single address or an array. `subject` is required.\n * At least one of `text` / `html` must be a non-empty string.\n */\nexport interface SendOptions {\n /**\n * Sender address. MUST land on the domain the API key is bound\n * to (the SDK backend enforces this with a 422 on mismatch).\n */\n from: string;\n /** Display name for the sender; the email-worker falls back to the\n * local-part capitalised. */\n fromName?: string;\n /** One recipient or an array. */\n to: string | string[];\n /** Optional reply-to override. */\n replyTo?: string;\n /** Subject line — required, non-empty. */\n subject: string;\n /** Plain-text body. Required iff `html` is also missing. */\n text?: string;\n /** HTML body. Required iff `text` is also missing. Inline\n * `cid:` images and remote `data:` urls are auto-extracted by\n * the email-worker into R2 embeds. */\n html?: string;\n /** Attachments. */\n attachments?: SendAttachment[];\n}\n\n/**\n * Result of a successful send. Matches the marketing-copy promise\n * in `apps/web/app/routes/home.tsx`:\n *\n * { \"id\": \"msg_8421\", \"status\": \"queued\" }\n */\nexport interface SendResult {\n /** Numeric email row id (stringified for JSON safety). */\n id: string;\n /** Always `\"queued\"` for now; the SDK backend doesn't surface\n * the SMTP `delivered` / `bounced` lifecycle — that comes via\n * webhooks in a future milestone. */\n status: \"queued\";\n}\n\n// ---------- Options & class ----------\n\nexport interface FlowmailsOptions {\n /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */\n apiKey: string;\n /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */\n baseURL?: string;\n /** Inject a `fetch` implementation (Workers environments, test harnesses). */\n fetch?: typeof globalThis.fetch;\n /**\n * Number of automatic retries on transient failures (5xx, 408,\n * 429). Defaults to 2. Set to 0 to disable. The retry budget is\n * bounded; doesn't apply to 4xx validation / auth failures.\n */\n maxRetries?: number;\n /**\n * Optional request-id header for cross-stack tracing. If set,\n * every outbound request carries `X-Flowmails-Request-Id`, and\n * the SDK backend echoes it back on the response so callers can\n * correlate platform logs with their own.\n */\n requestId?: string;\n}\n\nexport class Flowmails {\n private readonly apiKey: string;\n private readonly baseURL: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly maxRetries: number;\n private readonly requestId?: string;\n\n constructor(opts: FlowmailsOptions) {\n if (!opts.apiKey) {\n throw new Error(\"Flowmails: apiKey is required\");\n }\n this.apiKey = opts.apiKey;\n this.baseURL = (opts.baseURL ?? \"https://sdk.flowmails.net\").replace(\n /\\/+$/,\n \"\",\n );\n this.fetchFn = opts.fetch ?? globalThis.fetch;\n this.maxRetries = opts.maxRetries ?? 2;\n this.requestId = opts.requestId;\n }\n\n /**\n * Send mail through the SDK backend. The only v0.1 endpoint.\n *\n * Returns `{ id, status: \"queued\" }` on success; throws one of\n * `AuthenticationError` / `ValidationError` / `RateLimitError` /\n * `UpstreamError` on failure (all subclasses of `FlowmailsError`).\n */\n async send(opts: SendOptions): Promise<SendResult> {\n // The wire-shape renames (html → content, Uint8Array → base64)\n // happen here. Keeping this logic adjacent to the type\n // definitions avoids a separate \"resource\" indirection for a\n // single endpoint — when a second endpoint ships, this is the\n // place to extract a small internal helper.\n const body = {\n from: opts.from,\n fromName: opts.fromName,\n to: Array.isArray(opts.to) ? opts.to : [opts.to],\n replyTo: opts.replyTo,\n subject: opts.subject,\n text: opts.text,\n html: opts.html,\n attachments: opts.attachments?.map((a) => ({\n filename: a.filename,\n content:\n a.content instanceof Uint8Array\n ? bytesToBase64(a.content)\n : a.content,\n mimeType: a.mimeType,\n })),\n };\n\n return this.request<SendResult>(\"/api/v1/messages\", body);\n }\n\n /**\n * Private: low-level request helper with retry+backoff+error\n * mapping. SDK callers must use the typed `send()` method\n * instead — this exists so future public methods can share the\n * same retry budget / error class mapping without re-implementing.\n */\n private async request<T>(path: string, body: unknown): Promise<T> {\n const url = `${this.baseURL}${path}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n if (this.requestId) headers[\"X-Flowmails-Request-Id\"] = this.requestId;\n\n let lastError: FlowmailsError | null = null;\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n // 15s matches the SDK backend's upstream timeout — we want\n // our error to be \"request timed out\" rather than the\n // backend's generic 502.\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n lastError = new UpstreamError(\n \"network_error\",\n err instanceof Error ? err.message : undefined,\n 0,\n );\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // 2xx — happy path. Decode and return.\n if (res.ok) {\n return (await res.json()) as T;\n }\n\n // Non-2xx — render to a typed error.\n let payload: { error?: string; detail?: string; reason?: string } = {};\n try {\n payload = (await res.json()) as typeof payload;\n } catch {\n // Body wasn't JSON; fall back to status-based error.\n }\n\n const code = payload.error ?? \"request_failed\";\n\n if (res.status === 401) throw new AuthenticationError(code, res.status);\n if (res.status === 400 || res.status === 422) {\n throw new ValidationError(code, payload.detail, res.status);\n }\n if (res.status === 429) throw new RateLimitError(code, res.status);\n if (res.status >= 500 || res.status === 408) {\n lastError = new UpstreamError(code, payload.detail, res.status);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // Anything else: not retryable, throw immediately.\n throw new FlowmailsError(code, `Request failed: ${code}`, res.status);\n }\n\n // Shouldn't reach here — last iteration always throws. Type\n // assertion keeps the compiler happy without `any`.\n throw lastError ?? new FlowmailsError(\"unknown\", \"Unknown failure\", 0);\n }\n}\n\n// ---------- Module-level helpers ----------\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Browser-safe base64 of a `Uint8Array`. Avoids pulling in a\n // Buffer polyfill in the worker / browser bundles.\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++) {\n bin += String.fromCharCode(bytes[i]);\n }\n return btoa(bin);\n}\n\nfunction backoffMs(attempt: number): number {\n // Exponential backoff with jitter, capped at 4 s. attempt 0 → 250 ms.\n const base = Math.min(250 * 2 ** attempt, 4_000);\n return base + Math.floor(Math.random() * base);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}"]}
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@flowmails/flowmails-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Official JavaScript / TypeScript SDK for the Flowmails transactional email API (https://sdk.flowmails.net).",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsup",
23
+ "dev": "tsup --watch",
24
+ "typecheck": "tsc -p tsconfig.json --noEmit",
25
+ "clean": "rm -rf dist"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "devDependencies": {
31
+ "tsup": "^8.3.5",
32
+ "typescript": "^5.6.3"
33
+ },
34
+ "engines": {
35
+ "node": ">=18.0.0"
36
+ },
37
+ "license": "MIT"
38
+ }