@lunora/mail 1.0.0-alpha.14 → 1.0.0-alpha.140

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.
Files changed (43) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +3 -3
  3. package/dist/inbound/index.d.mts +340 -89
  4. package/dist/inbound/index.d.ts +340 -89
  5. package/dist/inbound/index.mjs +1 -2
  6. package/dist/index.d.mts +279 -97
  7. package/dist/index.d.ts +279 -97
  8. package/dist/index.mjs +1 -7
  9. package/dist/packem_shared/MailSendError-BYih5mnM.mjs +1 -0
  10. package/dist/packem_shared/assertValidIdempotencyKey-CyJq0nZq.mjs +3 -0
  11. package/dist/packem_shared/authenticatesFrom-UBe_EgRT.mjs +1 -0
  12. package/dist/packem_shared/capture-transport.d-G-OVrGhG.d.mts +170 -0
  13. package/dist/packem_shared/capture-transport.d-G-OVrGhG.d.ts +170 -0
  14. package/dist/packem_shared/consumeQueuedSend-BwNGdlaG.mjs +1 -0
  15. package/dist/packem_shared/createCaptureSink-C489s13k.mjs +1 -0
  16. package/dist/packem_shared/createCaptureTransport-DZhMUmaI.mjs +1 -0
  17. package/dist/packem_shared/createCloudflareTransport-Dxjf_b6q.mjs +1 -0
  18. package/dist/packem_shared/createInboundEmailHandler-BeWkwqF2.mjs +1 -0
  19. package/dist/packem_shared/createMailer-Cv1B9wYq.mjs +1 -0
  20. package/dist/packem_shared/createResendTransport-CsJfCLAP.mjs +1 -0
  21. package/dist/packem_shared/provider-transport-Ce2xVUuM.mjs +1 -0
  22. package/dist/packem_shared/renderEmail-xypKDdux.mjs +1 -0
  23. package/dist/packem_shared/shard-C5t-b7FX.mjs +1 -0
  24. package/dist/packem_shared/{shard.d-C4kxvfmd.d.mts → shard.d-DVADjmEJ.d.mts} +7 -12
  25. package/dist/packem_shared/{shard.d-C4kxvfmd.d.ts → shard.d-DVADjmEJ.d.ts} +7 -12
  26. package/dist/testing.d.mts +9 -9
  27. package/dist/testing.d.ts +9 -9
  28. package/dist/testing.mjs +1 -65
  29. package/package.json +6 -6
  30. package/dist/packem_shared/address-vSUAVU2T.mjs +0 -64
  31. package/dist/packem_shared/capture-transport.d-ChnhdPO2.d.mts +0 -117
  32. package/dist/packem_shared/capture-transport.d-ChnhdPO2.d.ts +0 -117
  33. package/dist/packem_shared/consumeQueuedSend-B9hTDOZ6.mjs +0 -77
  34. package/dist/packem_shared/createCaptureSink-B0c7fQJf.mjs +0 -77
  35. package/dist/packem_shared/createCaptureTransport-Crz_8822.mjs +0 -11
  36. package/dist/packem_shared/createCloudflareTransport-DXh1nUNi.mjs +0 -28
  37. package/dist/packem_shared/createInboundEmailHandler-BMB5t-qh.mjs +0 -74
  38. package/dist/packem_shared/createMailer-B4Z_Cgiu.mjs +0 -81
  39. package/dist/packem_shared/createResendTransport-CMQWjZoi.mjs +0 -16
  40. package/dist/packem_shared/parseInboundEmail-DXVOH0wz.mjs +0 -73
  41. package/dist/packem_shared/provider-transport-C0xHi3oy.mjs +0 -48
  42. package/dist/packem_shared/renderEmail-hyS1bpVP.mjs +0 -8
  43. package/dist/packem_shared/shard-DEDcQoFg.mjs +0 -36
package/dist/index.d.ts CHANGED
@@ -1,20 +1,28 @@
1
- import { M as MailTransport, L as LunoraMailOptions, a as Mailer, b as MailboxSink, S as SendOptions } from "./packem_shared/capture-transport.d-ChnhdPO2.js";
2
- export { type C as CapturedMail, type Q as QueueLike, type c as SendPayload, d as createCaptureTransport } from "./packem_shared/capture-transport.d-ChnhdPO2.js";
3
- import { D as DurableObjectJurisdiction } from "./packem_shared/shard.d-C4kxvfmd.js";
1
+ import { M as MailTransport, L as LunoraMailOptions, a as Mailer, Q as QueueLike, b as MailboxSink, S as SendOptions } from "./packem_shared/capture-transport.d-G-OVrGhG.js";
2
+ export { type C as CapturedMail, type c as SendPayload, d as createCaptureTransport } from "./packem_shared/capture-transport.d-G-OVrGhG.js";
3
+ import { D as DurableObjectJurisdiction } from "./packem_shared/shard.d-DVADjmEJ.js";
4
4
  import { ReactElement } from 'react';
5
+ import { LunoraError } from '@lunora/errors';
5
6
  /**
6
- * Sends a raw RFC 822 message through a Worker's Email send binding. The Workers
7
- * runtime owns the binding, so the caller supplies this thin callback — keeping
8
- * `@lunora/mail` free of a `cloudflare:email` import and unit-testable. Wire it
9
- * in your project as:
10
- *
11
- * ```ts
12
- * send: async (from, to, raw) => {
13
- * const { EmailMessage } = await import("cloudflare:email");
14
- * await env.SEND_EMAIL.send(new EmailMessage(from, to, raw));
15
- * }
16
- * ```
17
- */
7
+ * Refuse a key the provider or a sent-mail store would reject. Run before the
8
+ * store is read: a KV read failing on an over-long key would otherwise surface as
9
+ * a retryable store error and redeliver the message into the dead-letter queue.
10
+ * The same key fails the same way on every attempt, so the refusal is final.
11
+ */
12
+ declare const assertValidIdempotencyKey: (key: unknown) => void;
13
+ /**
14
+ * Sends a raw RFC 822 message through a Worker's Email send binding. The Workers
15
+ * runtime owns the binding, so the caller supplies this thin callback — keeping
16
+ * `@lunora/mail` free of a `cloudflare:email` import and unit-testable. Wire it
17
+ * in your project as:
18
+ *
19
+ * ```ts
20
+ * send: async (from, to, raw) => {
21
+ * const { EmailMessage } = await import("cloudflare:email");
22
+ * await env.SEND_EMAIL.send(new EmailMessage(from, to, raw));
23
+ * }
24
+ * ```
25
+ */
18
26
  type CloudflareSend = (from: string, to: string, raw: string) => Promise<void>;
