@lunora/mail 1.0.0-alpha.14 → 1.0.0-alpha.141
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +201 -104
- package/README.md +3 -3
- package/dist/inbound/index.d.mts +340 -89
- package/dist/inbound/index.d.ts +340 -89
- package/dist/inbound/index.mjs +1 -2
- package/dist/index.d.mts +279 -97
- package/dist/index.d.ts +279 -97
- package/dist/index.mjs +1 -7
- package/dist/packem_shared/MailSendError-BYih5mnM.mjs +1 -0
- package/dist/packem_shared/assertValidIdempotencyKey-CyJq0nZq.mjs +3 -0
- package/dist/packem_shared/authenticatesFrom-UBe_EgRT.mjs +1 -0
- package/dist/packem_shared/capture-transport.d-G-OVrGhG.d.mts +170 -0
- package/dist/packem_shared/capture-transport.d-G-OVrGhG.d.ts +170 -0
- package/dist/packem_shared/consumeQueuedSend-BwNGdlaG.mjs +1 -0
- package/dist/packem_shared/createCaptureSink-BCAMuG4n.mjs +1 -0
- package/dist/packem_shared/createCaptureTransport-DZhMUmaI.mjs +1 -0
- package/dist/packem_shared/createCloudflareTransport-Dxjf_b6q.mjs +1 -0
- package/dist/packem_shared/createInboundEmailHandler-ByzpfcEI.mjs +1 -0
- package/dist/packem_shared/createMailer-Cv1B9wYq.mjs +1 -0
- package/dist/packem_shared/createResendTransport-CsJfCLAP.mjs +1 -0
- package/dist/packem_shared/provider-transport-Ce2xVUuM.mjs +1 -0
- package/dist/packem_shared/renderEmail-xypKDdux.mjs +1 -0
- package/dist/packem_shared/shard-Bgo7dYFl.mjs +1 -0
- package/dist/packem_shared/{shard.d-C4kxvfmd.d.mts → shard.d-DVADjmEJ.d.mts} +7 -12
- package/dist/packem_shared/{shard.d-C4kxvfmd.d.ts → shard.d-DVADjmEJ.d.ts} +7 -12
- package/dist/testing.d.mts +9 -9
- package/dist/testing.d.ts +9 -9
- package/dist/testing.mjs +1 -65
- package/package.json +7 -6
- package/dist/packem_shared/address-vSUAVU2T.mjs +0 -64
- package/dist/packem_shared/capture-transport.d-ChnhdPO2.d.mts +0 -117
- package/dist/packem_shared/capture-transport.d-ChnhdPO2.d.ts +0 -117
- package/dist/packem_shared/consumeQueuedSend-B9hTDOZ6.mjs +0 -77
- package/dist/packem_shared/createCaptureSink-B0c7fQJf.mjs +0 -77
- package/dist/packem_shared/createCaptureTransport-Crz_8822.mjs +0 -11
- package/dist/packem_shared/createCloudflareTransport-DXh1nUNi.mjs +0 -28
- package/dist/packem_shared/createInboundEmailHandler-BMB5t-qh.mjs +0 -74
- package/dist/packem_shared/createMailer-B4Z_Cgiu.mjs +0 -81
- package/dist/packem_shared/createResendTransport-CMQWjZoi.mjs +0 -16
- package/dist/packem_shared/parseInboundEmail-DXVOH0wz.mjs +0 -73
- package/dist/packem_shared/provider-transport-C0xHi3oy.mjs +0 -48
- package/dist/packem_shared/renderEmail-hyS1bpVP.mjs +0 -8
- package/dist/packem_shared/shard-DEDcQoFg.mjs +0 -36
|
@@ -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 };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{assertValidIdempotencyKey as O}from"./assertValidIdempotencyKey-CyJq0nZq.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"./assertValidIdempotencyKey-CyJq0nZq.mjs";import{createCaptureTransport as c}from"./createCaptureTransport-DZhMUmaI.mjs";import"./createCloudflareTransport-Dxjf_b6q.mjs";import s from"./createMailer-Cv1B9wYq.mjs";import{LunoraError as l}from"@lunora/errors";import{D as m,a as p,p as E}from"./shard-Bgo7dYFl.mjs";import"./consumeQueuedSend-BwNGdlaG.mjs";import"./renderEmail-xypKDdux.mjs";import"./createResendTransport-CsJfCLAP.mjs";import"./MailSendError-BYih5mnM.mjs";const _="__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=p(i,o);try{return{id:(await E(d,{adminToken:a,envelope:{args:t,functionPath:_},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"}}}}),v=(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,v as createMailerFromEnv,A as shouldCaptureMail};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=Symbol.for("@lunora/mail.captureTransport"),a=r=>r[t]===!0,s=r=>({[t]:!0,send:async o=>r.record(o)});export{s as createCaptureTransport,a as isCaptureTransport};
|
|
@@ -0,0 +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-Ce2xVUuM.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-Bgo7dYFl.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{assertSafeHeaderValue as i,assertValidIdempotencyKey as b,assertSafeAddresses as h,assertHasContent as T}from"./assertValidIdempotencyKey-CyJq0nZq.mjs";import{isCaptureTransport as p}from"./createCaptureTransport-DZhMUmaI.mjs";import{createCloudflareTransport as S}from"./createCloudflareTransport-Dxjf_b6q.mjs";import{toQueuedPayload as E}from"./consumeQueuedSend-BwNGdlaG.mjs";import g from"./renderEmail-xypKDdux.mjs";import q from"./createResendTransport-CsJfCLAP.mjs";import{MailSendError as d}from"./MailSendError-BYih5mnM.mjs";const I=()=>{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")},U=6e4,y=2147483647,N=async(r,t)=>{let c;const s=new Promise((m,f)=>{c=setTimeout(()=>{f(new d({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(c)}},v=r=>{if(r.cloudflareSend)return S({from:r.from,send:r.cloudflareSend});if(r.apiKey)return q(r.apiKey,r.from);if(r.queue)return{send:()=>Promise.reject(new d({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??U;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 c=r.transport??v(r),s=async e=>{let{html:u}=e,{text:n}=e;if(e.react){const o=await g(e.react);u=u??o.html,n=n??o.text}if(i("subject",e.subject),b(e.idempotencyKey),e.headers)for(const[o,w]of Object.entries(e.headers))i(`header name "${o}"`,o),i(`header "${o}" value`,w);const a=e.from??r.from;return h({bcc:e.bcc,cc:e.cc,from:a,replyTo:e.replyTo,to:e.to}),T({html:u,text:n}),{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:n,to:e.to}},m=async e=>{const u=await s(e),{idempotencyKey:n}=e;try{return await N(c.send(u,{idempotencyKey:n}),t)}catch(a){if(!(a instanceof d))throw new d({cause:a,retryable:!0});const o=n!==void 0&&c.dedupesOnIdempotencyKey===!0;throw a.outcomeUnknown&&a.retryable!==o?new d({cause:a.cause,message:a.message,outcomeUnknown:!0,retryable:o}):a}};return{queue:async e=>{if(!r.queue){if(p(c))return await m(e),{queued:!0};throw new l("INTERNAL","@lunora/mail: `queue` binding is required for mailer.queue()")}const u=await s(e),n=e.idempotencyKey??I();return await r.queue.send(E({...u,idempotencyKey:n})),{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-Ce2xVUuM.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{toAddressList as s,assertHasContent as u,toAddress as o}from"./assertValidIdempotencyKey-CyJq0nZq.mjs";import{MailSendError as n}from"./MailSendError-BYih5mnM.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",a=/^\d{3}$/,d=e=>typeof e=="number"?e:typeof e=="string"&&a.test(e)?Number(e):void 0,m="ETIMEDOUT",i=e=>{const t=[];for(let r=e;r instanceof Error&&t.length<5;r=r.cause)t.push(r);return t},l=e=>i(e).some(t=>"code"in t&&t.code===m),c=e=>{for(const t of i(e)){const r=d("code"in t?t.code:void 0);if(r!==void 0)return r}},h=409,b=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}},g=(e,t,r)=>(u(e),{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}),y=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: ${f(e.error)}`),l(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)===h?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:b(e.error)});return{id:e.data.messageId}};export{y as i,p as r,g as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=async e=>{const{render:a,toPlainText:r}=await import("@react-email/render"),t=await a(e,{pretty:!1});return{html:t,text:r(t)}};export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{encodeWire as a}from"@lunora/wire";const c=Symbol.for("lunora:app-jurisdiction"),d=globalThis,l=()=>d[c],f="__root__",h=(t,r)=>{const e=l();if(r!==void 0&&e!==void 0&&r!==e)throw new TypeError(`@lunora/mail: jurisdiction "${r}" contradicts the app's declared jurisdiction "${e}" — drop the option; mail follows the schema's \`.jurisdiction()\``);const o=r??e;if(o===void 0)return t;if(typeof t.jurisdiction!="function")throw new TypeError(`@lunora/mail: Durable Object namespace does not support jurisdiction("${o}") — update @cloudflare/workers-types or remove the jurisdiction`);return t.jurisdiction(o)},y=async(t,r)=>{const o=await t.get(t.idFromName(r.shardKey)).fetch("https://shard.internal/rpc",{body:JSON.stringify({...r.envelope,args:r.envelope.args===void 0?void 0:a(r.envelope.args)}),headers:{authorization:`Bearer ${r.adminToken}`,"content-type":"application/json","x-lunora-system":"1"},method:"POST"});if(o.ok===!1)throw new s("INTERNAL",`${r.label} failed (HTTP ${String(o.status??"?")}).`);const i=await o.json();if(typeof i=="object"&&i!==null&&"error"in i){const{error:n}=i;if(n!=null)throw new s("INTERNAL",`${r.label} returned an error: ${JSON.stringify(n)}`)}return i};export{f as D,h as a,y as p};
|
|
@@ -11,24 +11,19 @@ interface ShardStubLike {
|
|
|
11
11
|
}>;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
* Cloudflare Durable Object data-residency jurisdiction. Widening union —
|
|
15
|
-
* Cloudflare adds values over time.
|
|
16
|
-
* @see https://developers.cloudflare.com/durable-objects/reference/data-location/
|
|
17
|
-
*/
|
|
14
|
+
* Cloudflare Durable Object data-residency jurisdiction. Widening union —
|
|
15
|
+
* Cloudflare adds values over time.
|
|
16
|
+
* @see https://developers.cloudflare.com/durable-objects/reference/data-location/
|
|
17
|
+
*/
|
|
18
18
|
type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
|
|
19
19
|
/** Structural projection of the `SHARD` Durable Object namespace. */
|
|
20
20
|
interface ShardNamespaceLike {
|
|
21
21
|
get: (id: unknown) => ShardStubLike;
|
|
22
22
|
idFromName: (name: string) => unknown;
|
|
23
23
|
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
* Derive a jurisdiction-restricted subnamespace. Optional because older
|
|
25
|
+
* workers-types releases (and test doubles) may not expose it.
|
|
26
|
+
*/
|
|
27
27
|
jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => ShardNamespaceLike;
|
|
28
28
|
}
|
|
29
|
-
/**
|
|
30
|
-
* Return a jurisdiction-restricted view of `namespace`, or `namespace`
|
|
31
|
-
* unchanged when no jurisdiction is configured. Fail-closed when the binding
|
|
32
|
-
* lacks `.jurisdiction()` so a residency constraint is never silently dropped.
|
|
33
|
-
*/
|
|
34
29
|
export { DurableObjectJurisdiction as D, ShardNamespaceLike as S, ShardStubLike as a };
|
|
@@ -11,24 +11,19 @@ interface ShardStubLike {
|
|
|
11
11
|
}>;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
* Cloudflare Durable Object data-residency jurisdiction. Widening union —
|
|
15
|
-
* Cloudflare adds values over time.
|
|
16
|
-
* @see https://developers.cloudflare.com/durable-objects/reference/data-location/
|
|
17
|
-
*/
|
|
14
|
+
* Cloudflare Durable Object data-residency jurisdiction. Widening union —
|
|
15
|
+
* Cloudflare adds values over time.
|
|
16
|
+
* @see https://developers.cloudflare.com/durable-objects/reference/data-location/
|
|
17
|
+
*/
|
|
18
18
|
type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
|
|
19
19
|
/** Structural projection of the `SHARD` Durable Object namespace. */
|
|
20
20
|
interface ShardNamespaceLike {
|
|
21
21
|
get: (id: unknown) => ShardStubLike;
|
|
22
22
|
idFromName: (name: string) => unknown;
|
|
23
23
|
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
* Derive a jurisdiction-restricted subnamespace. Optional because older
|
|
25
|
+
* workers-types releases (and test doubles) may not expose it.
|
|
26
|
+
*/
|
|
27
27
|
jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => ShardNamespaceLike;
|
|
28
28
|
}
|
|
29
|
-
/**
|
|
30
|
-
* Return a jurisdiction-restricted view of `namespace`, or `namespace`
|
|
31
|
-
* unchanged when no jurisdiction is configured. Fail-closed when the binding
|
|
32
|
-
* lacks `.jurisdiction()` so a residency constraint is never silently dropped.
|
|
33
|
-
*/
|
|
34
29
|
export { DurableObjectJurisdiction as D, ShardNamespaceLike as S, ShardStubLike as a };
|
package/dist/testing.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CapturedMail } from "./packem_shared/capture-transport.d-
|
|
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?: {
|
|
@@ -33,16 +33,16 @@ interface WaitForMailOptions extends InboxOptions {
|
|
|
33
33
|
/** Read the captured-mail inbox (newest first). */
|
|
34
34
|
declare const listCapturedMail: (options: InboxOptions) => Promise<CapturedMail[]>;
|
|
35
35
|
/**
|
|
36
|
-
* Poll the captured-mail inbox until a message addressed to `to` (optionally
|
|
37
|
-
* matching `subjectMatch`) appears, then return it. Throws on timeout. Entries
|
|
38
|
-
* are newest-first, so the most recent matching message wins.
|
|
39
|
-
*/
|
|
36
|
+
* Poll the captured-mail inbox until a message addressed to `to` (optionally
|
|
37
|
+
* matching `subjectMatch`) appears, then return it. Throws on timeout. Entries
|
|
38
|
+
* are newest-first, so the most recent matching message wins.
|
|
39
|
+
*/
|
|
40
40
|
declare const waitForMail: (options: WaitForMailOptions) => Promise<CapturedMail>;
|
|
41
41
|
/**
|
|
42
|
-
* Pull the first link out of a captured message — html first, then text. Pass
|
|
43
|
-
* `match` to require the URL contain a substring (e.g. `"/reset-password"`),
|
|
44
|
-
* which disambiguates the action link from a logo/footer URL.
|
|
45
|
-
*/
|
|
42
|
+
* Pull the first link out of a captured message — html first, then text. Pass
|
|
43
|
+
* `match` to require the URL contain a substring (e.g. `"/reset-password"`),
|
|
44
|
+
* which disambiguates the action link from a logo/footer URL.
|
|
45
|
+
*/
|
|
46
46
|
declare const extractLink: (mail: CapturedMail, options?: {
|
|
47
47
|
match?: string;
|
|
48
48
|
}) => string;
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CapturedMail } from "./packem_shared/capture-transport.d-
|
|
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?: {
|
|
@@ -33,16 +33,16 @@ interface WaitForMailOptions extends InboxOptions {
|
|
|
33
33
|
/** Read the captured-mail inbox (newest first). */
|
|
34
34
|
declare const listCapturedMail: (options: InboxOptions) => Promise<CapturedMail[]>;
|
|
35
35
|
/**
|
|
36
|
-
* Poll the captured-mail inbox until a message addressed to `to` (optionally
|
|
37
|
-
* matching `subjectMatch`) appears, then return it. Throws on timeout. Entries
|
|
38
|
-
* are newest-first, so the most recent matching message wins.
|
|
39
|
-
*/
|
|
36
|
+
* Poll the captured-mail inbox until a message addressed to `to` (optionally
|
|
37
|
+
* matching `subjectMatch`) appears, then return it. Throws on timeout. Entries
|
|
38
|
+
* are newest-first, so the most recent matching message wins.
|
|
39
|
+
*/
|
|
40
40
|
declare const waitForMail: (options: WaitForMailOptions) => Promise<CapturedMail>;
|
|
41
41
|
/**
|
|
42
|
-
* Pull the first link out of a captured message — html first, then text. Pass
|
|
43
|
-
* `match` to require the URL contain a substring (e.g. `"/reset-password"`),
|
|
44
|
-
* which disambiguates the action link from a logo/footer URL.
|
|
45
|
-
*/
|
|
42
|
+
* Pull the first link out of a captured message — html first, then text. Pass
|
|
43
|
+
* `match` to require the URL contain a substring (e.g. `"/reset-password"`),
|
|
44
|
+
* which disambiguates the action link from a logo/footer URL.
|
|
45
|
+
*/
|
|
46
46
|
declare const extractLink: (mail: CapturedMail, options?: {
|
|
47
47
|
match?: string;
|
|
48
48
|
}) => string;
|
package/dist/testing.mjs
CHANGED
|
@@ -1,65 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
const GET_CAPTURED_MAIL_OP = "__lunora_admin__:getCapturedMail";
|
|
4
|
-
const DEFAULT_RPC_PATH = "/_lunora/rpc";
|
|
5
|
-
const TRAILING_SLASH = /\/$/;
|
|
6
|
-
const sleep = async (ms) => new Promise((resolve) => {
|
|
7
|
-
setTimeout(resolve, ms);
|
|
8
|
-
});
|
|
9
|
-
const recipients = (mail) => Array.isArray(mail.to) ? mail.to : [mail.to];
|
|
10
|
-
const listCapturedMail = async (options) => {
|
|
11
|
-
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
12
|
-
const endpoint = `${options.baseUrl.replace(TRAILING_SLASH, "")}${DEFAULT_RPC_PATH}`;
|
|
13
|
-
const response = await fetchImpl(endpoint, {
|
|
14
|
-
body: JSON.stringify({ args: { limit: options.limit ?? 50 }, functionPath: GET_CAPTURED_MAIL_OP }),
|
|
15
|
-
headers: { authorization: `Bearer ${options.adminToken}`, "content-type": "application/json" },
|
|
16
|
-
method: "POST"
|
|
17
|
-
});
|
|
18
|
-
if (!response.ok) {
|
|
19
|
-
throw new LunoraError("INTERNAL", `@lunora/mail/testing: getCapturedMail failed (HTTP ${String(response.status)})`);
|
|
20
|
-
}
|
|
21
|
-
const body = await response.json();
|
|
22
|
-
return body.result?.entries ?? [];
|
|
23
|
-
};
|
|
24
|
-
const waitForMail = async (options) => {
|
|
25
|
-
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
26
|
-
const pollMs = options.pollMs ?? 250;
|
|
27
|
-
const deadline = Date.now() + timeoutMs;
|
|
28
|
-
for (; ; ) {
|
|
29
|
-
const entries = await listCapturedMail(options);
|
|
30
|
-
const match = entries.find(
|
|
31
|
-
(mail) => recipients(mail).includes(options.to) && (options.subjectMatch === void 0 || mail.subject.includes(options.subjectMatch))
|
|
32
|
-
);
|
|
33
|
-
if (match) {
|
|
34
|
-
return match;
|
|
35
|
-
}
|
|
36
|
-
if (Date.now() >= deadline) {
|
|
37
|
-
throw new LunoraError(
|
|
38
|
-
"INTERNAL",
|
|
39
|
-
`@lunora/mail/testing: no mail to "${options.to}"${options.subjectMatch === void 0 ? "" : ` matching "${options.subjectMatch}"`} within ${String(timeoutMs)}ms`
|
|
40
|
-
);
|
|
41
|
-
}
|
|
42
|
-
await sleep(pollMs);
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
const URL_PATTERN = /https?:\/\/[^\s"'<>)]+/g;
|
|
46
|
-
const AMPERSAND_ENTITY = /&(?:amp|#0*38|#x0*26);/giu;
|
|
47
|
-
const decodeUrlEntities = (url) => url.replaceAll(AMPERSAND_ENTITY, "&");
|
|
48
|
-
const extractLink = (mail, options = {}) => {
|
|
49
|
-
for (const source of [mail.html, mail.text]) {
|
|
50
|
-
if (source === void 0) {
|
|
51
|
-
continue;
|
|
52
|
-
}
|
|
53
|
-
const matches = source.match(URL_PATTERN) ?? [];
|
|
54
|
-
const link = matches.find((candidate) => options.match === void 0 || candidate.includes(options.match));
|
|
55
|
-
if (link !== void 0) {
|
|
56
|
-
return decodeUrlEntities(link);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
throw new LunoraError(
|
|
60
|
-
"INTERNAL",
|
|
61
|
-
`@lunora/mail/testing: no link${options.match === void 0 ? "" : ` containing "${options.match}"`} found in the captured message`
|
|
62
|
-
);
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
export { extractLink, listCapturedMail, waitForMail };
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";const u="__lunora_admin__:getCapturedMail",h="/_lunora/rpc",m=/\/$/,d=async t=>new Promise(e=>{setTimeout(e,t)}),T=/<([^<>]*)>\s*$/u,l=t=>(T.exec(t)?.[1]??t).trim().toLowerCase(),f=t=>(Array.isArray(t.to)?t.to:[t.to]).map(e=>l(e)),A=async t=>{const e=t.fetch??globalThis.fetch,c=`${t.baseUrl.replace(m,"")}${h}`,n=await e(c,{body:JSON.stringify({args:{limit:t.limit??50},functionPath:u}),headers:{authorization:`Bearer ${t.adminToken}`,"content-type":"application/json"},method:"POST"});if(!n.ok)throw new i("INTERNAL",`@lunora/mail/testing: getCapturedMail failed (HTTP ${String(n.status)})`);return(await n.json()).result?.entries??[]},E=async t=>{const e=t.timeoutMs??1e4,c=t.pollMs??250,n=Date.now()+e;for(;;){const a=await A(t),s=l(t.to),o=a.find(r=>f(r).includes(s)&&(t.subjectMatch===void 0||r.subject.includes(t.subjectMatch)));if(o)return o;if(Date.now()>=n)throw new i("INTERNAL",`@lunora/mail/testing: no mail to "${t.to}"${t.subjectMatch===void 0?"":` matching "${t.subjectMatch}"`} within ${String(e)}ms`);await d(c)}},w=/https?:\/\/[^\s"'<>)]+/g,g=/(?<![\w-])href\s*=\s*["']?(https?:\/\/[^\s"'<>]+)/giu,M=/&(?:amp|#0*38|#x0*26);/giu,_=t=>t.replaceAll(M,"&"),N=(t,e={})=>{const c=[...(t.html??"").matchAll(g)].map(a=>a[1]??""),n=t.text?.match(w)??[];for(const a of[c,n]){const s=a.find(o=>e.match===void 0||o.includes(e.match));if(s!==void 0)return _(s)}throw new i("INTERNAL",`@lunora/mail/testing: no link${e.match===void 0?"":` containing "${e.match}"`} found in the captured message`)};export{N as extractLink,A as listCapturedMail,E as waitForMail};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/mail",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.141",
|
|
4
4
|
"description": "Email for Lunora: Resend adapter, TSX templates, and queue-backed sends",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
],
|
|
15
15
|
"homepage": "https://lunora.sh",
|
|
16
16
|
"bugs": "https://github.com/anolilab/lunora/issues",
|
|
17
|
-
"license": "
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
18
|
"author": {
|
|
19
19
|
"name": "Daniel Bannert",
|
|
20
20
|
"email": "d.bannert@anolilab.de"
|
|
@@ -54,10 +54,11 @@
|
|
|
54
54
|
"access": "public"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
58
|
-
"@
|
|
59
|
-
"@
|
|
60
|
-
"
|
|
57
|
+
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
58
|
+
"@lunora/wire": "1.0.0-alpha.6",
|
|
59
|
+
"@react-email/render": "2.1.0",
|
|
60
|
+
"@visulima/email": "4.2.0",
|
|
61
|
+
"postal-mime": "4.0.8"
|
|
61
62
|
},
|
|
62
63
|
"peerDependencies": {
|
|
63
64
|
"react": "^19.2.7"
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { LunoraError } from '@lunora/errors';
|
|
2
|
-
|
|
3
|
-
const MAX_EMAIL_LENGTH = 320;
|
|
4
|
-
const MAX_NAME_LENGTH = 256;
|
|
5
|
-
const ADDRESS_PATTERN = /^([^<]*)<([^>]*)>\s*$/;
|
|
6
|
-
const assertSafeAddressField = (field, value) => {
|
|
7
|
-
if (value.includes("\r") || value.includes("\n") || value.includes(",")) {
|
|
8
|
-
throw new LunoraError("INTERNAL", `@lunora/mail: address ${field} must not contain CR, LF, or comma`);
|
|
9
|
-
}
|
|
10
|
-
};
|
|
11
|
-
const assertSafeHeaderValue = (label, value) => {
|
|
12
|
-
if (value.includes("\r") || value.includes("\n")) {
|
|
13
|
-
throw new LunoraError("INTERNAL", `@lunora/mail: ${label} must not contain CR or LF`);
|
|
14
|
-
}
|
|
15
|
-
};
|
|
16
|
-
const toBracketedAddress = (name, email) => {
|
|
17
|
-
if (name.length > MAX_NAME_LENGTH) {
|
|
18
|
-
throw new LunoraError("INTERNAL", `@lunora/mail: address name must be <= ${String(MAX_NAME_LENGTH)} characters`);
|
|
19
|
-
}
|
|
20
|
-
if (email.length > MAX_EMAIL_LENGTH) {
|
|
21
|
-
throw new LunoraError("INTERNAL", `@lunora/mail: address email must be <= ${String(MAX_EMAIL_LENGTH)} characters`);
|
|
22
|
-
}
|
|
23
|
-
if (name) {
|
|
24
|
-
assertSafeAddressField("name", name);
|
|
25
|
-
}
|
|
26
|
-
assertSafeAddressField("email", email);
|
|
27
|
-
return name ? { email, name } : { email };
|
|
28
|
-
};
|
|
29
|
-
const toBareAddress = (input) => {
|
|
30
|
-
const email = input.trim();
|
|
31
|
-
if (email.length > MAX_EMAIL_LENGTH) {
|
|
32
|
-
throw new LunoraError("INTERNAL", `@lunora/mail: address email must be <= ${String(MAX_EMAIL_LENGTH)} characters`);
|
|
33
|
-
}
|
|
34
|
-
assertSafeAddressField("email", email);
|
|
35
|
-
return { email };
|
|
36
|
-
};
|
|
37
|
-
const toAddress = (input) => {
|
|
38
|
-
const match = ADDRESS_PATTERN.exec(input);
|
|
39
|
-
const email = (match?.[2] ?? "").trim();
|
|
40
|
-
if (match && email) {
|
|
41
|
-
return toBracketedAddress((match[1] ?? "").trim(), email);
|
|
42
|
-
}
|
|
43
|
-
return toBareAddress(input);
|
|
44
|
-
};
|
|
45
|
-
const toAddressList = (input) => {
|
|
46
|
-
if (input === void 0) {
|
|
47
|
-
return void 0;
|
|
48
|
-
}
|
|
49
|
-
const list = Array.isArray(input) ? input : [input];
|
|
50
|
-
return list.map((entry) => toAddress(entry));
|
|
51
|
-
};
|
|
52
|
-
const assertSafeAddresses = (payload) => {
|
|
53
|
-
toAddressList(payload.to);
|
|
54
|
-
toAddressList(payload.cc);
|
|
55
|
-
toAddressList(payload.bcc);
|
|
56
|
-
if (payload.from !== void 0) {
|
|
57
|
-
toAddress(payload.from);
|
|
58
|
-
}
|
|
59
|
-
if (payload.replyTo !== void 0) {
|
|
60
|
-
toAddress(payload.replyTo);
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
export { assertSafeHeaderValue as a, assertSafeAddresses as b, toAddress as c, toAddressList as t };
|