@lunora/mail 1.0.0-alpha.137 → 1.0.0-alpha.139

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 (29) hide show
  1. package/dist/inbound/index.d.mts +17 -3
  2. package/dist/inbound/index.d.ts +17 -3
  3. package/dist/inbound/index.mjs +1 -1
  4. package/dist/index.d.mts +118 -33
  5. package/dist/index.d.ts +118 -33
  6. package/dist/index.mjs +1 -1
  7. package/dist/packem_shared/MailSendError-BYih5mnM.mjs +1 -0
  8. package/dist/packem_shared/address-BKzIBZxE.mjs +3 -0
  9. package/dist/packem_shared/{authenticatesFrom-BDGSL3q4.mjs → authenticatesFrom-DCtlMHNq.mjs} +1 -1
  10. package/dist/packem_shared/{capture-transport.d-BD67fxbB.d.ts → capture-transport.d-G-OVrGhG.d.mts} +51 -11
  11. package/dist/packem_shared/{capture-transport.d-BD67fxbB.d.mts → capture-transport.d-G-OVrGhG.d.ts} +51 -11
  12. package/dist/packem_shared/consumeQueuedSend-CDDDeoAz.mjs +1 -0
  13. package/dist/packem_shared/createCaptureSink-CEqX4_iD.mjs +1 -0
  14. package/dist/packem_shared/{createCloudflareTransport-fOhfy2fP.mjs → createCloudflareTransport-2pH3460e.mjs} +1 -1
  15. package/dist/packem_shared/createInboundEmailHandler-BeWkwqF2.mjs +1 -0
  16. package/dist/packem_shared/createMailer-DuQciU65.mjs +1 -0
  17. package/dist/packem_shared/createResendTransport-DdsftR55.mjs +1 -0
  18. package/dist/packem_shared/provider-transport-C-ioZWVF.mjs +1 -0
  19. package/dist/testing.d.mts +1 -1
  20. package/dist/testing.d.ts +1 -1
  21. package/package.json +1 -1
  22. package/dist/packem_shared/MailSendError-HH5Yimut.mjs +0 -1
  23. package/dist/packem_shared/address-oKy_d0aG.mjs +0 -3
  24. package/dist/packem_shared/consumeQueuedSend-CRfALnCU.mjs +0 -1
  25. package/dist/packem_shared/createCaptureSink-BSAR1HTL.mjs +0 -1
  26. package/dist/packem_shared/createInboundEmailHandler-CixBJpmc.mjs +0 -1
  27. package/dist/packem_shared/createMailer-C5NIzkNb.mjs +0 -1
  28. package/dist/packem_shared/createResendTransport-q3surKen.mjs +0 -1
  29. package/dist/packem_shared/provider-transport-DklK6xUa.mjs +0 -1