19
27
  interface CloudflareTransportOptions {
20
28
  /** Default sender used when a `SendOptions.from` isn't supplied. */
@@ -23,75 +31,91 @@ interface CloudflareTransportOptions {
23
31
  send: CloudflareSend;
24
32
  }
25
33
  /**
26
- * Build the default Cloudflare Email Workers transport via `@visulima/email`.
27
- * Cloudflare's `send_email` binding is **single-recipient** and only delivers to
28
- * **verified Email Routing destination addresses**, and the underlying provider
29
- * rejects any `cc`/`bcc` or a non-single `to` outright. So this enforces a single
30
- * `to` recipient (throwing a clear error instead of silently dropping the rest)
31
- * and rejects `cc`/`bcc` rather than forwarding them into a generic "send failed".
32
- * Multi-recipient transactional mail must fan out one send per recipient at the
33
- * call site. In dev the capture transport intercepts before this runs, so the
34
- * verified-address constraint never bites the dev loop.
35
- */
34
+ * Build the default Cloudflare Email Workers transport via `@visulima/email`.
35
+ * Cloudflare's `send_email` binding is **single-recipient** and only delivers to
36
+ * **verified Email Routing destination addresses**, and the underlying provider
37
+ * rejects any `cc`/`bcc` or a non-single `to` outright. So this enforces a single
38
+ * `to` recipient (throwing a clear error instead of silently dropping the rest)
39
+ * and rejects `cc`/`bcc` rather than forwarding them into a generic "send failed".
40
+ * Multi-recipient transactional mail must fan out one send per recipient at the
41
+ * call site. In dev the capture transport intercepts before this runs, so the
42
+ * verified-address constraint never bites the dev loop.
43
+ */
36
44
  declare const createCloudflareTransport: (options: CloudflareTransportOptions) => MailTransport;
37
45
  /**
38
- * Create a mailer bound to a transport.
39
- *
40
- * SECURITY — recipient policy and HTML content are the caller's responsibility.
41
- * The mailer fully blocks header/CRLF/comma injection in addresses
42
- * (`assertSafeAddresses` / `assertSafeHeaderValue`), but it does NOT decide WHO
43
- * you may send to or WHAT HTML you render.
44
- *
45
- * Open relay: derive `to`/`cc`/`bcc` from server-trusted state, never from raw
46
- * request input, and prefer a fixed/allowlisted `from` — sending to an arbitrary
47
- * user-supplied address turns your deployment into a spam relay.
48
- *
49
- * Template XSS / content injection: treat template HTML like any other HTML sink
50
- * — never interpolate untrusted data into raw markup (or a
51
- * `dangerouslySetInnerHTML`-style template) without escaping. The mailer sends
52
- * whatever HTML you hand it verbatim.
53
- */
46
+ * Create a mailer bound to a transport.
47
+ *
48
+ * SECURITY — recipient policy and HTML content are the caller's responsibility.
49
+ * The mailer fully blocks header/CRLF/comma injection in addresses
50
+ * (`assertSafeAddresses` / `assertSafeHeaderValue`), but it does NOT decide WHO
51
+ * you may send to or WHAT HTML you render.
52
+ *
53
+ * Open relay: derive `to`/`cc`/`bcc` from server-trusted state, never from raw
54
+ * request input, and prefer a fixed/allowlisted `from` — sending to an arbitrary
55
+ * user-supplied address turns your deployment into a spam relay.
56
+ *
57
+ * Template XSS / content injection: treat template HTML like any other HTML sink
58
+ * — never interpolate untrusted data into raw markup (or a
59
+ * `dangerouslySetInnerHTML`-style template) without escaping. The mailer sends
60
+ * whatever HTML you hand it verbatim.
61
+ */
54
62
  declare const createMailer: (options: LunoraMailOptions) => Mailer;
55
63
  /** A Worker `env` projected as a plain record (vars, secrets, and bindings are `unknown`-valued). */
56
64
  type MailEnv = Record<string, unknown>;
57
65
  /** Options for {@link createMailerFromEnv}. */
58
66
  interface FromEnvOptions {
59
- /** RFC 822 send callback bound to the Worker's `send_email` binding (Cloudflare default transport). */
67
+ /**
68
+ * RFC 822 send callback bound to the Worker's Cloudflare Email binding (the
69
+ * default transport). Honoured whenever it is passed, whatever the binding is
70
+ * named: passing it is the caller's choice of transport, so pass it only when
71
+ * the binding exists.
72
+ */
60
73
  cloudflareSend?: CloudflareSend;
61
74
  /**
62
- * Pin the captured-mail inbox shard to a Cloudflare data-residency
63
- * jurisdiction. Pass the same value as the worker's `jurisdiction` so the
64
- * dev inbox co-resides with app data. Omit for the un-pinned global namespace.
65
- */
75
+ * Pin the captured-mail inbox shard to a Cloudflare data-residency
76
+ * jurisdiction. Defaults to the jurisdiction the schema declares
77
+ * (`.jurisdiction("eu")`), so a generated app needs nothing here; set it only
78
+ * for a hand-written worker, to the same value as its `jurisdiction`. A value
79
+ * that contradicts the schema's throws.
80
+ */
66
81
  jurisdiction?: DurableObjectJurisdiction;
82
+ /** Cloudflare Queue binding backing `mailer.queue()`; without it `queue()` throws outside capture mode. */
83
+ queue?: QueueLike;
67
84
  /** Shard the captured-mail inbox lives on; override if your worker sets a custom `defaultShardKey`. */
68
85
  rootShard?: string;
86
+ /** `send()` deadline in milliseconds; see `LunoraMailOptions.sendTimeoutMs`. */
87
+ sendTimeoutMs?: number;
69
88
  }
70
89
  /**
71
- * Whether outbound mail should be captured (into the studio inbox) rather than
72
- * delivered. Explicit `LUNORA_MAIL_CAPTURE` (`"1"`/`"true"` vs `"0"`/`"false"`)
73
- * always wins; unset, capture is on only in a development environment. It does
74
- * NOT fall back to "no SEND_EMAIL binding ⇒ capture" — a production deploy that
75
- * forgot the binding must fail loudly on send, not silently swallow mail.
76
- */
90
+ * Whether outbound mail should be captured (into the studio inbox) rather than
91
+ * delivered. Explicit `LUNORA_MAIL_CAPTURE` (`"1"`/`"true"` vs `"0"`/`"false"`)
92
+ * always wins; unset, capture is on only when every set environment var (`CF_ENV`,
93
+ * `ENVIRONMENT`, `NODE_ENV`, `WORKER_ENV`) names a development one. It does
94
+ * NOT fall back to "no SEND_EMAIL binding ⇒ capture" — a production deploy that
95
+ * forgot the binding must fail loudly on send, not silently swallow mail.
96
+ */
77
97
  declare const shouldCaptureMail: (env: MailEnv) => boolean;
78
98
  /**
79
- * Build the {@link MailboxSink} that records a captured message into the studio's
80
- * root-shard inbox via the reserved `recordMail` admin RPC — the same
81
- * worker→root-shard path the runtime uses for auth events. Best-effort: without
82
- * the `SHARD` binding or `LUNORA_ADMIN_TOKEN` it returns a sentinel id so a send
83
- * never fails for lack of somewhere to record.
84
- */
99
+ * Build the {@link MailboxSink} that records a captured message into the studio's
100
+ * root-shard inbox via the reserved `recordMail` admin RPC — the same
101
+ * worker→root-shard path the runtime uses for auth events. Best-effort: without
102
+ * the `SHARD` binding or `LUNORA_ADMIN_TOKEN` it returns a sentinel id so a send
103
+ * never fails for lack of somewhere to record — but it says so first (see below).
104
+ */
85
105
  declare const createCaptureSink: (env: MailEnv, rootShard?: string, jurisdiction?: DurableObjectJurisdiction) => MailboxSink;
86
106
  /**
87
- * Build a {@link Mailer} from a Worker `env`. In a dev environment every send is
88
- * captured into the studio's Mail inbox; otherwise it delivers via the supplied
89
- * `cloudflareSend` (the `SEND_EMAIL` binding) or, failing that, `RESEND_API_KEY`.
90
- * Throws when neither a capture context nor a real transport is available, so a
91
- * misconfigured production deploy fails loudly instead of silently dropping mail.
92
- *
93
- * `MAIL_FROM` is required (the default sender).
94
- */
107
+ * Build a {@link Mailer} from a Worker `env`. In a dev environment every send is
108
+ * captured into the studio's Mail inbox; otherwise it delivers via the supplied
109
+ * `cloudflareSend` (when passed) or,
110
+ * failing that, `RESEND_API_KEY`. With no real transport `send()` rejects, so a
111
+ * misconfigured production deploy fails loudly instead of silently dropping mail
112
+ * — while `queue()` still works for a producer-only worker.
113
+ *
114
+ * A queue consumer should build its mailer here too: `consumeQueuedSend` goes
115
+ * through `send()`, so in dev queued mail is captured at consume time.
116
+ *
117
+ * `MAIL_FROM` is required (the default sender).
118
+ */
95
119
  declare const createMailerFromEnv: (env: MailEnv, options?: FromEnvOptions) => Mailer;
96
120
  /** Serializable representation of a `SendOptions` payload — drops the `react` field. */
97
121
  interface QueuedSend {
@@ -100,51 +124,209 @@ interface QueuedSend {
100
124
  from?: string;
101
125
  headers?: Record<string, string>;
102
126
  html?: string;
127
+ /**
128
+ * Stable dedup key, minted at enqueue time by `createMailer(...).queue()` — see
129
+ * `SendOptions.idempotencyKey`. `consumeQueuedSend` dedupes on it when given a
130
+ * `sent` store, and forwards it to the provider.
131
+ */
132
+ idempotencyKey?: string;
103
133
  replyTo?: string;
104
134
  subject: string;
105
135
  text?: string;
106
136
  to: string | string[];
107
137
  }
108
138
  /**
109
- * Narrow a `SendOptions` to its serializable `QueuedSend` shape by dropping the
110
- * non-cloneable `react` field. React elements are not structured-cloneable, so
111
- * the queue body must carry only the pre-rendered html/text and scalar fields.
112
- */
139
+ * Narrow a `SendOptions` to its serializable `QueuedSend` shape by dropping the
140
+ * non-cloneable `react` field. React elements are not structured-cloneable, so
141
+ * the queue body must carry only the pre-rendered html/text and scalar fields.
142
+ */
113
143
  declare const toQueuedPayload: (options: SendOptions) => QueuedSend;
114
144
  /**
115
- * Helper used by Queue consumers: rehydrate a `QueuedSend` payload and forward
116
- * to a configured `Mailer.send()`. Use this inside your Worker's `queue()`
117
- * handler.
118
- *
119
- * ```ts
120
- * export default {
121
- * queue: async (batch, env) => {
122
- * const mailer = createMailer({ apiKey: env.RESEND_API_KEY, from: "..." });
123
- * for (const message of batch.messages) {
124
- * await consumeQueuedSend(mailer, message.body);
125
- * }
126
- * },
127
- * };
128
- * ```
129
- */
130
- declare const consumeQueuedSend: (mailer: Mailer, payload: unknown) => Promise<{
145
+ * Where {@link consumeQueuedSend} records the idempotency keys it has already
146
+ * sent, mapped to the provider's message id. Shaped after Workers KV's
147
+ * `get` / `put`, so a `KVNamespace` binding passes as-is; a Durable Object or
148
+ * D1-backed adapter works too. Only a string from `get` counts as sent, so an
149
+ * adapter may answer a missing key with `null` (KV) or `undefined` (Durable
150
+ * Object storage).
151
+ */
152
+ interface SentMailStore {
153
+ get: (key: string) => Promise<string | null | undefined>;
154
+ put: (key: string, value: string, options: {
155
+ expirationTtl: number;
156
+ }) => Promise<void>;
157
+ }
158
+ interface ConsumeQueuedSendOptions {
159
+ /**
160
+ * Which delivery of the message this is: pass the Cloudflare Queues `message.attempts` (1 for the first). Used
161
+ * without a `sent` store, where every redelivery follows a send that reached the provider: one older than the
162
+ * provider's dedupe window (`enqueuedAt`) is then refused before any request. With a store, the marks it keeps per
163
+ * delivery decide instead, so a delivery that failed before the send (the store was down) is still sent.
164
+ */
165
+ attempts?: number;
166
+ /**
167
+ * When the message was first enqueued: pass the Cloudflare Queues
168
+ * `message.timestamp`. Resend drops a repeated key for only 24 hours, so an
169
+ * outcome-unknown failure of a message older than 23 hours is not retryable,
170
+ * because a redelivery could then mail a second copy. Without it, nothing
171
+ * tracks that window.
172
+ */
173
+ enqueuedAt?: Date;
174
+ /**
175
+ * Collapse redeliveries: a message whose `idempotencyKey` is already in the
176
+ * store is acknowledged without a second send, and a sent message's key is
177
+ * recorded here. With a store, a body without an `idempotencyKey` is refused.
178
+ * Passing the key with an `undefined` value (an unbound `env.SENT`) logs a
179
+ * warning on every call, because dedupe is then off.
180
+ */
181
+ sent?: SentMailStore;
182
+ /**
183
+ * How long a sent key is remembered, in whole seconds, at least 60 (default
184
+ * 86 400), the range Workers KV accepts. A redelivery later than this sends
185
+ * again. Anything else fails every message as a retryable `MailSendError`.
186
+ */
187
+ sentTtlSeconds?: number;
188
+ }
189
+ /**
190
+ * Helper used by Queue consumers: validate a `QueuedSend` body and send it
191
+ * through `mailer.send()`. Use it inside your Worker's `queue()` handler, and
192
+ * `ack()` each message it settles.
193
+ *
194
+ * Pass `sent` (a KV namespace, or anything shaped like one) to collapse
195
+ * Cloudflare Queues' at-least-once redelivery: a key already in the store
196
+ * returns its recorded id with `deduplicated: true` and sends nothing, and a
197
+ * successful send records its key. Only a success is recorded, so a retryable
198
+ * or outcome-unknown failure never blocks a later attempt. Beside the key it
199
+ * keeps attempt marks, one pair per delivery `n` (pass `attempts`): `sending`
200
+ * just before it asks the provider, `failed` once that send is known not to have
201
+ * gone out, each under its own key and kept 15 days. A redelivery past the
202
+ * provider's dedupe window is refused while any earlier delivery has `sending`
203
+ * without `failed`, so a message whose earlier deliveries never reached the
204
+ * provider is still sent; a mark that cannot be written fails the send as
205
+ * retryable. A store that cannot
206
+ * be read, or does not answer within 10 seconds, fails the send as retryable,
207
+ * since nothing has gone out; a store that cannot be written after the send, or
208
+ * does not answer within 10 seconds, is logged and the id still returned, because throwing then would redeliver a
209
+ * message the provider already accepted.
210
+ *
211
+ * This NARROWS the duplicate window; it does not close it, and nothing on this
212
+ * path can. The mark is written after the provider accepted the message, so a
213
+ * crash in between still redelivers and resends, and a KV read is eventually
214
+ * consistent — a redelivery seconds later can miss a mark that was written.
215
+ * Delivery is at-least-once end to end. An app that must not double-send needs a
216
+ * strongly-consistent mark taken BEFORE the send (a Durable Object or D1 row
217
+ * claimed by this key, released on failure), and even then the send-then-crash
218
+ * window is only ever traded for a send-that-may-not-have-happened one. With
219
+ * Resend the key also travels as the `Idempotency-Key` request header, so Resend
220
+ * itself drops a repeat inside its own 24-hour window; pass `enqueuedAt` and
221
+ * `attempts` so a send that may have landed is not repeated once that window is
222
+ * nearly over.
223
+ *
224
+ * ```ts
225
+ * export default {
226
+ * queue: async (batch, env) => {
227
+ * // createMailerFromEnv, so dev captures the message here instead of sending it.
228
+ * const mailer = createMailerFromEnv(env);
229
+ * for (const message of batch.messages) {
230
+ * try {
231
+ * await consumeQueuedSend(mailer, message.body, { attempts: message.attempts, enqueuedAt: message.timestamp, sent: env.SENT });
232
+ * } catch (error) {
233
+ * // Transient, or a send that may have landed with a provider that dedupes on the key (Resend).
234
+ * if (isRetryableMailError(error)) {
235
+ * // The first attempt may still be running at the provider (Resend's client keeps a request
236
+ * // going for about two minutes), so give it time: a repeat inside that window is a 409.
237
+ * message.retry(isOutcomeUnknownMailError(error) ? { delaySeconds: 180 } : undefined);
238
+ * continue;
239
+ * }
240
+ *
241
+ * // A timeout no provider dedupes may have been delivered, so a retry could send a second
242
+ * // copy: check the provider's logs. Anything else is a refusal or a malformed body.
243
+ * console.error(isOutcomeUnknownMailError(error) ? "mail outcome unknown" : "mail refused", error);
244
+ * message.ack();
245
+ * continue;
246
+ * }
247
+ * // Per message: without it a single throw retries the whole batch.
248
+ * message.ack();
249
+ * }
250
+ * },
251
+ * };
252
+ * ```
253
+ */
254
+ declare const consumeQueuedSend: (mailer: Mailer, payload: unknown, options?: ConsumeQueuedSendOptions) => Promise<{
255
+ deduplicated: boolean;
131
256
  id: string;
132
257
  }>;
133
258
  /**
134
- * Render a React element to an HTML/text pair suitable for inlining into a
135
- * provider payload. Wraps `@react-email/render` so we can swap to
136
- * `@visulima/email`'s react-email template engine without touching callers.
137
- */
259
+ * Render a React element to an HTML/text pair suitable for inlining into a
260
+ * provider payload. Wraps `@react-email/render` so we can swap to
261
+ * `@visulima/email`'s react-email template engine without touching callers.
262
+ *
263
+ * The renderer is imported lazily so its top-level evaluation (prettier and
264
+ * html-to-text, in its workerd build) is deferred until the first React render
265
+ * instead of running on cold start. Bundlers may still include the code.
266
+ */
138
267
  declare const renderEmail: (element: ReactElement) => Promise<{
139
268
  html: string;
140
269
  text: string;
141
270
  }>;
142
271
  /**
143
- * Build a Resend-backed transport via `@visulima/email`. Wraps the provider's
144
- * `sendEmail()` into the minimal `{ send(payload) -> { id } }` shape the rest of
145
- * `@lunora/mail` consumes. Kept reachable as a named export so a project that
146
- * prefers Resend over the Cloudflare default can pass
147
- * `transport: createResendTransport(apiKey, from)` to `createMailer`.
148
- */
272
+ * Build a Resend-backed transport via `@visulima/email`. Wraps the provider's
273
+ * `sendEmail()` into the minimal `{ send(payload) -> { id } }` shape the rest of
274
+ * `@lunora/mail` consumes. Kept reachable as a named export so a project that
275
+ * prefers Resend over the Cloudflare default can pass
276
+ * `transport: createResendTransport(apiKey, from)` to `createMailer`.
277
+ */
149
278
  declare const createResendTransport: (apiKey: string, defaultFrom: string) => MailTransport;
150
- export { type CloudflareSend, type CloudflareTransportOptions, type FromEnvOptions, type LunoraMailOptions, type MailEnv, type MailTransport, type MailboxSink, type Mailer, type QueuedSend, type SendOptions, consumeQueuedSend, createCaptureSink, createCloudflareTransport, createMailer, createMailerFromEnv, createResendTransport, renderEmail, shouldCaptureMail, toQueuedPayload };
279
+ /** What a {@link MailSendError} carries on `data`, so a caller can tell a retry from a refusal. */
280
+ interface MailSendErrorData {
281
+ /**
282
+ * The send was cut off before the provider answered (the mailer's send deadline, or the
283
+ * provider's own request timeout), or the provider is still processing an earlier send under
284
+ * the same idempotency key (Resend's 409), so it may have been delivered. `retryable` is then true
285
+ * only when the send carried an idempotency key and its transport's provider dedupes on it
286
+ * (`MailTransport.dedupesOnIdempotencyKey`), so a repeat cannot mail a second copy, and
287
+ * `consumeQueuedSend` clears it again for a message older than that provider's dedupe window.
288
+ */
289
+ outcomeUnknown: boolean;
290
+ /** Whether repeating the same message may succeed. A refused address or malformed message never will. */
291
+ retryable: boolean;
292
+ }
293
+ /**
294
+ * A send that did not deliver. `retryable` is the decision a queue consumer
295
+ * needs: a send is a refusal only when the provider answered with an explicit
296
+ * permanent HTTP status (anything but 408, 429 and 5xx); every other failure may
297
+ * clear on a redelivery. Retrying a refusal only drains the queue into its
298
+ * dead-letter queue.
299
+ *
300
+ * A send that timed out is `outcomeUnknown`: the provider may have accepted it.
301
+ * It is `retryable` only when the transport forwarded the send's idempotency key
302
+ * to a provider that dedupes on it (Resend), so the repeat is dropped if the
303
+ * first one landed. Otherwise a queue consumer acks and reports it rather than
304
+ * mailing the recipient a second copy.
305
+ */
306
+ declare class MailSendError extends LunoraError {
307
+ static override [Symbol.hasInstance](value: unknown): boolean;
308
+ readonly outcomeUnknown: boolean;
309
+ readonly retryable: boolean;
310
+ constructor(options: {
311
+ cause?: unknown;
312
+ message?: string;
313
+ outcomeUnknown?: boolean;
314
+ retryable: boolean;
315
+ });
316
+ }
317
+ /**
318
+ * Whether a failed send is worth a queue redelivery. Only an error the mail
319
+ * path classified as retryable qualifies. Everything else, including the
320
+ * shape-check refusals `consumeQueuedSend` throws before any provider call, is
321
+ * a message that will never send.
322
+ */
323
+ declare const isRetryableMailError: (error: unknown) => boolean;
324
+ /**
325
+ * Whether a failed send may nonetheless have been delivered — it timed out
326
+ * before the provider answered, or the provider is still processing an earlier
327
+ * send under its key. Check {@link isRetryableMailError} first: a
328
+ * retryable one is safe to redeliver because the provider dedupes on its key.
329
+ * One that is not must be reported (check the provider's logs), not resent.
330
+ */
331
+ declare const isOutcomeUnknownMailError: (error: unknown) => boolean;
332
+ export { type CloudflareSend, type CloudflareTransportOptions, type ConsumeQueuedSendOptions, type FromEnvOptions, type LunoraMailOptions, type MailEnv, MailSendError, type MailSendErrorData, type MailTransport, type MailboxSink, type Mailer, type QueueLike, type QueuedSend, type SendOptions, type SentMailStore, assertValidIdempotencyKey, consumeQueuedSend, createCaptureSink, createCloudflareTransport, createMailer, createMailerFromEnv, createResendTransport, isOutcomeUnknownMailError, isRetryableMailError, renderEmail, shouldCaptureMail, toQueuedPayload };
package/dist/index.mjs CHANGED
@@ -1,7 +1 @@
1
- export { createCaptureTransport } from './packem_shared/createCaptureTransport-Crz_8822.mjs';
2
- export { createCloudflareTransport } from './packem_shared/createCloudflareTransport-DXh1nUNi.mjs';
3
- export { default as createMailer } from './packem_shared/createMailer-B4Z_Cgiu.mjs';
4
- export { createCaptureSink, createMailerFromEnv, shouldCaptureMail } from './packem_shared/createCaptureSink-B0c7fQJf.mjs';
5
- export { consumeQueuedSend, toQueuedPayload } from './packem_shared/consumeQueuedSend-B9hTDOZ6.mjs';
6
- export { default as renderEmail } from './packem_shared/renderEmail-hyS1bpVP.mjs';
7
- export { default as createResendTransport } from './packem_shared/createResendTransport-CMQWjZoi.mjs';
1
+ import{assertValidIdempotencyKey as o}from"./packem_shared/assertValidIdempotencyKey-CyJq0nZq.mjs";import{createCaptureTransport as t}from"./packem_shared/createCaptureTransport-DZhMUmaI.mjs";import{createCloudflareTransport as p}from"./packem_shared/createCloudflareTransport-Dxjf_b6q.mjs";import{default as m}from"./packem_shared/createMailer-Cv1B9wYq.mjs";import{createCaptureSink as u,createMailerFromEnv as f,shouldCaptureMail as s}from"./packem_shared/createCaptureSink-C489s13k.mjs";import{consumeQueuedSend as c,toQueuedPayload as x}from"./packem_shared/consumeQueuedSend-BwNGdlaG.mjs";import{default as E}from"./packem_shared/renderEmail-xypKDdux.mjs";import{default as C}from"./packem_shared/createResendTransport-CsJfCLAP.mjs";import{MailSendError as T,isOutcomeUnknownMailError as k,isRetryableMailError as Q}from"./packem_shared/MailSendError-BYih5mnM.mjs";export{T as MailSendError,o as assertValidIdempotencyKey,c as consumeQueuedSend,u as createCaptureSink,t as createCaptureTransport,p as createCloudflareTransport,m as createMailer,f as createMailerFromEnv,C as createResendTransport,k as isOutcomeUnknownMailError,Q as isRetryableMailError,E as renderEmail,s as shouldCaptureMail,x as toQueuedPayload};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";const t=Symbol.for("@lunora/mail/MailSendError");class o extends c{static[Symbol.hasInstance](e){return typeof e=="object"&&e!==null&&e[t]===!0}outcomeUnknown;retryable;constructor(e){const n=e.outcomeUnknown??!1,a={outcomeUnknown:n,retryable:e.retryable};super("INTERNAL",e.message??"@lunora/mail: send failed",{cause:e.cause,data:a,name:"MailSendError"}),Object.defineProperty(this,t,{value:!0}),this.outcomeUnknown=n,this.retryable=e.retryable}}const s=r=>r instanceof o&&r.retryable,u=r=>r instanceof o&&r.outcomeUnknown;export{o as MailSendError,u as isOutcomeUnknownMailError,s as isRetryableMailError};
@@ -0,0 +1,3 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{MailSendError as c}from"./MailSendError-BYih5mnM.mjs";const o=320,l=256,f=/^([^<]*)<([^>]*)>\s*$/,a=(t,r)=>{if(r.includes("\r")||r.includes(`
2
+ `)||r.includes(","))throw new s("INTERNAL",`@lunora/mail: address ${t} must not contain CR, LF, or comma`)},g=(t,r)=>{if(r.includes("\r")||r.includes(`
3
+ `))throw new s("INTERNAL",`@lunora/mail: ${t} must not contain CR or LF`)},d=(t,r)=>{if(t.length>l)throw new s("INTERNAL",`@lunora/mail: address name must be <= ${String(l)} characters`);if(r.length>o)throw new s("INTERNAL",`@lunora/mail: address email must be <= ${String(o)} characters`);return t&&a("name",t),a("email",r),t?{email:r,name:t}:{email:r}},u=t=>{const r=t.trim();if(r.length>o)throw new s("INTERNAL",`@lunora/mail: address email must be <= ${String(o)} characters`);return a("email",r),{email:r}},m=t=>{const r=f.exec(t),e=(r?.[2]??"").trim();return r&&e?d((r[1]??"").trim(),e):u(t)},i=t=>{if(t===void 0)return;const r=Array.isArray(t)?t:[t];if(r.length!==0)return r.map(e=>m(e))},w=t=>{if(i(t.to)===void 0)throw new s("INTERNAL","@lunora/mail: at least one recipient is required");i(t.cc),i(t.bcc),t.from!==void 0&&m(t.from),t.replyTo!==void 0&&m(t.replyTo)},h=/^[\u0021-\u007E]{1,256}$/u,N=t=>{if(t!==void 0&&(typeof t!="string"||!h.test(t)||t==="."||t===".."))throw new c({message:"@lunora/mail: `idempotencyKey` must be a string of 1-256 visible ASCII characters, other than `.` or `..`",retryable:!1})},T=t=>{for(const n of["html","text"])if(t[n]!==void 0&&typeof t[n]!="string")throw new c({message:`@lunora/mail: \`${n}\` must be a string, got ${typeof t[n]}`,retryable:!1});const r=typeof t.text=="string"&&t.text!=="",e=typeof t.html=="string"&&t.html!=="";if(!r&&!e)throw new c({message:"@lunora/mail: a message needs `text` or `html` content (or `react` to render them)",retryable:!1})};export{T as assertHasContent,w as assertSafeAddresses,g as assertSafeHeaderValue,N as assertValidIdempotencyKey,m as toAddress,i as toAddressList};
@@ -0,0 +1 @@
1
+ import l from"postal-mime";import{assertSafeHeaderValue as c}from"./assertValidIdempotencyKey-CyJq0nZq.mjs";const d=(s,e)=>{if(e!==void 0)return c(`inbound ${s}`,e),e},p=s=>s===null?s:s==="inline"?"inline":"attachment",f=s=>s.address!==void 0&&s.address!==""?s.name?`${s.name} <${s.address}>`:s.address:s.group?s.group.map(e=>e.address??"").filter(e=>e!=="").join(", "):s.name??"",g=/"(?:[^"\\]|\\.)*(?:"|$)|\((?:[^()\\]|\\.)*(?:\)|$)/g,v=s=>s.replaceAll(g,e=>e.startsWith('"')?e.replaceAll(/[;=]/gu," "):" "),m=(s,e,n)=>{const i=v(s).matchAll(new RegExp(String.raw`(?:^|;)\s*${e}\s*(?:/\s*\d+\s*)?=\s*([a-z]+)([^;]*)`,"gi")),a=new RegExp(String.raw`\b${n.split(".").join(String.raw`\s*\.\s*`)}\s*=\s*"?([^\s;"]+)`,"i");return[...i].map(o=>{const t=a.exec(o[2]??"")?.[1];return{domain:t===void 0?null:t.slice(t.lastIndexOf("@")+1).toLowerCase(),result:(o[1]??"").toLowerCase()}})},h=s=>s===void 0||s===""?{dkim:[],dmarc:[],spf:[]}:{dkim:m(s,"dkim","header.d"),dmarc:m(s,"dmarc","header.from"),spf:m(s,"spf","smtp.mailfrom")},$=async s=>{const e=await l.parse(s),n={};for(const r of e.headers)c(`inbound header \`${r.key}\``,r.value),n[r.key]=r.value;const i=e.headers.find(r=>r.key==="authentication-results")?.value,a=(e.to??[]).map(r=>{const u=f(r);return c("inbound to",u),u}),o=e.from?f(e.from):"";return c("inbound from",o),{attachments:e.attachments.map(r=>({content:r.content,disposition:p(r.disposition),...r.encoding===void 0?{}:{encoding:r.encoding},filename:r.filename,mimeType:r.mimeType})),authentication:h(i),from:o,headers:n,...e.html===void 0?{}:{html:e.html},...d("inReplyTo",e.inReplyTo)===void 0?{}:{inReplyTo:e.inReplyTo},...d("messageId",e.messageId)===void 0?{}:{messageId:e.messageId},...d("references",e.references)===void 0?{}:{references:e.references},...d("subject",e.subject)===void 0?{}:{subject:e.subject},...e.text===void 0?{}:{text:e.text},to:a}},x=/<([^<>]*)>$/,b=s=>{const e=x.exec(s)?.[1]??s,n=e.indexOf("@");if(!(n===-1||n!==e.lastIndexOf("@")))return e.slice(n+1).trim().toLowerCase()},T=s=>{const e=b(s.from);if(e===void 0)return!1;const n=t=>t.some(r=>r.result==="pass"&&r.domain===e),{dkim:i,dmarc:a,spf:o}=s.authentication;return n(a)||n(o)||n(i)};export{T as authenticatesFrom,$ as parseInboundEmail};
@@ -0,0 +1,170 @@
1
+ import { ReactElement } from 'react';
2
+ /**
3
+ * Minimal projection of a Cloudflare Queue binding — accepts a JSON payload
4
+ * via `.send()`. Declared structurally so callers can pass either the real
5
+ * `Queue` binding or a unit-test double.
6
+ */
7
+ interface QueueLike {
8
+ send: (payload: unknown, options?: Record<string, unknown>) => Promise<void>;
9
+ }
10
+ /**
11
+ * Minimal projection of a transport adapter. Returning `{ id }` follows
12
+ * Resend's response shape; the real `@visulima/email` `MailManager` flattens
13
+ * provider responses to the same field for us.
14
+ */
15
+ interface MailTransport {
16
+ /**
17
+ * The provider drops a repeat of a send carrying the same `idempotencyKey`, so a
18
+ * send that may have landed is safe to retry when it carried one. Set only by a
19
+ * transport that forwards the key to such a provider (the Resend transport).
20
+ *
21
+ * A transport reports a send that may have landed by throwing
22
+ * `MailSendError({ outcomeUnknown: true, retryable: false })` and leaves the
23
+ * retry decision to `createMailer`'s `send()`, which makes it retryable when this
24
+ * flag is set and the send had a key, and not retryable otherwise, whatever the
25
+ * transport said.
26
+ */
27
+ dedupesOnIdempotencyKey?: boolean;
28
+ /**
29
+ * `options.idempotencyKey` is the send's stable dedupe key, when it has one. A
30
+ * transport whose provider dedupes on a key forwards it (the Resend transport
31
+ * sends it as the `Idempotency-Key` request header); others ignore it. It is
32
+ * never a message header.
33
+ */
34
+ send: (payload: SendPayload, options?: {
35
+ idempotencyKey?: string;
36
+ }) => Promise<{
37
+ id: string;
38
+ }>;
39
+ }
40
+ interface SendPayload {
41
+ bcc?: string[];
42
+ cc?: string[];
43
+ from?: string;
44
+ headers?: Record<string, string>;
45
+ html?: string;
46
+ replyTo?: string;
47
+ subject: string;
48
+ text?: string;
49
+ to: string | string[];
50
+ }
51
+ interface SendOptions {
52
+ bcc?: string[];
53
+ cc?: string[];
54
+ from?: string;
55
+ headers?: Record<string, string>;
56
+ html?: string;
57
+ /**
58
+ * Stable key for deduping a send across retries and Cloudflare Queues'
59
+ * at-least-once redelivery: 1-256 visible ASCII characters, other than `.` and
60
+ * `..` (Workers KV refuses both as key names). When omitted,
61
+ * `queue()` generates one at enqueue time so it survives redelivery (a key
62
+ * minted in the consumer would change on every retry, defeating the point).
63
+ * `consumeQueuedSend` dedupes on it when given a `sent` store, and the transport
64
+ * receives it: Resend dedupes on it as the `Idempotency-Key` request header, while
65
+ * the Cloudflare binding has no such hook and ignores it. See
66
+ * `consumeQueuedSend` for why that is a narrowed at-least-once rather than
67
+ * exactly-once.
68
+ *
69
+ * A key names one message, not one recipient: Resend never delivers a repeat
70
+ * of it within 24 hours, so a key reused for a new message
71
+ * (`verify:${userId}`) loses that message.
72
+ */
73
+ idempotencyKey?: string;
74
+ react?: ReactElement;
75
+ replyTo?: string;
76
+ subject: string;
77
+ text?: string;
78
+ to: string | string[];
79
+ }
80
+ interface LunoraMailOptions {
81
+ /** API key for the Resend transport (bring-your-own-provider). Ignored when `transport` or `cloudflareSend` is set. */
82
+ apiKey?: string;
83
+ /**
84
+ * RFC 822 send callback bound to the Worker's `send_email` binding. When set
85
+ * (and no explicit `transport` is supplied) the default transport is
86
+ * Cloudflare Email Workers — Lunora's default provider. Ignored when
87
+ * `transport` is set.
88
+ */
89
+ cloudflareSend?: (from: string, to: string, raw: string) => Promise<void>;
90
+ /** Default sender (`Name <addr@host>` or bare email). */
91
+ from: string;
92
+ /** Default queue binding for `mailer.queue()`. */
93
+ queue?: QueueLike;
94
+ /**
95
+ * How long `send()` waits for the transport before giving up, in milliseconds
96
+ * (default 60 000, at most 2 147 483 647, `setTimeout`'s limit). A send cut off here may still have been delivered, so it
97
+ * fails with an `outcomeUnknown` `MailSendError`. It is retryable only when the
98
+ * send carried an `idempotencyKey` and the transport's provider dedupes on it
99
+ * (Resend); otherwise a queue consumer acks and reports it instead of
100
+ * redelivering a possible duplicate. The transport's own work is not
101
+ * cancelled — the Cloudflare binding and the provider client take no abort
102
+ * signal.
103
+ *
104
+ * Resend's HTTP client has its own clock: it aborts each request after 30
105
+ * seconds (`ETIMEDOUT`, outcome-unknown the same way and never repeated by the
106
+ * client) and repeats a 408, 429 or 503 up to three times, so one Resend send
107
+ * can keep running for about two minutes after this deadline has failed it.
108
+ */
109
+ sendTimeoutMs?: number;
110
+ /** Override the underlying transport. Useful for tests, the dev capture transport, + multi-provider setups. */
111
+ transport?: MailTransport;
112
+ }
113
+ interface Mailer {
114
+ queue: (options: SendOptions) => Promise<{
115
+ queued: true;
116
+ }>;
117
+ send: (options: SendOptions) => Promise<{
118
+ id: string;
119
+ }>;
120
+ }
121
+ /**
122
+ * One captured outbound message as persisted by the dev mail catcher. Extends
123
+ * the rendered, validated {@link SendPayload} with an `id` and a capture
124
+ * timestamp assigned by the sink (the root-shard mailbox), so the studio inbox
125
+ * can list and open it.
126
+ *
127
+ * **Canonical captured-mail wire type — single source of truth.** Every other
128
+ * representation of a captured message mirrors this shape; consumers import it
129
+ * directly wherever the package dependency direction allows.
130
+ *
131
+ * `@lunora/studio`'s `CapturedMail` re-exports this (type-only dep on
132
+ * `@lunora/mail`). `@lunora/do`'s `CapturedMailRow` / `RecordMailInput` are
133
+ * documented mirrors — the DO runtime stays free of any `@lunora/mail` *runtime*
134
+ * dep — guarded by a compile-time structural assertion against this type, so a
135
+ * field added here that isn't mirrored fails the `@lunora/do` build.
136
+ *
137
+ * Add or change a captured-mail field here first; the guards will point at the
138
+ * mirrors that need the matching change.
139
+ */
140
+ interface CapturedMail extends SendPayload {
141
+ /** Epoch-ms the message was captured. */
142
+ capturedAt: number;
143
+ /** Stable id assigned to the captured message. */
144
+ id: string;
145
+ }
146
+ /**
147
+ * Minimal projection of the persistence target the capture transport writes to
148
+ * (the studio's root-shard mailbox). Declared structurally — like
149
+ * {@link import("./types").QueueLike} — so `@lunora/mail` stays free of any
150
+ * Durable Object / runtime dependency. The registry scaffold supplies the
151
+ * concrete sink that POSTs to the root shard's `__lunora_admin__:recordMail` RPC.
152
+ */
153
+ interface MailboxSink {
154
+ record: (mail: SendPayload) => Promise<{
155
+ id: string;
156
+ }>;
157
+ }
158
+ /**
159
+ * Build a capture {@link MailTransport}: instead of delivering, it persists the
160
+ * fully rendered + validated payload to `sink` and returns the assigned id.
161
+ *
162
+ * Wired in dev by the mail registry scaffold so `lunora dev` shows every send in
163
+ * the studio's Mail inbox — including `@lunora/auth`'s verification and
164
+ * forgot-password mail — with no provider credentials and nothing leaving the
165
+ * machine. Address/header validation already ran in `createMailer.buildPayload`
166
+ * before the payload reaches here, so the captured message is the same one a
167
+ * real transport would have sent.
168
+ */
169
+ declare const createCaptureTransport: (sink: MailboxSink) => MailTransport;
170
+ export { CapturedMail as C, LunoraMailOptions as L, MailTransport as M, QueueLike as Q, SendOptions as S, Mailer as a, MailboxSink as b, SendPayload as c, createCaptureTransport as d };