@@ -162,6 +162,11 @@ interface ForwardableEmailMessageLike {
162
162
  readonly headers: Headers;
163
163
  /** Stream of the raw RFC 822 message content. */
164
164
  readonly raw: ReadableStream<Uint8Array>;
165
+ /**
166
+ * Size of `raw` in bytes. Cloudflare always sets it; a message without a finite
167
+ * size is refused by the handler's size guard rather than read unbounded.
168
+ */
169
+ readonly rawSize: number;
165
170
  /** Reply to the sender with a new message. */
166
171
  reply: (message: {
167
172
  from: string;
@@ -222,10 +227,19 @@ interface InboundEmailHandlerOptions<TEnv = Record<string, unknown>> {
222
227
  /** Routes the parsed message onward (e.g. {@link dispatchToLunoraFunction}). */
223
228
  dispatch: InboundDispatch<TEnv>;
224
229
  /**
225
- * Called when `parse`, `verify`, or `dispatch` fails — but with two DIFFERENT
226
- * contracts, because only the first two decide the message's fate here:
230
+ * Largest message, in bytes (`message.rawSize`), the handler parses; anything
231
+ * bigger is refused through `onError` before a byte of it is read. Default
232
+ * 10 MiB. Parsing holds the raw bytes, the decoded parts and every attachment
233
+ * at once, so a message near Email Routing's 25 MiB ceiling can outgrow the
234
+ * isolate's 128 MB. Must be a positive, finite number.
235
+ */
236
+ maxRawBytes?: number;
237
+ /**
238
+ * Called when the size guard (`maxRawBytes`), `parse`, `verify`, or `dispatch`
239
+ * fails — but with two DIFFERENT contracts, because only the first three decide
240
+ * the message's fate here:
227
241
  *
228
- * - `parse` / `verify` — this hook DECIDES the outcome. The default
242
+ * - size / `parse` / `verify` — this hook DECIDES the outcome. The default
229
243
  * ({@link rejectOnError}) rejects via `message.setReject`; supplying your own
230
244
  * replaces that, so the message is accepted unless you reject it yourself.
231
245
  * - `dispatch` — this hook is OBSERVABILITY ONLY. It is called for the side
@@ -162,6 +162,11 @@ interface ForwardableEmailMessageLike {
162
162
  readonly headers: Headers;
163
163
  /** Stream of the raw RFC 822 message content. */
164
164
  readonly raw: ReadableStream<Uint8Array>;
165
+ /**
166
+ * Size of `raw` in bytes. Cloudflare always sets it; a message without a finite
167
+ * size is refused by the handler's size guard rather than read unbounded.
168
+ */
169
+ readonly rawSize: number;
165
170
  /** Reply to the sender with a new message. */
166
171
  reply: (message: {
167
172
  from: string;
@@ -222,10 +227,19 @@ interface InboundEmailHandlerOptions<TEnv = Record<string, unknown>> {
222
227
  /** Routes the parsed message onward (e.g. {@link dispatchToLunoraFunction}). */
223
228
  dispatch: InboundDispatch<TEnv>;
224
229
  /**
225
- * Called when `parse`, `verify`, or `dispatch` fails — but with two DIFFERENT
226
- * contracts, because only the first two decide the message's fate here:
230
+ * Largest message, in bytes (`message.rawSize`), the handler parses; anything
231
+ * bigger is refused through `onError` before a byte of it is read. Default
232
+ * 10 MiB. Parsing holds the raw bytes, the decoded parts and every attachment
233
+ * at once, so a message near Email Routing's 25 MiB ceiling can outgrow the
234
+ * isolate's 128 MB. Must be a positive, finite number.
235
+ */
236
+ maxRawBytes?: number;
237
+ /**
238
+ * Called when the size guard (`maxRawBytes`), `parse`, `verify`, or `dispatch`
239
+ * fails — but with two DIFFERENT contracts, because only the first three decide
240
+ * the message's fate here:
227
241
  *
228
- * - `parse` / `verify` — this hook DECIDES the outcome. The default
242
+ * - size / `parse` / `verify` — this hook DECIDES the outcome. The default
229
243
  * ({@link rejectOnError}) rejects via `message.setReject`; supplying your own
230
244
  * replaces that, so the message is accepted unless you reject it yourself.
231
245
  * - `dispatch` — this hook is OBSERVABILITY ONLY. It is called for the side
@@ -1 +1 @@
1
- import{createInboundEmailHandler as n,dispatchToLunoraFunction as r}from"../packem_shared/createInboundEmailHandler-CixBJpmc.mjs";import{authenticatesFrom as t,parseInboundEmail as i}from"../packem_shared/authenticatesFrom-BDGSL3q4.mjs";export{t as authenticatesFrom,n as createInboundEmailHandler,r as dispatchToLunoraFunction,i as parseInboundEmail};
1
+ import{createInboundEmailHandler as n,dispatchToLunoraFunction as r}from"../packem_shared/createInboundEmailHandler-BeWkwqF2.mjs";import{authenticatesFrom as t,parseInboundEmail as i}from"../packem_shared/authenticatesFrom-DCtlMHNq.mjs";export{t as authenticatesFrom,n as createInboundEmailHandler,r as dispatchToLunoraFunction,i as parseInboundEmail};
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
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-BD67fxbB.mjs";
2
- export { type C as CapturedMail, type c as SendPayload, d as createCaptureTransport } from "./packem_shared/capture-transport.d-BD67fxbB.mjs";
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.mjs";
2
+ export { type C as CapturedMail, type c as SendPayload, d as createCaptureTransport } from "./packem_shared/capture-transport.d-G-OVrGhG.mjs";
3
3
  import { D as DurableObjectJurisdiction } from "./packem_shared/shard.d-DVADjmEJ.mjs";
4
4
  import { ReactElement } from 'react';
5
5
  import { LunoraError } from '@lunora/errors';
@@ -76,6 +76,8 @@ interface FromEnvOptions {
76
76
  queue?: QueueLike;
77
77
  /** Shard the captured-mail inbox lives on; override if your worker sets a custom `defaultShardKey`. */
78
78
  rootShard?: string;
79
+ /** `send()` deadline in milliseconds; see `LunoraMailOptions.sendTimeoutMs`. */
80
+ sendTimeoutMs?: number;
79
81
  }
80
82
  /**
81
83
  * Whether outbound mail should be captured (into the studio inbox) rather than
@@ -117,8 +119,8 @@ interface QueuedSend {
117
119
  html?: string;
118
120
  /**
119
121
  * Stable dedup key, minted at enqueue time by `createMailer(...).queue()` — see
120
- * `SendOptions.idempotencyKey`. Carried through untouched by `consumeQueuedSend`;
121
- * a consumer wanting exactly-once delivery dedupes against its own store using it.
122
+ * `SendOptions.idempotencyKey`. `consumeQueuedSend` dedupes on it when given a
123
+ * `sent` store, and forwards it to the provider.
122
124
  */
123
125
  idempotencyKey?: string;
124
126
  replyTo?: string;
@@ -133,27 +135,84 @@ interface QueuedSend {
133
135
  */
134
136
  declare const toQueuedPayload: (options: SendOptions) => QueuedSend;
135
137
  /**
136
- * Helper used by Queue consumers: rehydrate a `QueuedSend` payload and forward
137
- * to a configured `Mailer.send()`. Use this inside your Worker's `queue()`
138
- * handler.
138
+ * Where {@link consumeQueuedSend} records the idempotency keys it has already
139
+ * sent, mapped to the provider's message id. Shaped after Workers KV's
140
+ * `get` / `put`, so a `KVNamespace` binding passes as-is; a Durable Object or
141
+ * D1-backed adapter works too. Only a string from `get` counts as sent, so an
142
+ * adapter may answer a missing key with `null` (KV) or `undefined` (Durable
143
+ * Object storage).
144
+ */
145
+ interface SentMailStore {
146
+ get: (key: string) => Promise<string | null | undefined>;
147
+ put: (key: string, value: string, options: {
148
+ expirationTtl: number;
149
+ }) => Promise<void>;
150
+ }
151
+ interface ConsumeQueuedSendOptions {
152
+ /**
153
+ * Which delivery of the message this is: pass the Cloudflare Queues `message.attempts` (1 for the first). Used
154
+ * without a `sent` store, where every redelivery follows a send that reached the provider: one older than the
155
+ * provider's dedupe window (`enqueuedAt`) is then refused before any request. With a store, the marks it keeps per
156
+ * delivery decide instead, so a delivery that failed before the send (the store was down) is still sent.
157
+ */
158
+ attempts?: number;
159
+ /**
160
+ * When the message was first enqueued: pass the Cloudflare Queues
161
+ * `message.timestamp`. Resend drops a repeated key for only 24 hours, so an
162
+ * outcome-unknown failure of a message older than 23 hours is not retryable,
163
+ * because a redelivery could then mail a second copy. Without it, nothing
164
+ * tracks that window.
165
+ */
166
+ enqueuedAt?: Date;
167
+ /**
168
+ * Collapse redeliveries: a message whose `idempotencyKey` is already in the
169
+ * store is acknowledged without a second send, and a sent message's key is
170
+ * recorded here. With a store, a body without an `idempotencyKey` is refused.
171
+ * Passing the key with an `undefined` value (an unbound `env.SENT`) logs a
172
+ * warning on every call, because dedupe is then off.
173
+ */
174
+ sent?: SentMailStore;
175
+ /**
176
+ * How long a sent key is remembered, in whole seconds, at least 60 (default
177
+ * 86 400), the range Workers KV accepts. A redelivery later than this sends
178
+ * again. Anything else fails every message as a retryable `MailSendError`.
179
+ */
180
+ sentTtlSeconds?: number;
181
+ }
182
+ /**
183
+ * Helper used by Queue consumers: validate a `QueuedSend` body and send it
184
+ * through `mailer.send()`. Use it inside your Worker's `queue()` handler, and
185
+ * `ack()` each message it settles.
139
186
  *
140
- * DEDUPE IS THE CONSUMER'S JOB, and this helper does not do it. The payload's
141
- * `idempotencyKey` was minted once at enqueue time so it survives redelivery, but
142
- * nothing downstream reads it: no transport forwards it to the provider (Resend
143
- * dedupes on an `Idempotency-Key` REQUEST header, which the provider client offers
144
- * no hook for — its `headers` field becomes message headers in the body). A
145
- * consumer that only acks is correct for the failure the ack covers and sends a
146
- * duplicate for the one it does not: the provider accepted the message and the
147
- * worker died before acking.
187
+ * Pass `sent` (a KV namespace, or anything shaped like one) to collapse
188
+ * Cloudflare Queues' at-least-once redelivery: a key already in the store
189
+ * returns its recorded id with `deduplicated: true` and sends nothing, and a
190
+ * successful send records its key. Only a success is recorded, so a retryable
191
+ * or outcome-unknown failure never blocks a later attempt. Beside the key it
192
+ * keeps attempt marks, one pair per delivery `n` (pass `attempts`): `sending`
193
+ * just before it asks the provider, `failed` once that send is known not to have
194
+ * gone out, each under its own key and kept 15 days. A redelivery past the
195
+ * provider's dedupe window is refused while any earlier delivery has `sending`
196
+ * without `failed`, so a message whose earlier deliveries never reached the
197
+ * provider is still sent; a mark that cannot be written fails the send as
198
+ * retryable. A store that cannot
199
+ * be read, or does not answer within 10 seconds, fails the send as retryable,
200
+ * since nothing has gone out; a store that cannot be written after the send, or
201
+ * does not answer within 10 seconds, is logged and the id still returned, because throwing then would redeliver a
202
+ * message the provider already accepted.
148
203
  *
149
- * The recipe below NARROWS that window; it does not close it, and nothing on
150
- * this path can. The mark is written after the provider accepted the message, so
151
- * a crash in between still redelivers and resends, and a KV read is eventually
204
+ * This NARROWS the duplicate window; it does not close it, and nothing on this
205
+ * path can. The mark is written after the provider accepted the message, so a
206
+ * crash in between still redelivers and resends, and a KV read is eventually
152
207
  * consistent — a redelivery seconds later can miss a mark that was written.
153
208
  * Delivery is at-least-once end to end. An app that must not double-send needs a
154
209
  * strongly-consistent mark taken BEFORE the send (a Durable Object or D1 row
155
210
  * claimed by this key, released on failure), and even then the send-then-crash
156
- * window is only ever traded for a send-that-may-not-have-happened one.
211
+ * window is only ever traded for a send-that-may-not-have-happened one. With
212
+ * Resend the key also travels as the `Idempotency-Key` request header, so Resend
213
+ * itself drops a repeat inside its own 24-hour window; pass `enqueuedAt` and
214
+ * `attempts` so a send that may have landed is not repeated once that window is
215
+ * nearly over.
157
216
  *
158
217
  * ```ts
159
218
  * export default {
@@ -161,32 +220,32 @@ declare const toQueuedPayload: (options: SendOptions) => QueuedSend;
161
220
  * // createMailerFromEnv, so dev captures the message here instead of sending it.
162
221
  * const mailer = createMailerFromEnv(env);
163
222
  * for (const message of batch.messages) {
164
- * const idempotencyKey = message.body?.idempotencyKey;
165
- * // Malformed, and no retry fixes it; unguarded, this would throw and retry the whole batch. Logged without the
166
- * // body, which can still carry recipients and content.
167
- * if (typeof idempotencyKey !== "string") { console.error("malformed mail message: no idempotencyKey"); message.ack(); continue; }
168
- * if (await env.SENT.get(idempotencyKey)) { message.ack(); continue; }
169
223
  * try {
170
- * await consumeQueuedSend(mailer, message.body);
224
+ * await consumeQueuedSend(mailer, message.body, { attempts: message.attempts, enqueuedAt: message.timestamp, sent: env.SENT });
171
225
  * } catch (error) {
172
- * // A refusal the provider will never accept: a retry only dead-letters it.
173
- * if (!isRetryableMailError(error)) {
174
- * console.error("mail refused", error);
175
- * message.ack();
226
+ * // Transient, or a send that may have landed with a provider that dedupes on the key (Resend).
227
+ * if (isRetryableMailError(error)) {
228
+ * // The first attempt may still be running at the provider (Resend's client keeps a request
229
+ * // going for about two minutes), so give it time: a repeat inside that window is a 409.
230
+ * message.retry(isOutcomeUnknownMailError(error) ? { delaySeconds: 180 } : undefined);
176
231
  * continue;
177
232
  * }
178
233
  *
179
- * message.retry();
234
+ * // A timeout no provider dedupes may have been delivered, so a retry could send a second
235
+ * // copy: check the provider's logs. Anything else is a refusal or a malformed body.
236
+ * console.error(isOutcomeUnknownMailError(error) ? "mail outcome unknown" : "mail refused", error);
237
+ * message.ack();
180
238
  * continue;
181
239
  * }
182
- * await env.SENT.put(idempotencyKey, "1", { expirationTtl: 86_400 });
240
+ * // Per message: without it a single throw retries the whole batch.
183
241
  * message.ack();
184
242
  * }
185
243
  * },
186
244
  * };
187
245
  * ```
188
246
  */
189
- declare const consumeQueuedSend: (mailer: Mailer, payload: unknown) => Promise<{
247
+ declare const consumeQueuedSend: (mailer: Mailer, payload: unknown, options?: ConsumeQueuedSendOptions) => Promise<{
248
+ deduplicated: boolean;
190
249
  id: string;
191
250
  }>;
192
251
  /**
@@ -212,6 +271,15 @@ declare const renderEmail: (element: ReactElement) => Promise<{
212
271
  declare const createResendTransport: (apiKey: string, defaultFrom: string) => MailTransport;
213
272
  /** What a {@link MailSendError} carries on `data`, so a caller can tell a retry from a refusal. */
214
273
  interface MailSendErrorData {
274
+ /**
275
+ * The send was cut off before the provider answered (the mailer's send deadline, or the
276
+ * provider's own request timeout), or the provider is still processing an earlier send under
277
+ * the same idempotency key (Resend's 409), so it may have been delivered. `retryable` is then true
278
+ * only when the send carried an idempotency key and its transport's provider dedupes on it
279
+ * (`MailTransport.dedupesOnIdempotencyKey`), so a repeat cannot mail a second copy, and
280
+ * `consumeQueuedSend` clears it again for a message older than that provider's dedupe window.
281
+ */
282
+ outcomeUnknown: boolean;
215
283
  /** Whether repeating the same message may succeed. A refused address or malformed message never will. */
216
284
  retryable: boolean;
217
285
  }
@@ -221,12 +289,21 @@ interface MailSendErrorData {
221
289
  * permanent HTTP status (anything but 408, 429 and 5xx); every other failure may
222
290
  * clear on a redelivery. Retrying a refusal only drains the queue into its
223
291
  * dead-letter queue.
292
+ *
293
+ * A send that timed out is `outcomeUnknown`: the provider may have accepted it.
294
+ * It is `retryable` only when the transport forwarded the send's idempotency key
295
+ * to a provider that dedupes on it (Resend), so the repeat is dropped if the
296
+ * first one landed. Otherwise a queue consumer acks and reports it rather than
297
+ * mailing the recipient a second copy.
224
298
  */
225
299
  declare class MailSendError extends LunoraError {
300
+ static override [Symbol.hasInstance](value: unknown): boolean;
301
+ readonly outcomeUnknown: boolean;
226
302
  readonly retryable: boolean;
227
303
  constructor(options: {
228
304
  cause?: unknown;
229
305
  message?: string;
306
+ outcomeUnknown?: boolean;
230
307
  retryable: boolean;
231
308
  });
232
309
  }
@@ -237,4 +314,12 @@ declare class MailSendError extends LunoraError {
237
314
  * a message that will never send.
238
315
  */
239
316
  declare const isRetryableMailError: (error: unknown) => boolean;
240
- export { type CloudflareSend, type CloudflareTransportOptions, type FromEnvOptions, type LunoraMailOptions, type MailEnv, MailSendError, type MailSendErrorData, type MailTransport, type MailboxSink, type Mailer, type QueueLike, type QueuedSend, type SendOptions, consumeQueuedSend, createCaptureSink, createCloudflareTransport, createMailer, createMailerFromEnv, createResendTransport, isRetryableMailError, renderEmail, shouldCaptureMail, toQueuedPayload };
317
+ /**
318
+ * Whether a failed send may nonetheless have been delivered — it timed out
319
+ * before the provider answered, or the provider is still processing an earlier
320
+ * send under its key. Check {@link isRetryableMailError} first: a
321
+ * retryable one is safe to redeliver because the provider dedupes on its key.
322
+ * One that is not must be reported (check the provider's logs), not resent.
323
+ */
324
+ declare const isOutcomeUnknownMailError: (error: unknown) => boolean;
325
+ 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, consumeQueuedSend, createCaptureSink, createCloudflareTransport, createMailer, createMailerFromEnv, createResendTransport, isOutcomeUnknownMailError, isRetryableMailError, renderEmail, shouldCaptureMail, toQueuedPayload };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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-BD67fxbB.js";
2
- export { type C as CapturedMail, type c as SendPayload, d as createCaptureTransport } from "./packem_shared/capture-transport.d-BD67fxbB.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
3
  import { D as DurableObjectJurisdiction } from "./packem_shared/shard.d-DVADjmEJ.js";
4
4
  import { ReactElement } from 'react';
5
5
  import { LunoraError } from '@lunora/errors';
@@ -76,6 +76,8 @@ interface FromEnvOptions {
76
76
  queue?: QueueLike;
77
77
  /** Shard the captured-mail inbox lives on; override if your worker sets a custom `defaultShardKey`. */
78
78
  rootShard?: string;
79
+ /** `send()` deadline in milliseconds; see `LunoraMailOptions.sendTimeoutMs`. */
80
+ sendTimeoutMs?: number;
79
81
  }
80
82
  /**
81
83
  * Whether outbound mail should be captured (into the studio inbox) rather than
@@ -117,8 +119,8 @@ interface QueuedSend {
117
119
  html?: string;
118
120
  /**
119
121
  * Stable dedup key, minted at enqueue time by `createMailer(...).queue()` — see
120
- * `SendOptions.idempotencyKey`. Carried through untouched by `consumeQueuedSend`;
121
- * a consumer wanting exactly-once delivery dedupes against its own store using it.
122
+ * `SendOptions.idempotencyKey`. `consumeQueuedSend` dedupes on it when given a
123
+ * `sent` store, and forwards it to the provider.
122
124
  */
123
125
  idempotencyKey?: string;
124
126
  replyTo?: string;
@@ -133,27 +135,84 @@ interface QueuedSend {
133
135
  */
134
136
  declare const toQueuedPayload: (options: SendOptions) => QueuedSend;
135
137
  /**
136
- * Helper used by Queue consumers: rehydrate a `QueuedSend` payload and forward
137
- * to a configured `Mailer.send()`. Use this inside your Worker's `queue()`
138
- * handler.
138
+ * Where {@link consumeQueuedSend} records the idempotency keys it has already
139
+ * sent, mapped to the provider's message id. Shaped after Workers KV's
140
+ * `get` / `put`, so a `KVNamespace` binding passes as-is; a Durable Object or
141
+ * D1-backed adapter works too. Only a string from `get` counts as sent, so an
142
+ * adapter may answer a missing key with `null` (KV) or `undefined` (Durable
143
+ * Object storage).
144
+ */
145
+ interface SentMailStore {
146
+ get: (key: string) => Promise<string | null | undefined>;
147
+ put: (key: string, value: string, options: {
148
+ expirationTtl: number;
149
+ }) => Promise<void>;
150
+ }
151
+ interface ConsumeQueuedSendOptions {
152
+ /**
153
+ * Which delivery of the message this is: pass the Cloudflare Queues `message.attempts` (1 for the first). Used
154
+ * without a `sent` store, where every redelivery follows a send that reached the provider: one older than the
155
+ * provider's dedupe window (`enqueuedAt`) is then refused before any request. With a store, the marks it keeps per
156
+ * delivery decide instead, so a delivery that failed before the send (the store was down) is still sent.
157
+ */
158
+ attempts?: number;
159
+ /**
160
+ * When the message was first enqueued: pass the Cloudflare Queues
161
+ * `message.timestamp`. Resend drops a repeated key for only 24 hours, so an
162
+ * outcome-unknown failure of a message older than 23 hours is not retryable,
163
+ * because a redelivery could then mail a second copy. Without it, nothing
164
+ * tracks that window.
165
+ */
166
+ enqueuedAt?: Date;
167
+ /**
168
+ * Collapse redeliveries: a message whose `idempotencyKey` is already in the
169
+ * store is acknowledged without a second send, and a sent message's key is
170
+ * recorded here. With a store, a body without an `idempotencyKey` is refused.
171
+ * Passing the key with an `undefined` value (an unbound `env.SENT`) logs a
172
+ * warning on every call, because dedupe is then off.
173
+ */
174
+ sent?: SentMailStore;
175
+ /**
176
+ * How long a sent key is remembered, in whole seconds, at least 60 (default
177
+ * 86 400), the range Workers KV accepts. A redelivery later than this sends
178
+ * again. Anything else fails every message as a retryable `MailSendError`.
179
+ */
180
+ sentTtlSeconds?: number;
181
+ }
182
+ /**
183
+ * Helper used by Queue consumers: validate a `QueuedSend` body and send it
184
+ * through `mailer.send()`. Use it inside your Worker's `queue()` handler, and
185
+ * `ack()` each message it settles.
139
186
  *
140
- * DEDUPE IS THE CONSUMER'S JOB, and this helper does not do it. The payload's
141
- * `idempotencyKey` was minted once at enqueue time so it survives redelivery, but
142
- * nothing downstream reads it: no transport forwards it to the provider (Resend
143
- * dedupes on an `Idempotency-Key` REQUEST header, which the provider client offers
144
- * no hook for — its `headers` field becomes message headers in the body). A
145
- * consumer that only acks is correct for the failure the ack covers and sends a
146
- * duplicate for the one it does not: the provider accepted the message and the
147
- * worker died before acking.
187
+ * Pass `sent` (a KV namespace, or anything shaped like one) to collapse
188
+ * Cloudflare Queues' at-least-once redelivery: a key already in the store
189
+ * returns its recorded id with `deduplicated: true` and sends nothing, and a
190
+ * successful send records its key. Only a success is recorded, so a retryable
191
+ * or outcome-unknown failure never blocks a later attempt. Beside the key it
192
+ * keeps attempt marks, one pair per delivery `n` (pass `attempts`): `sending`
193
+ * just before it asks the provider, `failed` once that send is known not to have
194
+ * gone out, each under its own key and kept 15 days. A redelivery past the
195
+ * provider's dedupe window is refused while any earlier delivery has `sending`
196
+ * without `failed`, so a message whose earlier deliveries never reached the
197
+ * provider is still sent; a mark that cannot be written fails the send as
198
+ * retryable. A store that cannot
199
+ * be read, or does not answer within 10 seconds, fails the send as retryable,
200
+ * since nothing has gone out; a store that cannot be written after the send, or
201
+ * does not answer within 10 seconds, is logged and the id still returned, because throwing then would redeliver a
202
+ * message the provider already accepted.
148
203
  *
149
- * The recipe below NARROWS that window; it does not close it, and nothing on
150
- * this path can. The mark is written after the provider accepted the message, so
151
- * a crash in between still redelivers and resends, and a KV read is eventually
204
+ * This NARROWS the duplicate window; it does not close it, and nothing on this
205
+ * path can. The mark is written after the provider accepted the message, so a
206
+ * crash in between still redelivers and resends, and a KV read is eventually
152
207
  * consistent — a redelivery seconds later can miss a mark that was written.
153
208
  * Delivery is at-least-once end to end. An app that must not double-send needs a
154
209
  * strongly-consistent mark taken BEFORE the send (a Durable Object or D1 row
155
210
  * claimed by this key, released on failure), and even then the send-then-crash
156
- * window is only ever traded for a send-that-may-not-have-happened one.
211
+ * window is only ever traded for a send-that-may-not-have-happened one. With
212
+ * Resend the key also travels as the `Idempotency-Key` request header, so Resend
213
+ * itself drops a repeat inside its own 24-hour window; pass `enqueuedAt` and
214
+ * `attempts` so a send that may have landed is not repeated once that window is
215
+ * nearly over.
157
216
  *
158
217
  * ```ts
159
218
  * export default {
@@ -161,32 +220,32 @@ declare const toQueuedPayload: (options: SendOptions) => QueuedSend;
161
220
  * // createMailerFromEnv, so dev captures the message here instead of sending it.
162
221
  * const mailer = createMailerFromEnv(env);
163
222
  * for (const message of batch.messages) {
164
- * const idempotencyKey = message.body?.idempotencyKey;
165
- * // Malformed, and no retry fixes it; unguarded, this would throw and retry the whole batch. Logged without the
166
- * // body, which can still carry recipients and content.
167
- * if (typeof idempotencyKey !== "string") { console.error("malformed mail message: no idempotencyKey"); message.ack(); continue; }
168
- * if (await env.SENT.get(idempotencyKey)) { message.ack(); continue; }
169
223
  * try {
170
- * await consumeQueuedSend(mailer, message.body);
224
+ * await consumeQueuedSend(mailer, message.body, { attempts: message.attempts, enqueuedAt: message.timestamp, sent: env.SENT });
171
225
  * } catch (error) {
172
- * // A refusal the provider will never accept: a retry only dead-letters it.
173
- * if (!isRetryableMailError(error)) {
174
- * console.error("mail refused", error);
175
- * message.ack();
226
+ * // Transient, or a send that may have landed with a provider that dedupes on the key (Resend).
227
+ * if (isRetryableMailError(error)) {
228
+ * // The first attempt may still be running at the provider (Resend's client keeps a request
229
+ * // going for about two minutes), so give it time: a repeat inside that window is a 409.
230
+ * message.retry(isOutcomeUnknownMailError(error) ? { delaySeconds: 180 } : undefined);
176
231
  * continue;
177
232
  * }
178
233
  *
179
- * message.retry();
234
+ * // A timeout no provider dedupes may have been delivered, so a retry could send a second
235
+ * // copy: check the provider's logs. Anything else is a refusal or a malformed body.
236
+ * console.error(isOutcomeUnknownMailError(error) ? "mail outcome unknown" : "mail refused", error);
237
+ * message.ack();
180
238
  * continue;
181
239
  * }
182
- * await env.SENT.put(idempotencyKey, "1", { expirationTtl: 86_400 });
240
+ * // Per message: without it a single throw retries the whole batch.
183
241
  * message.ack();
184
242
  * }
185
243
  * },
186
244
  * };
187
245
  * ```
188
246
  */
189
- declare const consumeQueuedSend: (mailer: Mailer, payload: unknown) => Promise<{
247
+ declare const consumeQueuedSend: (mailer: Mailer, payload: unknown, options?: ConsumeQueuedSendOptions) => Promise<{
248
+ deduplicated: boolean;
190
249
  id: string;
191
250
  }>;
192
251
  /**
@@ -212,6 +271,15 @@ declare const renderEmail: (element: ReactElement) => Promise<{
212
271
  declare const createResendTransport: (apiKey: string, defaultFrom: string) => MailTransport;
213
272
  /** What a {@link MailSendError} carries on `data`, so a caller can tell a retry from a refusal. */
214
273
  interface MailSendErrorData {
274
+ /**
275
+ * The send was cut off before the provider answered (the mailer's send deadline, or the
276
+ * provider's own request timeout), or the provider is still processing an earlier send under
277
+ * the same idempotency key (Resend's 409), so it may have been delivered. `retryable` is then true
278
+ * only when the send carried an idempotency key and its transport's provider dedupes on it
279
+ * (`MailTransport.dedupesOnIdempotencyKey`), so a repeat cannot mail a second copy, and
280
+ * `consumeQueuedSend` clears it again for a message older than that provider's dedupe window.
281
+ */
282
+ outcomeUnknown: boolean;
215
283
  /** Whether repeating the same message may succeed. A refused address or malformed message never will. */
216
284
  retryable: boolean;
217
285
  }
@@ -221,12 +289,21 @@ interface MailSendErrorData {
221
289
  * permanent HTTP status (anything but 408, 429 and 5xx); every other failure may
222
290
  * clear on a redelivery. Retrying a refusal only drains the queue into its
223
291
  * dead-letter queue.
292
+ *
293
+ * A send that timed out is `outcomeUnknown`: the provider may have accepted it.
294
+ * It is `retryable` only when the transport forwarded the send's idempotency key
295
+ * to a provider that dedupes on it (Resend), so the repeat is dropped if the
296
+ * first one landed. Otherwise a queue consumer acks and reports it rather than
297
+ * mailing the recipient a second copy.
224
298
  */
225
299
  declare class MailSendError extends LunoraError {
300
+ static override [Symbol.hasInstance](value: unknown): boolean;
301
+ readonly outcomeUnknown: boolean;
226
302
  readonly retryable: boolean;
227
303
  constructor(options: {
228
304
  cause?: unknown;
229
305
  message?: string;
306
+ outcomeUnknown?: boolean;
230
307
  retryable: boolean;
231
308
  });
232
309
  }
@@ -237,4 +314,12 @@ declare class MailSendError extends LunoraError {
237
314
  * a message that will never send.
238
315
  */
239
316
  declare const isRetryableMailError: (error: unknown) => boolean;
240
- export { type CloudflareSend, type CloudflareTransportOptions, type FromEnvOptions, type LunoraMailOptions, type MailEnv, MailSendError, type MailSendErrorData, type MailTransport, type MailboxSink, type Mailer, type QueueLike, type QueuedSend, type SendOptions, consumeQueuedSend, createCaptureSink, createCloudflareTransport, createMailer, createMailerFromEnv, createResendTransport, isRetryableMailError, renderEmail, shouldCaptureMail, toQueuedPayload };
317
+ /**
318
+ * Whether a failed send may nonetheless have been delivered — it timed out
319
+ * before the provider answered, or the provider is still processing an earlier
320
+ * send under its key. Check {@link isRetryableMailError} first: a
321
+ * retryable one is safe to redeliver because the provider dedupes on its key.
322
+ * One that is not must be reported (check the provider's logs), not resent.
323
+ */
324
+ declare const isOutcomeUnknownMailError: (error: unknown) => boolean;
325
+ 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, consumeQueuedSend, createCaptureSink, createCloudflareTransport, createMailer, createMailerFromEnv, createResendTransport, isOutcomeUnknownMailError, isRetryableMailError, renderEmail, shouldCaptureMail, toQueuedPayload };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{createCaptureTransport as a}from"./packem_shared/createCaptureTransport-DZhMUmaI.mjs";import{createCloudflareTransport as t}from"./packem_shared/createCloudflareTransport-fOhfy2fP.mjs";import{default as p}from"./packem_shared/createMailer-C5NIzkNb.mjs";import{createCaptureSink as d,createMailerFromEnv as f,shouldCaptureMail as m}from"./packem_shared/createCaptureSink-BSAR1HTL.mjs";import{consumeQueuedSend as s,toQueuedPayload as i}from"./packem_shared/consumeQueuedSend-CRfALnCU.mjs";import{default as c}from"./packem_shared/renderEmail-xypKDdux.mjs";import{default as C}from"./packem_shared/createResendTransport-q3surKen.mjs";import{MailSendError as S,isRetryableMailError as T}from"./packem_shared/MailSendError-HH5Yimut.mjs";export{S as MailSendError,s as consumeQueuedSend,d as createCaptureSink,a as createCaptureTransport,t as createCloudflareTransport,p as createMailer,f as createMailerFromEnv,C as createResendTransport,T as isRetryableMailError,c as renderEmail,m as shouldCaptureMail,i as toQueuedPayload};
1
+ import{createCaptureTransport as o}from"./packem_shared/createCaptureTransport-DZhMUmaI.mjs";import{createCloudflareTransport as t}from"./packem_shared/createCloudflareTransport-2pH3460e.mjs";import{default as p}from"./packem_shared/createMailer-DuQciU65.mjs";import{createCaptureSink as n,createMailerFromEnv as d,shouldCaptureMail as f}from"./packem_shared/createCaptureSink-CEqX4_iD.mjs";import{consumeQueuedSend as s,toQueuedPayload as i}from"./packem_shared/consumeQueuedSend-CDDDeoAz.mjs";import{default as x}from"./packem_shared/renderEmail-xypKDdux.mjs";import{default as E}from"./packem_shared/createResendTransport-DdsftR55.mjs";import{MailSendError as S,isOutcomeUnknownMailError as T,isRetryableMailError as k}from"./packem_shared/MailSendError-BYih5mnM.mjs";export{S as MailSendError,s as consumeQueuedSend,n as createCaptureSink,o as createCaptureTransport,t as createCloudflareTransport,p as createMailer,d as createMailerFromEnv,E as createResendTransport,T as isOutcomeUnknownMailError,k as isRetryableMailError,x as renderEmail,f as shouldCaptureMail,i 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 e}from"@lunora/errors";import{MailSendError as d}from"./MailSendError-BYih5mnM.mjs";const o=320,c=256,m=/^([^<]*)<([^>]*)>\s*$/,i=(r,t)=>{if(t.includes("\r")||t.includes(`
2
+ `)||t.includes(","))throw new e("INTERNAL",`@lunora/mail: address ${r} must not contain CR, LF, or comma`)},h=(r,t)=>{if(t.includes("\r")||t.includes(`
3
+ `))throw new e("INTERNAL",`@lunora/mail: ${r} must not contain CR or LF`)},l=(r,t)=>{if(r.length>c)throw new e("INTERNAL",`@lunora/mail: address name must be <= ${String(c)} characters`);if(t.length>o)throw new e("INTERNAL",`@lunora/mail: address email must be <= ${String(o)} characters`);return r&&i("name",r),i("email",t),r?{email:t,name:r}:{email:t}},u=r=>{const t=r.trim();if(t.length>o)throw new e("INTERNAL",`@lunora/mail: address email must be <= ${String(o)} characters`);return i("email",t),{email:t}},a=r=>{const t=m.exec(r),s=(t?.[2]??"").trim();return t&&s?l((t[1]??"").trim(),s):u(r)},n=r=>{if(r===void 0)return;const t=Array.isArray(r)?r:[r];if(t.length!==0)return t.map(s=>a(s))},N=r=>{if(n(r.to)===void 0)throw new e("INTERNAL","@lunora/mail: at least one recipient is required");n(r.cc),n(r.bcc),r.from!==void 0&&a(r.from),r.replyTo!==void 0&&a(r.replyTo)},f=/^[\u0021-\u007E]{1,256}$/u,T=r=>{if(r!==void 0&&(typeof r!="string"||!f.test(r)||r==="."||r===".."))throw new d({message:"@lunora/mail: `idempotencyKey` must be a string of 1-256 visible ASCII characters, other than `.` or `..`",retryable:!1})};export{h as a,T as b,a as c,N as d,n as t};
@@ -1 +1 @@
1
- import l from"postal-mime";import{a as c}from"./address-oKy_d0aG.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};
1
+ import l from"postal-mime";import{a as c}from"./address-BKzIBZxE.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};
@@ -13,7 +13,27 @@ interface QueueLike {
13
13
  * provider responses to the same field for us.
14
14
  */
15
15
  interface MailTransport {
16
- send: (payload: SendPayload) => Promise<{
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<{
17
37
  id: string;
18
38
  }>;
19
39
  }
@@ -35,16 +55,20 @@ interface SendOptions {
35
55
  headers?: Record<string, string>;
36
56
  html?: string;
37
57
  /**
38
- * Stable key for deduping a queued send across Cloudflare Queues' at-least-once
39
- * redelivery. Only meaningful for `mailer.queue()` — `mailer.send()` ignores it.
40
- * When omitted, `queue()` generates one at enqueue time so it survives redelivery
41
- * (a key minted in the consumer would change on every retry, defeating the point).
42
- * Not forwarded to the mail provider, and no transport can: Resend dedupes on an
43
- * `Idempotency-Key` REQUEST header, and the provider client exposes no hook for
44
- * one (its own `headers` field becomes message headers in the JSON body). So a
45
- * consumer that wants to collapse redeliveries MUST dedupe against its own store
46
- * using this key — see `consumeQueuedSend` for the shape, and for why that is a
47
- * narrowed at-least-once rather than exactly-once.
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.
48
72
  */
49
73
  idempotencyKey?: string;
50
74
  react?: ReactElement;
@@ -67,6 +91,22 @@ interface LunoraMailOptions {
67
91
  from: string;
68
92
  /** Default queue binding for `mailer.queue()`. */
69
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;
70
110
  /** Override the underlying transport. Useful for tests, the dev capture transport, + multi-provider setups. */
71
111
  transport?: MailTransport;
72
112
  }
@@ -13,7 +13,27 @@ interface QueueLike {
13
13
  * provider responses to the same field for us.
14
14
  */
15
15
  interface MailTransport {
16
- send: (payload: SendPayload) => Promise<{
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<{
17
37
  id: string;
18
38
  }>;
19
39
  }
@@ -35,16 +55,20 @@ interface SendOptions {
35
55
  headers?: Record<string, string>;
36
56
  html?: string;
37
57
  /**
38
- * Stable key for deduping a queued send across Cloudflare Queues' at-least-once
39
- * redelivery. Only meaningful for `mailer.queue()` — `mailer.send()` ignores it.
40
- * When omitted, `queue()` generates one at enqueue time so it survives redelivery
41
- * (a key minted in the consumer would change on every retry, defeating the point).
42
- * Not forwarded to the mail provider, and no transport can: Resend dedupes on an
43
- * `Idempotency-Key` REQUEST header, and the provider client exposes no hook for
44
- * one (its own `headers` field becomes message headers in the JSON body). So a
45
- * consumer that wants to collapse redeliveries MUST dedupe against its own store
46
- * using this key — see `consumeQueuedSend` for the shape, and for why that is a
47
- * narrowed at-least-once rather than exactly-once.
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.
48
72
  */
49
73
  idempotencyKey?: string;
50
74
  react?: ReactElement;
@@ -67,6 +91,22 @@ interface LunoraMailOptions {
67
91
  from: string;
68
92
  /** Default queue binding for `mailer.queue()`. */
69
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;
70
110
  /** Override the underlying transport. Useful for tests, the dev capture transport, + multi-provider setups. */
71
111
  transport?: MailTransport;
72
112
  }
@@ -0,0 +1 @@
1
+ import{b as O}from"./address-BKzIBZxE.mjs";import{MailSendError as y,isRetryableMailError as T,isOutcomeUnknownMailError as _}from"./MailSendError-BYih5mnM.mjs";const x=t=>{const e={...t};return delete e.react,e},N=86400,v=(t,e)=>`sending ${String(e)} ${t}`,E=(t,e)=>`failed ${String(e)} ${t}`,A=15*86400,k=t=>Math.max(t,A),w=1e4,D=1380*60*1e3,b=60,d=t=>new y({message:`@lunora/mail: ${t}`,retryable:!1}),$=t=>{if(!t||typeof t!="object"||Array.isArray(t))throw d("queue message body must be an object");const e=t;if(typeof e.subject!="string")throw d("queue message must have a string `subject`");const a=typeof e.to=="string",r=Array.isArray(e.to)&&e.to.every(c=>typeof c=="string");if(!a&&!r)throw d("queue message `to` must be a string or string[]");const n=(c,o)=>{if(o!==void 0){if(typeof o!="string")throw d(`queue message \`${c}\` must be a string`);return o}},s=(c,o)=>{if(o!==void 0){if(typeof o=="string")return[o];if(Array.isArray(o)&&o.every(u=>typeof u=="string"))return o;throw d(`queue message \`${c}\` must be a string or string[]`)}};let i;if(e.headers!==void 0){if(!e.headers||typeof e.headers!="object"||Array.isArray(e.headers))throw d("queue message `headers` must be an object of string values");const c=Object.entries(e.headers);for(const[o,u]of c)if(typeof u!="string")throw d(`queue message header "${o}" must be a string`);i=e.headers}const f=n("idempotencyKey",e.idempotencyKey);return O(f),{bcc:s("bcc",e.bcc),cc:s("cc",e.cc),from:n("from",e.from),headers:i,html:n("html",e.html),idempotencyKey:f,replyTo:n("replyTo",e.replyTo),subject:e.subject,text:n("text",e.text),to:e.to}},h=t=>{const e=t===void 0?0:Date.now()-t.getTime();return Number.isNaN(e)||e>=D},M=(t,e)=>{if(t&&h(e))throw new y({message:"@lunora/mail: an earlier delivery of this message may have been sent, and the provider no longer dedupes a key this old",outcomeUnknown:!0,retryable:!1})},S=async(t,e,a)=>{try{return await t.send(e)}catch(r){throw _(r)&&T(r)&&h(a)?new y({cause:r,message:"@lunora/mail: the send may have been delivered, and the provider no longer dedupes a key this old",outcomeUnknown:!0,retryable:!1}):r}},g=async t=>{let e;try{return await Promise.race([t,new Promise((a,r)=>{e=setTimeout(()=>{r(new Error(`the sent-mail store did not answer within ${String(w)}ms`))},w)})])}finally{clearTimeout(e)}},j=async(t,e,a)=>{const r=Array.from({length:a-1},(s,i)=>i+1);return(await g(Promise.all(r.map(async s=>await Promise.all([t.get(v(e,s)),t.get(E(e,s))]))))).some(([s,i])=>typeof s=="string"&&typeof i!="string")},I=async(t,e,a,r)=>{if(a<=1||!h(r))return;let n;try{n=await j(t,e,a)}catch(s){throw new y({cause:s,message:"@lunora/mail: could not read the sent-mail store",retryable:!0})}M(n,r)},p=(t,e,a,r)=>{const n=JSON.stringify({event:e,message:a,...r!==void 0&&{error:r instanceof Error?{message:r.message,name:r.name,stack:r.stack}:{message:typeof r=="string"?r:typeof r}}});console[t](n)},L=async(t,e,a,r)=>{try{await g(t.put(e,a,{expirationTtl:r}))}catch(n){p("error","lunora.mail.sent_record_failed","@lunora/mail: sent, but could not record the idempotency key; a redelivery may send again",n)}},q=async(t,e,a,r)=>{try{await g(t.put(E(e,a),"failed",{expirationTtl:k(r)}))}catch(n){p("warn","lunora.mail.attempt_mark_failed","@lunora/mail: could not mark a failed send; a late redelivery will be refused",n)}},R=async(t,e,a={})=>{const{attempts:r,enqueuedAt:n,sent:s,sentTtlSeconds:i=N}=a;if(!Number.isSafeInteger(i)||i<b)throw new y({message:`@lunora/mail: \`sentTtlSeconds\` must be a whole number of seconds, at least ${String(b)}`,retryable:!0});const f=$(e);if(!s)return"sent"in a&&p("warn","lunora.mail.sent_store_unbound","@lunora/mail: consumeQueuedSend got `sent: undefined` (is the KV namespace bound?), so redeliveries are not deduplicated"),M(r!==void 0&&r>1,n),{deduplicated:!1,...await S(t,f,n)};const l=f.idempotencyKey;if(l===void 0)throw d("queue message has no `idempotencyKey` to dedupe on");let c;try{c=await g(s.get(l))}catch(m){throw new y({cause:m,message:"@lunora/mail: could not read the sent-mail store",retryable:!0})}if(typeof c=="string")return{deduplicated:!0,id:c};const o=r??1;await I(s,l,o,n);try{await g(s.put(v(l,o),"sending",{expirationTtl:k(i)}))}catch(m){throw new y({cause:m,message:"@lunora/mail: could not mark the send in the sent-mail store",retryable:!0})}let u;try{({id:u}=await S(t,f,n))}catch(m){throw T(m)&&!_(m)&&await q(s,l,o,i),m}return await L(s,l,u,i),{deduplicated:!1,id:u}};export{R as consumeQueuedSend,x as toQueuedPayload};
@@ -0,0 +1 @@
1
+ import{createCaptureTransport as c}from"./createCaptureTransport-DZhMUmaI.mjs";import"./createCloudflareTransport-2pH3460e.mjs";import s from"./createMailer-DuQciU65.mjs";import{LunoraError as l}from"@lunora/errors";import{D as m,a as E,p as _}from"./shard-C5t-b7FX.mjs";import"./consumeQueuedSend-CDDDeoAz.mjs";import"./renderEmail-xypKDdux.mjs";import"./createResendTransport-DdsftR55.mjs";import"./MailSendError-BYih5mnM.mjs";const p="__lunora_admin__:recordMail",N=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,f=["CF_ENV","ENVIRONMENT","NODE_ENV","WORKER_ENV"],R=(e,r)=>{const o=e[r];if(typeof o!="string"||o==="")throw new l("INTERNAL",`@lunora/mail: missing env var \`${r}\` — set it in .dev.vars (and \`wrangler secret put ${r}\` for secrets).`);return o},A=e=>{const r=e.LUNORA_MAIL_CAPTURE;if(typeof r=="string"){const t=r.toLowerCase();if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;console.warn(`@lunora/mail: unrecognized LUNORA_MAIL_CAPTURE value "${r}" — expected "1"/"true" or "0"/"false"; falling back to environment detection.`)}const o=f.map(t=>e[t]).filter(t=>typeof t=="string"&&t!=="");return o.length>0&&o.every(t=>N.test(t))};let u=!1;const T=(e,r=m,o)=>({record:async t=>{const i=e.SHARD,a=typeof e.LUNORA_ADMIN_TOKEN=="string"?e.LUNORA_ADMIN_TOKEN:void 0;if(i===void 0||a===void 0)return u||(u=!0,console.warn("@lunora/mail: capturing mail but there is nowhere to record it — the `SHARD` binding and/or `LUNORA_ADMIN_TOKEN` is missing, so every captured message is discarded. Set both to see mail in the studio inbox, or set LUNORA_MAIL_CAPTURE=0 to deliver for real.")),{id:"uncaptured"};const d=E(i,o);try{return{id:(await _(d,{adminToken:a,envelope:{args:t,functionPath:p},label:"@lunora/mail: recording captured mail",shardKey:r})).result?.id??"captured"}}catch(n){return console.error("@lunora/mail: failed to record captured mail into the studio inbox —",n),{id:"uncaptured"}}}}),b=(e,r={})=>{const o=R(e,"MAIL_FROM");if(A(e))return s({from:o,queue:r.queue,sendTimeoutMs:r.sendTimeoutMs,transport:c(T(e,r.rootShard,r.jurisdiction))});const{cloudflareSend:t}=r,i=typeof e.RESEND_API_KEY=="string"&&e.RESEND_API_KEY!==""?e.RESEND_API_KEY:void 0;return s({apiKey:i,cloudflareSend:t,from:o,queue:r.queue,sendTimeoutMs:r.sendTimeoutMs})};export{T as createCaptureSink,b as createMailerFromEnv,A as shouldCaptureMail};
@@ -1 +1 @@
1
- import{cloudflareEmailProvider as l}from"@visulima/email/providers/cloudflare-email";import{r as d,t as m,i as f}from"./provider-transport-DklK6xUa.mjs";import{MailSendError as n}from"./MailSendError-HH5Yimut.mjs";const h=r=>{const t=l({send:r.send});return{send:async e=>{await t.initialize();const s=e.cc!==void 0&&e.cc.length>0,o=e.bcc!==void 0&&e.bcc.length>0;if(s||o)throw new n({message:"@lunora/mail: Cloudflare Email Workers does not support cc/bcc — fan out one send per recipient instead",retryable:!1});const{first:c,list:i}=d(e.to);if(i.length>1)throw new n({message:`@lunora/mail: Cloudflare Email Workers is single-recipient but received ${String(i.length)} \`to\` addresses — fan out one send per recipient instead`,retryable:!1});const a=await t.sendEmail(m(e,r.from,c));return f(a)}}};export{h as createCloudflareTransport};
1
+ import{cloudflareEmailProvider as l}from"@visulima/email/providers/cloudflare-email";import{r as d,t as m,i as f}from"./provider-transport-C-ioZWVF.mjs";import{MailSendError as n}from"./MailSendError-BYih5mnM.mjs";const h=r=>{const t=l({send:r.send});return{send:async e=>{await t.initialize();const s=e.cc!==void 0&&e.cc.length>0,o=e.bcc!==void 0&&e.bcc.length>0;if(s||o)throw new n({message:"@lunora/mail: Cloudflare Email Workers does not support cc/bcc — fan out one send per recipient instead",retryable:!1});const{first:c,list:i}=d(e.to);if(i.length>1)throw new n({message:`@lunora/mail: Cloudflare Email Workers is single-recipient but received ${String(i.length)} \`to\` addresses — fan out one send per recipient instead`,retryable:!1});const a=await t.sendEmail(m(e,r.from,c));return f(a)}}};export{h as createCloudflareTransport};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{D as l,p as f,a as w}from"./shard-C5t-b7FX.mjs";const E=r=>{let n="";for(let e=0;e<r.length;e+=32768)n+=String.fromCharCode(...r.subarray(e,e+32768));return btoa(n)},b="message could not be processed",y=10*1024*1024,h=(r,n)=>{console.error("@lunora/mail/inbound: dropping message —",r),n.message.setReject(b)},m=r=>r===!0||r===void 0,A=(r,n)=>{if(typeof r.rawSize!="number"||!Number.isFinite(r.rawSize))throw new c("INTERNAL","@lunora/mail/inbound: message has no rawSize, so its size cannot be checked against maxRawBytes");if(r.rawSize>n)throw new c("INTERNAL",`@lunora/mail/inbound: message is ${String(r.rawSize)} bytes, over the ${String(n)}-byte limit (maxRawBytes)`)},S=r=>{const n=r.onError??h,t=r.maxRawBytes??y;if(!Number.isFinite(t)||t<=0)throw new c("INTERNAL","@lunora/mail/inbound: `maxRawBytes` must be a positive, finite number of bytes");return async(e,a,i)=>{const o={ctx:i,env:a,message:e};let u;try{if(A(e,t),u=await r.parse(e.raw),r.verify){const s=await r.verify(u,o);if(!m(s))throw new c("INTERNAL","@lunora/mail/inbound: sender verification rejected the message")}}catch(s){await n(s,o);return}try{await r.dispatch(u,o)}catch(s){if(r.onError)try{await r.onError(s,o)}catch(d){console.error("@lunora/mail/inbound: onError threw while reporting a dispatch failure —",d)}if(r.retain)try{await r.retain(u,o,s);return}catch(d){console.error("@lunora/mail/inbound: retain failed to take ownership of the message —",d)}h(s,o)}}},g=4*1024*1024,N=/={1,2}$/,R=(r,n)=>{if(n!=="base64")return new TextEncoder().encode(r).byteLength;const t=N.exec(r)?.[0].length??0;return Math.floor(r.length*3/4)-t},T=r=>{if(r.attachments.length===0)return r;let n=0;return{...r,attachments:r.attachments.map(t=>{const{content:e}=t,a=typeof e=="string"?R(e,t.encoding):e.byteLength;if(n+a>g)return{...t,content:"",encoding:"base64",truncated:!0};if(n+=a,typeof e=="string")return t;const i=e instanceof Uint8Array?e:new Uint8Array(e);return{...t,content:E(i),encoding:"base64"}})}},v=r=>{const n=r.shardKey??l,t=r.resolveArgs??(e=>T(e));return async(e,a)=>{const i=r.adminToken??(typeof a.env.LUNORA_ADMIN_TOKEN=="string"?a.env.LUNORA_ADMIN_TOKEN:void 0);if(i===void 0||i==="")throw new c("INTERNAL","@lunora/mail/inbound: missing LUNORA_ADMIN_TOKEN — cannot authorize inbound dispatch to the shard RPC.");const o={args:t(e,a),functionPath:r.functionPath,shardKey:n};await f(w(r.shard,r.jurisdiction),{adminToken:i,envelope:o,label:`@lunora/mail/inbound: dispatch to \`${r.functionPath}\``,shardKey:n})}};export{S as createInboundEmailHandler,v as dispatchToLunoraFunction};
@@ -0,0 +1 @@
1
+ import{LunoraError as l}from"@lunora/errors";import{a as i,b,d as h}from"./address-BKzIBZxE.mjs";import{isCaptureTransport as T}from"./createCaptureTransport-DZhMUmaI.mjs";import{createCloudflareTransport as p}from"./createCloudflareTransport-2pH3460e.mjs";import{toQueuedPayload as S}from"./consumeQueuedSend-CDDDeoAz.mjs";import E from"./renderEmail-xypKDdux.mjs";import g from"./createResendTransport-DdsftR55.mjs";import{MailSendError as c}from"./MailSendError-BYih5mnM.mjs";const q=()=>{if(typeof crypto<"u"){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues=="function"){const r=crypto.getRandomValues(new Uint8Array(16));return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}}throw new Error("randomSessionId: no Web Crypto available — a session id needs crypto.randomUUID or crypto.getRandomValues")},I=6e4,y=2147483647,U=async(r,t)=>{let d;const s=new Promise((m,f)=>{d=setTimeout(()=>{f(new c({message:`@lunora/mail: send timed out after ${String(t)}ms, so it may have been delivered`,outcomeUnknown:!0,retryable:!1}))},t)});try{return await Promise.race([r,s])}finally{clearTimeout(d)}},N=r=>{if(r.cloudflareSend)return p({from:r.from,send:r.cloudflareSend});if(r.apiKey)return g(r.apiKey,r.from);if(r.queue)return{send:()=>Promise.reject(new c({message:"@lunora/mail: no transport configured — this mailer can only queue(); pass `transport`, `cloudflareSend` (a SEND_EMAIL binding) or `apiKey` (Resend) to send()",retryable:!0}))};throw new l("INTERNAL","@lunora/mail: a transport is required — pass `transport`, `cloudflareSend` (Cloudflare Email Workers, the default), or `apiKey` (Resend), or a `queue` for a producer-only mailer")},P=r=>{if(!r.from)throw new l("INTERNAL","@lunora/mail: `from` is required");const t=r.sendTimeoutMs??I;if(!Number.isFinite(t)||t<=0||t>y)throw new l("INTERNAL",`@lunora/mail: \`sendTimeoutMs\` must be a positive number of milliseconds, at most ${String(y)}`);const d=r.transport??N(r),s=async e=>{let{html:u}=e,{text:o}=e;if(e.react){const n=await E(e.react);u=u??n.html,o=o??n.text}if(i("subject",e.subject),b(e.idempotencyKey),e.headers)for(const[n,w]of Object.entries(e.headers))i(`header name "${n}"`,n),i(`header "${n}" value`,w);const a=e.from??r.from;return h({bcc:e.bcc,cc:e.cc,from:a,replyTo:e.replyTo,to:e.to}),{bcc:e.bcc?.length?e.bcc:void 0,cc:e.cc?.length?e.cc:void 0,from:a,headers:e.headers,html:u,replyTo:e.replyTo,subject:e.subject,text:o,to:e.to}},m=async e=>{const u=await s(e),{idempotencyKey:o}=e;try{return await U(d.send(u,{idempotencyKey:o}),t)}catch(a){if(!(a instanceof c))throw new c({cause:a,retryable:!0});const n=o!==void 0&&d.dedupesOnIdempotencyKey===!0;throw a.outcomeUnknown&&a.retryable!==n?new c({cause:a.cause,message:a.message,outcomeUnknown:!0,retryable:n}):a}};return{queue:async e=>{if(!r.queue){if(T(d))return await m(e),{queued:!0};throw new l("INTERNAL","@lunora/mail: `queue` binding is required for mailer.queue()")}const u=await s(e),o=e.idempotencyKey??q();return await r.queue.send(S({...u,idempotencyKey:o})),{queued:!0}},send:m}};export{P as default};
@@ -0,0 +1 @@
1
+ import{resendProvider as c}from"@visulima/email/providers/resend";import{r as m,t as p,i as l}from"./provider-transport-C-ioZWVF.mjs";const f=(i,n)=>{const e=c({apiKey:i});return{dedupesOnIdempotencyKey:!0,send:async(t,s)=>{await e.initialize();const{first:o,list:r}=m(t.to),a=p(t,n,r.length===1?o:r),d=await e.sendEmail({...a,idempotencyKey:s?.idempotencyKey});return l(d)}}};export{f as default};
@@ -0,0 +1 @@
1
+ import{t as s,c as o}from"./address-BKzIBZxE.mjs";import{MailSendError as n}from"./MailSendError-BYih5mnM.mjs";const u=e=>e instanceof Error?e.message:e==null?"send failed":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?e.toString():JSON.stringify(e)??"send failed",a=/^\d{3}$/,f=e=>typeof e=="number"?e:typeof e=="string"&&a.test(e)?Number(e):void 0,d="ETIMEDOUT",i=e=>{const t=[];for(let r=e;r instanceof Error&&t.length<5;r=r.cause)t.push(r);return t},m=e=>i(e).some(t=>"code"in t&&t.code===d),c=e=>{for(const t of i(e)){const r=f("code"in t?t.code:void 0);if(r!==void 0)return r}},l=409,h=e=>{if(!(e instanceof Error))return!0;const t=c(e);return t!==void 0&&t>=100&&t<=599?t===408||t===429||t>=500:!0},p=e=>{const t=s(e),[r]=t??[];if(!t||r===void 0)throw new n({message:"@lunora/mail: at least one recipient is required",retryable:!1});return{first:r,list:t}},T=(e,t,r)=>({bcc:s(e.bcc),cc:s(e.cc),from:o(e.from??t),headers:e.headers,html:e.html,replyTo:e.replyTo?o(e.replyTo):void 0,subject:e.subject,text:e.text,to:r}),g=e=>{if(e.success&&!e.data)throw new n({message:"@lunora/mail: provider accepted the send but returned no message id",retryable:!1});if(!e.success||!e.data)throw console.error(`@lunora/mail: send failed: ${u(e.error)}`),m(e.error)?new n({cause:e.error,message:"@lunora/mail: the provider timed out, so the send may have been delivered",outcomeUnknown:!0,retryable:!1}):c(e.error)===l?new n({cause:e.error,message:"@lunora/mail: the provider is still processing a send with this idempotency key, so it may be delivered",outcomeUnknown:!0,retryable:!1}):new n({cause:e.error,retryable:h(e.error)});return{id:e.data.messageId}};export{g as i,p as r,T as t};
@@ -1,4 +1,4 @@
1
- import { C as CapturedMail } from "./packem_shared/capture-transport.d-BD67fxbB.mjs";
1
+ import { C as CapturedMail } from "./packem_shared/capture-transport.d-G-OVrGhG.mjs";
2
2
  import 'react';
3
3
  /** Minimal `fetch` projection so a test can inject a stub. */
4
4
  type FetchLike = (input: string, init?: {
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as CapturedMail } from "./packem_shared/capture-transport.d-BD67fxbB.js";
1
+ import { C as CapturedMail } from "./packem_shared/capture-transport.d-G-OVrGhG.js";
2
2
  import 'react';
3
3
  /** Minimal `fetch` projection so a test can inject a stub. */
4
4
  type FetchLike = (input: string, init?: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/mail",
3
- "version": "1.0.0-alpha.137",
3
+ "version": "1.0.0-alpha.139",
4
4
  "description": "Email for Lunora: Resend adapter, TSX templates, and queue-backed sends",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{LunoraError as l}from"@lunora/errors";class t extends l{retryable;constructor(r){const a={retryable:r.retryable};super("INTERNAL",r.message??"@lunora/mail: send failed",{cause:r.cause,data:a,name:"MailSendError"}),this.retryable=r.retryable}}const n=e=>e instanceof t&&e.retryable;export{t as MailSendError,n as isRetryableMailError};
@@ -1,3 +0,0 @@
1
- import{LunoraError as t}from"@lunora/errors";const n=320,a=256,d=/^([^<]*)<([^>]*)>\s*$/,i=(r,s)=>{if(s.includes("\r")||s.includes(`
2
- `)||s.includes(","))throw new t("INTERNAL",`@lunora/mail: address ${r} must not contain CR, LF, or comma`)},u=(r,s)=>{if(s.includes("\r")||s.includes(`
3
- `))throw new t("INTERNAL",`@lunora/mail: ${r} must not contain CR or LF`)},m=(r,s)=>{if(r.length>a)throw new t("INTERNAL",`@lunora/mail: address name must be <= ${String(a)} characters`);if(s.length>n)throw new t("INTERNAL",`@lunora/mail: address email must be <= ${String(n)} characters`);return r&&i("name",r),i("email",s),r?{email:s,name:r}:{email:s}},l=r=>{const s=r.trim();if(s.length>n)throw new t("INTERNAL",`@lunora/mail: address email must be <= ${String(n)} characters`);return i("email",s),{email:s}},c=r=>{const s=d.exec(r),e=(s?.[2]??"").trim();return s&&e?m((s[1]??"").trim(),e):l(r)},o=r=>{if(r===void 0)return;const s=Array.isArray(r)?r:[r];if(s.length!==0)return s.map(e=>c(e))},f=r=>{if(o(r.to)===void 0)throw new t("INTERNAL","@lunora/mail: at least one recipient is required");o(r.cc),o(r.bcc),r.from!==void 0&&c(r.from),r.replyTo!==void 0&&c(r.replyTo)};export{u as a,c as b,f as c,o as t};
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";const d=n=>{const t={...n};return delete t.react,t},p=async(n,t)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new c("INTERNAL","@lunora/mail: queue message body must be an object");const e=t;if(typeof e.subject!="string")throw new TypeError("@lunora/mail: queue message must have a string `subject`");const y=typeof e.to=="string",m=Array.isArray(e.to)&&e.to.every(o=>typeof o=="string");if(!y&&!m)throw new c("INTERNAL","@lunora/mail: queue message `to` must be a string or string[]");const s=(o,r)=>{if(r!==void 0){if(typeof r!="string")throw new TypeError(`@lunora/mail: queue message \`${o}\` must be a string`);return r}},a=(o,r)=>{if(r!==void 0){if(typeof r=="string")return[r];if(Array.isArray(r)&&r.every(i=>typeof i=="string"))return r;throw new TypeError(`@lunora/mail: queue message \`${o}\` must be a string or string[]`)}};let u;if(e.headers!==void 0){if(!e.headers||typeof e.headers!="object"||Array.isArray(e.headers))throw new TypeError("@lunora/mail: queue message `headers` must be an object of string values");const o=Object.entries(e.headers);for(const[r,i]of o)if(typeof i!="string")throw new TypeError(`@lunora/mail: queue message header "${r}" must be a string`);u=e.headers}const f={bcc:a("bcc",e.bcc),cc:a("cc",e.cc),from:s("from",e.from),headers:u,html:s("html",e.html),idempotencyKey:s("idempotencyKey",e.idempotencyKey),replyTo:s("replyTo",e.replyTo),subject:e.subject,text:s("text",e.text),to:e.to};return n.send(f)};export{p as consumeQueuedSend,d as toQueuedPayload};
@@ -1 +0,0 @@
1
- import{createCaptureTransport as d}from"./createCaptureTransport-DZhMUmaI.mjs";import"./createCloudflareTransport-fOhfy2fP.mjs";import s from"./createMailer-C5NIzkNb.mjs";import{LunoraError as l}from"@lunora/errors";import{D as p,a as E,p as _}from"./shard-C5t-b7FX.mjs";import"./consumeQueuedSend-CRfALnCU.mjs";import"./renderEmail-xypKDdux.mjs";import"./createResendTransport-q3surKen.mjs";import"./MailSendError-HH5Yimut.mjs";const N="__lunora_admin__:recordMail",m=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,f=["CF_ENV","ENVIRONMENT","NODE_ENV","WORKER_ENV"],R=(r,e)=>{const o=r[e];if(typeof o!="string"||o==="")throw new l("INTERNAL",`@lunora/mail: missing env var \`${e}\` — set it in .dev.vars (and \`wrangler secret put ${e}\` for secrets).`);return o},A=r=>{const e=r.LUNORA_MAIL_CAPTURE;if(typeof e=="string"){const t=e.toLowerCase();if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;console.warn(`@lunora/mail: unrecognized LUNORA_MAIL_CAPTURE value "${e}" — expected "1"/"true" or "0"/"false"; falling back to environment detection.`)}const o=f.map(t=>r[t]).filter(t=>typeof t=="string"&&t!=="");return o.length>0&&o.every(t=>m.test(t))};let u=!1;const g=(r,e=p,o)=>({record:async t=>{const i=r.SHARD,a=typeof r.LUNORA_ADMIN_TOKEN=="string"?r.LUNORA_ADMIN_TOKEN:void 0;if(i===void 0||a===void 0)return u||(u=!0,console.warn("@lunora/mail: capturing mail but there is nowhere to record it — the `SHARD` binding and/or `LUNORA_ADMIN_TOKEN` is missing, so every captured message is discarded. Set both to see mail in the studio inbox, or set LUNORA_MAIL_CAPTURE=0 to deliver for real.")),{id:"uncaptured"};const c=E(i,o);try{return{id:(await _(c,{adminToken:a,envelope:{args:t,functionPath:N},label:"@lunora/mail: recording captured mail",shardKey:e})).result?.id??"captured"}}catch(n){return console.error("@lunora/mail: failed to record captured mail into the studio inbox —",n),{id:"uncaptured"}}}}),b=(r,e={})=>{const o=R(r,"MAIL_FROM");if(A(r))return s({from:o,queue:e.queue,transport:d(g(r,e.rootShard,e.jurisdiction))});const{cloudflareSend:t}=e,i=typeof r.RESEND_API_KEY=="string"&&r.RESEND_API_KEY!==""?r.RESEND_API_KEY:void 0;return s({apiKey:i,cloudflareSend:t,from:o,queue:e.queue})};export{g as createCaptureSink,b as createMailerFromEnv,A as shouldCaptureMail};
@@ -1 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";import{D as h,p as l,a as f}from"./shard-C5t-b7FX.mjs";const E=r=>{let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)},g="message could not be processed",d=(r,e)=>{console.error("@lunora/mail/inbound: dropping message —",r),e.message.setReject(g)},y=r=>r===!0||r===void 0,R=r=>{const e=r.onError??d;return async(t,n,a)=>{const o={ctx:a,env:n,message:t};let s;try{if(s=await r.parse(t.raw),r.verify){const i=await r.verify(s,o);if(!y(i))throw new u("INTERNAL","@lunora/mail/inbound: sender verification rejected the message")}}catch(i){await e(i,o);return}try{await r.dispatch(s,o)}catch(i){if(r.onError)try{await r.onError(i,o)}catch(c){console.error("@lunora/mail/inbound: onError threw while reporting a dispatch failure —",c)}if(r.retain)try{await r.retain(s,o,i);return}catch(c){console.error("@lunora/mail/inbound: retain failed to take ownership of the message —",c)}d(i,o)}}},A=4*1024*1024,b=/={1,2}$/,w=(r,e)=>{if(e!=="base64")return new TextEncoder().encode(r).byteLength;const t=b.exec(r)?.[0].length??0;return Math.floor(r.length*3/4)-t},N=r=>{if(r.attachments.length===0)return r;let e=0;return{...r,attachments:r.attachments.map(t=>{const{content:n}=t,a=typeof n=="string"?w(n,t.encoding):n.byteLength;if(e+a>A)return{...t,content:"",encoding:"base64",truncated:!0};if(e+=a,typeof n=="string")return t;const o=n instanceof Uint8Array?n:new Uint8Array(n);return{...t,content:E(o),encoding:"base64"}})}},_=r=>{const e=r.shardKey??h,t=r.resolveArgs??(n=>N(n));return async(n,a)=>{const o=r.adminToken??(typeof a.env.LUNORA_ADMIN_TOKEN=="string"?a.env.LUNORA_ADMIN_TOKEN:void 0);if(o===void 0||o==="")throw new u("INTERNAL","@lunora/mail/inbound: missing LUNORA_ADMIN_TOKEN — cannot authorize inbound dispatch to the shard RPC.");const s={args:t(n,a),functionPath:r.functionPath,shardKey:e};await l(f(r.shard,r.jurisdiction),{adminToken:o,envelope:s,label:`@lunora/mail/inbound: dispatch to \`${r.functionPath}\``,shardKey:e})}};export{R as createInboundEmailHandler,_ as dispatchToLunoraFunction};
@@ -1 +0,0 @@
1
- import{LunoraError as l}from"@lunora/errors";import{a as o,c as m}from"./address-oKy_d0aG.mjs";import{isCaptureTransport as i}from"./createCaptureTransport-DZhMUmaI.mjs";import{createCloudflareTransport as y}from"./createCloudflareTransport-fOhfy2fP.mjs";import{toQueuedPayload as b}from"./consumeQueuedSend-CRfALnCU.mjs";import w from"./renderEmail-xypKDdux.mjs";import h from"./createResendTransport-q3surKen.mjs";import{MailSendError as s}from"./MailSendError-HH5Yimut.mjs";const p=()=>{if(typeof crypto<"u"){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues=="function"){const r=crypto.getRandomValues(new Uint8Array(16));return Array.from(r,u=>u.toString(16).padStart(2,"0")).join("")}}throw new Error("randomSessionId: no Web Crypto available — a session id needs crypto.randomUUID or crypto.getRandomValues")},q=r=>{if(r.cloudflareSend)return y({from:r.from,send:r.cloudflareSend});if(r.apiKey)return h(r.apiKey,r.from);if(r.queue)return{send:()=>Promise.reject(new s({message:"@lunora/mail: no transport configured — this mailer can only queue(); pass `transport`, `cloudflareSend` (a SEND_EMAIL binding) or `apiKey` (Resend) to send()",retryable:!0}))};throw new l("INTERNAL","@lunora/mail: a transport is required — pass `transport`, `cloudflareSend` (Cloudflare Email Workers, the default), or `apiKey` (Resend), or a `queue` for a producer-only mailer")},K=r=>{if(!r.from)throw new l("INTERNAL","@lunora/mail: `from` is required");const u=r.transport??q(r),d=async e=>{let{html:t}=e,{text:a}=e;if(e.react){const n=await w(e.react);t=t??n.html,a=a??n.text}if(o("subject",e.subject),e.headers)for(const[n,f]of Object.entries(e.headers))o(`header name "${n}"`,n),o(`header "${n}" value`,f);const c=e.from??r.from;return m({bcc:e.bcc,cc:e.cc,from:c,replyTo:e.replyTo,to:e.to}),{bcc:e.bcc?.length?e.bcc:void 0,cc:e.cc?.length?e.cc:void 0,from:c,headers:e.headers,html:t,replyTo:e.replyTo,subject:e.subject,text:a,to:e.to}};return{queue:async e=>{if(!r.queue){if(i(u)){const c=await d(e);return await u.send(c),{queued:!0}}throw new l("INTERNAL","@lunora/mail: `queue` binding is required for mailer.queue()")}const t=await d(e),a=e.idempotencyKey??p();return await r.queue.send(b({...t,idempotencyKey:a})),{queued:!0}},send:async e=>{const t=await d(e);try{return await u.send(t)}catch(a){throw a instanceof s?a:new s({cause:a,retryable:!0})}}}};export{K as default};
@@ -1 +0,0 @@
1
- import{resendProvider as a}from"@visulima/email/providers/resend";import{r as d,t as c,i as l}from"./provider-transport-DklK6xUa.mjs";const u=(i,s)=>{const e=a({apiKey:i});return{send:async r=>{await e.initialize();const{first:n,list:t}=d(r.to),o=await e.sendEmail(c(r,s,t.length===1?n:t));return l(o)}}};export{u as default};
@@ -1 +0,0 @@
1
- import{t as n,b as o}from"./address-oKy_d0aG.mjs";import{MailSendError as s}from"./MailSendError-HH5Yimut.mjs";const f=e=>e instanceof Error?e.message:e==null?"send failed":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?e.toString():JSON.stringify(e)??"send failed",c=/^\d{3}$/,u=e=>typeof e=="number"?e:typeof e=="string"&&c.test(e)?Number(e):void 0,d=e=>{if(!(e instanceof Error))return!0;let t;for(let r=e,i=0;r instanceof Error&&i<5&&(t=u("code"in r?r.code:void 0),t===void 0);r=r.cause,i+=1);return t!==void 0&&t>=100&&t<=599?t===408||t===429||t>=500:!0},b=e=>{const t=n(e),[r]=t??[];if(!t||r===void 0)throw new s({message:"@lunora/mail: at least one recipient is required",retryable:!1});return{first:r,list:t}},l=(e,t,r)=>({bcc:n(e.bcc),cc:n(e.cc),from:o(e.from??t),headers:e.headers,html:e.html,replyTo:e.replyTo?o(e.replyTo):void 0,subject:e.subject,text:e.text,to:r}),p=e=>{if(e.success&&!e.data)throw new s({message:"@lunora/mail: provider accepted the send but returned no message id",retryable:!1});if(!e.success||!e.data)throw console.error(`@lunora/mail: send failed: ${f(e.error)}`),new s({cause:e.error,retryable:d(e.error)});return{id:e.data.messageId}};export{p as i,b as r,l as t};